diff --git a/.github/workflows/check-for-generated-files.yml b/.github/workflows/check-for-generated-files.yml new file mode 100644 index 000000000..233f8eda5 --- /dev/null +++ b/.github/workflows/check-for-generated-files.yml @@ -0,0 +1,85 @@ +name: Check for Generated Files + +on: + # Triggers the workflow on push or pull request events but only for the dev branch + pull_request: + branches: [dev] + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +jobs: + checkFiles: + name: Check Files + runs-on: ubuntu-latest + steps: + - name: Checkout files + uses: actions/checkout@v2 + + - name: Check bundle files + id: changed-bundle-files + uses: tj-actions/changed-files@v18.4 + with: + files: | + dist/* + index.html + main.bundle.js + main.bundle.js.map + + - name: Check documentation changes + id: changed-markdown-doc-files + uses: tj-actions/changed-files@v18.4 + with: + files: | + markdown/*.md + + - name: Warn when bundle files were changed + id: warn-bundles-changed + if: steps.changed-bundle-files.outputs.any_changed == 'true' + run: | + echo "One or more files in the bundle files were changed." >> warnings.txt + + - name: Warn when documentation markdown files were changed + id: warn-markdown-changed + if: steps.changed-markdown-doc-files.outputs.any_changed == 'true' + run: | + echo "One or more files in the markdown documentation were changed." >> warnings.txt + + - name: Print Warnings + id: get-warnings + run: | + if [ -f warnings.txt ] + then + echo "::set-output name=has_warnings::true" + else + echo "::set-output name=has_warnings::false" + touch warnings.txt + fi + + - name: Get Comment Body + id: get-comment-body + if : steps.get-warnings.outputs.has_warnings == 'true' + run: | + cat warnings.txt > comment.txt + echo "" >> comment.txt + echo "Please do not commit files generated by webpack or generated markdown" >> comment.txt + echo "" >> comment.txt + echo "See [CONTRIBUTING.md](https://github.com/danielyxie/bitburner/blob/dev/doc/CONTRIBUTING.md) for details." >> comment.txt + + body=$(cat comment.txt) + body="${body//'%'/'%25'}" + body="${body//$'\n'/'%0A'}" + body="${body//$'\r'/'%0D'}" + + echo ::set-output name=body::$body + - name: Add github comment on problem + if : steps.get-warnings.outputs.has_warnings == 'true' + uses: peter-evans/commit-comment@v1 + with: + body: ${{ steps.get-comment-body.outputs.body }} + - name: Flag as error + if : steps.get-warnings.outputs.has_warnings == 'true' + run: | + COMMIT_WARNINGS=$(cat warnings.txt) + echo "::warning:: $COMMIT_WARNINGS" + exit 1 diff --git a/css/staneksgift.scss b/css/staneksgift.scss deleted file mode 100644 index 83fccf3e4..000000000 --- a/css/staneksgift.scss +++ /dev/null @@ -1,23 +0,0 @@ -.staneksgift_row { - padding: 0; - margin: 0; -} - -.staneksgift_cell { - width: 25px; - height: 25px; - background-color: #808080; - font-color: white; - padding: 0px; - margin: 0px; - border: 1px solid black; - float: left; -} - -.staneksgift_cell:first-child { - clear: left; -} - -.staneksgift_container { - position: fixed; -} diff --git a/dist/engineStyle.bundle.js b/dist/engineStyle.bundle.js deleted file mode 100644 index 915986974..000000000 --- a/dist/engineStyle.bundle.js +++ /dev/null @@ -1,2 +0,0 @@ -!function(n){function t(t){for(var e,i,f=t[0],c=t[1],l=t[2],a=0,s=[];a li { - background-color: #555; } - -/* override the global styling */ -#active-scripts-total-production-active, -#active-scripts-total-prod-aug-total, -#active-scripts-total-prod-aug-avg { - margin: 0; - padding: 0; } - -/* Helper Classes */ -.hacker-green { - color: #adff2f; } - -.money-gold { - color: #ffd700; } - -.light-yellow { - color: #faffdf; } - -.unbuyable { - color: #66cfbc; } - -.failure { - color: #ff2929; - text-shadow: 0 0 0 #ff2929; } - -.success { - color: #3adb76; - text-shadow: 0 0 0 #3adb76; } - -.physical-yellow { - color: #faffdf; } - -.charisma-purple { - color: #a671d1; } - -.reputation { - color: #faffdf; } - -.smallfont { - font-size: 13px; } - -.samefont { - font-size: inherit; } - -.noscrollbar { - -ms-overflow-style: none; - /* IE and Edge */ - /* stylelint-disable-next-line property-no-unknown */ - scrollbar-width: none; - /* Firefox https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-width */ } - -.noscrollbar::-webkit-scrollbar { - display: none; } - -input[type="checkbox"] { - filter: invert(1) sepia(1) hue-rotate(41deg) brightness(100%) saturate(10); } - -.optionCheckbox { - margin: 5px; - float: right; } - -.optionRange { - -webkit-appearance: none; - background: #777; - outline: none; - opacity: 0.7; - height: 10px; - -webkit-transition: 0.2s; - transition: opacity 0.2s; - margin: 3px; } - -.optionRange::-webkit-slider-thumb { - -webkit-appearance: none; - appearance: none; - width: 10px; - height: 10px; - background: var(--my-font-color); - cursor: pointer; } - -.optionRange::-moz-range-thumb { - width: 10px; - height: 10px; - background: var(--my-font-color); - cursor: pointer; } - -.noselect, br { - -moz-user-select: -moz-none; - -khtml-user-select: none; - -webkit-user-select: none; - -ms-user-select: none; - user-select: none; } - -/* COLORS */ -/* Attributes */ -/* Styling for tooltip-style elements */ -/* Tool tips (when hovering over an element */ -.tooltip { - display: inline-block; - position: relative; - /* Positioned to left of element rather than right */ - /* Tooltip goes below cursor instead of above */ } - .tooltip .tooltiptext { - visibility: hidden; - width: 300px; - background-color: var(--my-background-color); - border: 2px solid var(--my-highlight-color); - color: #fff; - text-align: center; - padding: 4px; - left: 101%; - pointer-events: none; - position: absolute; - z-index: 99; } - .tooltip .tooltiptextleft { - visibility: hidden; - width: 300px; - background-color: var(--my-background-color); - border: 2px solid var(--my-highlight-color); - color: #fff; - text-align: center; - padding: 4px; - top: 50%; - left: 50%; - transform: translate(-100%, -100%); - /* Backwards compatibility */ - -webkit-transform: translate(-100%, -100%); - -moz-transform: translate(-100%, -100%); - -o-transform: translate(-100%, -100%); - -ms-transform: translate(-100%, -100%); - position: absolute; - z-index: 99; } - .tooltip .tooltiptextlow { - visibility: hidden; - width: 300px; - background-color: var(--my-background-color); - border: 2px solid var(--my-highlight-color); - color: #fff; - text-align: center; - padding: 4px; - left: 101%; - pointer-events: none; - position: absolute; - z-index: 99; - bottom: 25%; } - -/* Same thing as a normal tooltip except its a bit higher */ -.tooltip .tooltiptexthigh { - visibility: hidden; - width: 300px; - background-color: var(--my-background-color); - border: 2px solid var(--my-highlight-color); - color: #fff; - text-align: center; - padding: 4px; - left: 101%; - bottom: -25%; - position: absolute; - z-index: 99; } - -.tooltip:hover .tooltiptext, -.tooltip:hover .tooltiptexthigh, -.tooltip:hover .tooltiptextleft, -.tooltip:hover .tooltiptextlow { - visibility: visible; } - -.copy_tooltip { - position: relative; - display: inline-block; } - -.copy_tooltip_copied { - color: #fff; - transition: color 0.3s; } - -.copy_tooltip .copy_tooltip_text { - visibility: hidden; - font-size: 15px; - padding: 5px; - background-color: var(--my-background-color); - color: #fff; - text-align: center; - position: absolute; - z-index: 1; - top: 120%; - left: 5%; - opacity: 0; - border: 2px solid var(--my-highlight-color); } - -.copy_tooltip .copy_tooltip_text::after { - content: ""; - position: absolute; - bottom: 100%; - left: 50%; - margin-left: -6px; - border-width: 8px; - border-style: solid; - border-color: transparent transparent white transparent; } - -.copy_tooltip .copy_tooltip_text_visible { - visibility: visible; - opacity: 1; - transition: opacity 0.3s; } - -/* COLORS */ -/* Attributes */ -/* COLORS */ -/* Attributes */ -/* COLORS */ -/* Attributes */ -* { - font-size: 16px; - font-family: "Lucida Console", "Lucida Sans Unicode", "Fira Mono", "Consolas", "Courier New", Courier, monospace, "Times New Roman"; } - -*, -*:before, -*:after { - margin: 0; - padding: 0; - box-sizing: border-box; - vertical-align: middle; } - -:root { - --my-font-color: #0c0; - --my-background-color: #000; - --my-highlight-color: #fff; - --my-prompt-color: #f92672; } - -body { - background-color: var(--my-background-color); - -ms-overflow-style: none; - /* for Internet Explorer, Edge */ - scrollbar-width: none; - /* for Firefox */ } - -body::-webkit-scrollbar { - display: none; - /* for Chrome, Safari, and Opera */ } - -p, -pre, -h2, -h3, -h4, -.text, -td { - color: var(--my-font-color); } - -h1 { - font-size: 22px; - color: var(--my-font-color); } - -ul { - padding: 2px; - list-style-type: none; } - -li { - list-style-type: none; } - -#entire-game-container { - background-color: transparent; } - -/* Disable border highlight on elements */ -input:focus, -textarea:focus, -button:focus, -td:focus, -tr:focus { - outline: none; } - -/* Make html links ("a" elements) nice looking buttons with this class */ -a:link, -a:visited { - color: #fff; } - -.dropdown { - color: #fff; - background-color: #000; } - -.text-input { - color: #fff; - background-color: #000; - border-style: solid; - border-width: 1px; - border-color: white; } - -/* Notification icon (for create program right now only) */ -#create-program-tab { - position: relative; } - -#create-program-notification { - font-size: 10px; - position: absolute; - /* Position the badge within the relatively positioned button */ - top: 0; - right: 0; } - -#factions-tab { - position: relative; } - -#factions-notification { - font-size: 10px; - position: absolute; - /* Position the badge within the relatively positioned button */ - top: 0; - right: 0; } - -#augmentations-tab { - position: relative; } - -#augmentations-notification { - font-size: 10px; - position: absolute; - /* Position the badge within the relatively positioned button */ - top: 0; - right: 0; } - -.notification-on { - background-color: #fa3e3e; - color: #fff; - border-radius: 2px; - padding: 1px 3px; - font-size: 10px; - top: 0; - right: 0; - position: absolute; } - -.notification-off { - background-color: #333; - color: #333; - border-radius: 0; - padding: 0; - display: "none"; } - -.notification { - position: relative; - display: inline-block; } - -.notification .badge { - position: absolute; - top: 0; - right: 0; - padding: 2px; - background: red; - color: white; } - -/* help tip. Question mark that opens popup with info/details */ -.help-tip { - background-color: black; - border: 1px solid #fff; - border-radius: 5px; - color: #fff; - content: "?"; - display: inline-block; - margin-left: 3px; - padding: 1px; } - -.help-tip-big { - content: "?"; - padding: 3px; - margin-left: 3px; - color: #fff; - border: 1px solid #fff; - border-radius: 8px; - display: inline-block; } - -.help-tip:hover, -.help-tip-big:hover { - background-color: #888; } - -.help-tip:active, -.help-tip-big:active { - -webkit-box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6); - -moz-box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6); - box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6); } - -/* Flashing button (Red) */ -@-webkit-keyframes glowing { - 0% { - background-color: #b20000; - -webkit-box-shadow: 0 0 3px #b20000; } - 50% { - background-color: #f00; - -webkit-box-shadow: 0 0 40px #f00; } - 100% { - background-color: #b20000; - -webkit-box-shadow: 0 0 3px #b20000; } } - -@-moz-keyframes glowing { - 0% { - background-color: #b20000; - -moz-box-shadow: 0 0 3px #b20000; } - 50% { - background-color: #f00; - -moz-box-shadow: 0 0 40px #f00; } - 100% { - background-color: #b20000; - -moz-box-shadow: 0 0 3px #b20000; } } - -@-o-keyframes glowing { - 0% { - background-color: #b20000; - box-shadow: 0 0 3px #b20000; } - 50% { - background-color: #f00; - box-shadow: 0 0 40px #f00; } - 100% { - background-color: #b20000; - box-shadow: 0 0 3px #b20000; } } - -@keyframes glowing { - 0% { - background-color: #b20000; - box-shadow: 0 0 3px #b20000; } - 50% { - background-color: #f00; - box-shadow: 0 0 40px #f00; } - 100% { - background-color: #b20000; - box-shadow: 0 0 3px #b20000; } } - -.flashing-button { - -webkit-animation: glowing 1500ms infinite; - -moz-animation: glowing 1500ms infinite; - -o-animation: glowing 1500ms infinite; - animation: glowing 1500ms infinite; } - -/* Blinking Cursor */ -/* ----- blinking cursor animation ----- */ -.typed-cursor { - opacity: 1; - -webkit-animation: blink 0.95s infinite; - -moz-animation: blink 0.95s infinite; - -ms-animation: blink 0.95s infinite; - -o-animation: blink 0.95s infinite; - animation: blink 0.95s infinite; } - -@-keyframes blink { - 0% { - opacity: 1; } - 50% { - opacity: 0; } - 100% { - opacity: 1; } } - -@-webkit-keyframes blink { - 0% { - opacity: 1; } - 50% { - opacity: 0; } - 100% { - opacity: 1; } } - -@-moz-keyframes blink { - 0% { - opacity: 1; } - 50% { - opacity: 0; } - 100% { - opacity: 1; } } - -@-ms-keyframes blink { - 0% { - opacity: 1; } - 50% { - opacity: 0; } - 100% { - opacity: 1; } } - -@-o-keyframes blink { - 0% { - opacity: 1; } - 50% { - opacity: 0; } - 100% { - opacity: 1; } } - -/* Status text */ -@-webkit-keyframes status-text { - from { - opacity: 1; } - to { - opacity: 0; } } - -.status-text { - z-index: 2; - -webkit-animation: status-text 3s 1; } - -#status-text-container { - background-color: transparent; - position: absolute; - top: 0; - left: 50%; } - -#status-text { - background-color: transparent; - bottom: 0; - color: #fff; - display: none; - font-size: 20px; - margin-right: 14px; - opacity: 0; - padding: 4px; - right: 0; - top: 0; - width: auto; } - -/* Scan analyze links from AutoLink */ -.scan-analyze-link { - cursor: pointer; - color: #fff; - text-decoration: underline; } - .scan-analyze-link:hover { - text-decoration: none; } - -/* Accordion menus (Header with collapsible panel) */ -.accordion-header { - background-color: #444; - color: #fff; - font-size: 20px; - margin: 6px 6px 0 6px; - padding: 4px 6px; - cursor: pointer; - width: 80%; - text-align: left; - border: none; - outline: none; - position: relative; } - .accordion-header.active, .accordion-header:hover { - background-color: #555; } - .accordion-header.active:hover { - background-color: #666; } - .accordion-header:after { - content: "\2795"; - /* "plus" sign (+) */ - font-size: 14px; - float: right; - color: transparent; - text-shadow: 0 0 0 #fff; - position: absolute; - bottom: 5px; - right: 6px; } - .accordion-header.active:after { - content: "\2796"; - /* "minus" sign (-) */ } - -.accordion-panel { - margin: 0 6px 6px 6px; - padding: 0 6px 6px 6px; - width: 75%; - margin-left: 5%; - display: none; - background-color: #555; - overflow-y: auto; - overflow-x: none; } - .accordion-panel div, - .accordion-panel ul, - .accordion-panel p, - .accordion-panel ul > li { - background-color: #555; } - -/* override the global styling */ -#active-scripts-total-production-active, -#active-scripts-total-prod-aug-total, -#active-scripts-total-prod-aug-avg { - margin: 0; - padding: 0; } - -/* Helper Classes */ -.hacker-green { - color: #adff2f; } - -.money-gold { - color: #ffd700; } - -.light-yellow { - color: #faffdf; } - -.unbuyable { - color: #66cfbc; } - -.failure { - color: #ff2929; - text-shadow: 0 0 0 #ff2929; } - -.success { - color: #3adb76; - text-shadow: 0 0 0 #3adb76; } - -.physical-yellow { - color: #faffdf; } - -.charisma-purple { - color: #a671d1; } - -.reputation { - color: #faffdf; } - -.smallfont { - font-size: 13px; } - -.samefont { - font-size: inherit; } - -.noscrollbar { - -ms-overflow-style: none; - /* IE and Edge */ - /* stylelint-disable-next-line property-no-unknown */ - scrollbar-width: none; - /* Firefox https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-width */ } - -.noscrollbar::-webkit-scrollbar { - display: none; } - -input[type="checkbox"] { - filter: invert(1) sepia(1) hue-rotate(41deg) brightness(100%) saturate(10); } - -.optionCheckbox { - margin: 5px; - float: right; } - -.optionRange { - -webkit-appearance: none; - background: #777; - outline: none; - opacity: 0.7; - height: 10px; - -webkit-transition: 0.2s; - transition: opacity 0.2s; - margin: 3px; } - -.optionRange::-webkit-slider-thumb { - -webkit-appearance: none; - appearance: none; - width: 10px; - height: 10px; - background: var(--my-font-color); - cursor: pointer; } - -.optionRange::-moz-range-thumb { - width: 10px; - height: 10px; - background: var(--my-font-color); - cursor: pointer; } - -.noselect, br, .a-link-button, -.std-button, .a-link-button-bought, -.std-button-bought { - -moz-user-select: -moz-none; - -khtml-user-select: none; - -webkit-user-select: none; - -ms-user-select: none; - user-select: none; } - -/** - * Styling for all buttons - * - * Includes - } else { - attrs[name] = he.decode(doubleQuotedValue || singleQuotedValue || unquotedValue || ''); - } - } - } - - function parseEndTag(tag, tagName) { - var i; - var pos = 0; - var low = lowercase(tagName); - if (low) { - for (pos = stack.length - 1; pos >= 0; pos--) { - if (stack[pos] === low) { - break; // find the closest opened tag of the same type - } - } - } - if (pos >= 0) { - for (i = stack.length - 1; i >= pos; i--) { - if (handler.end) { // close all the open elements, up the stack - handler.end(stack[i]); - } - } - stack.length = pos; - } - } - } - - module.exports = parser; - - }, { "./attributes": 1, "./elements": 3, "./lowercase": 5, "he": 9 }], 8: [function (require, module, exports) { - 'use strict'; - - var he = require('he'); - var lowercase = require('./lowercase'); - var attributes = require('./attributes'); - var elements = require('./elements'); - - function sanitizer(buffer, options) { - var last; - var context; - var o = options || {}; - - reset(); - - return { - start: start, - end: end, - chars: chars - }; - - function out(value) { - buffer.push(value); - } - - function start(tag, attrs, unary) { - var low = lowercase(tag); - - if (context.ignoring) { - ignore(low); return; - } - if ((o.allowedTags || []).indexOf(low) === -1) { - ignore(low); return; - } - if (o.filter && !o.filter({ tag: low, attrs: attrs })) { - ignore(low); return; - } - - out('<'); - out(low); - Object.keys(attrs).forEach(parse); - out(unary ? '/>' : '>'); - - function parse(key) { - var value = attrs[key]; - var classesOk = (o.allowedClasses || {})[low] || []; - var attrsOk = (o.allowedAttributes || {})[low] || []; - attrsOk = attrsOk.concat((o.allowedAttributes || {})['*'] || []); - var valid; - var lkey = lowercase(key); - if (lkey === 'class' && attrsOk.indexOf(lkey) === -1) { - value = value.split(' ').filter(isValidClass).join(' ').trim(); - valid = value.length; - } else { - valid = attrsOk.indexOf(lkey) !== -1 && (attributes.uris[lkey] !== true || testUrl(value)); - } - if (valid) { - out(' '); - out(key); - if (typeof value === 'string') { - out('="'); - out(he.encode(value)); - out('"'); - } - } - function isValidClass(className) { - return classesOk && classesOk.indexOf(className) !== -1; - } - } - } - - function end(tag) { - var low = lowercase(tag); - var allowed = (o.allowedTags || []).indexOf(low) !== -1; - if (allowed) { - if (context.ignoring === false) { - out(''); - } else { - unignore(low); - } - } else { - unignore(low); - } - } - - function testUrl(text) { - var start = text[0]; - if (start === '#' || start === '/') { - return true; - } - var colon = text.indexOf(':'); - if (colon === -1) { - return true; - } - var questionmark = text.indexOf('?'); - if (questionmark !== -1 && colon > questionmark) { - return true; - } - var hash = text.indexOf('#'); - if (hash !== -1 && colon > hash) { - return true; - } - return o.allowedSchemes.some(matches); - - function matches(scheme) { - return text.indexOf(scheme + ':') === 0; - } - } - - function chars(text) { - if (context.ignoring === false) { - out(o.transformText ? o.transformText(text) : text); - } - } - - function ignore(tag) { - if (elements.voids[tag]) { - return; - } - if (context.ignoring === false) { - context = { ignoring: tag, depth: 1 }; - } else if (context.ignoring === tag) { - context.depth++; - } - } - - function unignore(tag) { - if (context.ignoring === tag) { - if (--context.depth <= 0) { - reset(); - } - } - } - - function reset() { - context = { ignoring: false, depth: 0 }; - } - } - - module.exports = sanitizer; - - }, { "./attributes": 1, "./elements": 3, "./lowercase": 5, "he": 9 }], 9: [function (require, module, exports) { - 'use strict'; - - var escapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''' - }; - var unescapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - ''': "'" - }; - var rescaped = /(&|<|>|"|')/g; - var runescaped = /[&<>"']/g; - - function escapeHtmlChar(match) { - return escapes[match]; - } - function unescapeHtmlChar(match) { - return unescapes[match]; - } - - function escapeHtml(text) { - return text == null ? '' : String(text).replace(runescaped, escapeHtmlChar); - } - - function unescapeHtml(html) { - return html == null ? '' : String(html).replace(rescaped, unescapeHtmlChar); - } - - escapeHtml.options = unescapeHtml.options = {}; - - module.exports = { - encode: escapeHtml, - escape: escapeHtml, - decode: unescapeHtml, - unescape: unescapeHtml, - version: '1.0.0-browser' - }; - - }, {}], 10: [function (require, module, exports) { - 'use strict'; - - function toMap(list) { - return list.reduce(asKey, {}); - } - - function asKey(accumulator, item) { - accumulator[item] = true; - return accumulator; - } - - module.exports = toMap; - - }, {}] -}, {}, [4]); - -// ESM-comment-begin -define("vs/base/common/insane/insane", function() { return { insane: __insane_func }; }); -// ESM-comment-end - -// ESM-uncomment-begin -// export var insane = __insane_func; -// ESM-uncomment-end - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[54/*vs/base/common/iterator*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Iterable = void 0; - var Iterable; - (function (Iterable) { - function is(thing) { - return thing && typeof thing === 'object' && typeof thing[Symbol.iterator] === 'function'; - } - Iterable.is = is; - const _empty = Object.freeze([]); - function empty() { - return _empty; - } - Iterable.empty = empty; - function* single(element) { - yield element; - } - Iterable.single = single; - function from(iterable) { - return iterable || _empty; - } - Iterable.from = from; - function isEmpty(iterable) { - return !iterable || iterable[Symbol.iterator]().next().done === true; - } - Iterable.isEmpty = isEmpty; - function first(iterable) { - return iterable[Symbol.iterator]().next().value; - } - Iterable.first = first; - function some(iterable, predicate) { - for (const element of iterable) { - if (predicate(element)) { - return true; - } - } - return false; - } - Iterable.some = some; - function find(iterable, predicate) { - for (const element of iterable) { - if (predicate(element)) { - return element; - } - } - return undefined; - } - Iterable.find = find; - function* filter(iterable, predicate) { - for (const element of iterable) { - if (predicate(element)) { - yield element; - } - } - } - Iterable.filter = filter; - function* map(iterable, fn) { - let index = 0; - for (const element of iterable) { - yield fn(element, index++); - } - } - Iterable.map = map; - function* concat(...iterables) { - for (const iterable of iterables) { - for (const element of iterable) { - yield element; - } - } - } - Iterable.concat = concat; - function* concatNested(iterables) { - for (const iterable of iterables) { - for (const element of iterable) { - yield element; - } - } - } - Iterable.concatNested = concatNested; - function reduce(iterable, reducer, initialValue) { - let value = initialValue; - for (const element of iterable) { - value = reducer(value, element); - } - return value; - } - Iterable.reduce = reduce; - /** - * Returns an iterable slice of the array, with the same semantics as `array.slice()`. - */ - function* slice(arr, from, to = arr.length) { - if (from < 0) { - from += arr.length; - } - if (to < 0) { - to += arr.length; - } - else if (to > arr.length) { - to = arr.length; - } - for (; from < to; from++) { - yield arr[from]; - } - } - Iterable.slice = slice; - /** - * Consumes `atMost` elements from iterable and returns the consumed elements, - * and an iterable for the rest of the elements. - */ - function consume(iterable, atMost = Number.POSITIVE_INFINITY) { - const consumed = []; - if (atMost === 0) { - return [consumed, iterable]; - } - const iterator = iterable[Symbol.iterator](); - for (let i = 0; i < atMost; i++) { - const next = iterator.next(); - if (next.done) { - return [consumed, Iterable.empty()]; - } - consumed.push(next.value); - } - return [consumed, { [Symbol.iterator]() { return iterator; } }]; - } - Iterable.consume = consume; - /** - * Returns whether the iterables are the same length and all items are - * equal using the comparator function. - */ - function equals(a, b, comparator = (at, bt) => at === bt) { - const ai = a[Symbol.iterator](); - const bi = b[Symbol.iterator](); - while (true) { - const an = ai.next(); - const bn = bi.next(); - if (an.done !== bn.done) { - return false; - } - else if (an.done) { - return true; - } - else if (!comparator(an.value, bn.value)) { - return false; - } - } - } - Iterable.equals = equals; - })(Iterable = exports.Iterable || (exports.Iterable = {})); -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/common/keyCodes*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/]), function (require, exports, errors_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ResolvedKeybinding = exports.ResolvedKeybindingPart = exports.ChordKeybinding = exports.SimpleKeybinding = exports.createSimpleKeybinding = exports.createKeybinding = exports.KeyChord = exports.KeyCodeUtils = void 0; - class KeyCodeStrMap { - constructor() { - this._keyCodeToStr = []; - this._strToKeyCode = Object.create(null); - } - define(keyCode, str) { - this._keyCodeToStr[keyCode] = str; - this._strToKeyCode[str.toLowerCase()] = keyCode; - } - keyCodeToStr(keyCode) { - return this._keyCodeToStr[keyCode]; - } - strToKeyCode(str) { - return this._strToKeyCode[str.toLowerCase()] || 0 /* Unknown */; - } - } - const uiMap = new KeyCodeStrMap(); - const userSettingsUSMap = new KeyCodeStrMap(); - const userSettingsGeneralMap = new KeyCodeStrMap(); - (function () { - function define(keyCode, uiLabel, usUserSettingsLabel = uiLabel, generalUserSettingsLabel = usUserSettingsLabel) { - uiMap.define(keyCode, uiLabel); - userSettingsUSMap.define(keyCode, usUserSettingsLabel); - userSettingsGeneralMap.define(keyCode, generalUserSettingsLabel); - } - define(0 /* Unknown */, 'unknown'); - define(1 /* Backspace */, 'Backspace'); - define(2 /* Tab */, 'Tab'); - define(3 /* Enter */, 'Enter'); - define(4 /* Shift */, 'Shift'); - define(5 /* Ctrl */, 'Ctrl'); - define(6 /* Alt */, 'Alt'); - define(7 /* PauseBreak */, 'PauseBreak'); - define(8 /* CapsLock */, 'CapsLock'); - define(9 /* Escape */, 'Escape'); - define(10 /* Space */, 'Space'); - define(11 /* PageUp */, 'PageUp'); - define(12 /* PageDown */, 'PageDown'); - define(13 /* End */, 'End'); - define(14 /* Home */, 'Home'); - define(15 /* LeftArrow */, 'LeftArrow', 'Left'); - define(16 /* UpArrow */, 'UpArrow', 'Up'); - define(17 /* RightArrow */, 'RightArrow', 'Right'); - define(18 /* DownArrow */, 'DownArrow', 'Down'); - define(19 /* Insert */, 'Insert'); - define(20 /* Delete */, 'Delete'); - define(21 /* KEY_0 */, '0'); - define(22 /* KEY_1 */, '1'); - define(23 /* KEY_2 */, '2'); - define(24 /* KEY_3 */, '3'); - define(25 /* KEY_4 */, '4'); - define(26 /* KEY_5 */, '5'); - define(27 /* KEY_6 */, '6'); - define(28 /* KEY_7 */, '7'); - define(29 /* KEY_8 */, '8'); - define(30 /* KEY_9 */, '9'); - define(31 /* KEY_A */, 'A'); - define(32 /* KEY_B */, 'B'); - define(33 /* KEY_C */, 'C'); - define(34 /* KEY_D */, 'D'); - define(35 /* KEY_E */, 'E'); - define(36 /* KEY_F */, 'F'); - define(37 /* KEY_G */, 'G'); - define(38 /* KEY_H */, 'H'); - define(39 /* KEY_I */, 'I'); - define(40 /* KEY_J */, 'J'); - define(41 /* KEY_K */, 'K'); - define(42 /* KEY_L */, 'L'); - define(43 /* KEY_M */, 'M'); - define(44 /* KEY_N */, 'N'); - define(45 /* KEY_O */, 'O'); - define(46 /* KEY_P */, 'P'); - define(47 /* KEY_Q */, 'Q'); - define(48 /* KEY_R */, 'R'); - define(49 /* KEY_S */, 'S'); - define(50 /* KEY_T */, 'T'); - define(51 /* KEY_U */, 'U'); - define(52 /* KEY_V */, 'V'); - define(53 /* KEY_W */, 'W'); - define(54 /* KEY_X */, 'X'); - define(55 /* KEY_Y */, 'Y'); - define(56 /* KEY_Z */, 'Z'); - define(57 /* Meta */, 'Meta'); - define(58 /* ContextMenu */, 'ContextMenu'); - define(59 /* F1 */, 'F1'); - define(60 /* F2 */, 'F2'); - define(61 /* F3 */, 'F3'); - define(62 /* F4 */, 'F4'); - define(63 /* F5 */, 'F5'); - define(64 /* F6 */, 'F6'); - define(65 /* F7 */, 'F7'); - define(66 /* F8 */, 'F8'); - define(67 /* F9 */, 'F9'); - define(68 /* F10 */, 'F10'); - define(69 /* F11 */, 'F11'); - define(70 /* F12 */, 'F12'); - define(71 /* F13 */, 'F13'); - define(72 /* F14 */, 'F14'); - define(73 /* F15 */, 'F15'); - define(74 /* F16 */, 'F16'); - define(75 /* F17 */, 'F17'); - define(76 /* F18 */, 'F18'); - define(77 /* F19 */, 'F19'); - define(78 /* NumLock */, 'NumLock'); - define(79 /* ScrollLock */, 'ScrollLock'); - define(80 /* US_SEMICOLON */, ';', ';', 'OEM_1'); - define(81 /* US_EQUAL */, '=', '=', 'OEM_PLUS'); - define(82 /* US_COMMA */, ',', ',', 'OEM_COMMA'); - define(83 /* US_MINUS */, '-', '-', 'OEM_MINUS'); - define(84 /* US_DOT */, '.', '.', 'OEM_PERIOD'); - define(85 /* US_SLASH */, '/', '/', 'OEM_2'); - define(86 /* US_BACKTICK */, '`', '`', 'OEM_3'); - define(110 /* ABNT_C1 */, 'ABNT_C1'); - define(111 /* ABNT_C2 */, 'ABNT_C2'); - define(87 /* US_OPEN_SQUARE_BRACKET */, '[', '[', 'OEM_4'); - define(88 /* US_BACKSLASH */, '\\', '\\', 'OEM_5'); - define(89 /* US_CLOSE_SQUARE_BRACKET */, ']', ']', 'OEM_6'); - define(90 /* US_QUOTE */, '\'', '\'', 'OEM_7'); - define(91 /* OEM_8 */, 'OEM_8'); - define(92 /* OEM_102 */, 'OEM_102'); - define(93 /* NUMPAD_0 */, 'NumPad0'); - define(94 /* NUMPAD_1 */, 'NumPad1'); - define(95 /* NUMPAD_2 */, 'NumPad2'); - define(96 /* NUMPAD_3 */, 'NumPad3'); - define(97 /* NUMPAD_4 */, 'NumPad4'); - define(98 /* NUMPAD_5 */, 'NumPad5'); - define(99 /* NUMPAD_6 */, 'NumPad6'); - define(100 /* NUMPAD_7 */, 'NumPad7'); - define(101 /* NUMPAD_8 */, 'NumPad8'); - define(102 /* NUMPAD_9 */, 'NumPad9'); - define(103 /* NUMPAD_MULTIPLY */, 'NumPad_Multiply'); - define(104 /* NUMPAD_ADD */, 'NumPad_Add'); - define(105 /* NUMPAD_SEPARATOR */, 'NumPad_Separator'); - define(106 /* NUMPAD_SUBTRACT */, 'NumPad_Subtract'); - define(107 /* NUMPAD_DECIMAL */, 'NumPad_Decimal'); - define(108 /* NUMPAD_DIVIDE */, 'NumPad_Divide'); - })(); - var KeyCodeUtils; - (function (KeyCodeUtils) { - function toString(keyCode) { - return uiMap.keyCodeToStr(keyCode); - } - KeyCodeUtils.toString = toString; - function fromString(key) { - return uiMap.strToKeyCode(key); - } - KeyCodeUtils.fromString = fromString; - function toUserSettingsUS(keyCode) { - return userSettingsUSMap.keyCodeToStr(keyCode); - } - KeyCodeUtils.toUserSettingsUS = toUserSettingsUS; - function toUserSettingsGeneral(keyCode) { - return userSettingsGeneralMap.keyCodeToStr(keyCode); - } - KeyCodeUtils.toUserSettingsGeneral = toUserSettingsGeneral; - function fromUserSettings(key) { - return userSettingsUSMap.strToKeyCode(key) || userSettingsGeneralMap.strToKeyCode(key); - } - KeyCodeUtils.fromUserSettings = fromUserSettings; - })(KeyCodeUtils = exports.KeyCodeUtils || (exports.KeyCodeUtils = {})); - function KeyChord(firstPart, secondPart) { - const chordPart = ((secondPart & 0x0000FFFF) << 16) >>> 0; - return (firstPart | chordPart) >>> 0; - } - exports.KeyChord = KeyChord; - function createKeybinding(keybinding, OS) { - if (keybinding === 0) { - return null; - } - const firstPart = (keybinding & 0x0000FFFF) >>> 0; - const chordPart = (keybinding & 0xFFFF0000) >>> 16; - if (chordPart !== 0) { - return new ChordKeybinding([ - createSimpleKeybinding(firstPart, OS), - createSimpleKeybinding(chordPart, OS) - ]); - } - return new ChordKeybinding([createSimpleKeybinding(firstPart, OS)]); - } - exports.createKeybinding = createKeybinding; - function createSimpleKeybinding(keybinding, OS) { - const ctrlCmd = (keybinding & 2048 /* CtrlCmd */ ? true : false); - const winCtrl = (keybinding & 256 /* WinCtrl */ ? true : false); - const ctrlKey = (OS === 2 /* Macintosh */ ? winCtrl : ctrlCmd); - const shiftKey = (keybinding & 1024 /* Shift */ ? true : false); - const altKey = (keybinding & 512 /* Alt */ ? true : false); - const metaKey = (OS === 2 /* Macintosh */ ? ctrlCmd : winCtrl); - const keyCode = (keybinding & 255 /* KeyCode */); - return new SimpleKeybinding(ctrlKey, shiftKey, altKey, metaKey, keyCode); - } - exports.createSimpleKeybinding = createSimpleKeybinding; - class SimpleKeybinding { - constructor(ctrlKey, shiftKey, altKey, metaKey, keyCode) { - this.ctrlKey = ctrlKey; - this.shiftKey = shiftKey; - this.altKey = altKey; - this.metaKey = metaKey; - this.keyCode = keyCode; - } - equals(other) { - return (this.ctrlKey === other.ctrlKey - && this.shiftKey === other.shiftKey - && this.altKey === other.altKey - && this.metaKey === other.metaKey - && this.keyCode === other.keyCode); - } - isModifierKey() { - return (this.keyCode === 0 /* Unknown */ - || this.keyCode === 5 /* Ctrl */ - || this.keyCode === 57 /* Meta */ - || this.keyCode === 6 /* Alt */ - || this.keyCode === 4 /* Shift */); - } - toChord() { - return new ChordKeybinding([this]); - } - /** - * Does this keybinding refer to the key code of a modifier and it also has the modifier flag? - */ - isDuplicateModifierCase() { - return ((this.ctrlKey && this.keyCode === 5 /* Ctrl */) - || (this.shiftKey && this.keyCode === 4 /* Shift */) - || (this.altKey && this.keyCode === 6 /* Alt */) - || (this.metaKey && this.keyCode === 57 /* Meta */)); - } - } - exports.SimpleKeybinding = SimpleKeybinding; - class ChordKeybinding { - constructor(parts) { - if (parts.length === 0) { - throw (0, errors_1.illegalArgument)(`parts`); - } - this.parts = parts; - } - } - exports.ChordKeybinding = ChordKeybinding; - class ResolvedKeybindingPart { - constructor(ctrlKey, shiftKey, altKey, metaKey, kbLabel, kbAriaLabel) { - this.ctrlKey = ctrlKey; - this.shiftKey = shiftKey; - this.altKey = altKey; - this.metaKey = metaKey; - this.keyLabel = kbLabel; - this.keyAriaLabel = kbAriaLabel; - } - } - exports.ResolvedKeybindingPart = ResolvedKeybindingPart; - /** - * A resolved keybinding. Can be a simple keybinding or a chord keybinding. - */ - class ResolvedKeybinding { - } - exports.ResolvedKeybinding = ResolvedKeybinding; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/common/lazy*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Lazy = void 0; - class Lazy { - constructor(executor) { - this.executor = executor; - this._didRun = false; - } - /** - * Get the wrapped value. - * - * This will force evaluation of the lazy value if it has not been resolved yet. Lazy values are only - * resolved once. `getValue` will re-throw exceptions that are hit while resolving the value - */ - getValue() { - if (!this._didRun) { - try { - this._value = this.executor(); - } - catch (err) { - this._error = err; - } - finally { - this._didRun = true; - } - } - if (this._error) { - throw this._error; - } - return this._value; - } - /** - * Get the wrapped value without forcing evaluation. - */ - get rawValue() { return this._value; } - } - exports.Lazy = Lazy; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[2/*vs/base/common/lifecycle*/], __M([0/*require*/,1/*exports*/,80/*vs/base/common/functional*/,54/*vs/base/common/iterator*/]), function (require, exports, functional_1, iterator_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ImmortalReference = exports.MutableDisposable = exports.Disposable = exports.DisposableStore = exports.toDisposable = exports.combinedDisposable = exports.dispose = exports.isDisposable = exports.MultiDisposeError = exports.markAsSingleton = exports.setDisposableTracker = void 0; - /** - * Enables logging of potentially leaked disposables. - * - * A disposable is considered leaked if it is not disposed or not registered as the child of - * another disposable. This tracking is very simple an only works for classes that either - * extend Disposable or use a DisposableStore. This means there are a lot of false positives. - */ - const TRACK_DISPOSABLES = false; - let disposableTracker = null; - function setDisposableTracker(tracker) { - disposableTracker = tracker; - } - exports.setDisposableTracker = setDisposableTracker; - if (TRACK_DISPOSABLES) { - const __is_disposable_tracked__ = '__is_disposable_tracked__'; - setDisposableTracker(new class { - trackDisposable(x) { - const stack = new Error('Potentially leaked disposable').stack; - setTimeout(() => { - if (!x[__is_disposable_tracked__]) { - console.log(stack); - } - }, 3000); - } - setParent(child, parent) { - if (child && child !== Disposable.None) { - try { - child[__is_disposable_tracked__] = true; - } - catch (_a) { - // noop - } - } - } - markAsDisposed(disposable) { - if (disposable && disposable !== Disposable.None) { - try { - disposable[__is_disposable_tracked__] = true; - } - catch (_a) { - // noop - } - } - } - markAsSingleton(disposable) { } - }); - } - function trackDisposable(x) { - disposableTracker === null || disposableTracker === void 0 ? void 0 : disposableTracker.trackDisposable(x); - return x; - } - function markAsDisposed(disposable) { - disposableTracker === null || disposableTracker === void 0 ? void 0 : disposableTracker.markAsDisposed(disposable); - } - function setParentOfDisposable(child, parent) { - disposableTracker === null || disposableTracker === void 0 ? void 0 : disposableTracker.setParent(child, parent); - } - function setParentOfDisposables(children, parent) { - if (!disposableTracker) { - return; - } - for (const child of children) { - disposableTracker.setParent(child, parent); - } - } - /** - * Indicates that the given object is a singleton which does not need to be disposed. - */ - function markAsSingleton(singleton) { - disposableTracker === null || disposableTracker === void 0 ? void 0 : disposableTracker.markAsSingleton(singleton); - return singleton; - } - exports.markAsSingleton = markAsSingleton; - class MultiDisposeError extends Error { - constructor(errors) { - super(`Encountered errors while disposing of store. Errors: [${errors.join(', ')}]`); - this.errors = errors; - } - } - exports.MultiDisposeError = MultiDisposeError; - function isDisposable(thing) { - return typeof thing.dispose === 'function' && thing.dispose.length === 0; - } - exports.isDisposable = isDisposable; - function dispose(arg) { - if (iterator_1.Iterable.is(arg)) { - let errors = []; - for (const d of arg) { - if (d) { - try { - d.dispose(); - } - catch (e) { - errors.push(e); - } - } - } - if (errors.length === 1) { - throw errors[0]; - } - else if (errors.length > 1) { - throw new MultiDisposeError(errors); - } - return Array.isArray(arg) ? [] : arg; - } - else if (arg) { - arg.dispose(); - return arg; - } - } - exports.dispose = dispose; - function combinedDisposable(...disposables) { - const parent = toDisposable(() => dispose(disposables)); - setParentOfDisposables(disposables, parent); - return parent; - } - exports.combinedDisposable = combinedDisposable; - function toDisposable(fn) { - const self = trackDisposable({ - dispose: (0, functional_1.once)(() => { - markAsDisposed(self); - fn(); - }) - }); - return self; - } - exports.toDisposable = toDisposable; - class DisposableStore { - constructor() { - this._toDispose = new Set(); - this._isDisposed = false; - trackDisposable(this); - } - /** - * Dispose of all registered disposables and mark this object as disposed. - * - * Any future disposables added to this object will be disposed of on `add`. - */ - dispose() { - if (this._isDisposed) { - return; - } - markAsDisposed(this); - this._isDisposed = true; - this.clear(); - } - /** - * Dispose of all registered disposables but do not mark this object as disposed. - */ - clear() { - try { - dispose(this._toDispose.values()); - } - finally { - this._toDispose.clear(); - } - } - add(o) { - if (!o) { - return o; - } - if (o === this) { - throw new Error('Cannot register a disposable on itself!'); - } - setParentOfDisposable(o, this); - if (this._isDisposed) { - if (!DisposableStore.DISABLE_DISPOSED_WARNING) { - console.warn(new Error('Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!').stack); - } - } - else { - this._toDispose.add(o); - } - return o; - } - } - exports.DisposableStore = DisposableStore; - DisposableStore.DISABLE_DISPOSED_WARNING = false; - class Disposable { - constructor() { - this._store = new DisposableStore(); - trackDisposable(this); - setParentOfDisposable(this._store, this); - } - dispose() { - markAsDisposed(this); - this._store.dispose(); - } - _register(o) { - if (o === this) { - throw new Error('Cannot register a disposable on itself!'); - } - return this._store.add(o); - } - } - exports.Disposable = Disposable; - Disposable.None = Object.freeze({ dispose() { } }); - /** - * Manages the lifecycle of a disposable value that may be changed. - * - * This ensures that when the disposable value is changed, the previously held disposable is disposed of. You can - * also register a `MutableDisposable` on a `Disposable` to ensure it is automatically cleaned up. - */ - class MutableDisposable { - constructor() { - this._isDisposed = false; - trackDisposable(this); - } - get value() { - return this._isDisposed ? undefined : this._value; - } - set value(value) { - var _a; - if (this._isDisposed || value === this._value) { - return; - } - (_a = this._value) === null || _a === void 0 ? void 0 : _a.dispose(); - if (value) { - setParentOfDisposable(value, this); - } - this._value = value; - } - clear() { - this.value = undefined; - } - dispose() { - var _a; - this._isDisposed = true; - markAsDisposed(this); - (_a = this._value) === null || _a === void 0 ? void 0 : _a.dispose(); - this._value = undefined; - } - /** - * Clears the value, but does not dispose it. - * The old value is returned. - */ - clearAndLeak() { - const oldValue = this._value; - this._value = undefined; - if (oldValue) { - setParentOfDisposable(oldValue, null); - } - return oldValue; - } - } - exports.MutableDisposable = MutableDisposable; - class ImmortalReference { - constructor(object) { - this.object = object; - } - dispose() { } - } - exports.ImmortalReference = ImmortalReference; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/common/linkedList*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.LinkedList = void 0; - class Node { - constructor(element) { - this.element = element; - this.next = Node.Undefined; - this.prev = Node.Undefined; - } - } - Node.Undefined = new Node(undefined); - class LinkedList { - constructor() { - this._first = Node.Undefined; - this._last = Node.Undefined; - this._size = 0; - } - get size() { - return this._size; - } - isEmpty() { - return this._first === Node.Undefined; - } - clear() { - let node = this._first; - while (node !== Node.Undefined) { - const next = node.next; - node.prev = Node.Undefined; - node.next = Node.Undefined; - node = next; - } - this._first = Node.Undefined; - this._last = Node.Undefined; - this._size = 0; - } - unshift(element) { - return this._insert(element, false); - } - push(element) { - return this._insert(element, true); - } - _insert(element, atTheEnd) { - const newNode = new Node(element); - if (this._first === Node.Undefined) { - this._first = newNode; - this._last = newNode; - } - else if (atTheEnd) { - // push - const oldLast = this._last; - this._last = newNode; - newNode.prev = oldLast; - oldLast.next = newNode; - } - else { - // unshift - const oldFirst = this._first; - this._first = newNode; - newNode.next = oldFirst; - oldFirst.prev = newNode; - } - this._size += 1; - let didRemove = false; - return () => { - if (!didRemove) { - didRemove = true; - this._remove(newNode); - } - }; - } - shift() { - if (this._first === Node.Undefined) { - return undefined; - } - else { - const res = this._first.element; - this._remove(this._first); - return res; - } - } - pop() { - if (this._last === Node.Undefined) { - return undefined; - } - else { - const res = this._last.element; - this._remove(this._last); - return res; - } - } - _remove(node) { - if (node.prev !== Node.Undefined && node.next !== Node.Undefined) { - // middle - const anchor = node.prev; - anchor.next = node.next; - node.next.prev = anchor; - } - else if (node.prev === Node.Undefined && node.next === Node.Undefined) { - // only node - this._first = Node.Undefined; - this._last = Node.Undefined; - } - else if (node.next === Node.Undefined) { - // last - this._last = this._last.prev; - this._last.next = Node.Undefined; - } - else if (node.prev === Node.Undefined) { - // first - this._first = this._first.next; - this._first.prev = Node.Undefined; - } - // done - this._size -= 1; - } - *[Symbol.iterator]() { - let node = this._first; - while (node !== Node.Undefined) { - yield node.element; - node = node.next; - } - } - } - exports.LinkedList = LinkedList; -}); - -/** - * marked - a markdown parser - * Copyright (c) 2011-2021, Christopher Jeffrey. (MIT Licensed) - * https://github.com/markedjs/marked - */ - -/** - * DO NOT EDIT THIS FILE - * The code in this file is generated from files in ./src/ - */ - -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define("vs/base/common/marked/marked", factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.marked = factory()); -}(this, (function () { 'use strict'; - - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } - } - - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; - } - - function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); - } - - function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - - return arr2; - } - - function _createForOfIteratorHelperLoose(o, allowArrayLike) { - var it; - - if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { - if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { - if (it) o = it; - var i = 0; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); - } - - function createCommonjsModule(fn) { - var module = { exports: {} }; - return fn(module, module.exports), module.exports; - } - - var defaults = createCommonjsModule(function (module) { - function getDefaults() { - return { - baseUrl: null, - breaks: false, - gfm: true, - headerIds: true, - headerPrefix: '', - highlight: null, - langPrefix: 'language-', - mangle: true, - pedantic: false, - renderer: null, - sanitize: false, - sanitizer: null, - silent: false, - smartLists: false, - smartypants: false, - tokenizer: null, - walkTokens: null, - xhtml: false - }; - } - - function changeDefaults(newDefaults) { - module.exports.defaults = newDefaults; - } - - module.exports = { - defaults: getDefaults(), - getDefaults: getDefaults, - changeDefaults: changeDefaults - }; - }); - - /** - * Helpers - */ - var escapeTest = /[&<>"']/; - var escapeReplace = /[&<>"']/g; - var escapeTestNoEncode = /[<>"']|&(?!#?\w+;)/; - var escapeReplaceNoEncode = /[<>"']|&(?!#?\w+;)/g; - var escapeReplacements = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''' - }; - - var getEscapeReplacement = function getEscapeReplacement(ch) { - return escapeReplacements[ch]; - }; - - function escape(html, encode) { - if (encode) { - if (escapeTest.test(html)) { - return html.replace(escapeReplace, getEscapeReplacement); - } - } else { - if (escapeTestNoEncode.test(html)) { - return html.replace(escapeReplaceNoEncode, getEscapeReplacement); - } - } - - return html; - } - - var unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig; - - function unescape(html) { - // explicitly match decimal, hex, and named HTML entities - return html.replace(unescapeTest, function (_, n) { - n = n.toLowerCase(); - if (n === 'colon') return ':'; - - if (n.charAt(0) === '#') { - return n.charAt(1) === 'x' ? String.fromCharCode(parseInt(n.substring(2), 16)) : String.fromCharCode(+n.substring(1)); - } - - return ''; - }); - } - - var caret = /(^|[^\[])\^/g; - - function edit(regex, opt) { - regex = regex.source || regex; - opt = opt || ''; - var obj = { - replace: function replace(name, val) { - val = val.source || val; - val = val.replace(caret, '$1'); - regex = regex.replace(name, val); - return obj; - }, - getRegex: function getRegex() { - return new RegExp(regex, opt); - } - }; - return obj; - } - - var nonWordAndColonTest = /[^\w:]/g; - var originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i; - - function cleanUrl(sanitize, base, href) { - if (sanitize) { - var prot; - - try { - prot = decodeURIComponent(unescape(href)).replace(nonWordAndColonTest, '').toLowerCase(); - } catch (e) { - return null; - } - - if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) { - return null; - } - } - - if (base && !originIndependentUrl.test(href)) { - href = resolveUrl(base, href); - } - - try { - href = encodeURI(href).replace(/%25/g, '%'); - } catch (e) { - return null; - } - - return href; - } - - var baseUrls = {}; - var justDomain = /^[^:]+:\/*[^/]*$/; - var protocol = /^([^:]+:)[\s\S]*$/; - var domain = /^([^:]+:\/*[^/]*)[\s\S]*$/; - - function resolveUrl(base, href) { - if (!baseUrls[' ' + base]) { - // we can ignore everything in base after the last slash of its path component, - // but we might need to add _that_ - // https://tools.ietf.org/html/rfc3986#section-3 - if (justDomain.test(base)) { - baseUrls[' ' + base] = base + '/'; - } else { - baseUrls[' ' + base] = rtrim(base, '/', true); - } - } - - base = baseUrls[' ' + base]; - var relativeBase = base.indexOf(':') === -1; - - if (href.substring(0, 2) === '//') { - if (relativeBase) { - return href; - } - - return base.replace(protocol, '$1') + href; - } else if (href.charAt(0) === '/') { - if (relativeBase) { - return href; - } - - return base.replace(domain, '$1') + href; - } else { - return base + href; - } - } - - var noopTest = { - exec: function noopTest() {} - }; - - function merge(obj) { - var i = 1, - target, - key; - - for (; i < arguments.length; i++) { - target = arguments[i]; - - for (key in target) { - if (Object.prototype.hasOwnProperty.call(target, key)) { - obj[key] = target[key]; - } - } - } - - return obj; - } - - function splitCells(tableRow, count) { - // ensure that every cell-delimiting pipe has a space - // before it to distinguish it from an escaped pipe - var row = tableRow.replace(/\|/g, function (match, offset, str) { - var escaped = false, - curr = offset; - - while (--curr >= 0 && str[curr] === '\\') { - escaped = !escaped; - } - - if (escaped) { - // odd number of slashes means | is escaped - // so we leave it alone - return '|'; - } else { - // add space before unescaped | - return ' |'; - } - }), - cells = row.split(/ \|/); - var i = 0; - - if (cells.length > count) { - cells.splice(count); - } else { - while (cells.length < count) { - cells.push(''); - } - } - - for (; i < cells.length; i++) { - // leading or trailing whitespace is ignored per the gfm spec - cells[i] = cells[i].trim().replace(/\\\|/g, '|'); - } - - return cells; - } // Remove trailing 'c's. Equivalent to str.replace(/c*$/, ''). - // /c*$/ is vulnerable to REDOS. - // invert: Remove suffix of non-c chars instead. Default falsey. - - - function rtrim(str, c, invert) { - var l = str.length; - - if (l === 0) { - return ''; - } // Length of suffix matching the invert condition. - - - var suffLen = 0; // Step left until we fail to match the invert condition. - - while (suffLen < l) { - var currChar = str.charAt(l - suffLen - 1); - - if (currChar === c && !invert) { - suffLen++; - } else if (currChar !== c && invert) { - suffLen++; - } else { - break; - } - } - - return str.substr(0, l - suffLen); - } - - function findClosingBracket(str, b) { - if (str.indexOf(b[1]) === -1) { - return -1; - } - - var l = str.length; - var level = 0, - i = 0; - - for (; i < l; i++) { - if (str[i] === '\\') { - i++; - } else if (str[i] === b[0]) { - level++; - } else if (str[i] === b[1]) { - level--; - - if (level < 0) { - return i; - } - } - } - - return -1; - } - - function checkSanitizeDeprecation(opt) { - if (opt && opt.sanitize && !opt.silent) { - console.warn('marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options'); - } - } // copied from https://stackoverflow.com/a/5450113/806777 - - - function repeatString(pattern, count) { - if (count < 1) { - return ''; - } - - var result = ''; - - while (count > 1) { - if (count & 1) { - result += pattern; - } - - count >>= 1; - pattern += pattern; - } - - return result + pattern; - } - - var helpers = { - escape: escape, - unescape: unescape, - edit: edit, - cleanUrl: cleanUrl, - resolveUrl: resolveUrl, - noopTest: noopTest, - merge: merge, - splitCells: splitCells, - rtrim: rtrim, - findClosingBracket: findClosingBracket, - checkSanitizeDeprecation: checkSanitizeDeprecation, - repeatString: repeatString - }; - - var defaults$1 = defaults.defaults; - var rtrim$1 = helpers.rtrim, - splitCells$1 = helpers.splitCells, - _escape = helpers.escape, - findClosingBracket$1 = helpers.findClosingBracket; - - function outputLink(cap, link, raw) { - var href = link.href; - var title = link.title ? _escape(link.title) : null; - var text = cap[1].replace(/\\([\[\]])/g, '$1'); - - if (cap[0].charAt(0) !== '!') { - return { - type: 'link', - raw: raw, - href: href, - title: title, - text: text - }; - } else { - return { - type: 'image', - raw: raw, - href: href, - title: title, - text: _escape(text) - }; - } - } - - function indentCodeCompensation(raw, text) { - var matchIndentToCode = raw.match(/^(\s+)(?:```)/); - - if (matchIndentToCode === null) { - return text; - } - - var indentToCode = matchIndentToCode[1]; - return text.split('\n').map(function (node) { - var matchIndentInNode = node.match(/^\s+/); - - if (matchIndentInNode === null) { - return node; - } - - var indentInNode = matchIndentInNode[0]; - - if (indentInNode.length >= indentToCode.length) { - return node.slice(indentToCode.length); - } - - return node; - }).join('\n'); - } - /** - * Tokenizer - */ - - - var Tokenizer_1 = /*#__PURE__*/function () { - function Tokenizer(options) { - this.options = options || defaults$1; - } - - var _proto = Tokenizer.prototype; - - _proto.space = function space(src) { - var cap = this.rules.block.newline.exec(src); - - if (cap) { - if (cap[0].length > 1) { - return { - type: 'space', - raw: cap[0] - }; - } - - return { - raw: '\n' - }; - } - }; - - _proto.code = function code(src) { - var cap = this.rules.block.code.exec(src); - - if (cap) { - var text = cap[0].replace(/^ {1,4}/gm, ''); - return { - type: 'code', - raw: cap[0], - codeBlockStyle: 'indented', - text: !this.options.pedantic ? rtrim$1(text, '\n') : text - }; - } - }; - - _proto.fences = function fences(src) { - var cap = this.rules.block.fences.exec(src); - - if (cap) { - var raw = cap[0]; - var text = indentCodeCompensation(raw, cap[3] || ''); - return { - type: 'code', - raw: raw, - lang: cap[2] ? cap[2].trim() : cap[2], - text: text - }; - } - }; - - _proto.heading = function heading(src) { - var cap = this.rules.block.heading.exec(src); - - if (cap) { - var text = cap[2].trim(); // remove trailing #s - - if (/#$/.test(text)) { - var trimmed = rtrim$1(text, '#'); - - if (this.options.pedantic) { - text = trimmed.trim(); - } else if (!trimmed || / $/.test(trimmed)) { - // CommonMark requires space before trailing #s - text = trimmed.trim(); - } - } - - return { - type: 'heading', - raw: cap[0], - depth: cap[1].length, - text: text - }; - } - }; - - _proto.nptable = function nptable(src) { - var cap = this.rules.block.nptable.exec(src); - - if (cap) { - var item = { - type: 'table', - header: splitCells$1(cap[1].replace(/^ *| *\| *$/g, '')), - align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), - cells: cap[3] ? cap[3].replace(/\n$/, '').split('\n') : [], - raw: cap[0] - }; - - if (item.header.length === item.align.length) { - var l = item.align.length; - var i; - - for (i = 0; i < l; i++) { - if (/^ *-+: *$/.test(item.align[i])) { - item.align[i] = 'right'; - } else if (/^ *:-+: *$/.test(item.align[i])) { - item.align[i] = 'center'; - } else if (/^ *:-+ *$/.test(item.align[i])) { - item.align[i] = 'left'; - } else { - item.align[i] = null; - } - } - - l = item.cells.length; - - for (i = 0; i < l; i++) { - item.cells[i] = splitCells$1(item.cells[i], item.header.length); - } - - return item; - } - } - }; - - _proto.hr = function hr(src) { - var cap = this.rules.block.hr.exec(src); - - if (cap) { - return { - type: 'hr', - raw: cap[0] - }; - } - }; - - _proto.blockquote = function blockquote(src) { - var cap = this.rules.block.blockquote.exec(src); - - if (cap) { - var text = cap[0].replace(/^ *> ?/gm, ''); - return { - type: 'blockquote', - raw: cap[0], - text: text - }; - } - }; - - _proto.list = function list(src) { - var cap = this.rules.block.list.exec(src); - - if (cap) { - var raw = cap[0]; - var bull = cap[2]; - var isordered = bull.length > 1; - var list = { - type: 'list', - raw: raw, - ordered: isordered, - start: isordered ? +bull.slice(0, -1) : '', - loose: false, - items: [] - }; // Get each top-level item. - - var itemMatch = cap[0].match(this.rules.block.item); - var next = false, - item, - space, - bcurr, - bnext, - addBack, - loose, - istask, - ischecked; - var l = itemMatch.length; - bcurr = this.rules.block.listItemStart.exec(itemMatch[0]); - - for (var i = 0; i < l; i++) { - item = itemMatch[i]; - raw = item; // Determine whether the next list item belongs here. - // Backpedal if it does not belong in this list. - - if (i !== l - 1) { - bnext = this.rules.block.listItemStart.exec(itemMatch[i + 1]); - - if (!this.options.pedantic ? bnext[1].length > bcurr[0].length || bnext[1].length > 3 : bnext[1].length > bcurr[1].length) { - // nested list - itemMatch.splice(i, 2, itemMatch[i] + '\n' + itemMatch[i + 1]); - i--; - l--; - continue; - } else { - if ( // different bullet style - !this.options.pedantic || this.options.smartLists ? bnext[2][bnext[2].length - 1] !== bull[bull.length - 1] : isordered === (bnext[2].length === 1)) { - addBack = itemMatch.slice(i + 1).join('\n'); - list.raw = list.raw.substring(0, list.raw.length - addBack.length); - i = l - 1; - } - } - - bcurr = bnext; - } // Remove the list item's bullet - // so it is seen as the next token. - - - space = item.length; - item = item.replace(/^ *([*+-]|\d+[.)]) ?/, ''); // Outdent whatever the - // list item contains. Hacky. - - if (~item.indexOf('\n ')) { - space -= item.length; - item = !this.options.pedantic ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '') : item.replace(/^ {1,4}/gm, ''); - } // Determine whether item is loose or not. - // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/ - // for discount behavior. - - - loose = next || /\n\n(?!\s*$)/.test(item); - - if (i !== l - 1) { - next = item.charAt(item.length - 1) === '\n'; - if (!loose) loose = next; - } - - if (loose) { - list.loose = true; - } // Check for task list items - - - if (this.options.gfm) { - istask = /^\[[ xX]\] /.test(item); - ischecked = undefined; - - if (istask) { - ischecked = item[1] !== ' '; - item = item.replace(/^\[[ xX]\] +/, ''); - } - } - - list.items.push({ - type: 'list_item', - raw: raw, - task: istask, - checked: ischecked, - loose: loose, - text: item - }); - } - - return list; - } - }; - - _proto.html = function html(src) { - var cap = this.rules.block.html.exec(src); - - if (cap) { - return { - type: this.options.sanitize ? 'paragraph' : 'html', - raw: cap[0], - pre: !this.options.sanitizer && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'), - text: this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : _escape(cap[0]) : cap[0] - }; - } - }; - - _proto.def = function def(src) { - var cap = this.rules.block.def.exec(src); - - if (cap) { - if (cap[3]) cap[3] = cap[3].substring(1, cap[3].length - 1); - var tag = cap[1].toLowerCase().replace(/\s+/g, ' '); - return { - tag: tag, - raw: cap[0], - href: cap[2], - title: cap[3] - }; - } - }; - - _proto.table = function table(src) { - var cap = this.rules.block.table.exec(src); - - if (cap) { - var item = { - type: 'table', - header: splitCells$1(cap[1].replace(/^ *| *\| *$/g, '')), - align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), - cells: cap[3] ? cap[3].replace(/\n$/, '').split('\n') : [] - }; - - if (item.header.length === item.align.length) { - item.raw = cap[0]; - var l = item.align.length; - var i; - - for (i = 0; i < l; i++) { - if (/^ *-+: *$/.test(item.align[i])) { - item.align[i] = 'right'; - } else if (/^ *:-+: *$/.test(item.align[i])) { - item.align[i] = 'center'; - } else if (/^ *:-+ *$/.test(item.align[i])) { - item.align[i] = 'left'; - } else { - item.align[i] = null; - } - } - - l = item.cells.length; - - for (i = 0; i < l; i++) { - item.cells[i] = splitCells$1(item.cells[i].replace(/^ *\| *| *\| *$/g, ''), item.header.length); - } - - return item; - } - } - }; - - _proto.lheading = function lheading(src) { - var cap = this.rules.block.lheading.exec(src); - - if (cap) { - return { - type: 'heading', - raw: cap[0], - depth: cap[2].charAt(0) === '=' ? 1 : 2, - text: cap[1] - }; - } - }; - - _proto.paragraph = function paragraph(src) { - var cap = this.rules.block.paragraph.exec(src); - - if (cap) { - return { - type: 'paragraph', - raw: cap[0], - text: cap[1].charAt(cap[1].length - 1) === '\n' ? cap[1].slice(0, -1) : cap[1] - }; - } - }; - - _proto.text = function text(src) { - var cap = this.rules.block.text.exec(src); - - if (cap) { - return { - type: 'text', - raw: cap[0], - text: cap[0] - }; - } - }; - - _proto.escape = function escape(src) { - var cap = this.rules.inline.escape.exec(src); - - if (cap) { - return { - type: 'escape', - raw: cap[0], - text: _escape(cap[1]) - }; - } - }; - - _proto.tag = function tag(src, inLink, inRawBlock) { - var cap = this.rules.inline.tag.exec(src); - - if (cap) { - if (!inLink && /^/i.test(cap[0])) { - inLink = false; - } - - if (!inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) { - inRawBlock = true; - } else if (inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) { - inRawBlock = false; - } - - return { - type: this.options.sanitize ? 'text' : 'html', - raw: cap[0], - inLink: inLink, - inRawBlock: inRawBlock, - text: this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : _escape(cap[0]) : cap[0] - }; - } - }; - - _proto.link = function link(src) { - var cap = this.rules.inline.link.exec(src); - - if (cap) { - var trimmedUrl = cap[2].trim(); - - if (!this.options.pedantic && /^$/.test(trimmedUrl)) { - return; - } // ending angle bracket cannot be escaped - - - var rtrimSlash = rtrim$1(trimmedUrl.slice(0, -1), '\\'); - - if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) { - return; - } - } else { - // find closing parenthesis - var lastParenIndex = findClosingBracket$1(cap[2], '()'); - - if (lastParenIndex > -1) { - var start = cap[0].indexOf('!') === 0 ? 5 : 4; - var linkLen = start + cap[1].length + lastParenIndex; - cap[2] = cap[2].substring(0, lastParenIndex); - cap[0] = cap[0].substring(0, linkLen).trim(); - cap[3] = ''; - } - } - - var href = cap[2]; - var title = ''; - - if (this.options.pedantic) { - // split pedantic href and title - var link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href); - - if (link) { - href = link[1]; - title = link[3]; - } - } else { - title = cap[3] ? cap[3].slice(1, -1) : ''; - } - - href = href.trim(); - - if (/^$/.test(trimmedUrl)) { - // pedantic allows starting angle bracket without ending angle bracket - href = href.slice(1); - } else { - href = href.slice(1, -1); - } - } - - return outputLink(cap, { - href: href ? href.replace(this.rules.inline._escapes, '$1') : href, - title: title ? title.replace(this.rules.inline._escapes, '$1') : title - }, cap[0]); - } - }; - - _proto.reflink = function reflink(src, links) { - var cap; - - if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) { - var link = (cap[2] || cap[1]).replace(/\s+/g, ' '); - link = links[link.toLowerCase()]; - - if (!link || !link.href) { - var text = cap[0].charAt(0); - return { - type: 'text', - raw: text, - text: text - }; - } - - return outputLink(cap, link, cap[0]); - } - }; - - _proto.emStrong = function emStrong(src, maskedSrc, prevChar) { - if (prevChar === void 0) { - prevChar = ''; - } - - var match = this.rules.inline.emStrong.lDelim.exec(src); - if (!match) return; - if (match[3] && prevChar.match(/(?:[0-9A-Za-z\xAA\xB2\xB3\xB5\xB9\xBA\xBC-\xBE\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u0660-\u0669\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08C7\u0904-\u0939\u093D\u0950\u0958-\u0961\u0966-\u096F\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09F9\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AE6-\u0AEF\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B6F\u0B71-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0BE6-\u0BF2\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C66-\u0C6F\u0C78-\u0C7E\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D58-\u0D61\u0D66-\u0D78\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DE6-\u0DEF\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F20-\u0F33\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F-\u1049\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u1090-\u1099\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1369-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A20-\u1A54\u1A80-\u1A89\u1A90-\u1A99\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B50-\u1B59\u1B83-\u1BA0\u1BAE-\u1BE5\u1C00-\u1C23\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2070\u2071\u2074-\u2079\u207F-\u2089\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2150-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2CFD\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3192-\u3195\u31A0-\u31BF\u31F0-\u31FF\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\u3400-\u4DBF\u4E00-\u9FFC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7BF\uA7C2-\uA7CA\uA7F5-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA830-\uA835\uA840-\uA873\uA882-\uA8B3\uA8D0-\uA8D9\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA900-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF-\uA9D9\uA9E0-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD07-\uDD33\uDD40-\uDD78\uDD8A\uDD8B\uDE80-\uDE9C\uDEA0-\uDED0\uDEE1-\uDEFB\uDF00-\uDF23\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC58-\uDC76\uDC79-\uDC9E\uDCA7-\uDCAF\uDCE0-\uDCF2\uDCF4\uDCF5\uDCFB-\uDD1B\uDD20-\uDD39\uDD80-\uDDB7\uDDBC-\uDDCF\uDDD2-\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE40-\uDE48\uDE60-\uDE7E\uDE80-\uDE9F\uDEC0-\uDEC7\uDEC9-\uDEE4\uDEEB-\uDEEF\uDF00-\uDF35\uDF40-\uDF55\uDF58-\uDF72\uDF78-\uDF91\uDFA9-\uDFAF]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDCFA-\uDD23\uDD30-\uDD39\uDE60-\uDE7E\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF27\uDF30-\uDF45\uDF51-\uDF54\uDFB0-\uDFCB\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC52-\uDC6F\uDC83-\uDCAF\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD03-\uDD26\uDD36-\uDD3F\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDD0-\uDDDA\uDDDC\uDDE1-\uDDF4\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDEF0-\uDEF9\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC50-\uDC59\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE50-\uDE59\uDE80-\uDEAA\uDEB8\uDEC0-\uDEC9\uDF00-\uDF1A\uDF30-\uDF3B]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCF2\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDD50-\uDD59\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC50-\uDC6C\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD50-\uDD59\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDDA0-\uDDA9\uDEE0-\uDEF2\uDFB0\uDFC0-\uDFD4]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF50-\uDF59\uDF5B-\uDF61\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE96\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82C[\uDC00-\uDD1E\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD834[\uDEE0-\uDEF3\uDF60-\uDF78]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD838[\uDD00-\uDD2C\uDD37-\uDD3D\uDD40-\uDD49\uDD4E\uDEC0-\uDEEB\uDEF0-\uDEF9]|\uD83A[\uDC00-\uDCC4\uDCC7-\uDCCF\uDD00-\uDD43\uDD4B\uDD50-\uDD59]|\uD83B[\uDC71-\uDCAB\uDCAD-\uDCAF\uDCB1-\uDCB4\uDD01-\uDD2D\uDD2F-\uDD3D\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD83C[\uDD00-\uDD0C]|\uD83E[\uDFF0-\uDFF9]|\uD869[\uDC00-\uDEDD\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A])/)) return; // _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well - - var nextChar = match[1] || match[2] || ''; - - if (!nextChar || nextChar && (prevChar === '' || this.rules.inline.punctuation.exec(prevChar))) { - var lLength = match[0].length - 1; - var rDelim, - rLength, - delimTotal = lLength, - midDelimTotal = 0; - var endReg = match[0][0] === '*' ? this.rules.inline.emStrong.rDelimAst : this.rules.inline.emStrong.rDelimUnd; - endReg.lastIndex = 0; - maskedSrc = maskedSrc.slice(-1 * src.length + lLength); // Bump maskedSrc to same section of string as src (move to lexer?) - - while ((match = endReg.exec(maskedSrc)) != null) { - rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6]; - if (!rDelim) continue; // matched the first alternative in rules.js (skip the * in __abc*abc__) - - rLength = rDelim.length; - - if (match[3] || match[4]) { - // found another Left Delim - delimTotal += rLength; - continue; - } else if (match[5] || match[6]) { - // either Left or Right Delim - if (lLength % 3 && !((lLength + rLength) % 3)) { - midDelimTotal += rLength; - continue; // CommonMark Emphasis Rules 9-10 - } - } - - delimTotal -= rLength; - if (delimTotal > 0) continue; // Haven't found enough closing delimiters - // If this is the last rDelimiter, remove extra characters. *a*** -> *a* - - if (delimTotal + midDelimTotal - rLength <= 0 && !maskedSrc.slice(endReg.lastIndex).match(endReg)) { - rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal); - } - - if (Math.min(lLength, rLength) % 2) { - return { - type: 'em', - raw: src.slice(0, lLength + match.index + rLength + 1), - text: src.slice(1, lLength + match.index + rLength) - }; - } - - if (Math.min(lLength, rLength) % 2 === 0) { - return { - type: 'strong', - raw: src.slice(0, lLength + match.index + rLength + 1), - text: src.slice(2, lLength + match.index + rLength - 1) - }; - } - } - } - }; - - _proto.codespan = function codespan(src) { - var cap = this.rules.inline.code.exec(src); - - if (cap) { - var text = cap[2].replace(/\n/g, ' '); - var hasNonSpaceChars = /[^ ]/.test(text); - var hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text); - - if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) { - text = text.substring(1, text.length - 1); - } - - text = _escape(text, true); - return { - type: 'codespan', - raw: cap[0], - text: text - }; - } - }; - - _proto.br = function br(src) { - var cap = this.rules.inline.br.exec(src); - - if (cap) { - return { - type: 'br', - raw: cap[0] - }; - } - }; - - _proto.del = function del(src) { - var cap = this.rules.inline.del.exec(src); - - if (cap) { - return { - type: 'del', - raw: cap[0], - text: cap[2] - }; - } - }; - - _proto.autolink = function autolink(src, mangle) { - var cap = this.rules.inline.autolink.exec(src); - - if (cap) { - var text, href; - - if (cap[2] === '@') { - text = _escape(this.options.mangle ? mangle(cap[1]) : cap[1]); - href = 'mailto:' + text; - } else { - text = _escape(cap[1]); - href = text; - } - - return { - type: 'link', - raw: cap[0], - text: text, - href: href, - tokens: [{ - type: 'text', - raw: text, - text: text - }] - }; - } - }; - - _proto.url = function url(src, mangle) { - var cap; - - if (cap = this.rules.inline.url.exec(src)) { - var text, href; - - if (cap[2] === '@') { - text = _escape(this.options.mangle ? mangle(cap[0]) : cap[0]); - href = 'mailto:' + text; - } else { - // do extended autolink path validation - var prevCapZero; - - do { - prevCapZero = cap[0]; - cap[0] = this.rules.inline._backpedal.exec(cap[0])[0]; - } while (prevCapZero !== cap[0]); - - text = _escape(cap[0]); - - if (cap[1] === 'www.') { - href = 'http://' + text; - } else { - href = text; - } - } - - return { - type: 'link', - raw: cap[0], - text: text, - href: href, - tokens: [{ - type: 'text', - raw: text, - text: text - }] - }; - } - }; - - _proto.inlineText = function inlineText(src, inRawBlock, smartypants) { - var cap = this.rules.inline.text.exec(src); - - if (cap) { - var text; - - if (inRawBlock) { - text = this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : _escape(cap[0]) : cap[0]; - } else { - text = _escape(this.options.smartypants ? smartypants(cap[0]) : cap[0]); - } - - return { - type: 'text', - raw: cap[0], - text: text - }; - } - }; - - return Tokenizer; - }(); - - var noopTest$1 = helpers.noopTest, - edit$1 = helpers.edit, - merge$1 = helpers.merge; - /** - * Block-Level Grammar - */ - - var block = { - newline: /^(?: *(?:\n|$))+/, - code: /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/, - fences: /^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/, - hr: /^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/, - heading: /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/, - blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/, - list: /^( {0,3})(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?! {0,3}bull )\n*|\s*$)/, - html: '^ {0,3}(?:' // optional indentation - + '<(script|pre|style)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)' // (1) - + '|comment[^\\n]*(\\n+|$)' // (2) - + '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3) - + '|\\n*|$)' // (4) - + '|\\n*|$)' // (5) - + '|)[\\s\\S]*?(?:\\n{2,}|$)' // (6) - + '|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)' // (7) open tag - + '|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)' // (7) closing tag - + ')', - def: /^ {0,3}\[(label)\]: *\n? *]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/, - nptable: noopTest$1, - table: noopTest$1, - lheading: /^([^\n]+)\n {0,3}(=+|-+) *(?:\n+|$)/, - // regex template, placeholders will be replaced according to different paragraph - // interruption rules of commonmark and the original markdown spec: - _paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html| +\n)[^\n]+)*)/, - text: /^[^\n]+/ - }; - block._label = /(?!\s*\])(?:\\[\[\]]|[^\[\]])+/; - block._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/; - block.def = edit$1(block.def).replace('label', block._label).replace('title', block._title).getRegex(); - block.bullet = /(?:[*+-]|\d{1,9}[.)])/; - block.item = /^( *)(bull) ?[^\n]*(?:\n(?! *bull ?)[^\n]*)*/; - block.item = edit$1(block.item, 'gm').replace(/bull/g, block.bullet).getRegex(); - block.listItemStart = edit$1(/^( *)(bull)/).replace('bull', block.bullet).getRegex(); - block.list = edit$1(block.list).replace(/bull/g, block.bullet).replace('hr', '\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))').replace('def', '\\n+(?=' + block.def.source + ')').getRegex(); - block._tag = 'address|article|aside|base|basefont|blockquote|body|caption' + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option' + '|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr' + '|track|ul'; - block._comment = /|$)/; - block.html = edit$1(block.html, 'i').replace('comment', block._comment).replace('tag', block._tag).replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(); - block.paragraph = edit$1(block._paragraph).replace('hr', block.hr).replace('heading', ' {0,3}#{1,6} ').replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs - .replace('blockquote', ' {0,3}>').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt - .replace('html', ')|<(?:script|pre|style|!--)').replace('tag', block._tag) // pars can be interrupted by type (6) html blocks - .getRegex(); - block.blockquote = edit$1(block.blockquote).replace('paragraph', block.paragraph).getRegex(); - /** - * Normal Block Grammar - */ - - block.normal = merge$1({}, block); - /** - * GFM Block Grammar - */ - - block.gfm = merge$1({}, block.normal, { - nptable: '^ *([^|\\n ].*\\|.*)\\n' // Header - + ' {0,3}([-:]+ *\\|[-| :]*)' // Align - + '(?:\\n((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)', - // Cells - table: '^ *\\|(.+)\\n' // Header - + ' {0,3}\\|?( *[-:]+[-| :]*)' // Align - + '(?:\\n *((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)' // Cells - - }); - block.gfm.nptable = edit$1(block.gfm.nptable).replace('hr', block.hr).replace('heading', ' {0,3}#{1,6} ').replace('blockquote', ' {0,3}>').replace('code', ' {4}[^\\n]').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt - .replace('html', ')|<(?:script|pre|style|!--)').replace('tag', block._tag) // tables can be interrupted by type (6) html blocks - .getRegex(); - block.gfm.table = edit$1(block.gfm.table).replace('hr', block.hr).replace('heading', ' {0,3}#{1,6} ').replace('blockquote', ' {0,3}>').replace('code', ' {4}[^\\n]').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt - .replace('html', ')|<(?:script|pre|style|!--)').replace('tag', block._tag) // tables can be interrupted by type (6) html blocks - .getRegex(); - /** - * Pedantic grammar (original John Gruber's loose markdown specification) - */ - - block.pedantic = merge$1({}, block.normal, { - html: edit$1('^ *(?:comment *(?:\\n|\\s*$)' + '|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)' // closed tag - + '|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))').replace('comment', block._comment).replace(/tag/g, '(?!(?:' + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b').getRegex(), - def: /^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, - heading: /^(#{1,6})(.*)(?:\n+|$)/, - fences: noopTest$1, - // fences not supported - paragraph: edit$1(block.normal._paragraph).replace('hr', block.hr).replace('heading', ' *#{1,6} *[^\n]').replace('lheading', block.lheading).replace('blockquote', ' {0,3}>').replace('|fences', '').replace('|list', '').replace('|html', '').getRegex() - }); - /** - * Inline-Level Grammar - */ - - var inline = { - escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/, - autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/, - url: noopTest$1, - tag: '^comment' + '|^' // self-closing tag - + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag - + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. - + '|^' // declaration, e.g. - + '|^', - // CDATA section - link: /^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/, - reflink: /^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/, - nolink: /^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/, - reflinkSearch: 'reflink|nolink(?!\\()', - emStrong: { - lDelim: /^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/, - // (1) and (2) can only be a Right Delimiter. (3) and (4) can only be Left. (5) and (6) can be either Left or Right. - // () Skip other delimiter (1) #*** (2) a***#, a*** (3) #***a, ***a (4) ***# (5) #***# (6) a***a - rDelimAst: /\_\_[^_]*?\*[^_]*?\_\_|[punct_](\*+)(?=[\s]|$)|[^punct*_\s](\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|[^punct*_\s](\*+)(?=[^punct*_\s])/, - rDelimUnd: /\*\*[^*]*?\_[^*]*?\*\*|[punct*](\_+)(?=[\s]|$)|[^punct*_\s](\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/ // ^- Not allowed for _ - - }, - code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/, - br: /^( {2,}|\\)\n(?!\s*$)/, - del: noopTest$1, - text: /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\?@\\[\\]`^{|}~'; - inline.punctuation = edit$1(inline.punctuation).replace(/punctuation/g, inline._punctuation).getRegex(); // sequences em should skip over [title](link), `code`, - - inline.blockSkip = /\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g; - inline.escapedEmSt = /\\\*|\\_/g; - inline._comment = edit$1(block._comment).replace('(?:-->|$)', '-->').getRegex(); - inline.emStrong.lDelim = edit$1(inline.emStrong.lDelim).replace(/punct/g, inline._punctuation).getRegex(); - inline.emStrong.rDelimAst = edit$1(inline.emStrong.rDelimAst, 'g').replace(/punct/g, inline._punctuation).getRegex(); - inline.emStrong.rDelimUnd = edit$1(inline.emStrong.rDelimUnd, 'g').replace(/punct/g, inline._punctuation).getRegex(); - inline._escapes = /\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g; - inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/; - inline._email = /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/; - inline.autolink = edit$1(inline.autolink).replace('scheme', inline._scheme).replace('email', inline._email).getRegex(); - inline._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/; - inline.tag = edit$1(inline.tag).replace('comment', inline._comment).replace('attribute', inline._attribute).getRegex(); - inline._label = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/; - inline._href = /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/; - inline._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/; - inline.link = edit$1(inline.link).replace('label', inline._label).replace('href', inline._href).replace('title', inline._title).getRegex(); - inline.reflink = edit$1(inline.reflink).replace('label', inline._label).getRegex(); - inline.reflinkSearch = edit$1(inline.reflinkSearch, 'g').replace('reflink', inline.reflink).replace('nolink', inline.nolink).getRegex(); - /** - * Normal Inline Grammar - */ - - inline.normal = merge$1({}, inline); - /** - * Pedantic Inline Grammar - */ - - inline.pedantic = merge$1({}, inline.normal, { - strong: { - start: /^__|\*\*/, - middle: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, - endAst: /\*\*(?!\*)/g, - endUnd: /__(?!_)/g - }, - em: { - start: /^_|\*/, - middle: /^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/, - endAst: /\*(?!\*)/g, - endUnd: /_(?!_)/g - }, - link: edit$1(/^!?\[(label)\]\((.*?)\)/).replace('label', inline._label).getRegex(), - reflink: edit$1(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace('label', inline._label).getRegex() - }); - /** - * GFM Inline Grammar - */ - - inline.gfm = merge$1({}, inline.normal, { - escape: edit$1(inline.escape).replace('])', '~|])').getRegex(), - _extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/, - url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, - _backpedal: /(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/, - del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/, - text: /^([`~]+|[^`~])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\ 0.5) { - ch = 'x' + ch.toString(16); - } - - out += '&#' + ch + ';'; - } - - return out; - } - /** - * Block Lexer - */ - - - var Lexer_1 = /*#__PURE__*/function () { - function Lexer(options) { - this.tokens = []; - this.tokens.links = Object.create(null); - this.options = options || defaults$2; - this.options.tokenizer = this.options.tokenizer || new Tokenizer_1(); - this.tokenizer = this.options.tokenizer; - this.tokenizer.options = this.options; - var rules = { - block: block$1.normal, - inline: inline$1.normal - }; - - if (this.options.pedantic) { - rules.block = block$1.pedantic; - rules.inline = inline$1.pedantic; - } else if (this.options.gfm) { - rules.block = block$1.gfm; - - if (this.options.breaks) { - rules.inline = inline$1.breaks; - } else { - rules.inline = inline$1.gfm; - } - } - - this.tokenizer.rules = rules; - } - /** - * Expose Rules - */ - - - /** - * Static Lex Method - */ - Lexer.lex = function lex(src, options) { - var lexer = new Lexer(options); - return lexer.lex(src); - } - /** - * Static Lex Inline Method - */ - ; - - Lexer.lexInline = function lexInline(src, options) { - var lexer = new Lexer(options); - return lexer.inlineTokens(src); - } - /** - * Preprocessing - */ - ; - - var _proto = Lexer.prototype; - - _proto.lex = function lex(src) { - src = src.replace(/\r\n|\r/g, '\n').replace(/\t/g, ' '); - this.blockTokens(src, this.tokens, true); - this.inline(this.tokens); - return this.tokens; - } - /** - * Lexing - */ - ; - - _proto.blockTokens = function blockTokens(src, tokens, top) { - if (tokens === void 0) { - tokens = []; - } - - if (top === void 0) { - top = true; - } - - if (this.options.pedantic) { - src = src.replace(/^ +$/gm, ''); - } - - var token, i, l, lastToken; - - while (src) { - // newline - if (token = this.tokenizer.space(src)) { - src = src.substring(token.raw.length); - - if (token.type) { - tokens.push(token); - } - - continue; - } // code - - - if (token = this.tokenizer.code(src)) { - src = src.substring(token.raw.length); - lastToken = tokens[tokens.length - 1]; // An indented code block cannot interrupt a paragraph. - - if (lastToken && lastToken.type === 'paragraph') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.text; - } else { - tokens.push(token); - } - - continue; - } // fences - - - if (token = this.tokenizer.fences(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } // heading - - - if (token = this.tokenizer.heading(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } // table no leading pipe (gfm) - - - if (token = this.tokenizer.nptable(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } // hr - - - if (token = this.tokenizer.hr(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } // blockquote - - - if (token = this.tokenizer.blockquote(src)) { - src = src.substring(token.raw.length); - token.tokens = this.blockTokens(token.text, [], top); - tokens.push(token); - continue; - } // list - - - if (token = this.tokenizer.list(src)) { - src = src.substring(token.raw.length); - l = token.items.length; - - for (i = 0; i < l; i++) { - token.items[i].tokens = this.blockTokens(token.items[i].text, [], false); - } - - tokens.push(token); - continue; - } // html - - - if (token = this.tokenizer.html(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } // def - - - if (top && (token = this.tokenizer.def(src))) { - src = src.substring(token.raw.length); - - if (!this.tokens.links[token.tag]) { - this.tokens.links[token.tag] = { - href: token.href, - title: token.title - }; - } - - continue; - } // table (gfm) - - - if (token = this.tokenizer.table(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } // lheading - - - if (token = this.tokenizer.lheading(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } // top-level paragraph - - - if (top && (token = this.tokenizer.paragraph(src))) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } // text - - - if (token = this.tokenizer.text(src)) { - src = src.substring(token.raw.length); - lastToken = tokens[tokens.length - 1]; - - if (lastToken && lastToken.type === 'text') { - lastToken.raw += '\n' + token.raw; - lastToken.text += '\n' + token.text; - } else { - tokens.push(token); - } - - continue; - } - - if (src) { - var errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); - - if (this.options.silent) { - console.error(errMsg); - break; - } else { - throw new Error(errMsg); - } - } - } - - return tokens; - }; - - _proto.inline = function inline(tokens) { - var i, j, k, l2, row, token; - var l = tokens.length; - - for (i = 0; i < l; i++) { - token = tokens[i]; - - switch (token.type) { - case 'paragraph': - case 'text': - case 'heading': - { - token.tokens = []; - this.inlineTokens(token.text, token.tokens); - break; - } - - case 'table': - { - token.tokens = { - header: [], - cells: [] - }; // header - - l2 = token.header.length; - - for (j = 0; j < l2; j++) { - token.tokens.header[j] = []; - this.inlineTokens(token.header[j], token.tokens.header[j]); - } // cells - - - l2 = token.cells.length; - - for (j = 0; j < l2; j++) { - row = token.cells[j]; - token.tokens.cells[j] = []; - - for (k = 0; k < row.length; k++) { - token.tokens.cells[j][k] = []; - this.inlineTokens(row[k], token.tokens.cells[j][k]); - } - } - - break; - } - - case 'blockquote': - { - this.inline(token.tokens); - break; - } - - case 'list': - { - l2 = token.items.length; - - for (j = 0; j < l2; j++) { - this.inline(token.items[j].tokens); - } - - break; - } - } - } - - return tokens; - } - /** - * Lexing/Compiling - */ - ; - - _proto.inlineTokens = function inlineTokens(src, tokens, inLink, inRawBlock) { - if (tokens === void 0) { - tokens = []; - } - - if (inLink === void 0) { - inLink = false; - } - - if (inRawBlock === void 0) { - inRawBlock = false; - } - - var token, lastToken; // String with links masked to avoid interference with em and strong - - var maskedSrc = src; - var match; - var keepPrevChar, prevChar; // Mask out reflinks - - if (this.tokens.links) { - var links = Object.keys(this.tokens.links); - - if (links.length > 0) { - while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) { - if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) { - maskedSrc = maskedSrc.slice(0, match.index) + '[' + repeatString$1('a', match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex); - } - } - } - } // Mask out other blocks - - - while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) { - maskedSrc = maskedSrc.slice(0, match.index) + '[' + repeatString$1('a', match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex); - } // Mask out escaped em & strong delimiters - - - while ((match = this.tokenizer.rules.inline.escapedEmSt.exec(maskedSrc)) != null) { - maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex); - } - - while (src) { - if (!keepPrevChar) { - prevChar = ''; - } - - keepPrevChar = false; // escape - - if (token = this.tokenizer.escape(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } // tag - - - if (token = this.tokenizer.tag(src, inLink, inRawBlock)) { - src = src.substring(token.raw.length); - inLink = token.inLink; - inRawBlock = token.inRawBlock; - var _lastToken = tokens[tokens.length - 1]; - - if (_lastToken && token.type === 'text' && _lastToken.type === 'text') { - _lastToken.raw += token.raw; - _lastToken.text += token.text; - } else { - tokens.push(token); - } - - continue; - } // link - - - if (token = this.tokenizer.link(src)) { - src = src.substring(token.raw.length); - - if (token.type === 'link') { - token.tokens = this.inlineTokens(token.text, [], true, inRawBlock); - } - - tokens.push(token); - continue; - } // reflink, nolink - - - if (token = this.tokenizer.reflink(src, this.tokens.links)) { - src = src.substring(token.raw.length); - var _lastToken2 = tokens[tokens.length - 1]; - - if (token.type === 'link') { - token.tokens = this.inlineTokens(token.text, [], true, inRawBlock); - tokens.push(token); - } else if (_lastToken2 && token.type === 'text' && _lastToken2.type === 'text') { - _lastToken2.raw += token.raw; - _lastToken2.text += token.text; - } else { - tokens.push(token); - } - - continue; - } // em & strong - - - if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) { - src = src.substring(token.raw.length); - token.tokens = this.inlineTokens(token.text, [], inLink, inRawBlock); - tokens.push(token); - continue; - } // code - - - if (token = this.tokenizer.codespan(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } // br - - - if (token = this.tokenizer.br(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } // del (gfm) - - - if (token = this.tokenizer.del(src)) { - src = src.substring(token.raw.length); - token.tokens = this.inlineTokens(token.text, [], inLink, inRawBlock); - tokens.push(token); - continue; - } // autolink - - - if (token = this.tokenizer.autolink(src, mangle)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } // url (gfm) - - - if (!inLink && (token = this.tokenizer.url(src, mangle))) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } // text - - - if (token = this.tokenizer.inlineText(src, inRawBlock, smartypants)) { - src = src.substring(token.raw.length); - - if (token.raw.slice(-1) !== '_') { - // Track prevChar before string of ____ started - prevChar = token.raw.slice(-1); - } - - keepPrevChar = true; - lastToken = tokens[tokens.length - 1]; - - if (lastToken && lastToken.type === 'text') { - lastToken.raw += token.raw; - lastToken.text += token.text; - } else { - tokens.push(token); - } - - continue; - } - - if (src) { - var errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); - - if (this.options.silent) { - console.error(errMsg); - break; - } else { - throw new Error(errMsg); - } - } - } - - return tokens; - }; - - _createClass(Lexer, null, [{ - key: "rules", - get: function get() { - return { - block: block$1, - inline: inline$1 - }; - } - }]); - - return Lexer; - }(); - - var defaults$3 = defaults.defaults; - var cleanUrl$1 = helpers.cleanUrl, - escape$1 = helpers.escape; - /** - * Renderer - */ - - var Renderer_1 = /*#__PURE__*/function () { - function Renderer(options) { - this.options = options || defaults$3; - } - - var _proto = Renderer.prototype; - - _proto.code = function code(_code, infostring, escaped) { - var lang = (infostring || '').match(/\S*/)[0]; - - if (this.options.highlight) { - var out = this.options.highlight(_code, lang); - - if (out != null && out !== _code) { - escaped = true; - _code = out; - } - } - - _code = _code.replace(/\n$/, '') + '\n'; - - if (!lang) { - return '
' + (escaped ? _code : escape$1(_code, true)) + '
\n'; - } - - return '
' + (escaped ? _code : escape$1(_code, true)) + '
\n'; - }; - - _proto.blockquote = function blockquote(quote) { - return '
\n' + quote + '
\n'; - }; - - _proto.html = function html(_html) { - return _html; - }; - - _proto.heading = function heading(text, level, raw, slugger) { - if (this.options.headerIds) { - return '' + text + '\n'; - } // ignore IDs - - - return '' + text + '\n'; - }; - - _proto.hr = function hr() { - return this.options.xhtml ? '
\n' : '
\n'; - }; - - _proto.list = function list(body, ordered, start) { - var type = ordered ? 'ol' : 'ul', - startatt = ordered && start !== 1 ? ' start="' + start + '"' : ''; - return '<' + type + startatt + '>\n' + body + '\n'; - }; - - _proto.listitem = function listitem(text) { - return '
  • ' + text + '
  • \n'; - }; - - _proto.checkbox = function checkbox(checked) { - return ' '; - }; - - _proto.paragraph = function paragraph(text) { - return '

    ' + text + '

    \n'; - }; - - _proto.table = function table(header, body) { - if (body) body = '' + body + ''; - return '\n' + '\n' + header + '\n' + body + '
    \n'; - }; - - _proto.tablerow = function tablerow(content) { - return '\n' + content + '\n'; - }; - - _proto.tablecell = function tablecell(content, flags) { - var type = flags.header ? 'th' : 'td'; - var tag = flags.align ? '<' + type + ' align="' + flags.align + '">' : '<' + type + '>'; - return tag + content + '\n'; - } // span level renderer - ; - - _proto.strong = function strong(text) { - return '' + text + ''; - }; - - _proto.em = function em(text) { - return '' + text + ''; - }; - - _proto.codespan = function codespan(text) { - return '' + text + ''; - }; - - _proto.br = function br() { - return this.options.xhtml ? '
    ' : '
    '; - }; - - _proto.del = function del(text) { - return '' + text + ''; - }; - - _proto.link = function link(href, title, text) { - href = cleanUrl$1(this.options.sanitize, this.options.baseUrl, href); - - if (href === null) { - return text; - } - - var out = '
    '; - return out; - }; - - _proto.image = function image(href, title, text) { - href = cleanUrl$1(this.options.sanitize, this.options.baseUrl, href); - - if (href === null) { - return text; - } - - var out = '' + text + '' : '>'; - return out; - }; - - _proto.text = function text(_text) { - return _text; - }; - - return Renderer; - }(); - - /** - * TextRenderer - * returns only the textual part of the token - */ - var TextRenderer_1 = /*#__PURE__*/function () { - function TextRenderer() {} - - var _proto = TextRenderer.prototype; - - // no need for block level renderers - _proto.strong = function strong(text) { - return text; - }; - - _proto.em = function em(text) { - return text; - }; - - _proto.codespan = function codespan(text) { - return text; - }; - - _proto.del = function del(text) { - return text; - }; - - _proto.html = function html(text) { - return text; - }; - - _proto.text = function text(_text) { - return _text; - }; - - _proto.link = function link(href, title, text) { - return '' + text; - }; - - _proto.image = function image(href, title, text) { - return '' + text; - }; - - _proto.br = function br() { - return ''; - }; - - return TextRenderer; - }(); - - /** - * Slugger generates header id - */ - var Slugger_1 = /*#__PURE__*/function () { - function Slugger() { - this.seen = {}; - } - - var _proto = Slugger.prototype; - - _proto.serialize = function serialize(value) { - return value.toLowerCase().trim() // remove html tags - .replace(/<[!\/a-z].*?>/ig, '') // remove unwanted chars - .replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, '').replace(/\s/g, '-'); - } - /** - * Finds the next safe (unique) slug to use - */ - ; - - _proto.getNextSafeSlug = function getNextSafeSlug(originalSlug, isDryRun) { - var slug = originalSlug; - var occurenceAccumulator = 0; - - if (this.seen.hasOwnProperty(slug)) { - occurenceAccumulator = this.seen[originalSlug]; - - do { - occurenceAccumulator++; - slug = originalSlug + '-' + occurenceAccumulator; - } while (this.seen.hasOwnProperty(slug)); - } - - if (!isDryRun) { - this.seen[originalSlug] = occurenceAccumulator; - this.seen[slug] = 0; - } - - return slug; - } - /** - * Convert string to unique id - * @param {object} options - * @param {boolean} options.dryrun Generates the next unique slug without updating the internal accumulator. - */ - ; - - _proto.slug = function slug(value, options) { - if (options === void 0) { - options = {}; - } - - var slug = this.serialize(value); - return this.getNextSafeSlug(slug, options.dryrun); - }; - - return Slugger; - }(); - - var defaults$4 = defaults.defaults; - var unescape$1 = helpers.unescape; - /** - * Parsing & Compiling - */ - - var Parser_1 = /*#__PURE__*/function () { - function Parser(options) { - this.options = options || defaults$4; - this.options.renderer = this.options.renderer || new Renderer_1(); - this.renderer = this.options.renderer; - this.renderer.options = this.options; - this.textRenderer = new TextRenderer_1(); - this.slugger = new Slugger_1(); - } - /** - * Static Parse Method - */ - - - Parser.parse = function parse(tokens, options) { - var parser = new Parser(options); - return parser.parse(tokens); - } - /** - * Static Parse Inline Method - */ - ; - - Parser.parseInline = function parseInline(tokens, options) { - var parser = new Parser(options); - return parser.parseInline(tokens); - } - /** - * Parse Loop - */ - ; - - var _proto = Parser.prototype; - - _proto.parse = function parse(tokens, top) { - if (top === void 0) { - top = true; - } - - var out = '', - i, - j, - k, - l2, - l3, - row, - cell, - header, - body, - token, - ordered, - start, - loose, - itemBody, - item, - checked, - task, - checkbox; - var l = tokens.length; - - for (i = 0; i < l; i++) { - token = tokens[i]; - - switch (token.type) { - case 'space': - { - continue; - } - - case 'hr': - { - out += this.renderer.hr(); - continue; - } - - case 'heading': - { - out += this.renderer.heading(this.parseInline(token.tokens), token.depth, unescape$1(this.parseInline(token.tokens, this.textRenderer)), this.slugger); - continue; - } - - case 'code': - { - out += this.renderer.code(token.text, token.lang, token.escaped); - continue; - } - - case 'table': - { - header = ''; // header - - cell = ''; - l2 = token.header.length; - - for (j = 0; j < l2; j++) { - cell += this.renderer.tablecell(this.parseInline(token.tokens.header[j]), { - header: true, - align: token.align[j] - }); - } - - header += this.renderer.tablerow(cell); - body = ''; - l2 = token.cells.length; - - for (j = 0; j < l2; j++) { - row = token.tokens.cells[j]; - cell = ''; - l3 = row.length; - - for (k = 0; k < l3; k++) { - cell += this.renderer.tablecell(this.parseInline(row[k]), { - header: false, - align: token.align[k] - }); - } - - body += this.renderer.tablerow(cell); - } - - out += this.renderer.table(header, body); - continue; - } - - case 'blockquote': - { - body = this.parse(token.tokens); - out += this.renderer.blockquote(body); - continue; - } - - case 'list': - { - ordered = token.ordered; - start = token.start; - loose = token.loose; - l2 = token.items.length; - body = ''; - - for (j = 0; j < l2; j++) { - item = token.items[j]; - checked = item.checked; - task = item.task; - itemBody = ''; - - if (item.task) { - checkbox = this.renderer.checkbox(checked); - - if (loose) { - if (item.tokens.length > 0 && item.tokens[0].type === 'text') { - item.tokens[0].text = checkbox + ' ' + item.tokens[0].text; - - if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') { - item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text; - } - } else { - item.tokens.unshift({ - type: 'text', - text: checkbox - }); - } - } else { - itemBody += checkbox; - } - } - - itemBody += this.parse(item.tokens, loose); - body += this.renderer.listitem(itemBody, task, checked); - } - - out += this.renderer.list(body, ordered, start); - continue; - } - - case 'html': - { - // TODO parse inline content if parameter markdown=1 - out += this.renderer.html(token.text); - continue; - } - - case 'paragraph': - { - out += this.renderer.paragraph(this.parseInline(token.tokens)); - continue; - } - - case 'text': - { - body = token.tokens ? this.parseInline(token.tokens) : token.text; - - while (i + 1 < l && tokens[i + 1].type === 'text') { - token = tokens[++i]; - body += '\n' + (token.tokens ? this.parseInline(token.tokens) : token.text); - } - - out += top ? this.renderer.paragraph(body) : body; - continue; - } - - default: - { - var errMsg = 'Token with "' + token.type + '" type was not found.'; - - if (this.options.silent) { - console.error(errMsg); - return; - } else { - throw new Error(errMsg); - } - } - } - } - - return out; - } - /** - * Parse Inline Tokens - */ - ; - - _proto.parseInline = function parseInline(tokens, renderer) { - renderer = renderer || this.renderer; - var out = '', - i, - token; - var l = tokens.length; - - for (i = 0; i < l; i++) { - token = tokens[i]; - - switch (token.type) { - case 'escape': - { - out += renderer.text(token.text); - break; - } - - case 'html': - { - out += renderer.html(token.text); - break; - } - - case 'link': - { - out += renderer.link(token.href, token.title, this.parseInline(token.tokens, renderer)); - break; - } - - case 'image': - { - out += renderer.image(token.href, token.title, token.text); - break; - } - - case 'strong': - { - out += renderer.strong(this.parseInline(token.tokens, renderer)); - break; - } - - case 'em': - { - out += renderer.em(this.parseInline(token.tokens, renderer)); - break; - } - - case 'codespan': - { - out += renderer.codespan(token.text); - break; - } - - case 'br': - { - out += renderer.br(); - break; - } - - case 'del': - { - out += renderer.del(this.parseInline(token.tokens, renderer)); - break; - } - - case 'text': - { - out += renderer.text(token.text); - break; - } - - default: - { - var errMsg = 'Token with "' + token.type + '" type was not found.'; - - if (this.options.silent) { - console.error(errMsg); - return; - } else { - throw new Error(errMsg); - } - } - } - } - - return out; - }; - - return Parser; - }(); - - var merge$2 = helpers.merge, - checkSanitizeDeprecation$1 = helpers.checkSanitizeDeprecation, - escape$2 = helpers.escape; - var getDefaults = defaults.getDefaults, - changeDefaults = defaults.changeDefaults, - defaults$5 = defaults.defaults; - /** - * Marked - */ - - function marked(src, opt, callback) { - // throw error in case of non string input - if (typeof src === 'undefined' || src === null) { - throw new Error('marked(): input parameter is undefined or null'); - } - - if (typeof src !== 'string') { - throw new Error('marked(): input parameter is of type ' + Object.prototype.toString.call(src) + ', string expected'); - } - - if (typeof opt === 'function') { - callback = opt; - opt = null; - } - - opt = merge$2({}, marked.defaults, opt || {}); - checkSanitizeDeprecation$1(opt); - - if (callback) { - var highlight = opt.highlight; - var tokens; - - try { - tokens = Lexer_1.lex(src, opt); - } catch (e) { - return callback(e); - } - - var done = function done(err) { - var out; - - if (!err) { - try { - out = Parser_1.parse(tokens, opt); - } catch (e) { - err = e; - } - } - - opt.highlight = highlight; - return err ? callback(err) : callback(null, out); - }; - - if (!highlight || highlight.length < 3) { - return done(); - } - - delete opt.highlight; - if (!tokens.length) return done(); - var pending = 0; - marked.walkTokens(tokens, function (token) { - if (token.type === 'code') { - pending++; - setTimeout(function () { - highlight(token.text, token.lang, function (err, code) { - if (err) { - return done(err); - } - - if (code != null && code !== token.text) { - token.text = code; - token.escaped = true; - } - - pending--; - - if (pending === 0) { - done(); - } - }); - }, 0); - } - }); - - if (pending === 0) { - done(); - } - - return; - } - - try { - var _tokens = Lexer_1.lex(src, opt); - - if (opt.walkTokens) { - marked.walkTokens(_tokens, opt.walkTokens); - } - - return Parser_1.parse(_tokens, opt); - } catch (e) { - e.message += '\nPlease report this to https://github.com/markedjs/marked.'; - - if (opt.silent) { - return '

    An error occurred:

    ' + escape$2(e.message + '', true) + '
    '; - } - - throw e; - } - } - /** - * Options - */ - - - marked.options = marked.setOptions = function (opt) { - merge$2(marked.defaults, opt); - changeDefaults(marked.defaults); - return marked; - }; - - marked.getDefaults = getDefaults; - marked.defaults = defaults$5; - /** - * Use Extension - */ - - marked.use = function (extension) { - var opts = merge$2({}, extension); - - if (extension.renderer) { - (function () { - var renderer = marked.defaults.renderer || new Renderer_1(); - - var _loop = function _loop(prop) { - var prevRenderer = renderer[prop]; - - renderer[prop] = function () { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - var ret = extension.renderer[prop].apply(renderer, args); - - if (ret === false) { - ret = prevRenderer.apply(renderer, args); - } - - return ret; - }; - }; - - for (var prop in extension.renderer) { - _loop(prop); - } - - opts.renderer = renderer; - })(); - } - - if (extension.tokenizer) { - (function () { - var tokenizer = marked.defaults.tokenizer || new Tokenizer_1(); - - var _loop2 = function _loop2(prop) { - var prevTokenizer = tokenizer[prop]; - - tokenizer[prop] = function () { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - - var ret = extension.tokenizer[prop].apply(tokenizer, args); - - if (ret === false) { - ret = prevTokenizer.apply(tokenizer, args); - } - - return ret; - }; - }; - - for (var prop in extension.tokenizer) { - _loop2(prop); - } - - opts.tokenizer = tokenizer; - })(); - } - - if (extension.walkTokens) { - var walkTokens = marked.defaults.walkTokens; - - opts.walkTokens = function (token) { - extension.walkTokens(token); - - if (walkTokens) { - walkTokens(token); - } - }; - } - - marked.setOptions(opts); - }; - /** - * Run callback for every token - */ - - - marked.walkTokens = function (tokens, callback) { - for (var _iterator = _createForOfIteratorHelperLoose(tokens), _step; !(_step = _iterator()).done;) { - var token = _step.value; - callback(token); - - switch (token.type) { - case 'table': - { - for (var _iterator2 = _createForOfIteratorHelperLoose(token.tokens.header), _step2; !(_step2 = _iterator2()).done;) { - var cell = _step2.value; - marked.walkTokens(cell, callback); - } - - for (var _iterator3 = _createForOfIteratorHelperLoose(token.tokens.cells), _step3; !(_step3 = _iterator3()).done;) { - var row = _step3.value; - - for (var _iterator4 = _createForOfIteratorHelperLoose(row), _step4; !(_step4 = _iterator4()).done;) { - var _cell = _step4.value; - marked.walkTokens(_cell, callback); - } - } - - break; - } - - case 'list': - { - marked.walkTokens(token.items, callback); - break; - } - - default: - { - if (token.tokens) { - marked.walkTokens(token.tokens, callback); - } - } - } - } - }; - /** - * Parse Inline - */ - - - marked.parseInline = function (src, opt) { - // throw error in case of non string input - if (typeof src === 'undefined' || src === null) { - throw new Error('marked.parseInline(): input parameter is undefined or null'); - } - - if (typeof src !== 'string') { - throw new Error('marked.parseInline(): input parameter is of type ' + Object.prototype.toString.call(src) + ', string expected'); - } - - opt = merge$2({}, marked.defaults, opt || {}); - checkSanitizeDeprecation$1(opt); - - try { - var tokens = Lexer_1.lexInline(src, opt); - - if (opt.walkTokens) { - marked.walkTokens(tokens, opt.walkTokens); - } - - return Parser_1.parseInline(tokens, opt); - } catch (e) { - e.message += '\nPlease report this to https://github.com/markedjs/marked.'; - - if (opt.silent) { - return '

    An error occurred:

    ' + escape$2(e.message + '', true) + '
    '; - } - - throw e; - } - }; - /** - * Expose - */ - - - marked.Parser = Parser_1; - marked.parser = Parser_1.parse; - marked.Renderer = Renderer_1; - marked.TextRenderer = TextRenderer_1; - marked.Lexer = Lexer_1; - marked.lexer = Lexer_1.lex; - marked.Tokenizer = Tokenizer_1; - marked.Slugger = Slugger_1; - marked.parse = marked; - var marked_1 = marked; - - return marked_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[286/*vs/base/common/navigator*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ArrayNavigator = void 0; - class ArrayNavigator { - constructor(items, start = 0, end = items.length, index = start - 1) { - this.items = items; - this.start = start; - this.end = end; - this.index = index; - } - current() { - if (this.index === this.start - 1 || this.index === this.end) { - return null; - } - return this.items[this.index]; - } - next() { - this.index = Math.min(this.index + 1, this.end); - return this.current(); - } - previous() { - this.index = Math.max(this.index - 1, this.start - 1); - return this.current(); - } - first() { - this.index = this.start; - return this.current(); - } - last() { - this.index = this.end - 1; - return this.current(); - } - } - exports.ArrayNavigator = ArrayNavigator; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[287/*vs/base/common/history*/], __M([0/*require*/,1/*exports*/,286/*vs/base/common/navigator*/]), function (require, exports, navigator_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.HistoryNavigator = void 0; - class HistoryNavigator { - constructor(history = [], limit = 10) { - this._initialize(history); - this._limit = limit; - this._onChange(); - } - add(t) { - this._history.delete(t); - this._history.add(t); - this._onChange(); - } - next() { - if (this._currentPosition() !== this._elements.length - 1) { - return this._navigator.next(); - } - return null; - } - previous() { - if (this._currentPosition() !== 0) { - return this._navigator.previous(); - } - return null; - } - current() { - return this._navigator.current(); - } - first() { - return this._navigator.first(); - } - last() { - return this._navigator.last(); - } - has(t) { - return this._history.has(t); - } - _onChange() { - this._reduceToLimit(); - const elements = this._elements; - this._navigator = new navigator_1.ArrayNavigator(elements, 0, elements.length, elements.length); - } - _reduceToLimit() { - const data = this._elements; - if (data.length > this._limit) { - this._initialize(data.slice(data.length - this._limit)); - } - } - _currentPosition() { - const currentElement = this._navigator.current(); - if (!currentElement) { - return -1; - } - return this._elements.indexOf(currentElement); - } - _initialize(history) { - this._history = new Set(); - for (const entry of history) { - this._history.add(entry); - } - } - get _elements() { - const elements = []; - this._history.forEach(e => elements.push(e)); - return elements; - } - } - exports.HistoryNavigator = HistoryNavigator; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[102/*vs/base/common/numbers*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MovingAverage = exports.clamp = void 0; - function clamp(value, min, max) { - return Math.min(Math.max(value, min), max); - } - exports.clamp = clamp; - class MovingAverage { - constructor() { - this._n = 1; - this._val = 0; - } - update(value) { - this._val = this._val + (value - this._val) / this._n; - this._n += 1; - return this; - } - get value() { - return this._val; - } - } - exports.MovingAverage = MovingAverage; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/common/platform*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - var _a; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.isLittleEndian = exports.OS = exports.setImmediate = exports.userAgent = exports.isIOS = exports.isWeb = exports.isNative = exports.isLinux = exports.isMacintosh = exports.isWindows = exports.isPreferringBrowserCodeLoad = exports.browserCodeLoadingCacheStrategy = exports.isElectronSandboxed = exports.globals = void 0; - const LANGUAGE_DEFAULT = 'en'; - let _isWindows = false; - let _isMacintosh = false; - let _isLinux = false; - let _isLinuxSnap = false; - let _isNative = false; - let _isWeb = false; - let _isIOS = false; - let _locale = undefined; - let _language = LANGUAGE_DEFAULT; - let _translationsConfigFile = undefined; - let _userAgent = undefined; - exports.globals = (typeof self === 'object' ? self : typeof global === 'object' ? global : {}); - let nodeProcess = undefined; - if (typeof exports.globals.vscode !== 'undefined' && typeof exports.globals.vscode.process !== 'undefined') { - // Native environment (sandboxed) - nodeProcess = exports.globals.vscode.process; - } - else if (typeof process !== 'undefined') { - // Native environment (non-sandboxed) - nodeProcess = process; - } - const isElectronRenderer = typeof ((_a = nodeProcess === null || nodeProcess === void 0 ? void 0 : nodeProcess.versions) === null || _a === void 0 ? void 0 : _a.electron) === 'string' && nodeProcess.type === 'renderer'; - exports.isElectronSandboxed = isElectronRenderer && (nodeProcess === null || nodeProcess === void 0 ? void 0 : nodeProcess.sandboxed); - exports.browserCodeLoadingCacheStrategy = (() => { - // Always enabled when sandbox is enabled - if (exports.isElectronSandboxed) { - return 'bypassHeatCheck'; - } - // Otherwise, only enabled conditionally - const env = nodeProcess === null || nodeProcess === void 0 ? void 0 : nodeProcess.env['VSCODE_BROWSER_CODE_LOADING']; - if (typeof env === 'string') { - if (env === 'none' || env === 'code' || env === 'bypassHeatCheck' || env === 'bypassHeatCheckAndEagerCompile') { - return env; - } - return 'bypassHeatCheck'; - } - return undefined; - })(); - exports.isPreferringBrowserCodeLoad = typeof exports.browserCodeLoadingCacheStrategy === 'string'; - // Web environment - if (typeof navigator === 'object' && !isElectronRenderer) { - _userAgent = navigator.userAgent; - _isWindows = _userAgent.indexOf('Windows') >= 0; - _isMacintosh = _userAgent.indexOf('Macintosh') >= 0; - _isIOS = (_userAgent.indexOf('Macintosh') >= 0 || _userAgent.indexOf('iPad') >= 0 || _userAgent.indexOf('iPhone') >= 0) && !!navigator.maxTouchPoints && navigator.maxTouchPoints > 0; - _isLinux = _userAgent.indexOf('Linux') >= 0; - _isWeb = true; - _locale = navigator.language; - _language = _locale; - } - // Native environment - else if (typeof nodeProcess === 'object') { - _isWindows = (nodeProcess.platform === 'win32'); - _isMacintosh = (nodeProcess.platform === 'darwin'); - _isLinux = (nodeProcess.platform === 'linux'); - _isLinuxSnap = _isLinux && !!nodeProcess.env['SNAP'] && !!nodeProcess.env['SNAP_REVISION']; - _locale = LANGUAGE_DEFAULT; - _language = LANGUAGE_DEFAULT; - const rawNlsConfig = nodeProcess.env['VSCODE_NLS_CONFIG']; - if (rawNlsConfig) { - try { - const nlsConfig = JSON.parse(rawNlsConfig); - const resolved = nlsConfig.availableLanguages['*']; - _locale = nlsConfig.locale; - // VSCode's default language is 'en' - _language = resolved ? resolved : LANGUAGE_DEFAULT; - _translationsConfigFile = nlsConfig._translationsConfigFile; - } - catch (e) { - } - } - _isNative = true; - } - // Unknown environment - else { - console.error('Unable to resolve platform.'); - } - let _platform = 0 /* Web */; - if (_isMacintosh) { - _platform = 1 /* Mac */; - } - else if (_isWindows) { - _platform = 3 /* Windows */; - } - else if (_isLinux) { - _platform = 2 /* Linux */; - } - exports.isWindows = _isWindows; - exports.isMacintosh = _isMacintosh; - exports.isLinux = _isLinux; - exports.isNative = _isNative; - exports.isWeb = _isWeb; - exports.isIOS = _isIOS; - exports.userAgent = _userAgent; - exports.setImmediate = (function defineSetImmediate() { - if (exports.globals.setImmediate) { - return exports.globals.setImmediate.bind(exports.globals); - } - if (typeof exports.globals.postMessage === 'function' && !exports.globals.importScripts) { - let pending = []; - exports.globals.addEventListener('message', (e) => { - if (e.data && e.data.vscodeSetImmediateId) { - for (let i = 0, len = pending.length; i < len; i++) { - const candidate = pending[i]; - if (candidate.id === e.data.vscodeSetImmediateId) { - pending.splice(i, 1); - candidate.callback(); - return; - } - } - } - }); - let lastId = 0; - return (callback) => { - const myId = ++lastId; - pending.push({ - id: myId, - callback: callback - }); - exports.globals.postMessage({ vscodeSetImmediateId: myId }, '*'); - }; - } - if (typeof (nodeProcess === null || nodeProcess === void 0 ? void 0 : nodeProcess.nextTick) === 'function') { - return nodeProcess.nextTick.bind(nodeProcess); - } - const _promise = Promise.resolve(); - return (callback) => _promise.then(callback); - })(); - exports.OS = (_isMacintosh || _isIOS ? 2 /* Macintosh */ : (_isWindows ? 1 /* Windows */ : 3 /* Linux */)); - let _isLittleEndian = true; - let _isLittleEndianComputed = false; - function isLittleEndian() { - if (!_isLittleEndianComputed) { - _isLittleEndianComputed = true; - const test = new Uint8Array(2); - test[0] = 1; - test[1] = 2; - const view = new Uint16Array(test.buffer); - _isLittleEndian = (view[0] === (2 << 8) + 1); - } - return _isLittleEndian; - } - exports.isLittleEndian = isLittleEndian; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[288/*vs/base/common/process*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/]), function (require, exports, platform_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.platform = exports.env = exports.cwd = void 0; - let safeProcess; - // Native sandbox environment - if (typeof platform_1.globals.vscode !== 'undefined' && typeof platform_1.globals.vscode.process !== 'undefined') { - const sandboxProcess = platform_1.globals.vscode.process; - safeProcess = { - get platform() { return sandboxProcess.platform; }, - get env() { return sandboxProcess.env; }, - cwd() { return sandboxProcess.cwd(); }, - nextTick(callback) { return (0, platform_1.setImmediate)(callback); } - }; - } - // Native node.js environment - else if (typeof process !== 'undefined') { - safeProcess = { - get platform() { return process.platform; }, - get env() { return process.env; }, - cwd() { return process.env['VSCODE_CWD'] || process.cwd(); }, - nextTick(callback) { return process.nextTick(callback); } - }; - } - // Web environment - else { - safeProcess = { - // Supported - get platform() { return platform_1.isWindows ? 'win32' : platform_1.isMacintosh ? 'darwin' : 'linux'; }, - nextTick(callback) { return (0, platform_1.setImmediate)(callback); }, - // Unsupported - get env() { return {}; }, - cwd() { return '/'; } - }; - } - /** - * Provides safe access to the `cwd` property in node.js, sandboxed or web - * environments. - * - * Note: in web, this property is hardcoded to be `/`. - */ - exports.cwd = safeProcess.cwd; - /** - * Provides safe access to the `env` property in node.js, sandboxed or web - * environments. - * - * Note: in web, this property is hardcoded to be `{}`. - */ - exports.env = safeProcess.env; - /** - * Provides safe access to the `platform` property in node.js, sandboxed or web - * environments. - */ - exports.platform = safeProcess.platform; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/common/path*/], __M([0/*require*/,1/*exports*/,288/*vs/base/common/process*/]), function (require, exports, process) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.sep = exports.extname = exports.basename = exports.dirname = exports.relative = exports.resolve = exports.normalize = exports.posix = exports.win32 = void 0; - const CHAR_UPPERCASE_A = 65; /* A */ - const CHAR_LOWERCASE_A = 97; /* a */ - const CHAR_UPPERCASE_Z = 90; /* Z */ - const CHAR_LOWERCASE_Z = 122; /* z */ - const CHAR_DOT = 46; /* . */ - const CHAR_FORWARD_SLASH = 47; /* / */ - const CHAR_BACKWARD_SLASH = 92; /* \ */ - const CHAR_COLON = 58; /* : */ - const CHAR_QUESTION_MARK = 63; /* ? */ - class ErrorInvalidArgType extends Error { - constructor(name, expected, actual) { - // determiner: 'must be' or 'must not be' - let determiner; - if (typeof expected === 'string' && expected.indexOf('not ') === 0) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } - else { - determiner = 'must be'; - } - const type = name.indexOf('.') !== -1 ? 'property' : 'argument'; - let msg = `The "${name}" ${type} ${determiner} of type ${expected}`; - msg += `. Received type ${typeof actual}`; - super(msg); - this.code = 'ERR_INVALID_ARG_TYPE'; - } - } - function validateString(value, name) { - if (typeof value !== 'string') { - throw new ErrorInvalidArgType(name, 'string', value); - } - } - function isPathSeparator(code) { - return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; - } - function isPosixPathSeparator(code) { - return code === CHAR_FORWARD_SLASH; - } - function isWindowsDeviceRoot(code) { - return code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z || - code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z; - } - // Resolves . and .. elements in a path with directory names - function normalizeString(path, allowAboveRoot, separator, isPathSeparator) { - let res = ''; - let lastSegmentLength = 0; - let lastSlash = -1; - let dots = 0; - let code = 0; - for (let i = 0; i <= path.length; ++i) { - if (i < path.length) { - code = path.charCodeAt(i); - } - else if (isPathSeparator(code)) { - break; - } - else { - code = CHAR_FORWARD_SLASH; - } - if (isPathSeparator(code)) { - if (lastSlash === i - 1 || dots === 1) { - // NOOP - } - else if (dots === 2) { - if (res.length < 2 || lastSegmentLength !== 2 || - res.charCodeAt(res.length - 1) !== CHAR_DOT || - res.charCodeAt(res.length - 2) !== CHAR_DOT) { - if (res.length > 2) { - const lastSlashIndex = res.lastIndexOf(separator); - if (lastSlashIndex === -1) { - res = ''; - lastSegmentLength = 0; - } - else { - res = res.slice(0, lastSlashIndex); - lastSegmentLength = res.length - 1 - res.lastIndexOf(separator); - } - lastSlash = i; - dots = 0; - continue; - } - else if (res.length !== 0) { - res = ''; - lastSegmentLength = 0; - lastSlash = i; - dots = 0; - continue; - } - } - if (allowAboveRoot) { - res += res.length > 0 ? `${separator}..` : '..'; - lastSegmentLength = 2; - } - } - else { - if (res.length > 0) { - res += `${separator}${path.slice(lastSlash + 1, i)}`; - } - else { - res = path.slice(lastSlash + 1, i); - } - lastSegmentLength = i - lastSlash - 1; - } - lastSlash = i; - dots = 0; - } - else if (code === CHAR_DOT && dots !== -1) { - ++dots; - } - else { - dots = -1; - } - } - return res; - } - function _format(sep, pathObject) { - if (pathObject === null || typeof pathObject !== 'object') { - throw new ErrorInvalidArgType('pathObject', 'Object', pathObject); - } - const dir = pathObject.dir || pathObject.root; - const base = pathObject.base || - `${pathObject.name || ''}${pathObject.ext || ''}`; - if (!dir) { - return base; - } - return dir === pathObject.root ? `${dir}${base}` : `${dir}${sep}${base}`; - } - exports.win32 = { - // path.resolve([from ...], to) - resolve(...pathSegments) { - let resolvedDevice = ''; - let resolvedTail = ''; - let resolvedAbsolute = false; - for (let i = pathSegments.length - 1; i >= -1; i--) { - let path; - if (i >= 0) { - path = pathSegments[i]; - validateString(path, 'path'); - // Skip empty entries - if (path.length === 0) { - continue; - } - } - else if (resolvedDevice.length === 0) { - path = process.cwd(); - } - else { - // Windows has the concept of drive-specific current working - // directories. If we've resolved a drive letter but not yet an - // absolute path, get cwd for that drive, or the process cwd if - // the drive cwd is not available. We're sure the device is not - // a UNC path at this points, because UNC paths are always absolute. - path = process.env[`=${resolvedDevice}`] || process.cwd(); - // Verify that a cwd was found and that it actually points - // to our drive. If not, default to the drive's root. - if (path === undefined || - path.slice(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && - path.charCodeAt(2) === CHAR_BACKWARD_SLASH) { - path = `${resolvedDevice}\\`; - } - } - const len = path.length; - let rootEnd = 0; - let device = ''; - let isAbsolute = false; - const code = path.charCodeAt(0); - // Try to match a root - if (len === 1) { - if (isPathSeparator(code)) { - // `path` contains just a path separator - rootEnd = 1; - isAbsolute = true; - } - } - else if (isPathSeparator(code)) { - // Possible UNC root - // If we started with a separator, we know we at least have an - // absolute path of some kind (UNC or otherwise) - isAbsolute = true; - if (isPathSeparator(path.charCodeAt(1))) { - // Matched double path separator at beginning - let j = 2; - let last = j; - // Match 1 or more non-path separators - while (j < len && !isPathSeparator(path.charCodeAt(j))) { - j++; - } - if (j < len && j !== last) { - const firstPart = path.slice(last, j); - // Matched! - last = j; - // Match 1 or more path separators - while (j < len && isPathSeparator(path.charCodeAt(j))) { - j++; - } - if (j < len && j !== last) { - // Matched! - last = j; - // Match 1 or more non-path separators - while (j < len && !isPathSeparator(path.charCodeAt(j))) { - j++; - } - if (j === len || j !== last) { - // We matched a UNC root - device = `\\\\${firstPart}\\${path.slice(last, j)}`; - rootEnd = j; - } - } - } - } - else { - rootEnd = 1; - } - } - else if (isWindowsDeviceRoot(code) && - path.charCodeAt(1) === CHAR_COLON) { - // Possible device root - device = path.slice(0, 2); - rootEnd = 2; - if (len > 2 && isPathSeparator(path.charCodeAt(2))) { - // Treat separator following drive name as an absolute path - // indicator - isAbsolute = true; - rootEnd = 3; - } - } - if (device.length > 0) { - if (resolvedDevice.length > 0) { - if (device.toLowerCase() !== resolvedDevice.toLowerCase()) { - // This path points to another device so it is not applicable - continue; - } - } - else { - resolvedDevice = device; - } - } - if (resolvedAbsolute) { - if (resolvedDevice.length > 0) { - break; - } - } - else { - resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`; - resolvedAbsolute = isAbsolute; - if (isAbsolute && resolvedDevice.length > 0) { - break; - } - } - } - // At this point the path should be resolved to a full absolute path, - // but handle relative paths to be safe (might happen when process.cwd() - // fails) - // Normalize the tail path - resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isPathSeparator); - return resolvedAbsolute ? - `${resolvedDevice}\\${resolvedTail}` : - `${resolvedDevice}${resolvedTail}` || '.'; - }, - normalize(path) { - validateString(path, 'path'); - const len = path.length; - if (len === 0) { - return '.'; - } - let rootEnd = 0; - let device; - let isAbsolute = false; - const code = path.charCodeAt(0); - // Try to match a root - if (len === 1) { - // `path` contains just a single char, exit early to avoid - // unnecessary work - return isPosixPathSeparator(code) ? '\\' : path; - } - if (isPathSeparator(code)) { - // Possible UNC root - // If we started with a separator, we know we at least have an absolute - // path of some kind (UNC or otherwise) - isAbsolute = true; - if (isPathSeparator(path.charCodeAt(1))) { - // Matched double path separator at beginning - let j = 2; - let last = j; - // Match 1 or more non-path separators - while (j < len && !isPathSeparator(path.charCodeAt(j))) { - j++; - } - if (j < len && j !== last) { - const firstPart = path.slice(last, j); - // Matched! - last = j; - // Match 1 or more path separators - while (j < len && isPathSeparator(path.charCodeAt(j))) { - j++; - } - if (j < len && j !== last) { - // Matched! - last = j; - // Match 1 or more non-path separators - while (j < len && !isPathSeparator(path.charCodeAt(j))) { - j++; - } - if (j === len) { - // We matched a UNC root only - // Return the normalized version of the UNC root since there - // is nothing left to process - return `\\\\${firstPart}\\${path.slice(last)}\\`; - } - if (j !== last) { - // We matched a UNC root with leftovers - device = `\\\\${firstPart}\\${path.slice(last, j)}`; - rootEnd = j; - } - } - } - } - else { - rootEnd = 1; - } - } - else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { - // Possible device root - device = path.slice(0, 2); - rootEnd = 2; - if (len > 2 && isPathSeparator(path.charCodeAt(2))) { - // Treat separator following drive name as an absolute path - // indicator - isAbsolute = true; - rootEnd = 3; - } - } - let tail = rootEnd < len ? - normalizeString(path.slice(rootEnd), !isAbsolute, '\\', isPathSeparator) : - ''; - if (tail.length === 0 && !isAbsolute) { - tail = '.'; - } - if (tail.length > 0 && isPathSeparator(path.charCodeAt(len - 1))) { - tail += '\\'; - } - if (device === undefined) { - return isAbsolute ? `\\${tail}` : tail; - } - return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`; - }, - isAbsolute(path) { - validateString(path, 'path'); - const len = path.length; - if (len === 0) { - return false; - } - const code = path.charCodeAt(0); - return isPathSeparator(code) || - // Possible device root - len > 2 && - isWindowsDeviceRoot(code) && - path.charCodeAt(1) === CHAR_COLON && - isPathSeparator(path.charCodeAt(2)); - }, - join(...paths) { - if (paths.length === 0) { - return '.'; - } - let joined; - let firstPart; - for (let i = 0; i < paths.length; ++i) { - const arg = paths[i]; - validateString(arg, 'path'); - if (arg.length > 0) { - if (joined === undefined) { - joined = firstPart = arg; - } - else { - joined += `\\${arg}`; - } - } - } - if (joined === undefined) { - return '.'; - } - // Make sure that the joined path doesn't start with two slashes, because - // normalize() will mistake it for an UNC path then. - // - // This step is skipped when it is very clear that the user actually - // intended to point at an UNC path. This is assumed when the first - // non-empty string arguments starts with exactly two slashes followed by - // at least one more non-slash character. - // - // Note that for normalize() to treat a path as an UNC path it needs to - // have at least 2 components, so we don't filter for that here. - // This means that the user can use join to construct UNC paths from - // a server name and a share name; for example: - // path.join('//server', 'share') -> '\\\\server\\share\\') - let needsReplace = true; - let slashCount = 0; - if (typeof firstPart === 'string' && isPathSeparator(firstPart.charCodeAt(0))) { - ++slashCount; - const firstLen = firstPart.length; - if (firstLen > 1 && isPathSeparator(firstPart.charCodeAt(1))) { - ++slashCount; - if (firstLen > 2) { - if (isPathSeparator(firstPart.charCodeAt(2))) { - ++slashCount; - } - else { - // We matched a UNC path in the first part - needsReplace = false; - } - } - } - } - if (needsReplace) { - // Find any more consecutive slashes we need to replace - while (slashCount < joined.length && - isPathSeparator(joined.charCodeAt(slashCount))) { - slashCount++; - } - // Replace the slashes if needed - if (slashCount >= 2) { - joined = `\\${joined.slice(slashCount)}`; - } - } - return exports.win32.normalize(joined); - }, - // It will solve the relative path from `from` to `to`, for instance: - // from = 'C:\\orandea\\test\\aaa' - // to = 'C:\\orandea\\impl\\bbb' - // The output of the function should be: '..\\..\\impl\\bbb' - relative(from, to) { - validateString(from, 'from'); - validateString(to, 'to'); - if (from === to) { - return ''; - } - const fromOrig = exports.win32.resolve(from); - const toOrig = exports.win32.resolve(to); - if (fromOrig === toOrig) { - return ''; - } - from = fromOrig.toLowerCase(); - to = toOrig.toLowerCase(); - if (from === to) { - return ''; - } - // Trim any leading backslashes - let fromStart = 0; - while (fromStart < from.length && - from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) { - fromStart++; - } - // Trim trailing backslashes (applicable to UNC paths only) - let fromEnd = from.length; - while (fromEnd - 1 > fromStart && - from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) { - fromEnd--; - } - const fromLen = fromEnd - fromStart; - // Trim any leading backslashes - let toStart = 0; - while (toStart < to.length && - to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) { - toStart++; - } - // Trim trailing backslashes (applicable to UNC paths only) - let toEnd = to.length; - while (toEnd - 1 > toStart && - to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) { - toEnd--; - } - const toLen = toEnd - toStart; - // Compare paths to find the longest common path from root - const length = fromLen < toLen ? fromLen : toLen; - let lastCommonSep = -1; - let i = 0; - for (; i < length; i++) { - const fromCode = from.charCodeAt(fromStart + i); - if (fromCode !== to.charCodeAt(toStart + i)) { - break; - } - else if (fromCode === CHAR_BACKWARD_SLASH) { - lastCommonSep = i; - } - } - // We found a mismatch before the first common path separator was seen, so - // return the original `to`. - if (i !== length) { - if (lastCommonSep === -1) { - return toOrig; - } - } - else { - if (toLen > length) { - if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) { - // We get here if `from` is the exact base path for `to`. - // For example: from='C:\\foo\\bar'; to='C:\\foo\\bar\\baz' - return toOrig.slice(toStart + i + 1); - } - if (i === 2) { - // We get here if `from` is the device root. - // For example: from='C:\\'; to='C:\\foo' - return toOrig.slice(toStart + i); - } - } - if (fromLen > length) { - if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) { - // We get here if `to` is the exact base path for `from`. - // For example: from='C:\\foo\\bar'; to='C:\\foo' - lastCommonSep = i; - } - else if (i === 2) { - // We get here if `to` is the device root. - // For example: from='C:\\foo\\bar'; to='C:\\' - lastCommonSep = 3; - } - } - if (lastCommonSep === -1) { - lastCommonSep = 0; - } - } - let out = ''; - // Generate the relative path based on the path difference between `to` and - // `from` - for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { - if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) { - out += out.length === 0 ? '..' : '\\..'; - } - } - toStart += lastCommonSep; - // Lastly, append the rest of the destination (`to`) path that comes after - // the common path parts - if (out.length > 0) { - return `${out}${toOrig.slice(toStart, toEnd)}`; - } - if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) { - ++toStart; - } - return toOrig.slice(toStart, toEnd); - }, - toNamespacedPath(path) { - // Note: this will *probably* throw somewhere. - if (typeof path !== 'string') { - return path; - } - if (path.length === 0) { - return ''; - } - const resolvedPath = exports.win32.resolve(path); - if (resolvedPath.length <= 2) { - return path; - } - if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) { - // Possible UNC root - if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) { - const code = resolvedPath.charCodeAt(2); - if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) { - // Matched non-long UNC root, convert the path to a long UNC path - return `\\\\?\\UNC\\${resolvedPath.slice(2)}`; - } - } - } - else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) && - resolvedPath.charCodeAt(1) === CHAR_COLON && - resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH) { - // Matched device root, convert the path to a long UNC path - return `\\\\?\\${resolvedPath}`; - } - return path; - }, - dirname(path) { - validateString(path, 'path'); - const len = path.length; - if (len === 0) { - return '.'; - } - let rootEnd = -1; - let offset = 0; - const code = path.charCodeAt(0); - if (len === 1) { - // `path` contains just a path separator, exit early to avoid - // unnecessary work or a dot. - return isPathSeparator(code) ? path : '.'; - } - // Try to match a root - if (isPathSeparator(code)) { - // Possible UNC root - rootEnd = offset = 1; - if (isPathSeparator(path.charCodeAt(1))) { - // Matched double path separator at beginning - let j = 2; - let last = j; - // Match 1 or more non-path separators - while (j < len && !isPathSeparator(path.charCodeAt(j))) { - j++; - } - if (j < len && j !== last) { - // Matched! - last = j; - // Match 1 or more path separators - while (j < len && isPathSeparator(path.charCodeAt(j))) { - j++; - } - if (j < len && j !== last) { - // Matched! - last = j; - // Match 1 or more non-path separators - while (j < len && !isPathSeparator(path.charCodeAt(j))) { - j++; - } - if (j === len) { - // We matched a UNC root only - return path; - } - if (j !== last) { - // We matched a UNC root with leftovers - // Offset by 1 to include the separator after the UNC root to - // treat it as a "normal root" on top of a (UNC) root - rootEnd = offset = j + 1; - } - } - } - } - // Possible device root - } - else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { - rootEnd = len > 2 && isPathSeparator(path.charCodeAt(2)) ? 3 : 2; - offset = rootEnd; - } - let end = -1; - let matchedSlash = true; - for (let i = len - 1; i >= offset; --i) { - if (isPathSeparator(path.charCodeAt(i))) { - if (!matchedSlash) { - end = i; - break; - } - } - else { - // We saw the first non-path separator - matchedSlash = false; - } - } - if (end === -1) { - if (rootEnd === -1) { - return '.'; - } - end = rootEnd; - } - return path.slice(0, end); - }, - basename(path, ext) { - if (ext !== undefined) { - validateString(ext, 'ext'); - } - validateString(path, 'path'); - let start = 0; - let end = -1; - let matchedSlash = true; - let i; - // Check for a drive letter prefix so as not to mistake the following - // path separator as an extra separator at the end of the path that can be - // disregarded - if (path.length >= 2 && - isWindowsDeviceRoot(path.charCodeAt(0)) && - path.charCodeAt(1) === CHAR_COLON) { - start = 2; - } - if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { - if (ext === path) { - return ''; - } - let extIdx = ext.length - 1; - let firstNonSlashEnd = -1; - for (i = path.length - 1; i >= start; --i) { - const code = path.charCodeAt(i); - if (isPathSeparator(code)) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - start = i + 1; - break; - } - } - else { - if (firstNonSlashEnd === -1) { - // We saw the first non-path separator, remember this index in case - // we need it if the extension ends up not matching - matchedSlash = false; - firstNonSlashEnd = i + 1; - } - if (extIdx >= 0) { - // Try to match the explicit extension - if (code === ext.charCodeAt(extIdx)) { - if (--extIdx === -1) { - // We matched the extension, so mark this as the end of our path - // component - end = i; - } - } - else { - // Extension does not match, so our result is the entire path - // component - extIdx = -1; - end = firstNonSlashEnd; - } - } - } - } - if (start === end) { - end = firstNonSlashEnd; - } - else if (end === -1) { - end = path.length; - } - return path.slice(start, end); - } - for (i = path.length - 1; i >= start; --i) { - if (isPathSeparator(path.charCodeAt(i))) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - start = i + 1; - break; - } - } - else if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // path component - matchedSlash = false; - end = i + 1; - } - } - if (end === -1) { - return ''; - } - return path.slice(start, end); - }, - extname(path) { - validateString(path, 'path'); - let start = 0; - let startDot = -1; - let startPart = 0; - let end = -1; - let matchedSlash = true; - // Track the state of characters (if any) we see before our first dot and - // after any path separator we find - let preDotState = 0; - // Check for a drive letter prefix so as not to mistake the following - // path separator as an extra separator at the end of the path that can be - // disregarded - if (path.length >= 2 && - path.charCodeAt(1) === CHAR_COLON && - isWindowsDeviceRoot(path.charCodeAt(0))) { - start = startPart = 2; - } - for (let i = path.length - 1; i >= start; --i) { - const code = path.charCodeAt(i); - if (isPathSeparator(code)) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - startPart = i + 1; - break; - } - continue; - } - if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // extension - matchedSlash = false; - end = i + 1; - } - if (code === CHAR_DOT) { - // If this is our first dot, mark it as the start of our extension - if (startDot === -1) { - startDot = i; - } - else if (preDotState !== 1) { - preDotState = 1; - } - } - else if (startDot !== -1) { - // We saw a non-dot and non-path separator before our dot, so we should - // have a good chance at having a non-empty extension - preDotState = -1; - } - } - if (startDot === -1 || - end === -1 || - // We saw a non-dot character immediately before the dot - preDotState === 0 || - // The (right-most) trimmed path component is exactly '..' - (preDotState === 1 && - startDot === end - 1 && - startDot === startPart + 1)) { - return ''; - } - return path.slice(startDot, end); - }, - format: _format.bind(null, '\\'), - parse(path) { - validateString(path, 'path'); - const ret = { root: '', dir: '', base: '', ext: '', name: '' }; - if (path.length === 0) { - return ret; - } - const len = path.length; - let rootEnd = 0; - let code = path.charCodeAt(0); - if (len === 1) { - if (isPathSeparator(code)) { - // `path` contains just a path separator, exit early to avoid - // unnecessary work - ret.root = ret.dir = path; - return ret; - } - ret.base = ret.name = path; - return ret; - } - // Try to match a root - if (isPathSeparator(code)) { - // Possible UNC root - rootEnd = 1; - if (isPathSeparator(path.charCodeAt(1))) { - // Matched double path separator at beginning - let j = 2; - let last = j; - // Match 1 or more non-path separators - while (j < len && !isPathSeparator(path.charCodeAt(j))) { - j++; - } - if (j < len && j !== last) { - // Matched! - last = j; - // Match 1 or more path separators - while (j < len && isPathSeparator(path.charCodeAt(j))) { - j++; - } - if (j < len && j !== last) { - // Matched! - last = j; - // Match 1 or more non-path separators - while (j < len && !isPathSeparator(path.charCodeAt(j))) { - j++; - } - if (j === len) { - // We matched a UNC root only - rootEnd = j; - } - else if (j !== last) { - // We matched a UNC root with leftovers - rootEnd = j + 1; - } - } - } - } - } - else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { - // Possible device root - if (len <= 2) { - // `path` contains just a drive root, exit early to avoid - // unnecessary work - ret.root = ret.dir = path; - return ret; - } - rootEnd = 2; - if (isPathSeparator(path.charCodeAt(2))) { - if (len === 3) { - // `path` contains just a drive root, exit early to avoid - // unnecessary work - ret.root = ret.dir = path; - return ret; - } - rootEnd = 3; - } - } - if (rootEnd > 0) { - ret.root = path.slice(0, rootEnd); - } - let startDot = -1; - let startPart = rootEnd; - let end = -1; - let matchedSlash = true; - let i = path.length - 1; - // Track the state of characters (if any) we see before our first dot and - // after any path separator we find - let preDotState = 0; - // Get non-dir info - for (; i >= rootEnd; --i) { - code = path.charCodeAt(i); - if (isPathSeparator(code)) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - startPart = i + 1; - break; - } - continue; - } - if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // extension - matchedSlash = false; - end = i + 1; - } - if (code === CHAR_DOT) { - // If this is our first dot, mark it as the start of our extension - if (startDot === -1) { - startDot = i; - } - else if (preDotState !== 1) { - preDotState = 1; - } - } - else if (startDot !== -1) { - // We saw a non-dot and non-path separator before our dot, so we should - // have a good chance at having a non-empty extension - preDotState = -1; - } - } - if (end !== -1) { - if (startDot === -1 || - // We saw a non-dot character immediately before the dot - preDotState === 0 || - // The (right-most) trimmed path component is exactly '..' - (preDotState === 1 && - startDot === end - 1 && - startDot === startPart + 1)) { - ret.base = ret.name = path.slice(startPart, end); - } - else { - ret.name = path.slice(startPart, startDot); - ret.base = path.slice(startPart, end); - ret.ext = path.slice(startDot, end); - } - } - // If the directory is the root, use the entire root as the `dir` including - // the trailing slash if any (`C:\abc` -> `C:\`). Otherwise, strip out the - // trailing slash (`C:\abc\def` -> `C:\abc`). - if (startPart > 0 && startPart !== rootEnd) { - ret.dir = path.slice(0, startPart - 1); - } - else { - ret.dir = ret.root; - } - return ret; - }, - sep: '\\', - delimiter: ';', - win32: null, - posix: null - }; - exports.posix = { - // path.resolve([from ...], to) - resolve(...pathSegments) { - let resolvedPath = ''; - let resolvedAbsolute = false; - for (let i = pathSegments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - const path = i >= 0 ? pathSegments[i] : process.cwd(); - validateString(path, 'path'); - // Skip empty entries - if (path.length === 0) { - continue; - } - resolvedPath = `${path}/${resolvedPath}`; - resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; - } - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - // Normalize the path - resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator); - if (resolvedAbsolute) { - return `/${resolvedPath}`; - } - return resolvedPath.length > 0 ? resolvedPath : '.'; - }, - normalize(path) { - validateString(path, 'path'); - if (path.length === 0) { - return '.'; - } - const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; - const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH; - // Normalize the path - path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator); - if (path.length === 0) { - if (isAbsolute) { - return '/'; - } - return trailingSeparator ? './' : '.'; - } - if (trailingSeparator) { - path += '/'; - } - return isAbsolute ? `/${path}` : path; - }, - isAbsolute(path) { - validateString(path, 'path'); - return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH; - }, - join(...paths) { - if (paths.length === 0) { - return '.'; - } - let joined; - for (let i = 0; i < paths.length; ++i) { - const arg = paths[i]; - validateString(arg, 'path'); - if (arg.length > 0) { - if (joined === undefined) { - joined = arg; - } - else { - joined += `/${arg}`; - } - } - } - if (joined === undefined) { - return '.'; - } - return exports.posix.normalize(joined); - }, - relative(from, to) { - validateString(from, 'from'); - validateString(to, 'to'); - if (from === to) { - return ''; - } - // Trim leading forward slashes. - from = exports.posix.resolve(from); - to = exports.posix.resolve(to); - if (from === to) { - return ''; - } - const fromStart = 1; - const fromEnd = from.length; - const fromLen = fromEnd - fromStart; - const toStart = 1; - const toLen = to.length - toStart; - // Compare paths to find the longest common path from root - const length = (fromLen < toLen ? fromLen : toLen); - let lastCommonSep = -1; - let i = 0; - for (; i < length; i++) { - const fromCode = from.charCodeAt(fromStart + i); - if (fromCode !== to.charCodeAt(toStart + i)) { - break; - } - else if (fromCode === CHAR_FORWARD_SLASH) { - lastCommonSep = i; - } - } - if (i === length) { - if (toLen > length) { - if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) { - // We get here if `from` is the exact base path for `to`. - // For example: from='/foo/bar'; to='/foo/bar/baz' - return to.slice(toStart + i + 1); - } - if (i === 0) { - // We get here if `from` is the root - // For example: from='/'; to='/foo' - return to.slice(toStart + i); - } - } - else if (fromLen > length) { - if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) { - // We get here if `to` is the exact base path for `from`. - // For example: from='/foo/bar/baz'; to='/foo/bar' - lastCommonSep = i; - } - else if (i === 0) { - // We get here if `to` is the root. - // For example: from='/foo/bar'; to='/' - lastCommonSep = 0; - } - } - } - let out = ''; - // Generate the relative path based on the path difference between `to` - // and `from`. - for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { - if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) { - out += out.length === 0 ? '..' : '/..'; - } - } - // Lastly, append the rest of the destination (`to`) path that comes after - // the common path parts. - return `${out}${to.slice(toStart + lastCommonSep)}`; - }, - toNamespacedPath(path) { - // Non-op on posix systems - return path; - }, - dirname(path) { - validateString(path, 'path'); - if (path.length === 0) { - return '.'; - } - const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH; - let end = -1; - let matchedSlash = true; - for (let i = path.length - 1; i >= 1; --i) { - if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { - if (!matchedSlash) { - end = i; - break; - } - } - else { - // We saw the first non-path separator - matchedSlash = false; - } - } - if (end === -1) { - return hasRoot ? '/' : '.'; - } - if (hasRoot && end === 1) { - return '//'; - } - return path.slice(0, end); - }, - basename(path, ext) { - if (ext !== undefined) { - validateString(ext, 'ext'); - } - validateString(path, 'path'); - let start = 0; - let end = -1; - let matchedSlash = true; - let i; - if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { - if (ext === path) { - return ''; - } - let extIdx = ext.length - 1; - let firstNonSlashEnd = -1; - for (i = path.length - 1; i >= 0; --i) { - const code = path.charCodeAt(i); - if (code === CHAR_FORWARD_SLASH) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - start = i + 1; - break; - } - } - else { - if (firstNonSlashEnd === -1) { - // We saw the first non-path separator, remember this index in case - // we need it if the extension ends up not matching - matchedSlash = false; - firstNonSlashEnd = i + 1; - } - if (extIdx >= 0) { - // Try to match the explicit extension - if (code === ext.charCodeAt(extIdx)) { - if (--extIdx === -1) { - // We matched the extension, so mark this as the end of our path - // component - end = i; - } - } - else { - // Extension does not match, so our result is the entire path - // component - extIdx = -1; - end = firstNonSlashEnd; - } - } - } - } - if (start === end) { - end = firstNonSlashEnd; - } - else if (end === -1) { - end = path.length; - } - return path.slice(start, end); - } - for (i = path.length - 1; i >= 0; --i) { - if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - start = i + 1; - break; - } - } - else if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // path component - matchedSlash = false; - end = i + 1; - } - } - if (end === -1) { - return ''; - } - return path.slice(start, end); - }, - extname(path) { - validateString(path, 'path'); - let startDot = -1; - let startPart = 0; - let end = -1; - let matchedSlash = true; - // Track the state of characters (if any) we see before our first dot and - // after any path separator we find - let preDotState = 0; - for (let i = path.length - 1; i >= 0; --i) { - const code = path.charCodeAt(i); - if (code === CHAR_FORWARD_SLASH) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - startPart = i + 1; - break; - } - continue; - } - if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // extension - matchedSlash = false; - end = i + 1; - } - if (code === CHAR_DOT) { - // If this is our first dot, mark it as the start of our extension - if (startDot === -1) { - startDot = i; - } - else if (preDotState !== 1) { - preDotState = 1; - } - } - else if (startDot !== -1) { - // We saw a non-dot and non-path separator before our dot, so we should - // have a good chance at having a non-empty extension - preDotState = -1; - } - } - if (startDot === -1 || - end === -1 || - // We saw a non-dot character immediately before the dot - preDotState === 0 || - // The (right-most) trimmed path component is exactly '..' - (preDotState === 1 && - startDot === end - 1 && - startDot === startPart + 1)) { - return ''; - } - return path.slice(startDot, end); - }, - format: _format.bind(null, '/'), - parse(path) { - validateString(path, 'path'); - const ret = { root: '', dir: '', base: '', ext: '', name: '' }; - if (path.length === 0) { - return ret; - } - const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; - let start; - if (isAbsolute) { - ret.root = '/'; - start = 1; - } - else { - start = 0; - } - let startDot = -1; - let startPart = 0; - let end = -1; - let matchedSlash = true; - let i = path.length - 1; - // Track the state of characters (if any) we see before our first dot and - // after any path separator we find - let preDotState = 0; - // Get non-dir info - for (; i >= start; --i) { - const code = path.charCodeAt(i); - if (code === CHAR_FORWARD_SLASH) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - startPart = i + 1; - break; - } - continue; - } - if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // extension - matchedSlash = false; - end = i + 1; - } - if (code === CHAR_DOT) { - // If this is our first dot, mark it as the start of our extension - if (startDot === -1) { - startDot = i; - } - else if (preDotState !== 1) { - preDotState = 1; - } - } - else if (startDot !== -1) { - // We saw a non-dot and non-path separator before our dot, so we should - // have a good chance at having a non-empty extension - preDotState = -1; - } - } - if (end !== -1) { - const start = startPart === 0 && isAbsolute ? 1 : startPart; - if (startDot === -1 || - // We saw a non-dot character immediately before the dot - preDotState === 0 || - // The (right-most) trimmed path component is exactly '..' - (preDotState === 1 && - startDot === end - 1 && - startDot === startPart + 1)) { - ret.base = ret.name = path.slice(start, end); - } - else { - ret.name = path.slice(start, startDot); - ret.base = path.slice(start, end); - ret.ext = path.slice(startDot, end); - } - } - if (startPart > 0) { - ret.dir = path.slice(0, startPart - 1); - } - else if (isAbsolute) { - ret.dir = '/'; - } - return ret; - }, - sep: '/', - delimiter: ':', - win32: null, - posix: null - }; - exports.posix.win32 = exports.win32.win32 = exports.win32; - exports.posix.posix = exports.win32.posix = exports.posix; - exports.normalize = (process.platform === 'win32' ? exports.win32.normalize : exports.posix.normalize); - exports.resolve = (process.platform === 'win32' ? exports.win32.resolve : exports.posix.resolve); - exports.relative = (process.platform === 'win32' ? exports.win32.relative : exports.posix.relative); - exports.dirname = (process.platform === 'win32' ? exports.win32.dirname : exports.posix.dirname); - exports.basename = (process.platform === 'win32' ? exports.win32.basename : exports.posix.basename); - exports.extname = (process.platform === 'win32' ? exports.win32.extname : exports.posix.extname); - exports.sep = (process.platform === 'win32' ? exports.win32.sep : exports.posix.sep); -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[126/*vs/base/common/range*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Range = void 0; - var Range; - (function (Range) { - /** - * Returns the intersection between two ranges as a range itself. - * Returns `{ start: 0, end: 0 }` if the intersection is empty. - */ - function intersect(one, other) { - if (one.start >= other.end || other.start >= one.end) { - return { start: 0, end: 0 }; - } - const start = Math.max(one.start, other.start); - const end = Math.min(one.end, other.end); - if (end - start <= 0) { - return { start: 0, end: 0 }; - } - return { start, end }; - } - Range.intersect = intersect; - function isEmpty(range) { - return range.end - range.start <= 0; - } - Range.isEmpty = isEmpty; - function intersects(one, other) { - return !isEmpty(intersect(one, other)); - } - Range.intersects = intersects; - function relativeComplement(one, other) { - const result = []; - const first = { start: one.start, end: Math.min(other.start, one.end) }; - const second = { start: Math.max(other.end, one.start), end: one.end }; - if (!isEmpty(first)) { - result.push(first); - } - if (!isEmpty(second)) { - result.push(second); - } - return result; - } - Range.relativeComplement = relativeComplement; - })(Range = exports.Range || (exports.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[289/*vs/base/browser/ui/list/rangeMap*/], __M([0/*require*/,1/*exports*/,126/*vs/base/common/range*/]), function (require, exports, range_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.RangeMap = exports.consolidate = exports.shift = exports.groupIntersect = void 0; - /** - * Returns the intersection between a ranged group and a range. - * Returns `[]` if the intersection is empty. - */ - function groupIntersect(range, groups) { - const result = []; - for (let r of groups) { - if (range.start >= r.range.end) { - continue; - } - if (range.end < r.range.start) { - break; - } - const intersection = range_1.Range.intersect(range, r.range); - if (range_1.Range.isEmpty(intersection)) { - continue; - } - result.push({ - range: intersection, - size: r.size - }); - } - return result; - } - exports.groupIntersect = groupIntersect; - /** - * Shifts a range by that `much`. - */ - function shift({ start, end }, much) { - return { start: start + much, end: end + much }; - } - exports.shift = shift; - /** - * Consolidates a collection of ranged groups. - * - * Consolidation is the process of merging consecutive ranged groups - * that share the same `size`. - */ - function consolidate(groups) { - const result = []; - let previousGroup = null; - for (let group of groups) { - const start = group.range.start; - const end = group.range.end; - const size = group.size; - if (previousGroup && size === previousGroup.size) { - previousGroup.range.end = end; - continue; - } - previousGroup = { range: { start, end }, size }; - result.push(previousGroup); - } - return result; - } - exports.consolidate = consolidate; - /** - * Concatenates several collections of ranged groups into a single - * collection. - */ - function concat(...groups) { - return consolidate(groups.reduce((r, g) => r.concat(g), [])); - } - class RangeMap { - constructor() { - this.groups = []; - this._size = 0; - } - splice(index, deleteCount, items = []) { - const diff = items.length - deleteCount; - const before = groupIntersect({ start: 0, end: index }, this.groups); - const after = groupIntersect({ start: index + deleteCount, end: Number.POSITIVE_INFINITY }, this.groups) - .map(g => ({ range: shift(g.range, diff), size: g.size })); - const middle = items.map((item, i) => ({ - range: { start: index + i, end: index + i + 1 }, - size: item.size - })); - this.groups = concat(before, middle, after); - this._size = this.groups.reduce((t, g) => t + (g.size * (g.range.end - g.range.start)), 0); - } - /** - * Returns the number of items in the range map. - */ - get count() { - const len = this.groups.length; - if (!len) { - return 0; - } - return this.groups[len - 1].range.end; - } - /** - * Returns the sum of the sizes of all items in the range map. - */ - get size() { - return this._size; - } - /** - * Returns the index of the item at the given position. - */ - indexAt(position) { - if (position < 0) { - return -1; - } - let index = 0; - let size = 0; - for (let group of this.groups) { - const count = group.range.end - group.range.start; - const newSize = size + (count * group.size); - if (position < newSize) { - return index + Math.floor((position - size) / group.size); - } - index += count; - size = newSize; - } - return index; - } - /** - * Returns the index of the item right after the item at the - * index of the given position. - */ - indexAfter(position) { - return Math.min(this.indexAt(position) + 1, this.count); - } - /** - * Returns the start position of the item at the given index. - */ - positionAt(index) { - if (index < 0) { - return -1; - } - let position = 0; - let count = 0; - for (let group of this.groups) { - const groupCount = group.range.end - group.range.start; - const newCount = count + groupCount; - if (index < newCount) { - return position + ((index - count) * group.size); - } - position += groupCount * group.size; - count = newCount; - } - return -1; - } - } - exports.RangeMap = RangeMap; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/common/stopwatch*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/]), function (require, exports, platform_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.StopWatch = void 0; - const hasPerformanceNow = (platform_1.globals.performance && typeof platform_1.globals.performance.now === 'function'); - class StopWatch { - constructor(highResolution) { - this._highResolution = hasPerformanceNow && highResolution; - this._startTime = this._now(); - this._stopTime = -1; - } - static create(highResolution = true) { - return new StopWatch(highResolution); - } - stop() { - this._stopTime = this._now(); - } - elapsed() { - if (this._stopTime !== -1) { - return this._stopTime - this._startTime; - } - return this._now() - this._startTime; - } - _now() { - return this._highResolution ? platform_1.globals.performance.now() : Date.now(); - } - } - exports.StopWatch = StopWatch; -}); - -define(__m[6/*vs/base/common/event*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,72/*vs/base/common/linkedList*/,81/*vs/base/common/stopwatch*/]), function (require, exports, errors_1, lifecycle_1, linkedList_1, stopwatch_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Relay = exports.EventBufferer = exports.DebounceEmitter = exports.PauseableEmitter = exports.Emitter = exports.Event = void 0; - var Event; - (function (Event) { - Event.None = () => lifecycle_1.Disposable.None; - /** - * Given an event, returns another event which only fires once. - */ - function once(event) { - return (listener, thisArgs = null, disposables) => { - // we need this, in case the event fires during the listener call - let didFire = false; - let result; - result = event(e => { - if (didFire) { - return; - } - else if (result) { - result.dispose(); - } - else { - didFire = true; - } - return listener.call(thisArgs, e); - }, null, disposables); - if (didFire) { - result.dispose(); - } - return result; - }; - } - Event.once = once; - /** - * @deprecated DO NOT use, this leaks memory - */ - function map(event, map) { - return snapshot((listener, thisArgs = null, disposables) => event(i => listener.call(thisArgs, map(i)), null, disposables)); - } - Event.map = map; - /** - * @deprecated DO NOT use, this leaks memory - */ - function forEach(event, each) { - return snapshot((listener, thisArgs = null, disposables) => event(i => { each(i); listener.call(thisArgs, i); }, null, disposables)); - } - Event.forEach = forEach; - function filter(event, filter) { - return snapshot((listener, thisArgs = null, disposables) => event(e => filter(e) && listener.call(thisArgs, e), null, disposables)); - } - Event.filter = filter; - /** - * Given an event, returns the same event but typed as `Event`. - */ - function signal(event) { - return event; - } - Event.signal = signal; - function any(...events) { - return (listener, thisArgs = null, disposables) => (0, lifecycle_1.combinedDisposable)(...events.map(event => event(e => listener.call(thisArgs, e), null, disposables))); - } - Event.any = any; - /** - * @deprecated DO NOT use, this leaks memory - */ - function reduce(event, merge, initial) { - let output = initial; - return map(event, e => { - output = merge(output, e); - return output; - }); - } - Event.reduce = reduce; - /** - * @deprecated DO NOT use, this leaks memory - */ - function snapshot(event) { - let listener; - const emitter = new Emitter({ - onFirstListenerAdd() { - listener = event(emitter.fire, emitter); - }, - onLastListenerRemove() { - listener.dispose(); - } - }); - return emitter.event; - } - /** - * @deprecated DO NOT use, this leaks memory - */ - function debounce(event, merge, delay = 100, leading = false, leakWarningThreshold) { - let subscription; - let output = undefined; - let handle = undefined; - let numDebouncedCalls = 0; - const emitter = new Emitter({ - leakWarningThreshold, - onFirstListenerAdd() { - subscription = event(cur => { - numDebouncedCalls++; - output = merge(output, cur); - if (leading && !handle) { - emitter.fire(output); - output = undefined; - } - clearTimeout(handle); - handle = setTimeout(() => { - const _output = output; - output = undefined; - handle = undefined; - if (!leading || numDebouncedCalls > 1) { - emitter.fire(_output); - } - numDebouncedCalls = 0; - }, delay); - }); - }, - onLastListenerRemove() { - subscription.dispose(); - } - }); - return emitter.event; - } - Event.debounce = debounce; - /** - * @deprecated DO NOT use, this leaks memory - */ - function latch(event, equals = (a, b) => a === b) { - let firstCall = true; - let cache; - return filter(event, value => { - const shouldEmit = firstCall || !equals(value, cache); - firstCall = false; - cache = value; - return shouldEmit; - }); - } - Event.latch = latch; - /** - * @deprecated DO NOT use, this leaks memory - */ - function split(event, isT) { - return [ - Event.filter(event, isT), - Event.filter(event, e => !isT(e)), - ]; - } - Event.split = split; - /** - * @deprecated DO NOT use, this leaks memory - */ - function buffer(event, nextTick = false, _buffer = []) { - let buffer = _buffer.slice(); - let listener = event(e => { - if (buffer) { - buffer.push(e); - } - else { - emitter.fire(e); - } - }); - const flush = () => { - if (buffer) { - buffer.forEach(e => emitter.fire(e)); - } - buffer = null; - }; - const emitter = new Emitter({ - onFirstListenerAdd() { - if (!listener) { - listener = event(e => emitter.fire(e)); - } - }, - onFirstListenerDidAdd() { - if (buffer) { - if (nextTick) { - setTimeout(flush); - } - else { - flush(); - } - } - }, - onLastListenerRemove() { - if (listener) { - listener.dispose(); - } - listener = null; - } - }); - return emitter.event; - } - Event.buffer = buffer; - class ChainableEvent { - constructor(event) { - this.event = event; - } - map(fn) { - return new ChainableEvent(map(this.event, fn)); - } - forEach(fn) { - return new ChainableEvent(forEach(this.event, fn)); - } - filter(fn) { - return new ChainableEvent(filter(this.event, fn)); - } - reduce(merge, initial) { - return new ChainableEvent(reduce(this.event, merge, initial)); - } - latch() { - return new ChainableEvent(latch(this.event)); - } - debounce(merge, delay = 100, leading = false, leakWarningThreshold) { - return new ChainableEvent(debounce(this.event, merge, delay, leading, leakWarningThreshold)); - } - on(listener, thisArgs, disposables) { - return this.event(listener, thisArgs, disposables); - } - once(listener, thisArgs, disposables) { - return once(this.event)(listener, thisArgs, disposables); - } - } - /** - * @deprecated DO NOT use, this leaks memory - */ - function chain(event) { - return new ChainableEvent(event); - } - Event.chain = chain; - function fromNodeEventEmitter(emitter, eventName, map = id => id) { - const fn = (...args) => result.fire(map(...args)); - const onFirstListenerAdd = () => emitter.on(eventName, fn); - const onLastListenerRemove = () => emitter.removeListener(eventName, fn); - const result = new Emitter({ onFirstListenerAdd, onLastListenerRemove }); - return result.event; - } - Event.fromNodeEventEmitter = fromNodeEventEmitter; - function fromDOMEventEmitter(emitter, eventName, map = id => id) { - const fn = (...args) => result.fire(map(...args)); - const onFirstListenerAdd = () => emitter.addEventListener(eventName, fn); - const onLastListenerRemove = () => emitter.removeEventListener(eventName, fn); - const result = new Emitter({ onFirstListenerAdd, onLastListenerRemove }); - return result.event; - } - Event.fromDOMEventEmitter = fromDOMEventEmitter; - function toPromise(event) { - return new Promise(resolve => once(event)(resolve)); - } - Event.toPromise = toPromise; - })(Event = exports.Event || (exports.Event = {})); - class EventProfiling { - constructor(name) { - this._listenerCount = 0; - this._invocationCount = 0; - this._elapsedOverall = 0; - this._name = `${name}_${EventProfiling._idPool++}`; - } - start(listenerCount) { - this._stopWatch = new stopwatch_1.StopWatch(true); - this._listenerCount = listenerCount; - } - stop() { - if (this._stopWatch) { - const elapsed = this._stopWatch.elapsed(); - this._elapsedOverall += elapsed; - this._invocationCount += 1; - console.info(`did FIRE ${this._name}: elapsed_ms: ${elapsed.toFixed(5)}, listener: ${this._listenerCount} (elapsed_overall: ${this._elapsedOverall.toFixed(2)}, invocations: ${this._invocationCount})`); - this._stopWatch = undefined; - } - } - } - EventProfiling._idPool = 0; - let _globalLeakWarningThreshold = -1; - class LeakageMonitor { - constructor(customThreshold, name = Math.random().toString(18).slice(2, 5)) { - this.customThreshold = customThreshold; - this.name = name; - this._warnCountdown = 0; - } - dispose() { - if (this._stacks) { - this._stacks.clear(); - } - } - check(listenerCount) { - let threshold = _globalLeakWarningThreshold; - if (typeof this.customThreshold === 'number') { - threshold = this.customThreshold; - } - if (threshold <= 0 || listenerCount < threshold) { - return undefined; - } - if (!this._stacks) { - this._stacks = new Map(); - } - const stack = new Error().stack.split('\n').slice(3).join('\n'); - const count = (this._stacks.get(stack) || 0); - this._stacks.set(stack, count + 1); - this._warnCountdown -= 1; - if (this._warnCountdown <= 0) { - // only warn on first exceed and then every time the limit - // is exceeded by 50% again - this._warnCountdown = threshold * 0.5; - // find most frequent listener and print warning - let topStack; - let topCount = 0; - for (const [stack, count] of this._stacks) { - if (!topStack || topCount < count) { - topStack = stack; - topCount = count; - } - } - console.warn(`[${this.name}] potential listener LEAK detected, having ${listenerCount} listeners already. MOST frequent listener (${topCount}):`); - console.warn(topStack); - } - return () => { - const count = (this._stacks.get(stack) || 0); - this._stacks.set(stack, count - 1); - }; - } - } - /** - * The Emitter can be used to expose an Event to the public - * to fire it from the insides. - * Sample: - class Document { - - private readonly _onDidChange = new Emitter<(value:string)=>any>(); - - public onDidChange = this._onDidChange.event; - - // getter-style - // get onDidChange(): Event<(value:string)=>any> { - // return this._onDidChange.event; - // } - - private _doIt() { - //... - this._onDidChange.fire(value); - } - } - */ - class Emitter { - constructor(options) { - var _a; - this._disposed = false; - this._options = options; - this._leakageMon = _globalLeakWarningThreshold > 0 ? new LeakageMonitor(this._options && this._options.leakWarningThreshold) : undefined; - this._perfMon = ((_a = this._options) === null || _a === void 0 ? void 0 : _a._profName) ? new EventProfiling(this._options._profName) : undefined; - } - /** - * For the public to allow to subscribe - * to events from this Emitter - */ - get event() { - if (!this._event) { - this._event = (listener, thisArgs, disposables) => { - var _a; - if (!this._listeners) { - this._listeners = new linkedList_1.LinkedList(); - } - const firstListener = this._listeners.isEmpty(); - if (firstListener && this._options && this._options.onFirstListenerAdd) { - this._options.onFirstListenerAdd(this); - } - const remove = this._listeners.push(!thisArgs ? listener : [listener, thisArgs]); - if (firstListener && this._options && this._options.onFirstListenerDidAdd) { - this._options.onFirstListenerDidAdd(this); - } - if (this._options && this._options.onListenerDidAdd) { - this._options.onListenerDidAdd(this, listener, thisArgs); - } - // check and record this emitter for potential leakage - const removeMonitor = (_a = this._leakageMon) === null || _a === void 0 ? void 0 : _a.check(this._listeners.size); - const result = (0, lifecycle_1.toDisposable)(() => { - if (removeMonitor) { - removeMonitor(); - } - if (!this._disposed) { - remove(); - if (this._options && this._options.onLastListenerRemove) { - const hasListeners = (this._listeners && !this._listeners.isEmpty()); - if (!hasListeners) { - this._options.onLastListenerRemove(this); - } - } - } - }); - if (disposables instanceof lifecycle_1.DisposableStore) { - disposables.add(result); - } - else if (Array.isArray(disposables)) { - disposables.push(result); - } - return result; - }; - } - return this._event; - } - /** - * To be kept private to fire an event to - * subscribers - */ - fire(event) { - var _a, _b; - if (this._listeners) { - // put all [listener,event]-pairs into delivery queue - // then emit all event. an inner/nested event might be - // the driver of this - if (!this._deliveryQueue) { - this._deliveryQueue = new linkedList_1.LinkedList(); - } - for (let listener of this._listeners) { - this._deliveryQueue.push([listener, event]); - } - // start/stop performance insight collection - (_a = this._perfMon) === null || _a === void 0 ? void 0 : _a.start(this._deliveryQueue.size); - while (this._deliveryQueue.size > 0) { - const [listener, event] = this._deliveryQueue.shift(); - try { - if (typeof listener === 'function') { - listener.call(undefined, event); - } - else { - listener[0].call(listener[1], event); - } - } - catch (e) { - (0, errors_1.onUnexpectedError)(e); - } - } - (_b = this._perfMon) === null || _b === void 0 ? void 0 : _b.stop(); - } - } - dispose() { - var _a, _b, _c, _d, _e; - if (!this._disposed) { - this._disposed = true; - (_a = this._listeners) === null || _a === void 0 ? void 0 : _a.clear(); - (_b = this._deliveryQueue) === null || _b === void 0 ? void 0 : _b.clear(); - (_d = (_c = this._options) === null || _c === void 0 ? void 0 : _c.onLastListenerRemove) === null || _d === void 0 ? void 0 : _d.call(_c); - (_e = this._leakageMon) === null || _e === void 0 ? void 0 : _e.dispose(); - } - } - } - exports.Emitter = Emitter; - class PauseableEmitter extends Emitter { - constructor(options) { - super(options); - this._isPaused = 0; - this._eventQueue = new linkedList_1.LinkedList(); - this._mergeFn = options === null || options === void 0 ? void 0 : options.merge; - } - pause() { - this._isPaused++; - } - resume() { - if (this._isPaused !== 0 && --this._isPaused === 0) { - if (this._mergeFn) { - // use the merge function to create a single composite - // event. make a copy in case firing pauses this emitter - const events = Array.from(this._eventQueue); - this._eventQueue.clear(); - super.fire(this._mergeFn(events)); - } - else { - // no merging, fire each event individually and test - // that this emitter isn't paused halfway through - while (!this._isPaused && this._eventQueue.size !== 0) { - super.fire(this._eventQueue.shift()); - } - } - } - } - fire(event) { - if (this._listeners) { - if (this._isPaused !== 0) { - this._eventQueue.push(event); - } - else { - super.fire(event); - } - } - } - } - exports.PauseableEmitter = PauseableEmitter; - class DebounceEmitter extends PauseableEmitter { - constructor(options) { - var _a; - super(options); - this._delay = (_a = options.delay) !== null && _a !== void 0 ? _a : 100; - } - fire(event) { - if (!this._handle) { - this.pause(); - this._handle = setTimeout(() => { - this._handle = undefined; - this.resume(); - }, this._delay); - } - super.fire(event); - } - } - exports.DebounceEmitter = DebounceEmitter; - /** - * The EventBufferer is useful in situations in which you want - * to delay firing your events during some code. - * You can wrap that code and be sure that the event will not - * be fired during that wrap. - * - * ``` - * const emitter: Emitter; - * const delayer = new EventDelayer(); - * const delayedEvent = delayer.wrapEvent(emitter.event); - * - * delayedEvent(console.log); - * - * delayer.bufferEvents(() => { - * emitter.fire(); // event will not be fired yet - * }); - * - * // event will only be fired at this point - * ``` - */ - class EventBufferer { - constructor() { - this.buffers = []; - } - wrapEvent(event) { - return (listener, thisArgs, disposables) => { - return event(i => { - const buffer = this.buffers[this.buffers.length - 1]; - if (buffer) { - buffer.push(() => listener.call(thisArgs, i)); - } - else { - listener.call(thisArgs, i); - } - }, undefined, disposables); - }; - } - bufferEvents(fn) { - const buffer = []; - this.buffers.push(buffer); - const r = fn(); - this.buffers.pop(); - buffer.forEach(flush => flush()); - return r; - } - } - exports.EventBufferer = EventBufferer; - /** - * A Relay is an event forwarder which functions as a replugabble event pipe. - * Once created, you can connect an input event to it and it will simply forward - * events from that input event through its own `event` property. The `input` - * can be changed at any point in time. - */ - class Relay { - constructor() { - this.listening = false; - this.inputEvent = Event.None; - this.inputEventListener = lifecycle_1.Disposable.None; - this.emitter = new Emitter({ - onFirstListenerDidAdd: () => { - this.listening = true; - this.inputEventListener = this.inputEvent(this.emitter.fire, this.emitter); - }, - onLastListenerRemove: () => { - this.listening = false; - this.inputEventListener.dispose(); - } - }); - this.event = this.emitter.event; - } - set input(event) { - this.inputEvent = event; - if (this.listening) { - this.inputEventListener.dispose(); - this.inputEventListener = event(this.emitter.fire, this.emitter); - } - } - dispose() { - this.inputEventListener.dispose(); - this.emitter.dispose(); - } - } - exports.Relay = Relay; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[39/*vs/base/browser/browser*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/]), function (require, exports, event_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.isStandalone = exports.isAndroid = exports.isWebkitWebView = exports.isSafari = exports.isChrome = exports.isWebKit = exports.isFirefox = exports.getPixelRatio = exports.getZoomFactor = exports.onDidChangeZoomLevel = exports.getTimeSinceLastZoomLevelChanged = exports.getZoomLevel = void 0; - class WindowManager { - constructor() { - // --- Zoom Level - this._zoomLevel = 0; - this._lastZoomLevelChangeTime = 0; - this._onDidChangeZoomLevel = new event_1.Emitter(); - this.onDidChangeZoomLevel = this._onDidChangeZoomLevel.event; - // --- Zoom Factor - this._zoomFactor = 1; - } - getZoomLevel() { - return this._zoomLevel; - } - getTimeSinceLastZoomLevelChanged() { - return Date.now() - this._lastZoomLevelChangeTime; - } - getZoomFactor() { - return this._zoomFactor; - } - // --- Pixel Ratio - getPixelRatio() { - let ctx = document.createElement('canvas').getContext('2d'); - let dpr = window.devicePixelRatio || 1; - let bsr = ctx.webkitBackingStorePixelRatio || - ctx.mozBackingStorePixelRatio || - ctx.msBackingStorePixelRatio || - ctx.oBackingStorePixelRatio || - ctx.backingStorePixelRatio || 1; - return dpr / bsr; - } - } - WindowManager.INSTANCE = new WindowManager(); - function getZoomLevel() { - return WindowManager.INSTANCE.getZoomLevel(); - } - exports.getZoomLevel = getZoomLevel; - /** Returns the time (in ms) since the zoom level was changed */ - function getTimeSinceLastZoomLevelChanged() { - return WindowManager.INSTANCE.getTimeSinceLastZoomLevelChanged(); - } - exports.getTimeSinceLastZoomLevelChanged = getTimeSinceLastZoomLevelChanged; - function onDidChangeZoomLevel(callback) { - return WindowManager.INSTANCE.onDidChangeZoomLevel(callback); - } - exports.onDidChangeZoomLevel = onDidChangeZoomLevel; - /** The zoom scale for an index, e.g. 1, 1.2, 1.4 */ - function getZoomFactor() { - return WindowManager.INSTANCE.getZoomFactor(); - } - exports.getZoomFactor = getZoomFactor; - function getPixelRatio() { - return WindowManager.INSTANCE.getPixelRatio(); - } - exports.getPixelRatio = getPixelRatio; - const userAgent = navigator.userAgent; - exports.isFirefox = (userAgent.indexOf('Firefox') >= 0); - exports.isWebKit = (userAgent.indexOf('AppleWebKit') >= 0); - exports.isChrome = (userAgent.indexOf('Chrome') >= 0); - exports.isSafari = (!exports.isChrome && (userAgent.indexOf('Safari') >= 0)); - exports.isWebkitWebView = (!exports.isChrome && !exports.isSafari && exports.isWebKit); - exports.isAndroid = (userAgent.indexOf('Android') >= 0); - exports.isStandalone = (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches); -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/browser/canIUse*/], __M([0/*require*/,1/*exports*/,39/*vs/base/browser/browser*/,17/*vs/base/common/platform*/]), function (require, exports, browser, platform) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.BrowserFeatures = void 0; - /** - * Browser feature we can support in current platform, browser and environment. - */ - exports.BrowserFeatures = { - clipboard: { - writeText: (platform.isNative - || (document.queryCommandSupported && document.queryCommandSupported('copy')) - || !!(navigator && navigator.clipboard && navigator.clipboard.writeText)), - readText: (platform.isNative - || !!(navigator && navigator.clipboard && navigator.clipboard.readText)) - }, - keyboard: (() => { - if (platform.isNative || browser.isStandalone) { - return 0 /* Always */; - } - if (navigator.keyboard || browser.isSafari) { - return 1 /* FullScreen */; - } - return 2 /* None */; - })(), - // 'ontouchstart' in window always evaluates to true with typescript's modern typings. This causes `window` to be - // `never` later in `window.navigator`. That's why we need the explicit `window as Window` cast - touch: 'ontouchstart' in window || navigator.maxTouchPoints > 0, - pointerEvents: window.PointerEvent && ('ontouchstart' in window || window.navigator.maxTouchPoints > 0 || navigator.maxTouchPoints > 0) - }; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/browser/event*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/]), function (require, exports, event_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.stopEvent = exports.DomEmitter = void 0; - class DomEmitter { - constructor(element, type, useCapture) { - const fn = (e) => this.emitter.fire(e); - this.emitter = new event_1.Emitter({ - onFirstListenerAdd: () => element.addEventListener(type, fn, useCapture), - onLastListenerRemove: () => element.removeEventListener(type, fn, useCapture) - }); - } - get event() { - return this.emitter.event; - } - dispose() { - this.emitter.dispose(); - } - } - exports.DomEmitter = DomEmitter; - function stopEvent(event) { - event.preventDefault(); - event.stopPropagation(); - return event; - } - exports.stopEvent = stopEvent; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/browser/keyboardEvent*/], __M([0/*require*/,1/*exports*/,39/*vs/base/browser/browser*/,41/*vs/base/common/keyCodes*/,17/*vs/base/common/platform*/]), function (require, exports, browser, keyCodes_1, platform) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.StandardKeyboardEvent = void 0; - let KEY_CODE_MAP = new Array(230); - let INVERSE_KEY_CODE_MAP = new Array(112 /* MAX_VALUE */); - (function () { - for (let i = 0; i < INVERSE_KEY_CODE_MAP.length; i++) { - INVERSE_KEY_CODE_MAP[i] = -1; - } - function define(code, keyCode) { - KEY_CODE_MAP[code] = keyCode; - INVERSE_KEY_CODE_MAP[keyCode] = code; - } - define(3, 7 /* PauseBreak */); // VK_CANCEL 0x03 Control-break processing - define(8, 1 /* Backspace */); - define(9, 2 /* Tab */); - define(13, 3 /* Enter */); - define(16, 4 /* Shift */); - define(17, 5 /* Ctrl */); - define(18, 6 /* Alt */); - define(19, 7 /* PauseBreak */); - define(20, 8 /* CapsLock */); - define(27, 9 /* Escape */); - define(32, 10 /* Space */); - define(33, 11 /* PageUp */); - define(34, 12 /* PageDown */); - define(35, 13 /* End */); - define(36, 14 /* Home */); - define(37, 15 /* LeftArrow */); - define(38, 16 /* UpArrow */); - define(39, 17 /* RightArrow */); - define(40, 18 /* DownArrow */); - define(45, 19 /* Insert */); - define(46, 20 /* Delete */); - define(48, 21 /* KEY_0 */); - define(49, 22 /* KEY_1 */); - define(50, 23 /* KEY_2 */); - define(51, 24 /* KEY_3 */); - define(52, 25 /* KEY_4 */); - define(53, 26 /* KEY_5 */); - define(54, 27 /* KEY_6 */); - define(55, 28 /* KEY_7 */); - define(56, 29 /* KEY_8 */); - define(57, 30 /* KEY_9 */); - define(65, 31 /* KEY_A */); - define(66, 32 /* KEY_B */); - define(67, 33 /* KEY_C */); - define(68, 34 /* KEY_D */); - define(69, 35 /* KEY_E */); - define(70, 36 /* KEY_F */); - define(71, 37 /* KEY_G */); - define(72, 38 /* KEY_H */); - define(73, 39 /* KEY_I */); - define(74, 40 /* KEY_J */); - define(75, 41 /* KEY_K */); - define(76, 42 /* KEY_L */); - define(77, 43 /* KEY_M */); - define(78, 44 /* KEY_N */); - define(79, 45 /* KEY_O */); - define(80, 46 /* KEY_P */); - define(81, 47 /* KEY_Q */); - define(82, 48 /* KEY_R */); - define(83, 49 /* KEY_S */); - define(84, 50 /* KEY_T */); - define(85, 51 /* KEY_U */); - define(86, 52 /* KEY_V */); - define(87, 53 /* KEY_W */); - define(88, 54 /* KEY_X */); - define(89, 55 /* KEY_Y */); - define(90, 56 /* KEY_Z */); - define(93, 58 /* ContextMenu */); - define(96, 93 /* NUMPAD_0 */); - define(97, 94 /* NUMPAD_1 */); - define(98, 95 /* NUMPAD_2 */); - define(99, 96 /* NUMPAD_3 */); - define(100, 97 /* NUMPAD_4 */); - define(101, 98 /* NUMPAD_5 */); - define(102, 99 /* NUMPAD_6 */); - define(103, 100 /* NUMPAD_7 */); - define(104, 101 /* NUMPAD_8 */); - define(105, 102 /* NUMPAD_9 */); - define(106, 103 /* NUMPAD_MULTIPLY */); - define(107, 104 /* NUMPAD_ADD */); - define(108, 105 /* NUMPAD_SEPARATOR */); - define(109, 106 /* NUMPAD_SUBTRACT */); - define(110, 107 /* NUMPAD_DECIMAL */); - define(111, 108 /* NUMPAD_DIVIDE */); - define(112, 59 /* F1 */); - define(113, 60 /* F2 */); - define(114, 61 /* F3 */); - define(115, 62 /* F4 */); - define(116, 63 /* F5 */); - define(117, 64 /* F6 */); - define(118, 65 /* F7 */); - define(119, 66 /* F8 */); - define(120, 67 /* F9 */); - define(121, 68 /* F10 */); - define(122, 69 /* F11 */); - define(123, 70 /* F12 */); - define(124, 71 /* F13 */); - define(125, 72 /* F14 */); - define(126, 73 /* F15 */); - define(127, 74 /* F16 */); - define(128, 75 /* F17 */); - define(129, 76 /* F18 */); - define(130, 77 /* F19 */); - define(144, 78 /* NumLock */); - define(145, 79 /* ScrollLock */); - define(186, 80 /* US_SEMICOLON */); - define(187, 81 /* US_EQUAL */); - define(188, 82 /* US_COMMA */); - define(189, 83 /* US_MINUS */); - define(190, 84 /* US_DOT */); - define(191, 85 /* US_SLASH */); - define(192, 86 /* US_BACKTICK */); - define(193, 110 /* ABNT_C1 */); - define(194, 111 /* ABNT_C2 */); - define(219, 87 /* US_OPEN_SQUARE_BRACKET */); - define(220, 88 /* US_BACKSLASH */); - define(221, 89 /* US_CLOSE_SQUARE_BRACKET */); - define(222, 90 /* US_QUOTE */); - define(223, 91 /* OEM_8 */); - define(226, 92 /* OEM_102 */); - /** - * https://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html - * If an Input Method Editor is processing key input and the event is keydown, return 229. - */ - define(229, 109 /* KEY_IN_COMPOSITION */); - if (browser.isFirefox) { - define(59, 80 /* US_SEMICOLON */); - define(107, 81 /* US_EQUAL */); - define(109, 83 /* US_MINUS */); - if (platform.isMacintosh) { - define(224, 57 /* Meta */); - } - } - else if (browser.isWebKit) { - define(91, 57 /* Meta */); - if (platform.isMacintosh) { - // the two meta keys in the Mac have different key codes (91 and 93) - define(93, 57 /* Meta */); - } - else { - define(92, 57 /* Meta */); - } - } - })(); - function extractKeyCode(e) { - if (e.charCode) { - // "keypress" events mostly - let char = String.fromCharCode(e.charCode).toUpperCase(); - return keyCodes_1.KeyCodeUtils.fromString(char); - } - return KEY_CODE_MAP[e.keyCode] || 0 /* Unknown */; - } - const ctrlKeyMod = (platform.isMacintosh ? 256 /* WinCtrl */ : 2048 /* CtrlCmd */); - const altKeyMod = 512 /* Alt */; - const shiftKeyMod = 1024 /* Shift */; - const metaKeyMod = (platform.isMacintosh ? 2048 /* CtrlCmd */ : 256 /* WinCtrl */); - class StandardKeyboardEvent { - constructor(source) { - this._standardKeyboardEventBrand = true; - let e = source; - this.browserEvent = e; - this.target = e.target; - this.ctrlKey = e.ctrlKey; - this.shiftKey = e.shiftKey; - this.altKey = e.altKey; - this.metaKey = e.metaKey; - this.keyCode = extractKeyCode(e); - this.code = e.code; - // console.info(e.type + ": keyCode: " + e.keyCode + ", which: " + e.which + ", charCode: " + e.charCode + ", detail: " + e.detail + " ====> " + this.keyCode + ' -- ' + KeyCode[this.keyCode]); - this.ctrlKey = this.ctrlKey || this.keyCode === 5 /* Ctrl */; - this.altKey = this.altKey || this.keyCode === 6 /* Alt */; - this.shiftKey = this.shiftKey || this.keyCode === 4 /* Shift */; - this.metaKey = this.metaKey || this.keyCode === 57 /* Meta */; - this._asKeybinding = this._computeKeybinding(); - this._asRuntimeKeybinding = this._computeRuntimeKeybinding(); - // console.log(`code: ${e.code}, keyCode: ${e.keyCode}, key: ${e.key}`); - } - preventDefault() { - if (this.browserEvent && this.browserEvent.preventDefault) { - this.browserEvent.preventDefault(); - } - } - stopPropagation() { - if (this.browserEvent && this.browserEvent.stopPropagation) { - this.browserEvent.stopPropagation(); - } - } - toKeybinding() { - return this._asRuntimeKeybinding; - } - equals(other) { - return this._asKeybinding === other; - } - _computeKeybinding() { - let key = 0 /* Unknown */; - if (this.keyCode !== 5 /* Ctrl */ && this.keyCode !== 4 /* Shift */ && this.keyCode !== 6 /* Alt */ && this.keyCode !== 57 /* Meta */) { - key = this.keyCode; - } - let result = 0; - if (this.ctrlKey) { - result |= ctrlKeyMod; - } - if (this.altKey) { - result |= altKeyMod; - } - if (this.shiftKey) { - result |= shiftKeyMod; - } - if (this.metaKey) { - result |= metaKeyMod; - } - result |= key; - return result; - } - _computeRuntimeKeybinding() { - let key = 0 /* Unknown */; - if (this.keyCode !== 5 /* Ctrl */ && this.keyCode !== 4 /* Shift */ && this.keyCode !== 6 /* Alt */ && this.keyCode !== 57 /* Meta */) { - key = this.keyCode; - } - return new keyCodes_1.SimpleKeybinding(this.ctrlKey, this.shiftKey, this.altKey, this.metaKey, key); - } - } - exports.StandardKeyboardEvent = StandardKeyboardEvent; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[55/*vs/base/browser/mouseEvent*/], __M([0/*require*/,1/*exports*/,39/*vs/base/browser/browser*/,196/*vs/base/browser/iframe*/,17/*vs/base/common/platform*/]), function (require, exports, browser, iframe_1, platform) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.StandardWheelEvent = exports.StandardMouseEvent = void 0; - class StandardMouseEvent { - constructor(e) { - this.timestamp = Date.now(); - this.browserEvent = e; - this.leftButton = e.button === 0; - this.middleButton = e.button === 1; - this.rightButton = e.button === 2; - this.buttons = e.buttons; - this.target = e.target; - this.detail = e.detail || 1; - if (e.type === 'dblclick') { - this.detail = 2; - } - this.ctrlKey = e.ctrlKey; - this.shiftKey = e.shiftKey; - this.altKey = e.altKey; - this.metaKey = e.metaKey; - if (typeof e.pageX === 'number') { - this.posx = e.pageX; - this.posy = e.pageY; - } - else { - // Probably hit by MSGestureEvent - this.posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; - this.posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; - } - // Find the position of the iframe this code is executing in relative to the iframe where the event was captured. - let iframeOffsets = iframe_1.IframeUtils.getPositionOfChildWindowRelativeToAncestorWindow(self, e.view); - this.posx -= iframeOffsets.left; - this.posy -= iframeOffsets.top; - } - preventDefault() { - this.browserEvent.preventDefault(); - } - stopPropagation() { - this.browserEvent.stopPropagation(); - } - } - exports.StandardMouseEvent = StandardMouseEvent; - class StandardWheelEvent { - constructor(e, deltaX = 0, deltaY = 0) { - this.browserEvent = e || null; - this.target = e ? (e.target || e.targetNode || e.srcElement) : null; - this.deltaY = deltaY; - this.deltaX = deltaX; - if (e) { - // Old (deprecated) wheel events - let e1 = e; - let e2 = e; - // vertical delta scroll - if (typeof e1.wheelDeltaY !== 'undefined') { - this.deltaY = e1.wheelDeltaY / 120; - } - else if (typeof e2.VERTICAL_AXIS !== 'undefined' && e2.axis === e2.VERTICAL_AXIS) { - this.deltaY = -e2.detail / 3; - } - else if (e.type === 'wheel') { - // Modern wheel event - // https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent - const ev = e; - if (ev.deltaMode === ev.DOM_DELTA_LINE) { - // the deltas are expressed in lines - if (browser.isFirefox && !platform.isMacintosh) { - this.deltaY = -e.deltaY / 3; - } - else { - this.deltaY = -e.deltaY; - } - } - else { - this.deltaY = -e.deltaY / 40; - } - } - // horizontal delta scroll - if (typeof e1.wheelDeltaX !== 'undefined') { - if (browser.isSafari && platform.isWindows) { - this.deltaX = -(e1.wheelDeltaX / 120); - } - else { - this.deltaX = e1.wheelDeltaX / 120; - } - } - else if (typeof e2.HORIZONTAL_AXIS !== 'undefined' && e2.axis === e2.HORIZONTAL_AXIS) { - this.deltaX = -e.detail / 3; - } - else if (e.type === 'wheel') { - // Modern wheel event - // https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent - const ev = e; - if (ev.deltaMode === ev.DOM_DELTA_LINE) { - // the deltas are expressed in lines - if (browser.isFirefox && !platform.isMacintosh) { - this.deltaX = -e.deltaX / 3; - } - else { - this.deltaX = -e.deltaX; - } - } - else { - this.deltaX = -e.deltaX / 40; - } - } - // Assume a vertical scroll if nothing else worked - if (this.deltaY === 0 && this.deltaX === 0 && e.wheelDelta) { - this.deltaY = e.wheelDelta / 120; - } - } - } - preventDefault() { - if (this.browserEvent) { - this.browserEvent.preventDefault(); - } - } - stopPropagation() { - if (this.browserEvent) { - this.browserEvent.stopPropagation(); - } - } - } - exports.StandardWheelEvent = StandardWheelEvent; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/common/cancellation*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/]), function (require, exports, event_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CancellationTokenSource = exports.CancellationToken = void 0; - const shortcutEvent = Object.freeze(function (callback, context) { - const handle = setTimeout(callback.bind(context), 0); - return { dispose() { clearTimeout(handle); } }; - }); - var CancellationToken; - (function (CancellationToken) { - function isCancellationToken(thing) { - if (thing === CancellationToken.None || thing === CancellationToken.Cancelled) { - return true; - } - if (thing instanceof MutableToken) { - return true; - } - if (!thing || typeof thing !== 'object') { - return false; - } - return typeof thing.isCancellationRequested === 'boolean' - && typeof thing.onCancellationRequested === 'function'; - } - CancellationToken.isCancellationToken = isCancellationToken; - CancellationToken.None = Object.freeze({ - isCancellationRequested: false, - onCancellationRequested: event_1.Event.None - }); - CancellationToken.Cancelled = Object.freeze({ - isCancellationRequested: true, - onCancellationRequested: shortcutEvent - }); - })(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {})); - class MutableToken { - constructor() { - this._isCancelled = false; - this._emitter = null; - } - cancel() { - if (!this._isCancelled) { - this._isCancelled = true; - if (this._emitter) { - this._emitter.fire(undefined); - this.dispose(); - } - } - } - get isCancellationRequested() { - return this._isCancelled; - } - get onCancellationRequested() { - if (this._isCancelled) { - return shortcutEvent; - } - if (!this._emitter) { - this._emitter = new event_1.Emitter(); - } - return this._emitter.event; - } - dispose() { - if (this._emitter) { - this._emitter.dispose(); - this._emitter = null; - } - } - } - class CancellationTokenSource { - constructor(parent) { - this._token = undefined; - this._parentListener = undefined; - this._parentListener = parent && parent.onCancellationRequested(this.cancel, this); - } - get token() { - if (!this._token) { - // be lazy and create the token only when - // actually needed - this._token = new MutableToken(); - } - return this._token; - } - cancel() { - if (!this._token) { - // save an object by returning the default - // cancelled token when cancellation happens - // before someone asks for the token - this._token = CancellationToken.Cancelled; - } - else if (this._token instanceof MutableToken) { - // actually cancel - this._token.cancel(); - } - } - dispose(cancel = false) { - if (cancel) { - this.cancel(); - } - if (this._parentListener) { - this._parentListener.dispose(); - } - if (!this._token) { - // ensure to initialize with an empty token if we had none - this._token = CancellationToken.None; - } - else if (this._token instanceof MutableToken) { - // actually dispose - this._token.dispose(); - } - } - } - exports.CancellationTokenSource = CancellationTokenSource; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -define(__m[15/*vs/base/common/async*/], __M([0/*require*/,1/*exports*/,23/*vs/base/common/cancellation*/,12/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/]), function (require, exports, cancellation_1, errors_1, lifecycle_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Promises = exports.IdleValue = exports.runWhenIdle = exports.RunOnceScheduler = exports.IntervalTimer = exports.TimeoutTimer = exports.first = exports.disposableTimeout = exports.timeout = exports.ThrottledDelayer = exports.Delayer = exports.Throttler = exports.raceCancellation = exports.createCancelablePromise = exports.isThenable = void 0; - function isThenable(obj) { - return !!obj && typeof obj.then === 'function'; - } - exports.isThenable = isThenable; - function createCancelablePromise(callback) { - const source = new cancellation_1.CancellationTokenSource(); - const thenable = callback(source.token); - const promise = new Promise((resolve, reject) => { - const subscription = source.token.onCancellationRequested(() => { - subscription.dispose(); - source.dispose(); - reject((0, errors_1.canceled)()); - }); - Promise.resolve(thenable).then(value => { - subscription.dispose(); - source.dispose(); - resolve(value); - }, err => { - subscription.dispose(); - source.dispose(); - reject(err); - }); - }); - return new class { - cancel() { - source.cancel(); - } - then(resolve, reject) { - return promise.then(resolve, reject); - } - catch(reject) { - return this.then(undefined, reject); - } - finally(onfinally) { - return promise.finally(onfinally); - } - }; - } - exports.createCancelablePromise = createCancelablePromise; - function raceCancellation(promise, token, defaultValue) { - return Promise.race([promise, new Promise(resolve => token.onCancellationRequested(() => resolve(defaultValue)))]); - } - exports.raceCancellation = raceCancellation; - /** - * A helper to prevent accumulation of sequential async tasks. - * - * Imagine a mail man with the sole task of delivering letters. As soon as - * a letter submitted for delivery, he drives to the destination, delivers it - * and returns to his base. Imagine that during the trip, N more letters were submitted. - * When the mail man returns, he picks those N letters and delivers them all in a - * single trip. Even though N+1 submissions occurred, only 2 deliveries were made. - * - * The throttler implements this via the queue() method, by providing it a task - * factory. Following the example: - * - * const throttler = new Throttler(); - * const letters = []; - * - * function deliver() { - * const lettersToDeliver = letters; - * letters = []; - * return makeTheTrip(lettersToDeliver); - * } - * - * function onLetterReceived(l) { - * letters.push(l); - * throttler.queue(deliver); - * } - */ - class Throttler { - constructor() { - this.activePromise = null; - this.queuedPromise = null; - this.queuedPromiseFactory = null; - } - queue(promiseFactory) { - if (this.activePromise) { - this.queuedPromiseFactory = promiseFactory; - if (!this.queuedPromise) { - const onComplete = () => { - this.queuedPromise = null; - const result = this.queue(this.queuedPromiseFactory); - this.queuedPromiseFactory = null; - return result; - }; - this.queuedPromise = new Promise(resolve => { - this.activePromise.then(onComplete, onComplete).then(resolve); - }); - } - return new Promise((resolve, reject) => { - this.queuedPromise.then(resolve, reject); - }); - } - this.activePromise = promiseFactory(); - return new Promise((resolve, reject) => { - this.activePromise.then((result) => { - this.activePromise = null; - resolve(result); - }, (err) => { - this.activePromise = null; - reject(err); - }); - }); - } - } - exports.Throttler = Throttler; - /** - * A helper to delay (debounce) execution of a task that is being requested often. - * - * Following the throttler, now imagine the mail man wants to optimize the number of - * trips proactively. The trip itself can be long, so he decides not to make the trip - * as soon as a letter is submitted. Instead he waits a while, in case more - * letters are submitted. After said waiting period, if no letters were submitted, he - * decides to make the trip. Imagine that N more letters were submitted after the first - * one, all within a short period of time between each other. Even though N+1 - * submissions occurred, only 1 delivery was made. - * - * The delayer offers this behavior via the trigger() method, into which both the task - * to be executed and the waiting period (delay) must be passed in as arguments. Following - * the example: - * - * const delayer = new Delayer(WAITING_PERIOD); - * const letters = []; - * - * function letterReceived(l) { - * letters.push(l); - * delayer.trigger(() => { return makeTheTrip(); }); - * } - */ - class Delayer { - constructor(defaultDelay) { - this.defaultDelay = defaultDelay; - this.timeout = null; - this.completionPromise = null; - this.doResolve = null; - this.doReject = null; - this.task = null; - } - trigger(task, delay = this.defaultDelay) { - this.task = task; - this.cancelTimeout(); - if (!this.completionPromise) { - this.completionPromise = new Promise((resolve, reject) => { - this.doResolve = resolve; - this.doReject = reject; - }).then(() => { - this.completionPromise = null; - this.doResolve = null; - if (this.task) { - const task = this.task; - this.task = null; - return task(); - } - return undefined; - }); - } - this.timeout = setTimeout(() => { - this.timeout = null; - if (this.doResolve) { - this.doResolve(null); - } - }, delay); - return this.completionPromise; - } - isTriggered() { - return this.timeout !== null; - } - cancel() { - this.cancelTimeout(); - if (this.completionPromise) { - if (this.doReject) { - this.doReject((0, errors_1.canceled)()); - } - this.completionPromise = null; - } - } - cancelTimeout() { - if (this.timeout !== null) { - clearTimeout(this.timeout); - this.timeout = null; - } - } - dispose() { - this.cancel(); - } - } - exports.Delayer = Delayer; - /** - * A helper to delay execution of a task that is being requested often, while - * preventing accumulation of consecutive executions, while the task runs. - * - * The mail man is clever and waits for a certain amount of time, before going - * out to deliver letters. While the mail man is going out, more letters arrive - * and can only be delivered once he is back. Once he is back the mail man will - * do one more trip to deliver the letters that have accumulated while he was out. - */ - class ThrottledDelayer { - constructor(defaultDelay) { - this.delayer = new Delayer(defaultDelay); - this.throttler = new Throttler(); - } - trigger(promiseFactory, delay) { - return this.delayer.trigger(() => this.throttler.queue(promiseFactory), delay); - } - dispose() { - this.delayer.dispose(); - } - } - exports.ThrottledDelayer = ThrottledDelayer; - function timeout(millis, token) { - if (!token) { - return createCancelablePromise(token => timeout(millis, token)); - } - return new Promise((resolve, reject) => { - const handle = setTimeout(() => { - disposable.dispose(); - resolve(); - }, millis); - const disposable = token.onCancellationRequested(() => { - clearTimeout(handle); - disposable.dispose(); - reject((0, errors_1.canceled)()); - }); - }); - } - exports.timeout = timeout; - function disposableTimeout(handler, timeout = 0) { - const timer = setTimeout(handler, timeout); - return (0, lifecycle_1.toDisposable)(() => clearTimeout(timer)); - } - exports.disposableTimeout = disposableTimeout; - function first(promiseFactories, shouldStop = t => !!t, defaultValue = null) { - let index = 0; - const len = promiseFactories.length; - const loop = () => { - if (index >= len) { - return Promise.resolve(defaultValue); - } - const factory = promiseFactories[index++]; - const promise = Promise.resolve(factory()); - return promise.then(result => { - if (shouldStop(result)) { - return Promise.resolve(result); - } - return loop(); - }); - }; - return loop(); - } - exports.first = first; - class TimeoutTimer { - constructor(runner, timeout) { - this._token = -1; - if (typeof runner === 'function' && typeof timeout === 'number') { - this.setIfNotSet(runner, timeout); - } - } - dispose() { - this.cancel(); - } - cancel() { - if (this._token !== -1) { - clearTimeout(this._token); - this._token = -1; - } - } - cancelAndSet(runner, timeout) { - this.cancel(); - this._token = setTimeout(() => { - this._token = -1; - runner(); - }, timeout); - } - setIfNotSet(runner, timeout) { - if (this._token !== -1) { - // timer is already set - return; - } - this._token = setTimeout(() => { - this._token = -1; - runner(); - }, timeout); - } - } - exports.TimeoutTimer = TimeoutTimer; - class IntervalTimer { - constructor() { - this._token = -1; - } - dispose() { - this.cancel(); - } - cancel() { - if (this._token !== -1) { - clearInterval(this._token); - this._token = -1; - } - } - cancelAndSet(runner, interval) { - this.cancel(); - this._token = setInterval(() => { - runner(); - }, interval); - } - } - exports.IntervalTimer = IntervalTimer; - class RunOnceScheduler { - constructor(runner, delay) { - this.timeoutToken = -1; - this.runner = runner; - this.timeout = delay; - this.timeoutHandler = this.onTimeout.bind(this); - } - /** - * Dispose RunOnceScheduler - */ - dispose() { - this.cancel(); - this.runner = null; - } - /** - * Cancel current scheduled runner (if any). - */ - cancel() { - if (this.isScheduled()) { - clearTimeout(this.timeoutToken); - this.timeoutToken = -1; - } - } - /** - * Cancel previous runner (if any) & schedule a new runner. - */ - schedule(delay = this.timeout) { - this.cancel(); - this.timeoutToken = setTimeout(this.timeoutHandler, delay); - } - get delay() { - return this.timeout; - } - set delay(value) { - this.timeout = value; - } - /** - * Returns true if scheduled. - */ - isScheduled() { - return this.timeoutToken !== -1; - } - onTimeout() { - this.timeoutToken = -1; - if (this.runner) { - this.doRun(); - } - } - doRun() { - if (this.runner) { - this.runner(); - } - } - } - exports.RunOnceScheduler = RunOnceScheduler; - (function () { - if (typeof requestIdleCallback !== 'function' || typeof cancelIdleCallback !== 'function') { - const dummyIdle = Object.freeze({ - didTimeout: true, - timeRemaining() { return 15; } - }); - exports.runWhenIdle = (runner) => { - const handle = setTimeout(() => runner(dummyIdle)); - let disposed = false; - return { - dispose() { - if (disposed) { - return; - } - disposed = true; - clearTimeout(handle); - } - }; - }; - } - else { - exports.runWhenIdle = (runner, timeout) => { - const handle = requestIdleCallback(runner, typeof timeout === 'number' ? { timeout } : undefined); - let disposed = false; - return { - dispose() { - if (disposed) { - return; - } - disposed = true; - cancelIdleCallback(handle); - } - }; - }; - } - })(); - /** - * An implementation of the "idle-until-urgent"-strategy as introduced - * here: https://philipwalton.com/articles/idle-until-urgent/ - */ - class IdleValue { - constructor(executor) { - this._didRun = false; - this._executor = () => { - try { - this._value = executor(); - } - catch (err) { - this._error = err; - } - finally { - this._didRun = true; - } - }; - this._handle = (0, exports.runWhenIdle)(() => this._executor()); - } - dispose() { - this._handle.dispose(); - } - get value() { - if (!this._didRun) { - this._handle.dispose(); - this._executor(); - } - if (this._error) { - throw this._error; - } - return this._value; - } - } - exports.IdleValue = IdleValue; - //#endregion - //#region Promises - var Promises; - (function (Promises) { - /** - * A drop-in replacement for `Promise.all` with the only difference - * that the method awaits every promise to either fulfill or reject. - * - * Similar to `Promise.all`, only the first error will be returned - * if any. - */ - function settled(promises) { - return __awaiter(this, void 0, void 0, function* () { - let firstError = undefined; - const result = yield Promise.all(promises.map(promise => promise.then(value => value, error => { - if (!firstError) { - firstError = error; - } - return undefined; // do not rethrow so that other promises can settle - }))); - if (typeof firstError !== 'undefined') { - throw firstError; - } - return result; // cast is needed and protected by the `throw` above - }); - } - Promises.settled = settled; - })(Promises = exports.Promises || (exports.Promises = {})); -}); -//#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[290/*vs/base/browser/ui/scrollbar/scrollbarVisibilityController*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/]), function (require, exports, async_1, lifecycle_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ScrollbarVisibilityController = void 0; - class ScrollbarVisibilityController extends lifecycle_1.Disposable { - constructor(visibility, visibleClassName, invisibleClassName) { - super(); - this._visibility = visibility; - this._visibleClassName = visibleClassName; - this._invisibleClassName = invisibleClassName; - this._domNode = null; - this._isVisible = false; - this._isNeeded = false; - this._rawShouldBeVisible = false; - this._shouldBeVisible = false; - this._revealTimer = this._register(new async_1.TimeoutTimer()); - } - setVisibility(visibility) { - if (this._visibility !== visibility) { - this._visibility = visibility; - this._updateShouldBeVisible(); - } - } - // ----------------- Hide / Reveal - setShouldBeVisible(rawShouldBeVisible) { - this._rawShouldBeVisible = rawShouldBeVisible; - this._updateShouldBeVisible(); - } - _applyVisibilitySetting() { - if (this._visibility === 2 /* Hidden */) { - return false; - } - if (this._visibility === 3 /* Visible */) { - return true; - } - return this._rawShouldBeVisible; - } - _updateShouldBeVisible() { - const shouldBeVisible = this._applyVisibilitySetting(); - if (this._shouldBeVisible !== shouldBeVisible) { - this._shouldBeVisible = shouldBeVisible; - this.ensureVisibility(); - } - } - setIsNeeded(isNeeded) { - if (this._isNeeded !== isNeeded) { - this._isNeeded = isNeeded; - this.ensureVisibility(); - } - } - setDomNode(domNode) { - this._domNode = domNode; - this._domNode.setClassName(this._invisibleClassName); - // Now that the flags & the dom node are in a consistent state, ensure the Hidden/Visible configuration - this.setShouldBeVisible(false); - } - ensureVisibility() { - if (!this._isNeeded) { - // Nothing to be rendered - this._hide(false); - return; - } - if (this._shouldBeVisible) { - this._reveal(); - } - else { - this._hide(true); - } - } - _reveal() { - if (this._isVisible) { - return; - } - this._isVisible = true; - // The CSS animation doesn't play otherwise - this._revealTimer.setIfNotSet(() => { - if (this._domNode) { - this._domNode.setClassName(this._visibleClassName); - } - }, 0); - } - _hide(withFadeAway) { - this._revealTimer.cancel(); - if (!this._isVisible) { - return; - } - this._isVisible = false; - if (this._domNode) { - this._domNode.setClassName(this._invisibleClassName + (withFadeAway ? ' fade' : '')); - } - } - } - exports.ScrollbarVisibilityController = ScrollbarVisibilityController; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[27/*vs/base/common/codicons*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/]), function (require, exports, event_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CSSIcon = exports.Codicon = exports.getCodiconAriaLabel = exports.registerCodicon = exports.iconRegistry = void 0; - class Registry { - constructor() { - this._icons = new Map(); - this._onDidRegister = new event_1.Emitter(); - } - add(icon) { - const existing = this._icons.get(icon.id); - if (!existing) { - this._icons.set(icon.id, icon); - this._onDidRegister.fire(icon); - } - else if (icon.description) { - existing.description = icon.description; - } - else { - console.error(`Duplicate registration of codicon ${icon.id}`); - } - } - get(id) { - return this._icons.get(id); - } - get all() { - return this._icons.values(); - } - get onDidRegister() { - return this._onDidRegister.event; - } - } - const _registry = new Registry(); - exports.iconRegistry = _registry; - function registerCodicon(id, def) { - return new Codicon(id, def); - } - exports.registerCodicon = registerCodicon; - // Selects all codicon names encapsulated in the `$()` syntax and wraps the - // results with spaces so that screen readers can read the text better. - function getCodiconAriaLabel(text) { - if (!text) { - return ''; - } - return text.replace(/\$\((.*?)\)/g, (_match, codiconName) => ` ${codiconName} `).trim(); - } - exports.getCodiconAriaLabel = getCodiconAriaLabel; - class Codicon { - constructor(id, definition, description) { - this.id = id; - this.definition = definition; - this.description = description; - _registry.add(this); - } - get classNames() { return 'codicon codicon-' + this.id; } - // classNamesArray is useful for migrating to ES6 classlist - get classNamesArray() { return ['codicon', 'codicon-' + this.id]; } - get cssSelector() { return '.codicon.codicon-' + this.id; } - } - exports.Codicon = Codicon; - var CSSIcon; - (function (CSSIcon) { - CSSIcon.iconNameSegment = '[A-Za-z0-9]+'; - CSSIcon.iconNameExpression = '[A-Za-z0-9\\-]+'; - CSSIcon.iconModifierExpression = '~[A-Za-z]+'; - const cssIconIdRegex = new RegExp(`^(${CSSIcon.iconNameExpression})(${CSSIcon.iconModifierExpression})?$`); - function asClassNameArray(icon) { - if (icon instanceof Codicon) { - return ['codicon', 'codicon-' + icon.id]; - } - const match = cssIconIdRegex.exec(icon.id); - if (!match) { - return asClassNameArray(Codicon.error); - } - let [, id, modifier] = match; - const classNames = ['codicon', 'codicon-' + id]; - if (modifier) { - classNames.push('codicon-modifier-' + modifier.substr(1)); - } - return classNames; - } - CSSIcon.asClassNameArray = asClassNameArray; - function asClassName(icon) { - return asClassNameArray(icon).join(' '); - } - CSSIcon.asClassName = asClassName; - function asCSSSelector(icon) { - return '.' + asClassNameArray(icon).join('.'); - } - CSSIcon.asCSSSelector = asCSSSelector; - })(CSSIcon = exports.CSSIcon || (exports.CSSIcon = {})); - (function (Codicon) { - // built-in icons, with image name - Codicon.add = new Codicon('add', { fontCharacter: '\\ea60' }); - Codicon.plus = new Codicon('plus', { fontCharacter: '\\ea60' }); - Codicon.gistNew = new Codicon('gist-new', { fontCharacter: '\\ea60' }); - Codicon.repoCreate = new Codicon('repo-create', { fontCharacter: '\\ea60' }); - Codicon.lightbulb = new Codicon('lightbulb', { fontCharacter: '\\ea61' }); - Codicon.lightBulb = new Codicon('light-bulb', { fontCharacter: '\\ea61' }); - Codicon.repo = new Codicon('repo', { fontCharacter: '\\ea62' }); - Codicon.repoDelete = new Codicon('repo-delete', { fontCharacter: '\\ea62' }); - Codicon.gistFork = new Codicon('gist-fork', { fontCharacter: '\\ea63' }); - Codicon.repoForked = new Codicon('repo-forked', { fontCharacter: '\\ea63' }); - Codicon.gitPullRequest = new Codicon('git-pull-request', { fontCharacter: '\\ea64' }); - Codicon.gitPullRequestAbandoned = new Codicon('git-pull-request-abandoned', { fontCharacter: '\\ea64' }); - Codicon.recordKeys = new Codicon('record-keys', { fontCharacter: '\\ea65' }); - Codicon.keyboard = new Codicon('keyboard', { fontCharacter: '\\ea65' }); - Codicon.tag = new Codicon('tag', { fontCharacter: '\\ea66' }); - Codicon.tagAdd = new Codicon('tag-add', { fontCharacter: '\\ea66' }); - Codicon.tagRemove = new Codicon('tag-remove', { fontCharacter: '\\ea66' }); - Codicon.person = new Codicon('person', { fontCharacter: '\\ea67' }); - Codicon.personFollow = new Codicon('person-follow', { fontCharacter: '\\ea67' }); - Codicon.personOutline = new Codicon('person-outline', { fontCharacter: '\\ea67' }); - Codicon.personFilled = new Codicon('person-filled', { fontCharacter: '\\ea67' }); - Codicon.gitBranch = new Codicon('git-branch', { fontCharacter: '\\ea68' }); - Codicon.gitBranchCreate = new Codicon('git-branch-create', { fontCharacter: '\\ea68' }); - Codicon.gitBranchDelete = new Codicon('git-branch-delete', { fontCharacter: '\\ea68' }); - Codicon.sourceControl = new Codicon('source-control', { fontCharacter: '\\ea68' }); - Codicon.mirror = new Codicon('mirror', { fontCharacter: '\\ea69' }); - Codicon.mirrorPublic = new Codicon('mirror-public', { fontCharacter: '\\ea69' }); - Codicon.star = new Codicon('star', { fontCharacter: '\\ea6a' }); - Codicon.starAdd = new Codicon('star-add', { fontCharacter: '\\ea6a' }); - Codicon.starDelete = new Codicon('star-delete', { fontCharacter: '\\ea6a' }); - Codicon.starEmpty = new Codicon('star-empty', { fontCharacter: '\\ea6a' }); - Codicon.comment = new Codicon('comment', { fontCharacter: '\\ea6b' }); - Codicon.commentAdd = new Codicon('comment-add', { fontCharacter: '\\ea6b' }); - Codicon.alert = new Codicon('alert', { fontCharacter: '\\ea6c' }); - Codicon.warning = new Codicon('warning', { fontCharacter: '\\ea6c' }); - Codicon.search = new Codicon('search', { fontCharacter: '\\ea6d' }); - Codicon.searchSave = new Codicon('search-save', { fontCharacter: '\\ea6d' }); - Codicon.logOut = new Codicon('log-out', { fontCharacter: '\\ea6e' }); - Codicon.signOut = new Codicon('sign-out', { fontCharacter: '\\ea6e' }); - Codicon.logIn = new Codicon('log-in', { fontCharacter: '\\ea6f' }); - Codicon.signIn = new Codicon('sign-in', { fontCharacter: '\\ea6f' }); - Codicon.eye = new Codicon('eye', { fontCharacter: '\\ea70' }); - Codicon.eyeUnwatch = new Codicon('eye-unwatch', { fontCharacter: '\\ea70' }); - Codicon.eyeWatch = new Codicon('eye-watch', { fontCharacter: '\\ea70' }); - Codicon.circleFilled = new Codicon('circle-filled', { fontCharacter: '\\ea71' }); - Codicon.primitiveDot = new Codicon('primitive-dot', { fontCharacter: '\\ea71' }); - Codicon.closeDirty = new Codicon('close-dirty', { fontCharacter: '\\ea71' }); - Codicon.debugBreakpoint = new Codicon('debug-breakpoint', { fontCharacter: '\\ea71' }); - Codicon.debugBreakpointDisabled = new Codicon('debug-breakpoint-disabled', { fontCharacter: '\\ea71' }); - Codicon.debugHint = new Codicon('debug-hint', { fontCharacter: '\\ea71' }); - Codicon.primitiveSquare = new Codicon('primitive-square', { fontCharacter: '\\ea72' }); - Codicon.edit = new Codicon('edit', { fontCharacter: '\\ea73' }); - Codicon.pencil = new Codicon('pencil', { fontCharacter: '\\ea73' }); - Codicon.info = new Codicon('info', { fontCharacter: '\\ea74' }); - Codicon.issueOpened = new Codicon('issue-opened', { fontCharacter: '\\ea74' }); - Codicon.gistPrivate = new Codicon('gist-private', { fontCharacter: '\\ea75' }); - Codicon.gitForkPrivate = new Codicon('git-fork-private', { fontCharacter: '\\ea75' }); - Codicon.lock = new Codicon('lock', { fontCharacter: '\\ea75' }); - Codicon.mirrorPrivate = new Codicon('mirror-private', { fontCharacter: '\\ea75' }); - Codicon.close = new Codicon('close', { fontCharacter: '\\ea76' }); - Codicon.removeClose = new Codicon('remove-close', { fontCharacter: '\\ea76' }); - Codicon.x = new Codicon('x', { fontCharacter: '\\ea76' }); - Codicon.repoSync = new Codicon('repo-sync', { fontCharacter: '\\ea77' }); - Codicon.sync = new Codicon('sync', { fontCharacter: '\\ea77' }); - Codicon.clone = new Codicon('clone', { fontCharacter: '\\ea78' }); - Codicon.desktopDownload = new Codicon('desktop-download', { fontCharacter: '\\ea78' }); - Codicon.beaker = new Codicon('beaker', { fontCharacter: '\\ea79' }); - Codicon.microscope = new Codicon('microscope', { fontCharacter: '\\ea79' }); - Codicon.vm = new Codicon('vm', { fontCharacter: '\\ea7a' }); - Codicon.deviceDesktop = new Codicon('device-desktop', { fontCharacter: '\\ea7a' }); - Codicon.file = new Codicon('file', { fontCharacter: '\\ea7b' }); - Codicon.fileText = new Codicon('file-text', { fontCharacter: '\\ea7b' }); - Codicon.more = new Codicon('more', { fontCharacter: '\\ea7c' }); - Codicon.ellipsis = new Codicon('ellipsis', { fontCharacter: '\\ea7c' }); - Codicon.kebabHorizontal = new Codicon('kebab-horizontal', { fontCharacter: '\\ea7c' }); - Codicon.mailReply = new Codicon('mail-reply', { fontCharacter: '\\ea7d' }); - Codicon.reply = new Codicon('reply', { fontCharacter: '\\ea7d' }); - Codicon.organization = new Codicon('organization', { fontCharacter: '\\ea7e' }); - Codicon.organizationFilled = new Codicon('organization-filled', { fontCharacter: '\\ea7e' }); - Codicon.organizationOutline = new Codicon('organization-outline', { fontCharacter: '\\ea7e' }); - Codicon.newFile = new Codicon('new-file', { fontCharacter: '\\ea7f' }); - Codicon.fileAdd = new Codicon('file-add', { fontCharacter: '\\ea7f' }); - Codicon.newFolder = new Codicon('new-folder', { fontCharacter: '\\ea80' }); - Codicon.fileDirectoryCreate = new Codicon('file-directory-create', { fontCharacter: '\\ea80' }); - Codicon.trash = new Codicon('trash', { fontCharacter: '\\ea81' }); - Codicon.trashcan = new Codicon('trashcan', { fontCharacter: '\\ea81' }); - Codicon.history = new Codicon('history', { fontCharacter: '\\ea82' }); - Codicon.clock = new Codicon('clock', { fontCharacter: '\\ea82' }); - Codicon.folder = new Codicon('folder', { fontCharacter: '\\ea83' }); - Codicon.fileDirectory = new Codicon('file-directory', { fontCharacter: '\\ea83' }); - Codicon.symbolFolder = new Codicon('symbol-folder', { fontCharacter: '\\ea83' }); - Codicon.logoGithub = new Codicon('logo-github', { fontCharacter: '\\ea84' }); - Codicon.markGithub = new Codicon('mark-github', { fontCharacter: '\\ea84' }); - Codicon.github = new Codicon('github', { fontCharacter: '\\ea84' }); - Codicon.terminal = new Codicon('terminal', { fontCharacter: '\\ea85' }); - Codicon.console = new Codicon('console', { fontCharacter: '\\ea85' }); - Codicon.repl = new Codicon('repl', { fontCharacter: '\\ea85' }); - Codicon.zap = new Codicon('zap', { fontCharacter: '\\ea86' }); - Codicon.symbolEvent = new Codicon('symbol-event', { fontCharacter: '\\ea86' }); - Codicon.error = new Codicon('error', { fontCharacter: '\\ea87' }); - Codicon.stop = new Codicon('stop', { fontCharacter: '\\ea87' }); - Codicon.variable = new Codicon('variable', { fontCharacter: '\\ea88' }); - Codicon.symbolVariable = new Codicon('symbol-variable', { fontCharacter: '\\ea88' }); - Codicon.array = new Codicon('array', { fontCharacter: '\\ea8a' }); - Codicon.symbolArray = new Codicon('symbol-array', { fontCharacter: '\\ea8a' }); - Codicon.symbolModule = new Codicon('symbol-module', { fontCharacter: '\\ea8b' }); - Codicon.symbolPackage = new Codicon('symbol-package', { fontCharacter: '\\ea8b' }); - Codicon.symbolNamespace = new Codicon('symbol-namespace', { fontCharacter: '\\ea8b' }); - Codicon.symbolObject = new Codicon('symbol-object', { fontCharacter: '\\ea8b' }); - Codicon.symbolMethod = new Codicon('symbol-method', { fontCharacter: '\\ea8c' }); - Codicon.symbolFunction = new Codicon('symbol-function', { fontCharacter: '\\ea8c' }); - Codicon.symbolConstructor = new Codicon('symbol-constructor', { fontCharacter: '\\ea8c' }); - Codicon.symbolBoolean = new Codicon('symbol-boolean', { fontCharacter: '\\ea8f' }); - Codicon.symbolNull = new Codicon('symbol-null', { fontCharacter: '\\ea8f' }); - Codicon.symbolNumeric = new Codicon('symbol-numeric', { fontCharacter: '\\ea90' }); - Codicon.symbolNumber = new Codicon('symbol-number', { fontCharacter: '\\ea90' }); - Codicon.symbolStructure = new Codicon('symbol-structure', { fontCharacter: '\\ea91' }); - Codicon.symbolStruct = new Codicon('symbol-struct', { fontCharacter: '\\ea91' }); - Codicon.symbolParameter = new Codicon('symbol-parameter', { fontCharacter: '\\ea92' }); - Codicon.symbolTypeParameter = new Codicon('symbol-type-parameter', { fontCharacter: '\\ea92' }); - Codicon.symbolKey = new Codicon('symbol-key', { fontCharacter: '\\ea93' }); - Codicon.symbolText = new Codicon('symbol-text', { fontCharacter: '\\ea93' }); - Codicon.symbolReference = new Codicon('symbol-reference', { fontCharacter: '\\ea94' }); - Codicon.goToFile = new Codicon('go-to-file', { fontCharacter: '\\ea94' }); - Codicon.symbolEnum = new Codicon('symbol-enum', { fontCharacter: '\\ea95' }); - Codicon.symbolValue = new Codicon('symbol-value', { fontCharacter: '\\ea95' }); - Codicon.symbolRuler = new Codicon('symbol-ruler', { fontCharacter: '\\ea96' }); - Codicon.symbolUnit = new Codicon('symbol-unit', { fontCharacter: '\\ea96' }); - Codicon.activateBreakpoints = new Codicon('activate-breakpoints', { fontCharacter: '\\ea97' }); - Codicon.archive = new Codicon('archive', { fontCharacter: '\\ea98' }); - Codicon.arrowBoth = new Codicon('arrow-both', { fontCharacter: '\\ea99' }); - Codicon.arrowDown = new Codicon('arrow-down', { fontCharacter: '\\ea9a' }); - Codicon.arrowLeft = new Codicon('arrow-left', { fontCharacter: '\\ea9b' }); - Codicon.arrowRight = new Codicon('arrow-right', { fontCharacter: '\\ea9c' }); - Codicon.arrowSmallDown = new Codicon('arrow-small-down', { fontCharacter: '\\ea9d' }); - Codicon.arrowSmallLeft = new Codicon('arrow-small-left', { fontCharacter: '\\ea9e' }); - Codicon.arrowSmallRight = new Codicon('arrow-small-right', { fontCharacter: '\\ea9f' }); - Codicon.arrowSmallUp = new Codicon('arrow-small-up', { fontCharacter: '\\eaa0' }); - Codicon.arrowUp = new Codicon('arrow-up', { fontCharacter: '\\eaa1' }); - Codicon.bell = new Codicon('bell', { fontCharacter: '\\eaa2' }); - Codicon.bold = new Codicon('bold', { fontCharacter: '\\eaa3' }); - Codicon.book = new Codicon('book', { fontCharacter: '\\eaa4' }); - Codicon.bookmark = new Codicon('bookmark', { fontCharacter: '\\eaa5' }); - Codicon.debugBreakpointConditionalUnverified = new Codicon('debug-breakpoint-conditional-unverified', { fontCharacter: '\\eaa6' }); - Codicon.debugBreakpointConditional = new Codicon('debug-breakpoint-conditional', { fontCharacter: '\\eaa7' }); - Codicon.debugBreakpointConditionalDisabled = new Codicon('debug-breakpoint-conditional-disabled', { fontCharacter: '\\eaa7' }); - Codicon.debugBreakpointDataUnverified = new Codicon('debug-breakpoint-data-unverified', { fontCharacter: '\\eaa8' }); - Codicon.debugBreakpointData = new Codicon('debug-breakpoint-data', { fontCharacter: '\\eaa9' }); - Codicon.debugBreakpointDataDisabled = new Codicon('debug-breakpoint-data-disabled', { fontCharacter: '\\eaa9' }); - Codicon.debugBreakpointLogUnverified = new Codicon('debug-breakpoint-log-unverified', { fontCharacter: '\\eaaa' }); - Codicon.debugBreakpointLog = new Codicon('debug-breakpoint-log', { fontCharacter: '\\eaab' }); - Codicon.debugBreakpointLogDisabled = new Codicon('debug-breakpoint-log-disabled', { fontCharacter: '\\eaab' }); - Codicon.briefcase = new Codicon('briefcase', { fontCharacter: '\\eaac' }); - Codicon.broadcast = new Codicon('broadcast', { fontCharacter: '\\eaad' }); - Codicon.browser = new Codicon('browser', { fontCharacter: '\\eaae' }); - Codicon.bug = new Codicon('bug', { fontCharacter: '\\eaaf' }); - Codicon.calendar = new Codicon('calendar', { fontCharacter: '\\eab0' }); - Codicon.caseSensitive = new Codicon('case-sensitive', { fontCharacter: '\\eab1' }); - Codicon.check = new Codicon('check', { fontCharacter: '\\eab2' }); - Codicon.checklist = new Codicon('checklist', { fontCharacter: '\\eab3' }); - Codicon.chevronDown = new Codicon('chevron-down', { fontCharacter: '\\eab4' }); - Codicon.chevronLeft = new Codicon('chevron-left', { fontCharacter: '\\eab5' }); - Codicon.chevronRight = new Codicon('chevron-right', { fontCharacter: '\\eab6' }); - Codicon.chevronUp = new Codicon('chevron-up', { fontCharacter: '\\eab7' }); - Codicon.chromeClose = new Codicon('chrome-close', { fontCharacter: '\\eab8' }); - Codicon.chromeMaximize = new Codicon('chrome-maximize', { fontCharacter: '\\eab9' }); - Codicon.chromeMinimize = new Codicon('chrome-minimize', { fontCharacter: '\\eaba' }); - Codicon.chromeRestore = new Codicon('chrome-restore', { fontCharacter: '\\eabb' }); - Codicon.circleOutline = new Codicon('circle-outline', { fontCharacter: '\\eabc' }); - Codicon.debugBreakpointUnverified = new Codicon('debug-breakpoint-unverified', { fontCharacter: '\\eabc' }); - Codicon.circleSlash = new Codicon('circle-slash', { fontCharacter: '\\eabd' }); - Codicon.circuitBoard = new Codicon('circuit-board', { fontCharacter: '\\eabe' }); - Codicon.clearAll = new Codicon('clear-all', { fontCharacter: '\\eabf' }); - Codicon.clippy = new Codicon('clippy', { fontCharacter: '\\eac0' }); - Codicon.closeAll = new Codicon('close-all', { fontCharacter: '\\eac1' }); - Codicon.cloudDownload = new Codicon('cloud-download', { fontCharacter: '\\eac2' }); - Codicon.cloudUpload = new Codicon('cloud-upload', { fontCharacter: '\\eac3' }); - Codicon.code = new Codicon('code', { fontCharacter: '\\eac4' }); - Codicon.collapseAll = new Codicon('collapse-all', { fontCharacter: '\\eac5' }); - Codicon.colorMode = new Codicon('color-mode', { fontCharacter: '\\eac6' }); - Codicon.commentDiscussion = new Codicon('comment-discussion', { fontCharacter: '\\eac7' }); - Codicon.compareChanges = new Codicon('compare-changes', { fontCharacter: '\\eafd' }); - Codicon.creditCard = new Codicon('credit-card', { fontCharacter: '\\eac9' }); - Codicon.dash = new Codicon('dash', { fontCharacter: '\\eacc' }); - Codicon.dashboard = new Codicon('dashboard', { fontCharacter: '\\eacd' }); - Codicon.database = new Codicon('database', { fontCharacter: '\\eace' }); - Codicon.debugContinue = new Codicon('debug-continue', { fontCharacter: '\\eacf' }); - Codicon.debugDisconnect = new Codicon('debug-disconnect', { fontCharacter: '\\ead0' }); - Codicon.debugPause = new Codicon('debug-pause', { fontCharacter: '\\ead1' }); - Codicon.debugRestart = new Codicon('debug-restart', { fontCharacter: '\\ead2' }); - Codicon.debugStart = new Codicon('debug-start', { fontCharacter: '\\ead3' }); - Codicon.debugStepInto = new Codicon('debug-step-into', { fontCharacter: '\\ead4' }); - Codicon.debugStepOut = new Codicon('debug-step-out', { fontCharacter: '\\ead5' }); - Codicon.debugStepOver = new Codicon('debug-step-over', { fontCharacter: '\\ead6' }); - Codicon.debugStop = new Codicon('debug-stop', { fontCharacter: '\\ead7' }); - Codicon.debug = new Codicon('debug', { fontCharacter: '\\ead8' }); - Codicon.deviceCameraVideo = new Codicon('device-camera-video', { fontCharacter: '\\ead9' }); - Codicon.deviceCamera = new Codicon('device-camera', { fontCharacter: '\\eada' }); - Codicon.deviceMobile = new Codicon('device-mobile', { fontCharacter: '\\eadb' }); - Codicon.diffAdded = new Codicon('diff-added', { fontCharacter: '\\eadc' }); - Codicon.diffIgnored = new Codicon('diff-ignored', { fontCharacter: '\\eadd' }); - Codicon.diffModified = new Codicon('diff-modified', { fontCharacter: '\\eade' }); - Codicon.diffRemoved = new Codicon('diff-removed', { fontCharacter: '\\eadf' }); - Codicon.diffRenamed = new Codicon('diff-renamed', { fontCharacter: '\\eae0' }); - Codicon.diff = new Codicon('diff', { fontCharacter: '\\eae1' }); - Codicon.discard = new Codicon('discard', { fontCharacter: '\\eae2' }); - Codicon.editorLayout = new Codicon('editor-layout', { fontCharacter: '\\eae3' }); - Codicon.emptyWindow = new Codicon('empty-window', { fontCharacter: '\\eae4' }); - Codicon.exclude = new Codicon('exclude', { fontCharacter: '\\eae5' }); - Codicon.extensions = new Codicon('extensions', { fontCharacter: '\\eae6' }); - Codicon.eyeClosed = new Codicon('eye-closed', { fontCharacter: '\\eae7' }); - Codicon.fileBinary = new Codicon('file-binary', { fontCharacter: '\\eae8' }); - Codicon.fileCode = new Codicon('file-code', { fontCharacter: '\\eae9' }); - Codicon.fileMedia = new Codicon('file-media', { fontCharacter: '\\eaea' }); - Codicon.filePdf = new Codicon('file-pdf', { fontCharacter: '\\eaeb' }); - Codicon.fileSubmodule = new Codicon('file-submodule', { fontCharacter: '\\eaec' }); - Codicon.fileSymlinkDirectory = new Codicon('file-symlink-directory', { fontCharacter: '\\eaed' }); - Codicon.fileSymlinkFile = new Codicon('file-symlink-file', { fontCharacter: '\\eaee' }); - Codicon.fileZip = new Codicon('file-zip', { fontCharacter: '\\eaef' }); - Codicon.files = new Codicon('files', { fontCharacter: '\\eaf0' }); - Codicon.filter = new Codicon('filter', { fontCharacter: '\\eaf1' }); - Codicon.flame = new Codicon('flame', { fontCharacter: '\\eaf2' }); - Codicon.foldDown = new Codicon('fold-down', { fontCharacter: '\\eaf3' }); - Codicon.foldUp = new Codicon('fold-up', { fontCharacter: '\\eaf4' }); - Codicon.fold = new Codicon('fold', { fontCharacter: '\\eaf5' }); - Codicon.folderActive = new Codicon('folder-active', { fontCharacter: '\\eaf6' }); - Codicon.folderOpened = new Codicon('folder-opened', { fontCharacter: '\\eaf7' }); - Codicon.gear = new Codicon('gear', { fontCharacter: '\\eaf8' }); - Codicon.gift = new Codicon('gift', { fontCharacter: '\\eaf9' }); - Codicon.gistSecret = new Codicon('gist-secret', { fontCharacter: '\\eafa' }); - Codicon.gist = new Codicon('gist', { fontCharacter: '\\eafb' }); - Codicon.gitCommit = new Codicon('git-commit', { fontCharacter: '\\eafc' }); - Codicon.gitCompare = new Codicon('git-compare', { fontCharacter: '\\eafd' }); - Codicon.gitMerge = new Codicon('git-merge', { fontCharacter: '\\eafe' }); - Codicon.githubAction = new Codicon('github-action', { fontCharacter: '\\eaff' }); - Codicon.githubAlt = new Codicon('github-alt', { fontCharacter: '\\eb00' }); - Codicon.globe = new Codicon('globe', { fontCharacter: '\\eb01' }); - Codicon.grabber = new Codicon('grabber', { fontCharacter: '\\eb02' }); - Codicon.graph = new Codicon('graph', { fontCharacter: '\\eb03' }); - Codicon.gripper = new Codicon('gripper', { fontCharacter: '\\eb04' }); - Codicon.heart = new Codicon('heart', { fontCharacter: '\\eb05' }); - Codicon.home = new Codicon('home', { fontCharacter: '\\eb06' }); - Codicon.horizontalRule = new Codicon('horizontal-rule', { fontCharacter: '\\eb07' }); - Codicon.hubot = new Codicon('hubot', { fontCharacter: '\\eb08' }); - Codicon.inbox = new Codicon('inbox', { fontCharacter: '\\eb09' }); - Codicon.issueClosed = new Codicon('issue-closed', { fontCharacter: '\\eba4' }); - Codicon.issueReopened = new Codicon('issue-reopened', { fontCharacter: '\\eb0b' }); - Codicon.issues = new Codicon('issues', { fontCharacter: '\\eb0c' }); - Codicon.italic = new Codicon('italic', { fontCharacter: '\\eb0d' }); - Codicon.jersey = new Codicon('jersey', { fontCharacter: '\\eb0e' }); - Codicon.json = new Codicon('json', { fontCharacter: '\\eb0f' }); - Codicon.kebabVertical = new Codicon('kebab-vertical', { fontCharacter: '\\eb10' }); - Codicon.key = new Codicon('key', { fontCharacter: '\\eb11' }); - Codicon.law = new Codicon('law', { fontCharacter: '\\eb12' }); - Codicon.lightbulbAutofix = new Codicon('lightbulb-autofix', { fontCharacter: '\\eb13' }); - Codicon.linkExternal = new Codicon('link-external', { fontCharacter: '\\eb14' }); - Codicon.link = new Codicon('link', { fontCharacter: '\\eb15' }); - Codicon.listOrdered = new Codicon('list-ordered', { fontCharacter: '\\eb16' }); - Codicon.listUnordered = new Codicon('list-unordered', { fontCharacter: '\\eb17' }); - Codicon.liveShare = new Codicon('live-share', { fontCharacter: '\\eb18' }); - Codicon.loading = new Codicon('loading', { fontCharacter: '\\eb19' }); - Codicon.location = new Codicon('location', { fontCharacter: '\\eb1a' }); - Codicon.mailRead = new Codicon('mail-read', { fontCharacter: '\\eb1b' }); - Codicon.mail = new Codicon('mail', { fontCharacter: '\\eb1c' }); - Codicon.markdown = new Codicon('markdown', { fontCharacter: '\\eb1d' }); - Codicon.megaphone = new Codicon('megaphone', { fontCharacter: '\\eb1e' }); - Codicon.mention = new Codicon('mention', { fontCharacter: '\\eb1f' }); - Codicon.milestone = new Codicon('milestone', { fontCharacter: '\\eb20' }); - Codicon.mortarBoard = new Codicon('mortar-board', { fontCharacter: '\\eb21' }); - Codicon.move = new Codicon('move', { fontCharacter: '\\eb22' }); - Codicon.multipleWindows = new Codicon('multiple-windows', { fontCharacter: '\\eb23' }); - Codicon.mute = new Codicon('mute', { fontCharacter: '\\eb24' }); - Codicon.noNewline = new Codicon('no-newline', { fontCharacter: '\\eb25' }); - Codicon.note = new Codicon('note', { fontCharacter: '\\eb26' }); - Codicon.octoface = new Codicon('octoface', { fontCharacter: '\\eb27' }); - Codicon.openPreview = new Codicon('open-preview', { fontCharacter: '\\eb28' }); - Codicon.package_ = new Codicon('package', { fontCharacter: '\\eb29' }); - Codicon.paintcan = new Codicon('paintcan', { fontCharacter: '\\eb2a' }); - Codicon.pin = new Codicon('pin', { fontCharacter: '\\eb2b' }); - Codicon.play = new Codicon('play', { fontCharacter: '\\eb2c' }); - Codicon.run = new Codicon('run', { fontCharacter: '\\eb2c' }); - Codicon.plug = new Codicon('plug', { fontCharacter: '\\eb2d' }); - Codicon.preserveCase = new Codicon('preserve-case', { fontCharacter: '\\eb2e' }); - Codicon.preview = new Codicon('preview', { fontCharacter: '\\eb2f' }); - Codicon.project = new Codicon('project', { fontCharacter: '\\eb30' }); - Codicon.pulse = new Codicon('pulse', { fontCharacter: '\\eb31' }); - Codicon.question = new Codicon('question', { fontCharacter: '\\eb32' }); - Codicon.quote = new Codicon('quote', { fontCharacter: '\\eb33' }); - Codicon.radioTower = new Codicon('radio-tower', { fontCharacter: '\\eb34' }); - Codicon.reactions = new Codicon('reactions', { fontCharacter: '\\eb35' }); - Codicon.references = new Codicon('references', { fontCharacter: '\\eb36' }); - Codicon.refresh = new Codicon('refresh', { fontCharacter: '\\eb37' }); - Codicon.regex = new Codicon('regex', { fontCharacter: '\\eb38' }); - Codicon.remoteExplorer = new Codicon('remote-explorer', { fontCharacter: '\\eb39' }); - Codicon.remote = new Codicon('remote', { fontCharacter: '\\eb3a' }); - Codicon.remove = new Codicon('remove', { fontCharacter: '\\eb3b' }); - Codicon.replaceAll = new Codicon('replace-all', { fontCharacter: '\\eb3c' }); - Codicon.replace = new Codicon('replace', { fontCharacter: '\\eb3d' }); - Codicon.repoClone = new Codicon('repo-clone', { fontCharacter: '\\eb3e' }); - Codicon.repoForcePush = new Codicon('repo-force-push', { fontCharacter: '\\eb3f' }); - Codicon.repoPull = new Codicon('repo-pull', { fontCharacter: '\\eb40' }); - Codicon.repoPush = new Codicon('repo-push', { fontCharacter: '\\eb41' }); - Codicon.report = new Codicon('report', { fontCharacter: '\\eb42' }); - Codicon.requestChanges = new Codicon('request-changes', { fontCharacter: '\\eb43' }); - Codicon.rocket = new Codicon('rocket', { fontCharacter: '\\eb44' }); - Codicon.rootFolderOpened = new Codicon('root-folder-opened', { fontCharacter: '\\eb45' }); - Codicon.rootFolder = new Codicon('root-folder', { fontCharacter: '\\eb46' }); - Codicon.rss = new Codicon('rss', { fontCharacter: '\\eb47' }); - Codicon.ruby = new Codicon('ruby', { fontCharacter: '\\eb48' }); - Codicon.saveAll = new Codicon('save-all', { fontCharacter: '\\eb49' }); - Codicon.saveAs = new Codicon('save-as', { fontCharacter: '\\eb4a' }); - Codicon.save = new Codicon('save', { fontCharacter: '\\eb4b' }); - Codicon.screenFull = new Codicon('screen-full', { fontCharacter: '\\eb4c' }); - Codicon.screenNormal = new Codicon('screen-normal', { fontCharacter: '\\eb4d' }); - Codicon.searchStop = new Codicon('search-stop', { fontCharacter: '\\eb4e' }); - Codicon.server = new Codicon('server', { fontCharacter: '\\eb50' }); - Codicon.settingsGear = new Codicon('settings-gear', { fontCharacter: '\\eb51' }); - Codicon.settings = new Codicon('settings', { fontCharacter: '\\eb52' }); - Codicon.shield = new Codicon('shield', { fontCharacter: '\\eb53' }); - Codicon.smiley = new Codicon('smiley', { fontCharacter: '\\eb54' }); - Codicon.sortPrecedence = new Codicon('sort-precedence', { fontCharacter: '\\eb55' }); - Codicon.splitHorizontal = new Codicon('split-horizontal', { fontCharacter: '\\eb56' }); - Codicon.splitVertical = new Codicon('split-vertical', { fontCharacter: '\\eb57' }); - Codicon.squirrel = new Codicon('squirrel', { fontCharacter: '\\eb58' }); - Codicon.starFull = new Codicon('star-full', { fontCharacter: '\\eb59' }); - Codicon.starHalf = new Codicon('star-half', { fontCharacter: '\\eb5a' }); - Codicon.symbolClass = new Codicon('symbol-class', { fontCharacter: '\\eb5b' }); - Codicon.symbolColor = new Codicon('symbol-color', { fontCharacter: '\\eb5c' }); - Codicon.symbolConstant = new Codicon('symbol-constant', { fontCharacter: '\\eb5d' }); - Codicon.symbolEnumMember = new Codicon('symbol-enum-member', { fontCharacter: '\\eb5e' }); - Codicon.symbolField = new Codicon('symbol-field', { fontCharacter: '\\eb5f' }); - Codicon.symbolFile = new Codicon('symbol-file', { fontCharacter: '\\eb60' }); - Codicon.symbolInterface = new Codicon('symbol-interface', { fontCharacter: '\\eb61' }); - Codicon.symbolKeyword = new Codicon('symbol-keyword', { fontCharacter: '\\eb62' }); - Codicon.symbolMisc = new Codicon('symbol-misc', { fontCharacter: '\\eb63' }); - Codicon.symbolOperator = new Codicon('symbol-operator', { fontCharacter: '\\eb64' }); - Codicon.symbolProperty = new Codicon('symbol-property', { fontCharacter: '\\eb65' }); - Codicon.wrench = new Codicon('wrench', { fontCharacter: '\\eb65' }); - Codicon.wrenchSubaction = new Codicon('wrench-subaction', { fontCharacter: '\\eb65' }); - Codicon.symbolSnippet = new Codicon('symbol-snippet', { fontCharacter: '\\eb66' }); - Codicon.tasklist = new Codicon('tasklist', { fontCharacter: '\\eb67' }); - Codicon.telescope = new Codicon('telescope', { fontCharacter: '\\eb68' }); - Codicon.textSize = new Codicon('text-size', { fontCharacter: '\\eb69' }); - Codicon.threeBars = new Codicon('three-bars', { fontCharacter: '\\eb6a' }); - Codicon.thumbsdown = new Codicon('thumbsdown', { fontCharacter: '\\eb6b' }); - Codicon.thumbsup = new Codicon('thumbsup', { fontCharacter: '\\eb6c' }); - Codicon.tools = new Codicon('tools', { fontCharacter: '\\eb6d' }); - Codicon.triangleDown = new Codicon('triangle-down', { fontCharacter: '\\eb6e' }); - Codicon.triangleLeft = new Codicon('triangle-left', { fontCharacter: '\\eb6f' }); - Codicon.triangleRight = new Codicon('triangle-right', { fontCharacter: '\\eb70' }); - Codicon.triangleUp = new Codicon('triangle-up', { fontCharacter: '\\eb71' }); - Codicon.twitter = new Codicon('twitter', { fontCharacter: '\\eb72' }); - Codicon.unfold = new Codicon('unfold', { fontCharacter: '\\eb73' }); - Codicon.unlock = new Codicon('unlock', { fontCharacter: '\\eb74' }); - Codicon.unmute = new Codicon('unmute', { fontCharacter: '\\eb75' }); - Codicon.unverified = new Codicon('unverified', { fontCharacter: '\\eb76' }); - Codicon.verified = new Codicon('verified', { fontCharacter: '\\eb77' }); - Codicon.versions = new Codicon('versions', { fontCharacter: '\\eb78' }); - Codicon.vmActive = new Codicon('vm-active', { fontCharacter: '\\eb79' }); - Codicon.vmOutline = new Codicon('vm-outline', { fontCharacter: '\\eb7a' }); - Codicon.vmRunning = new Codicon('vm-running', { fontCharacter: '\\eb7b' }); - Codicon.watch = new Codicon('watch', { fontCharacter: '\\eb7c' }); - Codicon.whitespace = new Codicon('whitespace', { fontCharacter: '\\eb7d' }); - Codicon.wholeWord = new Codicon('whole-word', { fontCharacter: '\\eb7e' }); - Codicon.window = new Codicon('window', { fontCharacter: '\\eb7f' }); - Codicon.wordWrap = new Codicon('word-wrap', { fontCharacter: '\\eb80' }); - Codicon.zoomIn = new Codicon('zoom-in', { fontCharacter: '\\eb81' }); - Codicon.zoomOut = new Codicon('zoom-out', { fontCharacter: '\\eb82' }); - Codicon.listFilter = new Codicon('list-filter', { fontCharacter: '\\eb83' }); - Codicon.listFlat = new Codicon('list-flat', { fontCharacter: '\\eb84' }); - Codicon.listSelection = new Codicon('list-selection', { fontCharacter: '\\eb85' }); - Codicon.selection = new Codicon('selection', { fontCharacter: '\\eb85' }); - Codicon.listTree = new Codicon('list-tree', { fontCharacter: '\\eb86' }); - Codicon.debugBreakpointFunctionUnverified = new Codicon('debug-breakpoint-function-unverified', { fontCharacter: '\\eb87' }); - Codicon.debugBreakpointFunction = new Codicon('debug-breakpoint-function', { fontCharacter: '\\eb88' }); - Codicon.debugBreakpointFunctionDisabled = new Codicon('debug-breakpoint-function-disabled', { fontCharacter: '\\eb88' }); - Codicon.debugStackframeActive = new Codicon('debug-stackframe-active', { fontCharacter: '\\eb89' }); - Codicon.debugStackframeDot = new Codicon('debug-stackframe-dot', { fontCharacter: '\\eb8a' }); - Codicon.debugStackframe = new Codicon('debug-stackframe', { fontCharacter: '\\eb8b' }); - Codicon.debugStackframeFocused = new Codicon('debug-stackframe-focused', { fontCharacter: '\\eb8b' }); - Codicon.debugBreakpointUnsupported = new Codicon('debug-breakpoint-unsupported', { fontCharacter: '\\eb8c' }); - Codicon.symbolString = new Codicon('symbol-string', { fontCharacter: '\\eb8d' }); - Codicon.debugReverseContinue = new Codicon('debug-reverse-continue', { fontCharacter: '\\eb8e' }); - Codicon.debugStepBack = new Codicon('debug-step-back', { fontCharacter: '\\eb8f' }); - Codicon.debugRestartFrame = new Codicon('debug-restart-frame', { fontCharacter: '\\eb90' }); - Codicon.callIncoming = new Codicon('call-incoming', { fontCharacter: '\\eb92' }); - Codicon.callOutgoing = new Codicon('call-outgoing', { fontCharacter: '\\eb93' }); - Codicon.menu = new Codicon('menu', { fontCharacter: '\\eb94' }); - Codicon.expandAll = new Codicon('expand-all', { fontCharacter: '\\eb95' }); - Codicon.feedback = new Codicon('feedback', { fontCharacter: '\\eb96' }); - Codicon.groupByRefType = new Codicon('group-by-ref-type', { fontCharacter: '\\eb97' }); - Codicon.ungroupByRefType = new Codicon('ungroup-by-ref-type', { fontCharacter: '\\eb98' }); - Codicon.account = new Codicon('account', { fontCharacter: '\\eb99' }); - Codicon.bellDot = new Codicon('bell-dot', { fontCharacter: '\\eb9a' }); - Codicon.debugConsole = new Codicon('debug-console', { fontCharacter: '\\eb9b' }); - Codicon.library = new Codicon('library', { fontCharacter: '\\eb9c' }); - Codicon.output = new Codicon('output', { fontCharacter: '\\eb9d' }); - Codicon.runAll = new Codicon('run-all', { fontCharacter: '\\eb9e' }); - Codicon.syncIgnored = new Codicon('sync-ignored', { fontCharacter: '\\eb9f' }); - Codicon.pinned = new Codicon('pinned', { fontCharacter: '\\eba0' }); - Codicon.githubInverted = new Codicon('github-inverted', { fontCharacter: '\\eba1' }); - Codicon.debugAlt = new Codicon('debug-alt', { fontCharacter: '\\eb91' }); - Codicon.serverProcess = new Codicon('server-process', { fontCharacter: '\\eba2' }); - Codicon.serverEnvironment = new Codicon('server-environment', { fontCharacter: '\\eba3' }); - Codicon.pass = new Codicon('pass', { fontCharacter: '\\eba4' }); - Codicon.stopCircle = new Codicon('stop-circle', { fontCharacter: '\\eba5' }); - Codicon.playCircle = new Codicon('play-circle', { fontCharacter: '\\eba6' }); - Codicon.record = new Codicon('record', { fontCharacter: '\\eba7' }); - Codicon.debugAltSmall = new Codicon('debug-alt-small', { fontCharacter: '\\eba8' }); - Codicon.vmConnect = new Codicon('vm-connect', { fontCharacter: '\\eba9' }); - Codicon.cloud = new Codicon('cloud', { fontCharacter: '\\ebaa' }); - Codicon.merge = new Codicon('merge', { fontCharacter: '\\ebab' }); - Codicon.exportIcon = new Codicon('export', { fontCharacter: '\\ebac' }); - Codicon.graphLeft = new Codicon('graph-left', { fontCharacter: '\\ebad' }); - Codicon.magnet = new Codicon('magnet', { fontCharacter: '\\ebae' }); - Codicon.notebook = new Codicon('notebook', { fontCharacter: '\\ebaf' }); - Codicon.redo = new Codicon('redo', { fontCharacter: '\\ebb0' }); - Codicon.checkAll = new Codicon('check-all', { fontCharacter: '\\ebb1' }); - Codicon.pinnedDirty = new Codicon('pinned-dirty', { fontCharacter: '\\ebb2' }); - Codicon.passFilled = new Codicon('pass-filled', { fontCharacter: '\\ebb3' }); - Codicon.circleLargeFilled = new Codicon('circle-large-filled', { fontCharacter: '\\ebb4' }); - Codicon.circleLargeOutline = new Codicon('circle-large-outline', { fontCharacter: '\\ebb5' }); - Codicon.combine = new Codicon('combine', { fontCharacter: '\\ebb6' }); - Codicon.gather = new Codicon('gather', { fontCharacter: '\\ebb6' }); - Codicon.table = new Codicon('table', { fontCharacter: '\\ebb7' }); - Codicon.variableGroup = new Codicon('variable-group', { fontCharacter: '\\ebb8' }); - Codicon.typeHierarchy = new Codicon('type-hierarchy', { fontCharacter: '\\ebb9' }); - Codicon.typeHierarchySub = new Codicon('type-hierarchy-sub', { fontCharacter: '\\ebba' }); - Codicon.typeHierarchySuper = new Codicon('type-hierarchy-super', { fontCharacter: '\\ebbb' }); - Codicon.gitPullRequestCreate = new Codicon('git-pull-request-create', { fontCharacter: '\\ebbc' }); - Codicon.runAbove = new Codicon('run-above', { fontCharacter: '\\ebbd' }); - Codicon.runBelow = new Codicon('run-below', { fontCharacter: '\\ebbe' }); - Codicon.notebookTemplate = new Codicon('notebook-template', { fontCharacter: '\\ebbf' }); - Codicon.debugRerun = new Codicon('debug-rerun', { fontCharacter: '\\ebc0' }); - Codicon.workspaceTrusted = new Codicon('workspace-trusted', { fontCharacter: '\\ebc1' }); - Codicon.workspaceUntrusted = new Codicon('workspace-untrusted', { fontCharacter: '\\ebc2' }); - Codicon.workspaceUnspecified = new Codicon('workspace-unspecified', { fontCharacter: '\\ebc3' }); - Codicon.terminalCmd = new Codicon('terminal-cmd', { fontCharacter: '\\ebc4' }); - Codicon.terminalDebian = new Codicon('terminal-debian', { fontCharacter: '\\ebc5' }); - Codicon.terminalLinux = new Codicon('terminal-linux', { fontCharacter: '\\ebc6' }); - Codicon.terminalPowershell = new Codicon('terminal-powershell', { fontCharacter: '\\ebc7' }); - Codicon.terminalTmux = new Codicon('terminal-tmux', { fontCharacter: '\\ebc8' }); - Codicon.terminalUbuntu = new Codicon('terminal-ubuntu', { fontCharacter: '\\ebc9' }); - Codicon.terminalBash = new Codicon('terminal-bash', { fontCharacter: '\\ebca' }); - Codicon.arrowSwap = new Codicon('arrow-swap', { fontCharacter: '\\ebcb' }); - Codicon.copy = new Codicon('copy', { fontCharacter: '\\ebcc' }); - Codicon.personAdd = new Codicon('person-add', { fontCharacter: '\\ebcd' }); - Codicon.filterFilled = new Codicon('filter-filled', { fontCharacter: '\\ebce' }); - Codicon.wand = new Codicon('wand', { fontCharacter: '\\ebcf' }); - Codicon.debugLineByLine = new Codicon('debug-line-by-line', { fontCharacter: '\\ebd0' }); - Codicon.inspect = new Codicon('inspect', { fontCharacter: '\\ebd1' }); - Codicon.layers = new Codicon('layers', { fontCharacter: '\\ebd2' }); - Codicon.layersDot = new Codicon('layers-dot', { fontCharacter: '\\ebd3' }); - Codicon.layersActive = new Codicon('layers-active', { fontCharacter: '\\ebd4' }); - Codicon.compass = new Codicon('compass', { fontCharacter: '\\ebd5' }); - Codicon.compassDot = new Codicon('compass-dot', { fontCharacter: '\\ebd6' }); - Codicon.compassActive = new Codicon('compass-active', { fontCharacter: '\\ebd7' }); - Codicon.azure = new Codicon('azure', { fontCharacter: '\\ebd8' }); - Codicon.issueDraft = new Codicon('issue-draft', { fontCharacter: '\\ebd9' }); - Codicon.gitPullRequestClosed = new Codicon('git-pull-request-closed', { fontCharacter: '\\ebda' }); - Codicon.gitPullRequestDraft = new Codicon('git-pull-request-draft', { fontCharacter: '\\ebdb' }); - Codicon.debugAll = new Codicon('debug-all', { fontCharacter: '\\ebdc' }); - Codicon.debugCoverage = new Codicon('debug-coverage', { fontCharacter: '\\ebdd' }); - Codicon.dropDownButton = new Codicon('drop-down-button', Codicon.chevronDown.definition); - })(Codicon = exports.Codicon || (exports.Codicon = {})); -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/browser/ui/tree/treeIcons*/], __M([0/*require*/,1/*exports*/,27/*vs/base/common/codicons*/]), function (require, exports, codicons_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.treeItemLoadingIcon = exports.treeFilterClearIcon = exports.treeFilterOnTypeOffIcon = exports.treeFilterOnTypeOnIcon = exports.treeItemExpandedIcon = void 0; - exports.treeItemExpandedIcon = (0, codicons_1.registerCodicon)('tree-item-expanded', codicons_1.Codicon.chevronDown); // collapsed is done with rotation - exports.treeFilterOnTypeOnIcon = (0, codicons_1.registerCodicon)('tree-filter-on-type-on', codicons_1.Codicon.listFilter); - exports.treeFilterOnTypeOffIcon = (0, codicons_1.registerCodicon)('tree-filter-on-type-off', codicons_1.Codicon.listSelection); - exports.treeFilterClearIcon = (0, codicons_1.registerCodicon)('tree-filter-clear', codicons_1.Codicon.close); - exports.treeItemLoadingIcon = (0, codicons_1.registerCodicon)('tree-item-loading', codicons_1.Codicon.loading); -}); - -define(__m[291/*vs/base/common/comparers*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/]), function (require, exports, async_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.compareByPrefix = exports.compareAnything = exports.compareFileNames = void 0; - // When comparing large numbers of strings it's better for performance to create an - // Intl.Collator object and use the function provided by its compare property - // than it is to use String.prototype.localeCompare() - // A collator with numeric sorting enabled, and no sensitivity to case, accents or diacritics. - const intlFileNameCollatorBaseNumeric = new async_1.IdleValue(() => { - const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }); - return { - collator: collator, - collatorIsNumeric: collator.resolvedOptions().numeric - }; - }); - /** Compares filenames without distinguishing the name from the extension. Disambiguates by unicode comparison. */ - function compareFileNames(one, other, caseSensitive = false) { - const a = one || ''; - const b = other || ''; - const result = intlFileNameCollatorBaseNumeric.value.collator.compare(a, b); - // Using the numeric option will make compare(`foo1`, `foo01`) === 0. Disambiguate. - if (intlFileNameCollatorBaseNumeric.value.collatorIsNumeric && result === 0 && a !== b) { - return a < b ? -1 : 1; - } - return result; - } - exports.compareFileNames = compareFileNames; - function compareAnything(one, other, lookFor) { - const elementAName = one.toLowerCase(); - const elementBName = other.toLowerCase(); - // Sort prefix matches over non prefix matches - const prefixCompare = compareByPrefix(one, other, lookFor); - if (prefixCompare) { - return prefixCompare; - } - // Sort suffix matches over non suffix matches - const elementASuffixMatch = elementAName.endsWith(lookFor); - const elementBSuffixMatch = elementBName.endsWith(lookFor); - if (elementASuffixMatch !== elementBSuffixMatch) { - return elementASuffixMatch ? -1 : 1; - } - // Understand file names - const r = compareFileNames(elementAName, elementBName); - if (r !== 0) { - return r; - } - // Compare by name - return elementAName.localeCompare(elementBName); - } - exports.compareAnything = compareAnything; - function compareByPrefix(one, other, lookFor) { - const elementAName = one.toLowerCase(); - const elementBName = other.toLowerCase(); - // Sort prefix matches over non prefix matches - const elementAPrefixMatch = elementAName.startsWith(lookFor); - const elementBPrefixMatch = elementBName.startsWith(lookFor); - if (elementAPrefixMatch !== elementBPrefixMatch) { - return elementAPrefixMatch ? -1 : 1; - } - // Same prefix: Sort shorter matches to the top to have those on top that match more precisely - else if (elementAPrefixMatch && elementBPrefixMatch) { - if (elementAName.length < elementBName.length) { - return -1; - } - if (elementAName.length > elementBName.length) { - return 1; - } - } - return 0; - } - exports.compareByPrefix = compareByPrefix; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[127/*vs/base/common/scrollable*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/]), function (require, exports, event_1, lifecycle_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.SmoothScrollingOperation = exports.SmoothScrollingUpdate = exports.Scrollable = exports.ScrollState = void 0; - class ScrollState { - constructor(width, scrollWidth, scrollLeft, height, scrollHeight, scrollTop) { - this._scrollStateBrand = undefined; - width = width | 0; - scrollWidth = scrollWidth | 0; - scrollLeft = scrollLeft | 0; - height = height | 0; - scrollHeight = scrollHeight | 0; - scrollTop = scrollTop | 0; - this.rawScrollLeft = scrollLeft; // before validation - this.rawScrollTop = scrollTop; // before validation - if (width < 0) { - width = 0; - } - if (scrollLeft + width > scrollWidth) { - scrollLeft = scrollWidth - width; - } - if (scrollLeft < 0) { - scrollLeft = 0; - } - if (height < 0) { - height = 0; - } - if (scrollTop + height > scrollHeight) { - scrollTop = scrollHeight - height; - } - if (scrollTop < 0) { - scrollTop = 0; - } - this.width = width; - this.scrollWidth = scrollWidth; - this.scrollLeft = scrollLeft; - this.height = height; - this.scrollHeight = scrollHeight; - this.scrollTop = scrollTop; - } - equals(other) { - return (this.rawScrollLeft === other.rawScrollLeft - && this.rawScrollTop === other.rawScrollTop - && this.width === other.width - && this.scrollWidth === other.scrollWidth - && this.scrollLeft === other.scrollLeft - && this.height === other.height - && this.scrollHeight === other.scrollHeight - && this.scrollTop === other.scrollTop); - } - withScrollDimensions(update, useRawScrollPositions) { - return new ScrollState((typeof update.width !== 'undefined' ? update.width : this.width), (typeof update.scrollWidth !== 'undefined' ? update.scrollWidth : this.scrollWidth), useRawScrollPositions ? this.rawScrollLeft : this.scrollLeft, (typeof update.height !== 'undefined' ? update.height : this.height), (typeof update.scrollHeight !== 'undefined' ? update.scrollHeight : this.scrollHeight), useRawScrollPositions ? this.rawScrollTop : this.scrollTop); - } - withScrollPosition(update) { - return new ScrollState(this.width, this.scrollWidth, (typeof update.scrollLeft !== 'undefined' ? update.scrollLeft : this.rawScrollLeft), this.height, this.scrollHeight, (typeof update.scrollTop !== 'undefined' ? update.scrollTop : this.rawScrollTop)); - } - createScrollEvent(previous, inSmoothScrolling) { - const widthChanged = (this.width !== previous.width); - const scrollWidthChanged = (this.scrollWidth !== previous.scrollWidth); - const scrollLeftChanged = (this.scrollLeft !== previous.scrollLeft); - const heightChanged = (this.height !== previous.height); - const scrollHeightChanged = (this.scrollHeight !== previous.scrollHeight); - const scrollTopChanged = (this.scrollTop !== previous.scrollTop); - return { - inSmoothScrolling: inSmoothScrolling, - oldWidth: previous.width, - oldScrollWidth: previous.scrollWidth, - oldScrollLeft: previous.scrollLeft, - width: this.width, - scrollWidth: this.scrollWidth, - scrollLeft: this.scrollLeft, - oldHeight: previous.height, - oldScrollHeight: previous.scrollHeight, - oldScrollTop: previous.scrollTop, - height: this.height, - scrollHeight: this.scrollHeight, - scrollTop: this.scrollTop, - widthChanged: widthChanged, - scrollWidthChanged: scrollWidthChanged, - scrollLeftChanged: scrollLeftChanged, - heightChanged: heightChanged, - scrollHeightChanged: scrollHeightChanged, - scrollTopChanged: scrollTopChanged, - }; - } - } - exports.ScrollState = ScrollState; - class Scrollable extends lifecycle_1.Disposable { - constructor(smoothScrollDuration, scheduleAtNextAnimationFrame) { - super(); - this._scrollableBrand = undefined; - this._onScroll = this._register(new event_1.Emitter()); - this.onScroll = this._onScroll.event; - this._smoothScrollDuration = smoothScrollDuration; - this._scheduleAtNextAnimationFrame = scheduleAtNextAnimationFrame; - this._state = new ScrollState(0, 0, 0, 0, 0, 0); - this._smoothScrolling = null; - } - dispose() { - if (this._smoothScrolling) { - this._smoothScrolling.dispose(); - this._smoothScrolling = null; - } - super.dispose(); - } - setSmoothScrollDuration(smoothScrollDuration) { - this._smoothScrollDuration = smoothScrollDuration; - } - validateScrollPosition(scrollPosition) { - return this._state.withScrollPosition(scrollPosition); - } - getScrollDimensions() { - return this._state; - } - setScrollDimensions(dimensions, useRawScrollPositions) { - const newState = this._state.withScrollDimensions(dimensions, useRawScrollPositions); - this._setState(newState, Boolean(this._smoothScrolling)); - // Validate outstanding animated scroll position target - if (this._smoothScrolling) { - this._smoothScrolling.acceptScrollDimensions(this._state); - } - } - /** - * Returns the final scroll position that the instance will have once the smooth scroll animation concludes. - * If no scroll animation is occurring, it will return the current scroll position instead. - */ - getFutureScrollPosition() { - if (this._smoothScrolling) { - return this._smoothScrolling.to; - } - return this._state; - } - /** - * Returns the current scroll position. - * Note: This result might be an intermediate scroll position, as there might be an ongoing smooth scroll animation. - */ - getCurrentScrollPosition() { - return this._state; - } - setScrollPositionNow(update) { - // no smooth scrolling requested - const newState = this._state.withScrollPosition(update); - // Terminate any outstanding smooth scrolling - if (this._smoothScrolling) { - this._smoothScrolling.dispose(); - this._smoothScrolling = null; - } - this._setState(newState, false); - } - setScrollPositionSmooth(update, reuseAnimation) { - if (this._smoothScrollDuration === 0) { - // Smooth scrolling not supported. - return this.setScrollPositionNow(update); - } - if (this._smoothScrolling) { - // Combine our pending scrollLeft/scrollTop with incoming scrollLeft/scrollTop - update = { - scrollLeft: (typeof update.scrollLeft === 'undefined' ? this._smoothScrolling.to.scrollLeft : update.scrollLeft), - scrollTop: (typeof update.scrollTop === 'undefined' ? this._smoothScrolling.to.scrollTop : update.scrollTop) - }; - // Validate `update` - const validTarget = this._state.withScrollPosition(update); - if (this._smoothScrolling.to.scrollLeft === validTarget.scrollLeft && this._smoothScrolling.to.scrollTop === validTarget.scrollTop) { - // No need to interrupt or extend the current animation since we're going to the same place - return; - } - let newSmoothScrolling; - if (reuseAnimation) { - newSmoothScrolling = new SmoothScrollingOperation(this._smoothScrolling.from, validTarget, this._smoothScrolling.startTime, this._smoothScrolling.duration); - } - else { - newSmoothScrolling = this._smoothScrolling.combine(this._state, validTarget, this._smoothScrollDuration); - } - this._smoothScrolling.dispose(); - this._smoothScrolling = newSmoothScrolling; - } - else { - // Validate `update` - const validTarget = this._state.withScrollPosition(update); - this._smoothScrolling = SmoothScrollingOperation.start(this._state, validTarget, this._smoothScrollDuration); - } - // Begin smooth scrolling animation - this._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(() => { - if (!this._smoothScrolling) { - return; - } - this._smoothScrolling.animationFrameDisposable = null; - this._performSmoothScrolling(); - }); - } - _performSmoothScrolling() { - if (!this._smoothScrolling) { - return; - } - const update = this._smoothScrolling.tick(); - const newState = this._state.withScrollPosition(update); - this._setState(newState, true); - if (!this._smoothScrolling) { - // Looks like someone canceled the smooth scrolling - // from the scroll event handler - return; - } - if (update.isDone) { - this._smoothScrolling.dispose(); - this._smoothScrolling = null; - return; - } - // Continue smooth scrolling animation - this._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(() => { - if (!this._smoothScrolling) { - return; - } - this._smoothScrolling.animationFrameDisposable = null; - this._performSmoothScrolling(); - }); - } - _setState(newState, inSmoothScrolling) { - const oldState = this._state; - if (oldState.equals(newState)) { - // no change - return; - } - this._state = newState; - this._onScroll.fire(this._state.createScrollEvent(oldState, inSmoothScrolling)); - } - } - exports.Scrollable = Scrollable; - class SmoothScrollingUpdate { - constructor(scrollLeft, scrollTop, isDone) { - this.scrollLeft = scrollLeft; - this.scrollTop = scrollTop; - this.isDone = isDone; - } - } - exports.SmoothScrollingUpdate = SmoothScrollingUpdate; - function createEaseOutCubic(from, to) { - const delta = to - from; - return function (completion) { - return from + delta * easeOutCubic(completion); - }; - } - function createComposed(a, b, cut) { - return function (completion) { - if (completion < cut) { - return a(completion / cut); - } - return b((completion - cut) / (1 - cut)); - }; - } - class SmoothScrollingOperation { - constructor(from, to, startTime, duration) { - this.from = from; - this.to = to; - this.duration = duration; - this.startTime = startTime; - this.animationFrameDisposable = null; - this._initAnimations(); - } - _initAnimations() { - this.scrollLeft = this._initAnimation(this.from.scrollLeft, this.to.scrollLeft, this.to.width); - this.scrollTop = this._initAnimation(this.from.scrollTop, this.to.scrollTop, this.to.height); - } - _initAnimation(from, to, viewportSize) { - const delta = Math.abs(from - to); - if (delta > 2.5 * viewportSize) { - let stop1, stop2; - if (from < to) { - // scroll to 75% of the viewportSize - stop1 = from + 0.75 * viewportSize; - stop2 = to - 0.75 * viewportSize; - } - else { - stop1 = from - 0.75 * viewportSize; - stop2 = to + 0.75 * viewportSize; - } - return createComposed(createEaseOutCubic(from, stop1), createEaseOutCubic(stop2, to), 0.33); - } - return createEaseOutCubic(from, to); - } - dispose() { - if (this.animationFrameDisposable !== null) { - this.animationFrameDisposable.dispose(); - this.animationFrameDisposable = null; - } - } - acceptScrollDimensions(state) { - this.to = state.withScrollPosition(this.to); - this._initAnimations(); - } - tick() { - return this._tick(Date.now()); - } - _tick(now) { - const completion = (now - this.startTime) / this.duration; - if (completion < 1) { - const newScrollLeft = this.scrollLeft(completion); - const newScrollTop = this.scrollTop(completion); - return new SmoothScrollingUpdate(newScrollLeft, newScrollTop, false); - } - return new SmoothScrollingUpdate(this.to.scrollLeft, this.to.scrollTop, true); - } - combine(from, to, duration) { - return SmoothScrollingOperation.start(from, to, duration); - } - static start(from, to, duration) { - // +10 / -10 : pretend the animation already started for a quicker response to a scroll request - duration = duration + 10; - const startTime = Date.now() - 10; - return new SmoothScrollingOperation(from, to, startTime, duration); - } - } - exports.SmoothScrollingOperation = SmoothScrollingOperation; - function easeInCubic(t) { - return Math.pow(t, 3); - } - function easeOutCubic(t) { - return 1 - easeInCubic(1 - t); - } -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[8/*vs/base/common/strings*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getLeftDeleteOffset = exports.breakBetweenGraphemeBreakType = exports.getGraphemeBreakType = exports.singleLetterHash = exports.containsUppercaseCharacter = exports.startsWithUTF8BOM = exports.UTF8_BOM_CHARACTER = exports.isEmojiImprecise = exports.isFullWidthCharacter = exports.containsFullWidthCharacter = exports.containsUnusualLineTerminators = exports.UNUSUAL_LINE_TERMINATORS = exports.isBasicASCII = exports.containsEmoji = exports.containsRTL = exports.decodeUTF8 = exports.prevCharLength = exports.nextCharLength = exports.getNextCodePoint = exports.computeCodePoint = exports.isLowSurrogate = exports.isHighSurrogate = exports.commonSuffixLength = exports.commonPrefixLength = exports.startsWithIgnoreCase = exports.equalsIgnoreCase = exports.isUpperAsciiLetter = exports.isLowerAsciiLetter = exports.compareSubstringIgnoreCase = exports.compareIgnoreCase = exports.compareSubstring = exports.compare = exports.lastNonWhitespaceIndex = exports.getLeadingWhitespace = exports.firstNonWhitespaceIndex = exports.splitLines = exports.regExpFlags = exports.regExpLeadsToEndlessLoop = exports.createRegExp = exports.stripWildcards = exports.convertSimple2RegExpPattern = exports.rtrim = exports.ltrim = exports.trim = exports.escapeRegExpCharacters = exports.escape = exports.format = exports.isFalsyOrWhitespace = void 0; - function isFalsyOrWhitespace(str) { - if (!str || typeof str !== 'string') { - return true; - } - return str.trim().length === 0; - } - exports.isFalsyOrWhitespace = isFalsyOrWhitespace; - const _formatRegexp = /{(\d+)}/g; - /** - * Helper to produce a string with a variable number of arguments. Insert variable segments - * into the string using the {n} notation where N is the index of the argument following the string. - * @param value string to which formatting is applied - * @param args replacements for {n}-entries - */ - function format(value, ...args) { - if (args.length === 0) { - return value; - } - return value.replace(_formatRegexp, function (match, group) { - const idx = parseInt(group, 10); - return isNaN(idx) || idx < 0 || idx >= args.length ? - match : - args[idx]; - }); - } - exports.format = format; - /** - * Converts HTML characters inside the string to use entities instead. Makes the string safe from - * being used e.g. in HTMLElement.innerHTML. - */ - function escape(html) { - return html.replace(/[<>&]/g, function (match) { - switch (match) { - case '<': return '<'; - case '>': return '>'; - case '&': return '&'; - default: return match; - } - }); - } - exports.escape = escape; - /** - * Escapes regular expression characters in a given string - */ - function escapeRegExpCharacters(value) { - return value.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g, '\\$&'); - } - exports.escapeRegExpCharacters = escapeRegExpCharacters; - /** - * Removes all occurrences of needle from the beginning and end of haystack. - * @param haystack string to trim - * @param needle the thing to trim (default is a blank) - */ - function trim(haystack, needle = ' ') { - const trimmed = ltrim(haystack, needle); - return rtrim(trimmed, needle); - } - exports.trim = trim; - /** - * Removes all occurrences of needle from the beginning of haystack. - * @param haystack string to trim - * @param needle the thing to trim - */ - function ltrim(haystack, needle) { - if (!haystack || !needle) { - return haystack; - } - const needleLen = needle.length; - if (needleLen === 0 || haystack.length === 0) { - return haystack; - } - let offset = 0; - while (haystack.indexOf(needle, offset) === offset) { - offset = offset + needleLen; - } - return haystack.substring(offset); - } - exports.ltrim = ltrim; - /** - * Removes all occurrences of needle from the end of haystack. - * @param haystack string to trim - * @param needle the thing to trim - */ - function rtrim(haystack, needle) { - if (!haystack || !needle) { - return haystack; - } - const needleLen = needle.length, haystackLen = haystack.length; - if (needleLen === 0 || haystackLen === 0) { - return haystack; - } - let offset = haystackLen, idx = -1; - while (true) { - idx = haystack.lastIndexOf(needle, offset - 1); - if (idx === -1 || idx + needleLen !== offset) { - break; - } - if (idx === 0) { - return ''; - } - offset = idx; - } - return haystack.substring(0, offset); - } - exports.rtrim = rtrim; - function convertSimple2RegExpPattern(pattern) { - return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&').replace(/[\*]/g, '.*'); - } - exports.convertSimple2RegExpPattern = convertSimple2RegExpPattern; - function stripWildcards(pattern) { - return pattern.replace(/\*/g, ''); - } - exports.stripWildcards = stripWildcards; - function createRegExp(searchString, isRegex, options = {}) { - if (!searchString) { - throw new Error('Cannot create regex from empty string'); - } - if (!isRegex) { - searchString = escapeRegExpCharacters(searchString); - } - if (options.wholeWord) { - if (!/\B/.test(searchString.charAt(0))) { - searchString = '\\b' + searchString; - } - if (!/\B/.test(searchString.charAt(searchString.length - 1))) { - searchString = searchString + '\\b'; - } - } - let modifiers = ''; - if (options.global) { - modifiers += 'g'; - } - if (!options.matchCase) { - modifiers += 'i'; - } - if (options.multiline) { - modifiers += 'm'; - } - if (options.unicode) { - modifiers += 'u'; - } - return new RegExp(searchString, modifiers); - } - exports.createRegExp = createRegExp; - function regExpLeadsToEndlessLoop(regexp) { - // Exit early if it's one of these special cases which are meant to match - // against an empty string - if (regexp.source === '^' || regexp.source === '^$' || regexp.source === '$' || regexp.source === '^\\s*$') { - return false; - } - // We check against an empty string. If the regular expression doesn't advance - // (e.g. ends in an endless loop) it will match an empty string. - const match = regexp.exec(''); - return !!(match && regexp.lastIndex === 0); - } - exports.regExpLeadsToEndlessLoop = regExpLeadsToEndlessLoop; - function regExpFlags(regexp) { - return (regexp.global ? 'g' : '') - + (regexp.ignoreCase ? 'i' : '') - + (regexp.multiline ? 'm' : '') - + (regexp /* standalone editor compilation */.unicode ? 'u' : ''); - } - exports.regExpFlags = regExpFlags; - function splitLines(str) { - return str.split(/\r\n|\r|\n/); - } - exports.splitLines = splitLines; - /** - * Returns first index of the string that is not whitespace. - * If string is empty or contains only whitespaces, returns -1 - */ - function firstNonWhitespaceIndex(str) { - for (let i = 0, len = str.length; i < len; i++) { - const chCode = str.charCodeAt(i); - if (chCode !== 32 /* Space */ && chCode !== 9 /* Tab */) { - return i; - } - } - return -1; - } - exports.firstNonWhitespaceIndex = firstNonWhitespaceIndex; - /** - * Returns the leading whitespace of the string. - * If the string contains only whitespaces, returns entire string - */ - function getLeadingWhitespace(str, start = 0, end = str.length) { - for (let i = start; i < end; i++) { - const chCode = str.charCodeAt(i); - if (chCode !== 32 /* Space */ && chCode !== 9 /* Tab */) { - return str.substring(start, i); - } - } - return str.substring(start, end); - } - exports.getLeadingWhitespace = getLeadingWhitespace; - /** - * Returns last index of the string that is not whitespace. - * If string is empty or contains only whitespaces, returns -1 - */ - function lastNonWhitespaceIndex(str, startIndex = str.length - 1) { - for (let i = startIndex; i >= 0; i--) { - const chCode = str.charCodeAt(i); - if (chCode !== 32 /* Space */ && chCode !== 9 /* Tab */) { - return i; - } - } - return -1; - } - exports.lastNonWhitespaceIndex = lastNonWhitespaceIndex; - function compare(a, b) { - if (a < b) { - return -1; - } - else if (a > b) { - return 1; - } - else { - return 0; - } - } - exports.compare = compare; - function compareSubstring(a, b, aStart = 0, aEnd = a.length, bStart = 0, bEnd = b.length) { - for (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) { - let codeA = a.charCodeAt(aStart); - let codeB = b.charCodeAt(bStart); - if (codeA < codeB) { - return -1; - } - else if (codeA > codeB) { - return 1; - } - } - const aLen = aEnd - aStart; - const bLen = bEnd - bStart; - if (aLen < bLen) { - return -1; - } - else if (aLen > bLen) { - return 1; - } - return 0; - } - exports.compareSubstring = compareSubstring; - function compareIgnoreCase(a, b) { - return compareSubstringIgnoreCase(a, b, 0, a.length, 0, b.length); - } - exports.compareIgnoreCase = compareIgnoreCase; - function compareSubstringIgnoreCase(a, b, aStart = 0, aEnd = a.length, bStart = 0, bEnd = b.length) { - for (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) { - let codeA = a.charCodeAt(aStart); - let codeB = b.charCodeAt(bStart); - if (codeA === codeB) { - // equal - continue; - } - const diff = codeA - codeB; - if (diff === 32 && isUpperAsciiLetter(codeB)) { //codeB =[65-90] && codeA =[97-122] - continue; - } - else if (diff === -32 && isUpperAsciiLetter(codeA)) { //codeB =[97-122] && codeA =[65-90] - continue; - } - if (isLowerAsciiLetter(codeA) && isLowerAsciiLetter(codeB)) { - // - return diff; - } - else { - return compareSubstring(a.toLowerCase(), b.toLowerCase(), aStart, aEnd, bStart, bEnd); - } - } - const aLen = aEnd - aStart; - const bLen = bEnd - bStart; - if (aLen < bLen) { - return -1; - } - else if (aLen > bLen) { - return 1; - } - return 0; - } - exports.compareSubstringIgnoreCase = compareSubstringIgnoreCase; - function isLowerAsciiLetter(code) { - return code >= 97 /* a */ && code <= 122 /* z */; - } - exports.isLowerAsciiLetter = isLowerAsciiLetter; - function isUpperAsciiLetter(code) { - return code >= 65 /* A */ && code <= 90 /* Z */; - } - exports.isUpperAsciiLetter = isUpperAsciiLetter; - function isAsciiLetter(code) { - return isLowerAsciiLetter(code) || isUpperAsciiLetter(code); - } - function equalsIgnoreCase(a, b) { - return a.length === b.length && doEqualsIgnoreCase(a, b); - } - exports.equalsIgnoreCase = equalsIgnoreCase; - function doEqualsIgnoreCase(a, b, stopAt = a.length) { - for (let i = 0; i < stopAt; i++) { - const codeA = a.charCodeAt(i); - const codeB = b.charCodeAt(i); - if (codeA === codeB) { - continue; - } - // a-z A-Z - if (isAsciiLetter(codeA) && isAsciiLetter(codeB)) { - const diff = Math.abs(codeA - codeB); - if (diff !== 0 && diff !== 32) { - return false; - } - } - // Any other charcode - else { - if (String.fromCharCode(codeA).toLowerCase() !== String.fromCharCode(codeB).toLowerCase()) { - return false; - } - } - } - return true; - } - function startsWithIgnoreCase(str, candidate) { - const candidateLength = candidate.length; - if (candidate.length > str.length) { - return false; - } - return doEqualsIgnoreCase(str, candidate, candidateLength); - } - exports.startsWithIgnoreCase = startsWithIgnoreCase; - /** - * @returns the length of the common prefix of the two strings. - */ - function commonPrefixLength(a, b) { - let i, len = Math.min(a.length, b.length); - for (i = 0; i < len; i++) { - if (a.charCodeAt(i) !== b.charCodeAt(i)) { - return i; - } - } - return len; - } - exports.commonPrefixLength = commonPrefixLength; - /** - * @returns the length of the common suffix of the two strings. - */ - function commonSuffixLength(a, b) { - let i, len = Math.min(a.length, b.length); - const aLastIndex = a.length - 1; - const bLastIndex = b.length - 1; - for (i = 0; i < len; i++) { - if (a.charCodeAt(aLastIndex - i) !== b.charCodeAt(bLastIndex - i)) { - return i; - } - } - return len; - } - exports.commonSuffixLength = commonSuffixLength; - /** - * See http://en.wikipedia.org/wiki/Surrogate_pair - */ - function isHighSurrogate(charCode) { - return (0xD800 <= charCode && charCode <= 0xDBFF); - } - exports.isHighSurrogate = isHighSurrogate; - /** - * See http://en.wikipedia.org/wiki/Surrogate_pair - */ - function isLowSurrogate(charCode) { - return (0xDC00 <= charCode && charCode <= 0xDFFF); - } - exports.isLowSurrogate = isLowSurrogate; - /** - * See http://en.wikipedia.org/wiki/Surrogate_pair - */ - function computeCodePoint(highSurrogate, lowSurrogate) { - return ((highSurrogate - 0xD800) << 10) + (lowSurrogate - 0xDC00) + 0x10000; - } - exports.computeCodePoint = computeCodePoint; - /** - * get the code point that begins at offset `offset` - */ - function getNextCodePoint(str, len, offset) { - const charCode = str.charCodeAt(offset); - if (isHighSurrogate(charCode) && offset + 1 < len) { - const nextCharCode = str.charCodeAt(offset + 1); - if (isLowSurrogate(nextCharCode)) { - return computeCodePoint(charCode, nextCharCode); - } - } - return charCode; - } - exports.getNextCodePoint = getNextCodePoint; - /** - * get the code point that ends right before offset `offset` - */ - function getPrevCodePoint(str, offset) { - const charCode = str.charCodeAt(offset - 1); - if (isLowSurrogate(charCode) && offset > 1) { - const prevCharCode = str.charCodeAt(offset - 2); - if (isHighSurrogate(prevCharCode)) { - return computeCodePoint(prevCharCode, charCode); - } - } - return charCode; - } - function nextCharLength(str, offset) { - const graphemeBreakTree = GraphemeBreakTree.getInstance(); - const initialOffset = offset; - const len = str.length; - const initialCodePoint = getNextCodePoint(str, len, offset); - offset += (initialCodePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1); - let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(initialCodePoint); - while (offset < len) { - const nextCodePoint = getNextCodePoint(str, len, offset); - const nextGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(nextCodePoint); - if (breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) { - break; - } - offset += (nextCodePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1); - graphemeBreakType = nextGraphemeBreakType; - } - return (offset - initialOffset); - } - exports.nextCharLength = nextCharLength; - function prevCharLength(str, offset) { - const graphemeBreakTree = GraphemeBreakTree.getInstance(); - const initialOffset = offset; - const initialCodePoint = getPrevCodePoint(str, offset); - offset -= (initialCodePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1); - let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(initialCodePoint); - while (offset > 0) { - const prevCodePoint = getPrevCodePoint(str, offset); - const prevGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(prevCodePoint); - if (breakBetweenGraphemeBreakType(prevGraphemeBreakType, graphemeBreakType)) { - break; - } - offset -= (prevCodePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1); - graphemeBreakType = prevGraphemeBreakType; - } - return (initialOffset - offset); - } - exports.prevCharLength = prevCharLength; - /** - * A manual decoding of a UTF8 string. - * Use only in environments which do not offer native conversion methods! - */ - function decodeUTF8(buffer) { - // https://en.wikipedia.org/wiki/UTF-8 - const len = buffer.byteLength; - const result = []; - let offset = 0; - while (offset < len) { - const v0 = buffer[offset]; - let codePoint; - if (v0 >= 0b11110000 && offset + 3 < len) { - // 4 bytes - codePoint = ((((buffer[offset++] & 0b00000111) << 18) >>> 0) - | (((buffer[offset++] & 0b00111111) << 12) >>> 0) - | (((buffer[offset++] & 0b00111111) << 6) >>> 0) - | (((buffer[offset++] & 0b00111111) << 0) >>> 0)); - } - else if (v0 >= 0b11100000 && offset + 2 < len) { - // 3 bytes - codePoint = ((((buffer[offset++] & 0b00001111) << 12) >>> 0) - | (((buffer[offset++] & 0b00111111) << 6) >>> 0) - | (((buffer[offset++] & 0b00111111) << 0) >>> 0)); - } - else if (v0 >= 0b11000000 && offset + 1 < len) { - // 2 bytes - codePoint = ((((buffer[offset++] & 0b00011111) << 6) >>> 0) - | (((buffer[offset++] & 0b00111111) << 0) >>> 0)); - } - else { - // 1 byte - codePoint = buffer[offset++]; - } - if ((codePoint >= 0 && codePoint <= 0xD7FF) || (codePoint >= 0xE000 && codePoint <= 0xFFFF)) { - // Basic Multilingual Plane - result.push(String.fromCharCode(codePoint)); - } - else if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) { - // Supplementary Planes - const uPrime = codePoint - 0x10000; - const w1 = 0xD800 + ((uPrime & 0b11111111110000000000) >>> 10); - const w2 = 0xDC00 + ((uPrime & 0b00000000001111111111) >>> 0); - result.push(String.fromCharCode(w1)); - result.push(String.fromCharCode(w2)); - } - else { - // illegal code point - result.push(String.fromCharCode(0xFFFD)); - } - } - return result.join(''); - } - exports.decodeUTF8 = decodeUTF8; - /** - * Generated using https://github.com/alexdima/unicode-utils/blob/master/generate-rtl-test.js - */ - const CONTAINS_RTL = /(?:[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05F4\u0608\u060B\u060D\u061B-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u0710\u0712-\u072F\u074D-\u07A5\u07B1-\u07EA\u07F4\u07F5\u07FA-\u0815\u081A\u0824\u0828\u0830-\u0858\u085E-\u08BD\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFD3D\uFD50-\uFDFC\uFE70-\uFEFC]|\uD802[\uDC00-\uDD1B\uDD20-\uDE00\uDE10-\uDE33\uDE40-\uDEE4\uDEEB-\uDF35\uDF40-\uDFFF]|\uD803[\uDC00-\uDCFF]|\uD83A[\uDC00-\uDCCF\uDD00-\uDD43\uDD50-\uDFFF]|\uD83B[\uDC00-\uDEBB])/; - /** - * Returns true if `str` contains any Unicode character that is classified as "R" or "AL". - */ - function containsRTL(str) { - return CONTAINS_RTL.test(str); - } - exports.containsRTL = containsRTL; - /** - * Generated using https://github.com/alexdima/unicode-utils/blob/master/generate-emoji-test.js - */ - const CONTAINS_EMOJI = /(?:[\u231A\u231B\u23F0\u23F3\u2600-\u27BF\u2B50\u2B55]|\uD83C[\uDDE6-\uDDFF\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F\uDE80-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD00-\uDDFF\uDE70-\uDED6])/; - function containsEmoji(str) { - return CONTAINS_EMOJI.test(str); - } - exports.containsEmoji = containsEmoji; - const IS_BASIC_ASCII = /^[\t\n\r\x20-\x7E]*$/; - /** - * Returns true if `str` contains only basic ASCII characters in the range 32 - 126 (including 32 and 126) or \n, \r, \t - */ - function isBasicASCII(str) { - return IS_BASIC_ASCII.test(str); - } - exports.isBasicASCII = isBasicASCII; - exports.UNUSUAL_LINE_TERMINATORS = /[\u2028\u2029]/; // LINE SEPARATOR (LS) or PARAGRAPH SEPARATOR (PS) - /** - * Returns true if `str` contains unusual line terminators, like LS or PS - */ - function containsUnusualLineTerminators(str) { - return exports.UNUSUAL_LINE_TERMINATORS.test(str); - } - exports.containsUnusualLineTerminators = containsUnusualLineTerminators; - function containsFullWidthCharacter(str) { - for (let i = 0, len = str.length; i < len; i++) { - if (isFullWidthCharacter(str.charCodeAt(i))) { - return true; - } - } - return false; - } - exports.containsFullWidthCharacter = containsFullWidthCharacter; - function isFullWidthCharacter(charCode) { - // Do a cheap trick to better support wrapping of wide characters, treat them as 2 columns - // http://jrgraphix.net/research/unicode_blocks.php - // 2E80 — 2EFF CJK Radicals Supplement - // 2F00 — 2FDF Kangxi Radicals - // 2FF0 — 2FFF Ideographic Description Characters - // 3000 — 303F CJK Symbols and Punctuation - // 3040 — 309F Hiragana - // 30A0 — 30FF Katakana - // 3100 — 312F Bopomofo - // 3130 — 318F Hangul Compatibility Jamo - // 3190 — 319F Kanbun - // 31A0 — 31BF Bopomofo Extended - // 31F0 — 31FF Katakana Phonetic Extensions - // 3200 — 32FF Enclosed CJK Letters and Months - // 3300 — 33FF CJK Compatibility - // 3400 — 4DBF CJK Unified Ideographs Extension A - // 4DC0 — 4DFF Yijing Hexagram Symbols - // 4E00 — 9FFF CJK Unified Ideographs - // A000 — A48F Yi Syllables - // A490 — A4CF Yi Radicals - // AC00 — D7AF Hangul Syllables - // [IGNORE] D800 — DB7F High Surrogates - // [IGNORE] DB80 — DBFF High Private Use Surrogates - // [IGNORE] DC00 — DFFF Low Surrogates - // [IGNORE] E000 — F8FF Private Use Area - // F900 — FAFF CJK Compatibility Ideographs - // [IGNORE] FB00 — FB4F Alphabetic Presentation Forms - // [IGNORE] FB50 — FDFF Arabic Presentation Forms-A - // [IGNORE] FE00 — FE0F Variation Selectors - // [IGNORE] FE20 — FE2F Combining Half Marks - // [IGNORE] FE30 — FE4F CJK Compatibility Forms - // [IGNORE] FE50 — FE6F Small Form Variants - // [IGNORE] FE70 — FEFF Arabic Presentation Forms-B - // FF00 — FFEF Halfwidth and Fullwidth Forms - // [https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms] - // of which FF01 - FF5E fullwidth ASCII of 21 to 7E - // [IGNORE] and FF65 - FFDC halfwidth of Katakana and Hangul - // [IGNORE] FFF0 — FFFF Specials - charCode = +charCode; // @perf - return ((charCode >= 0x2E80 && charCode <= 0xD7AF) - || (charCode >= 0xF900 && charCode <= 0xFAFF) - || (charCode >= 0xFF01 && charCode <= 0xFF5E)); - } - exports.isFullWidthCharacter = isFullWidthCharacter; - /** - * A fast function (therefore imprecise) to check if code points are emojis. - * Generated using https://github.com/alexdima/unicode-utils/blob/master/generate-emoji-test.js - */ - function isEmojiImprecise(x) { - return ((x >= 0x1F1E6 && x <= 0x1F1FF) || (x === 8986) || (x === 8987) || (x === 9200) - || (x === 9203) || (x >= 9728 && x <= 10175) || (x === 11088) || (x === 11093) - || (x >= 127744 && x <= 128591) || (x >= 128640 && x <= 128764) - || (x >= 128992 && x <= 129003) || (x >= 129280 && x <= 129535) - || (x >= 129648 && x <= 129750)); - } - exports.isEmojiImprecise = isEmojiImprecise; - // -- UTF-8 BOM - exports.UTF8_BOM_CHARACTER = String.fromCharCode(65279 /* UTF8_BOM */); - function startsWithUTF8BOM(str) { - return !!(str && str.length > 0 && str.charCodeAt(0) === 65279 /* UTF8_BOM */); - } - exports.startsWithUTF8BOM = startsWithUTF8BOM; - function containsUppercaseCharacter(target, ignoreEscapedChars = false) { - if (!target) { - return false; - } - if (ignoreEscapedChars) { - target = target.replace(/\\./g, ''); - } - return target.toLowerCase() !== target; - } - exports.containsUppercaseCharacter = containsUppercaseCharacter; - /** - * Produces 'a'-'z', followed by 'A'-'Z'... followed by 'a'-'z', etc. - */ - function singleLetterHash(n) { - const LETTERS_CNT = (90 /* Z */ - 65 /* A */ + 1); - n = n % (2 * LETTERS_CNT); - if (n < LETTERS_CNT) { - return String.fromCharCode(97 /* a */ + n); - } - return String.fromCharCode(65 /* A */ + n - LETTERS_CNT); - } - exports.singleLetterHash = singleLetterHash; - //#region Unicode Grapheme Break - function getGraphemeBreakType(codePoint) { - const graphemeBreakTree = GraphemeBreakTree.getInstance(); - return graphemeBreakTree.getGraphemeBreakType(codePoint); - } - exports.getGraphemeBreakType = getGraphemeBreakType; - function breakBetweenGraphemeBreakType(breakTypeA, breakTypeB) { - // http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundary_Rules - // !!! Let's make the common case a bit faster - if (breakTypeA === 0 /* Other */) { - // see https://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakTest-13.0.0d10.html#table - return (breakTypeB !== 5 /* Extend */ && breakTypeB !== 7 /* SpacingMark */); - } - // Do not break between a CR and LF. Otherwise, break before and after controls. - // GB3 CR × LF - // GB4 (Control | CR | LF) ÷ - // GB5 ÷ (Control | CR | LF) - if (breakTypeA === 2 /* CR */) { - if (breakTypeB === 3 /* LF */) { - return false; // GB3 - } - } - if (breakTypeA === 4 /* Control */ || breakTypeA === 2 /* CR */ || breakTypeA === 3 /* LF */) { - return true; // GB4 - } - if (breakTypeB === 4 /* Control */ || breakTypeB === 2 /* CR */ || breakTypeB === 3 /* LF */) { - return true; // GB5 - } - // Do not break Hangul syllable sequences. - // GB6 L × (L | V | LV | LVT) - // GB7 (LV | V) × (V | T) - // GB8 (LVT | T) × T - if (breakTypeA === 8 /* L */) { - if (breakTypeB === 8 /* L */ || breakTypeB === 9 /* V */ || breakTypeB === 11 /* LV */ || breakTypeB === 12 /* LVT */) { - return false; // GB6 - } - } - if (breakTypeA === 11 /* LV */ || breakTypeA === 9 /* V */) { - if (breakTypeB === 9 /* V */ || breakTypeB === 10 /* T */) { - return false; // GB7 - } - } - if (breakTypeA === 12 /* LVT */ || breakTypeA === 10 /* T */) { - if (breakTypeB === 10 /* T */) { - return false; // GB8 - } - } - // Do not break before extending characters or ZWJ. - // GB9 × (Extend | ZWJ) - if (breakTypeB === 5 /* Extend */ || breakTypeB === 13 /* ZWJ */) { - return false; // GB9 - } - // The GB9a and GB9b rules only apply to extended grapheme clusters: - // Do not break before SpacingMarks, or after Prepend characters. - // GB9a × SpacingMark - // GB9b Prepend × - if (breakTypeB === 7 /* SpacingMark */) { - return false; // GB9a - } - if (breakTypeA === 1 /* Prepend */) { - return false; // GB9b - } - // Do not break within emoji modifier sequences or emoji zwj sequences. - // GB11 \p{Extended_Pictographic} Extend* ZWJ × \p{Extended_Pictographic} - if (breakTypeA === 13 /* ZWJ */ && breakTypeB === 14 /* Extended_Pictographic */) { - // Note: we are not implementing the rule entirely here to avoid introducing states - return false; // GB11 - } - // GB12 sot (RI RI)* RI × RI - // GB13 [^RI] (RI RI)* RI × RI - if (breakTypeA === 6 /* Regional_Indicator */ && breakTypeB === 6 /* Regional_Indicator */) { - // Note: we are not implementing the rule entirely here to avoid introducing states - return false; // GB12 & GB13 - } - // GB999 Any ÷ Any - return true; - } - exports.breakBetweenGraphemeBreakType = breakBetweenGraphemeBreakType; - class GraphemeBreakTree { - constructor() { - this._data = getGraphemeBreakRawData(); - } - static getInstance() { - if (!GraphemeBreakTree._INSTANCE) { - GraphemeBreakTree._INSTANCE = new GraphemeBreakTree(); - } - return GraphemeBreakTree._INSTANCE; - } - getGraphemeBreakType(codePoint) { - // !!! Let's make 7bit ASCII a bit faster: 0..31 - if (codePoint < 32) { - if (codePoint === 10 /* LineFeed */) { - return 3 /* LF */; - } - if (codePoint === 13 /* CarriageReturn */) { - return 2 /* CR */; - } - return 4 /* Control */; - } - // !!! Let's make 7bit ASCII a bit faster: 32..126 - if (codePoint < 127) { - return 0 /* Other */; - } - const data = this._data; - const nodeCount = data.length / 3; - let nodeIndex = 1; - while (nodeIndex <= nodeCount) { - if (codePoint < data[3 * nodeIndex]) { - // go left - nodeIndex = 2 * nodeIndex; - } - else if (codePoint > data[3 * nodeIndex + 1]) { - // go right - nodeIndex = 2 * nodeIndex + 1; - } - else { - // hit - return data[3 * nodeIndex + 2]; - } - } - return 0 /* Other */; - } - } - GraphemeBreakTree._INSTANCE = null; - function getGraphemeBreakRawData() { - // generated using https://github.com/alexdima/unicode-utils/blob/master/generate-grapheme-break.js - return JSON.parse('[0,0,0,51592,51592,11,44424,44424,11,72251,72254,5,7150,7150,7,48008,48008,11,55176,55176,11,128420,128420,14,3276,3277,5,9979,9980,14,46216,46216,11,49800,49800,11,53384,53384,11,70726,70726,5,122915,122916,5,129320,129327,14,2558,2558,5,5906,5908,5,9762,9763,14,43360,43388,8,45320,45320,11,47112,47112,11,48904,48904,11,50696,50696,11,52488,52488,11,54280,54280,11,70082,70083,1,71350,71350,7,73111,73111,5,127892,127893,14,128726,128727,14,129473,129474,14,2027,2035,5,2901,2902,5,3784,3789,5,6754,6754,5,8418,8420,5,9877,9877,14,11088,11088,14,44008,44008,5,44872,44872,11,45768,45768,11,46664,46664,11,47560,47560,11,48456,48456,11,49352,49352,11,50248,50248,11,51144,51144,11,52040,52040,11,52936,52936,11,53832,53832,11,54728,54728,11,69811,69814,5,70459,70460,5,71096,71099,7,71998,71998,5,72874,72880,5,119149,119149,7,127374,127374,14,128335,128335,14,128482,128482,14,128765,128767,14,129399,129400,14,129680,129685,14,1476,1477,5,2377,2380,7,2759,2760,5,3137,3140,7,3458,3459,7,4153,4154,5,6432,6434,5,6978,6978,5,7675,7679,5,9723,9726,14,9823,9823,14,9919,9923,14,10035,10036,14,42736,42737,5,43596,43596,5,44200,44200,11,44648,44648,11,45096,45096,11,45544,45544,11,45992,45992,11,46440,46440,11,46888,46888,11,47336,47336,11,47784,47784,11,48232,48232,11,48680,48680,11,49128,49128,11,49576,49576,11,50024,50024,11,50472,50472,11,50920,50920,11,51368,51368,11,51816,51816,11,52264,52264,11,52712,52712,11,53160,53160,11,53608,53608,11,54056,54056,11,54504,54504,11,54952,54952,11,68108,68111,5,69933,69940,5,70197,70197,7,70498,70499,7,70845,70845,5,71229,71229,5,71727,71735,5,72154,72155,5,72344,72345,5,73023,73029,5,94095,94098,5,121403,121452,5,126981,127182,14,127538,127546,14,127990,127990,14,128391,128391,14,128445,128449,14,128500,128505,14,128752,128752,14,129160,129167,14,129356,129356,14,129432,129442,14,129648,129651,14,129751,131069,14,173,173,4,1757,1757,1,2274,2274,1,2494,2494,5,2641,2641,5,2876,2876,5,3014,3016,7,3262,3262,7,3393,3396,5,3570,3571,7,3968,3972,5,4228,4228,7,6086,6086,5,6679,6680,5,6912,6915,5,7080,7081,5,7380,7392,5,8252,8252,14,9096,9096,14,9748,9749,14,9784,9786,14,9833,9850,14,9890,9894,14,9938,9938,14,9999,9999,14,10085,10087,14,12349,12349,14,43136,43137,7,43454,43456,7,43755,43755,7,44088,44088,11,44312,44312,11,44536,44536,11,44760,44760,11,44984,44984,11,45208,45208,11,45432,45432,11,45656,45656,11,45880,45880,11,46104,46104,11,46328,46328,11,46552,46552,11,46776,46776,11,47000,47000,11,47224,47224,11,47448,47448,11,47672,47672,11,47896,47896,11,48120,48120,11,48344,48344,11,48568,48568,11,48792,48792,11,49016,49016,11,49240,49240,11,49464,49464,11,49688,49688,11,49912,49912,11,50136,50136,11,50360,50360,11,50584,50584,11,50808,50808,11,51032,51032,11,51256,51256,11,51480,51480,11,51704,51704,11,51928,51928,11,52152,52152,11,52376,52376,11,52600,52600,11,52824,52824,11,53048,53048,11,53272,53272,11,53496,53496,11,53720,53720,11,53944,53944,11,54168,54168,11,54392,54392,11,54616,54616,11,54840,54840,11,55064,55064,11,65438,65439,5,69633,69633,5,69837,69837,1,70018,70018,7,70188,70190,7,70368,70370,7,70465,70468,7,70712,70719,5,70835,70840,5,70850,70851,5,71132,71133,5,71340,71340,7,71458,71461,5,71985,71989,7,72002,72002,7,72193,72202,5,72281,72283,5,72766,72766,7,72885,72886,5,73104,73105,5,92912,92916,5,113824,113827,4,119173,119179,5,121505,121519,5,125136,125142,5,127279,127279,14,127489,127490,14,127570,127743,14,127900,127901,14,128254,128254,14,128369,128370,14,128400,128400,14,128425,128432,14,128468,128475,14,128489,128494,14,128715,128720,14,128745,128745,14,128759,128760,14,129004,129023,14,129296,129304,14,129340,129342,14,129388,129392,14,129404,129407,14,129454,129455,14,129485,129487,14,129659,129663,14,129719,129727,14,917536,917631,5,13,13,2,1160,1161,5,1564,1564,4,1807,1807,1,2085,2087,5,2363,2363,7,2402,2403,5,2507,2508,7,2622,2624,7,2691,2691,7,2786,2787,5,2881,2884,5,3006,3006,5,3072,3072,5,3170,3171,5,3267,3268,7,3330,3331,7,3406,3406,1,3538,3540,5,3655,3662,5,3897,3897,5,4038,4038,5,4184,4185,5,4352,4447,8,6068,6069,5,6155,6157,5,6448,6449,7,6742,6742,5,6783,6783,5,6966,6970,5,7042,7042,7,7143,7143,7,7212,7219,5,7412,7412,5,8206,8207,4,8294,8303,4,8596,8601,14,9410,9410,14,9742,9742,14,9757,9757,14,9770,9770,14,9794,9794,14,9828,9828,14,9855,9855,14,9882,9882,14,9900,9903,14,9929,9933,14,9963,9967,14,9987,9988,14,10006,10006,14,10062,10062,14,10175,10175,14,11744,11775,5,42607,42607,5,43043,43044,7,43263,43263,5,43444,43445,7,43569,43570,5,43698,43700,5,43766,43766,5,44032,44032,11,44144,44144,11,44256,44256,11,44368,44368,11,44480,44480,11,44592,44592,11,44704,44704,11,44816,44816,11,44928,44928,11,45040,45040,11,45152,45152,11,45264,45264,11,45376,45376,11,45488,45488,11,45600,45600,11,45712,45712,11,45824,45824,11,45936,45936,11,46048,46048,11,46160,46160,11,46272,46272,11,46384,46384,11,46496,46496,11,46608,46608,11,46720,46720,11,46832,46832,11,46944,46944,11,47056,47056,11,47168,47168,11,47280,47280,11,47392,47392,11,47504,47504,11,47616,47616,11,47728,47728,11,47840,47840,11,47952,47952,11,48064,48064,11,48176,48176,11,48288,48288,11,48400,48400,11,48512,48512,11,48624,48624,11,48736,48736,11,48848,48848,11,48960,48960,11,49072,49072,11,49184,49184,11,49296,49296,11,49408,49408,11,49520,49520,11,49632,49632,11,49744,49744,11,49856,49856,11,49968,49968,11,50080,50080,11,50192,50192,11,50304,50304,11,50416,50416,11,50528,50528,11,50640,50640,11,50752,50752,11,50864,50864,11,50976,50976,11,51088,51088,11,51200,51200,11,51312,51312,11,51424,51424,11,51536,51536,11,51648,51648,11,51760,51760,11,51872,51872,11,51984,51984,11,52096,52096,11,52208,52208,11,52320,52320,11,52432,52432,11,52544,52544,11,52656,52656,11,52768,52768,11,52880,52880,11,52992,52992,11,53104,53104,11,53216,53216,11,53328,53328,11,53440,53440,11,53552,53552,11,53664,53664,11,53776,53776,11,53888,53888,11,54000,54000,11,54112,54112,11,54224,54224,11,54336,54336,11,54448,54448,11,54560,54560,11,54672,54672,11,54784,54784,11,54896,54896,11,55008,55008,11,55120,55120,11,64286,64286,5,66272,66272,5,68900,68903,5,69762,69762,7,69817,69818,5,69927,69931,5,70003,70003,5,70070,70078,5,70094,70094,7,70194,70195,7,70206,70206,5,70400,70401,5,70463,70463,7,70475,70477,7,70512,70516,5,70722,70724,5,70832,70832,5,70842,70842,5,70847,70848,5,71088,71089,7,71102,71102,7,71219,71226,5,71231,71232,5,71342,71343,7,71453,71455,5,71463,71467,5,71737,71738,5,71995,71996,5,72000,72000,7,72145,72147,7,72160,72160,5,72249,72249,7,72273,72278,5,72330,72342,5,72752,72758,5,72850,72871,5,72882,72883,5,73018,73018,5,73031,73031,5,73109,73109,5,73461,73462,7,94031,94031,5,94192,94193,7,119142,119142,7,119155,119162,4,119362,119364,5,121476,121476,5,122888,122904,5,123184,123190,5,126976,126979,14,127184,127231,14,127344,127345,14,127405,127461,14,127514,127514,14,127561,127567,14,127778,127779,14,127896,127896,14,127985,127986,14,127995,127999,5,128326,128328,14,128360,128366,14,128378,128378,14,128394,128397,14,128405,128406,14,128422,128423,14,128435,128443,14,128453,128464,14,128479,128480,14,128484,128487,14,128496,128498,14,128640,128709,14,128723,128724,14,128736,128741,14,128747,128748,14,128755,128755,14,128762,128762,14,128981,128991,14,129096,129103,14,129292,129292,14,129311,129311,14,129329,129330,14,129344,129349,14,129360,129374,14,129394,129394,14,129402,129402,14,129413,129425,14,129445,129450,14,129466,129471,14,129483,129483,14,129511,129535,14,129653,129655,14,129667,129670,14,129705,129711,14,129731,129743,14,917505,917505,4,917760,917999,5,10,10,3,127,159,4,768,879,5,1471,1471,5,1536,1541,1,1648,1648,5,1767,1768,5,1840,1866,5,2070,2073,5,2137,2139,5,2307,2307,7,2366,2368,7,2382,2383,7,2434,2435,7,2497,2500,5,2519,2519,5,2563,2563,7,2631,2632,5,2677,2677,5,2750,2752,7,2763,2764,7,2817,2817,5,2879,2879,5,2891,2892,7,2914,2915,5,3008,3008,5,3021,3021,5,3076,3076,5,3146,3149,5,3202,3203,7,3264,3265,7,3271,3272,7,3298,3299,5,3390,3390,5,3402,3404,7,3426,3427,5,3535,3535,5,3544,3550,7,3635,3635,7,3763,3763,7,3893,3893,5,3953,3966,5,3981,3991,5,4145,4145,7,4157,4158,5,4209,4212,5,4237,4237,5,4520,4607,10,5970,5971,5,6071,6077,5,6089,6099,5,6277,6278,5,6439,6440,5,6451,6456,7,6683,6683,5,6744,6750,5,6765,6770,7,6846,6846,5,6964,6964,5,6972,6972,5,7019,7027,5,7074,7077,5,7083,7085,5,7146,7148,7,7154,7155,7,7222,7223,5,7394,7400,5,7416,7417,5,8204,8204,5,8233,8233,4,8288,8292,4,8413,8416,5,8482,8482,14,8986,8987,14,9193,9203,14,9654,9654,14,9733,9733,14,9745,9745,14,9752,9752,14,9760,9760,14,9766,9766,14,9774,9775,14,9792,9792,14,9800,9811,14,9825,9826,14,9831,9831,14,9852,9853,14,9872,9873,14,9880,9880,14,9885,9887,14,9896,9897,14,9906,9916,14,9926,9927,14,9936,9936,14,9941,9960,14,9974,9974,14,9982,9985,14,9992,9997,14,10002,10002,14,10017,10017,14,10055,10055,14,10071,10071,14,10145,10145,14,11013,11015,14,11503,11505,5,12334,12335,5,12951,12951,14,42612,42621,5,43014,43014,5,43047,43047,7,43204,43205,5,43335,43345,5,43395,43395,7,43450,43451,7,43561,43566,5,43573,43574,5,43644,43644,5,43710,43711,5,43758,43759,7,44005,44005,5,44012,44012,7,44060,44060,11,44116,44116,11,44172,44172,11,44228,44228,11,44284,44284,11,44340,44340,11,44396,44396,11,44452,44452,11,44508,44508,11,44564,44564,11,44620,44620,11,44676,44676,11,44732,44732,11,44788,44788,11,44844,44844,11,44900,44900,11,44956,44956,11,45012,45012,11,45068,45068,11,45124,45124,11,45180,45180,11,45236,45236,11,45292,45292,11,45348,45348,11,45404,45404,11,45460,45460,11,45516,45516,11,45572,45572,11,45628,45628,11,45684,45684,11,45740,45740,11,45796,45796,11,45852,45852,11,45908,45908,11,45964,45964,11,46020,46020,11,46076,46076,11,46132,46132,11,46188,46188,11,46244,46244,11,46300,46300,11,46356,46356,11,46412,46412,11,46468,46468,11,46524,46524,11,46580,46580,11,46636,46636,11,46692,46692,11,46748,46748,11,46804,46804,11,46860,46860,11,46916,46916,11,46972,46972,11,47028,47028,11,47084,47084,11,47140,47140,11,47196,47196,11,47252,47252,11,47308,47308,11,47364,47364,11,47420,47420,11,47476,47476,11,47532,47532,11,47588,47588,11,47644,47644,11,47700,47700,11,47756,47756,11,47812,47812,11,47868,47868,11,47924,47924,11,47980,47980,11,48036,48036,11,48092,48092,11,48148,48148,11,48204,48204,11,48260,48260,11,48316,48316,11,48372,48372,11,48428,48428,11,48484,48484,11,48540,48540,11,48596,48596,11,48652,48652,11,48708,48708,11,48764,48764,11,48820,48820,11,48876,48876,11,48932,48932,11,48988,48988,11,49044,49044,11,49100,49100,11,49156,49156,11,49212,49212,11,49268,49268,11,49324,49324,11,49380,49380,11,49436,49436,11,49492,49492,11,49548,49548,11,49604,49604,11,49660,49660,11,49716,49716,11,49772,49772,11,49828,49828,11,49884,49884,11,49940,49940,11,49996,49996,11,50052,50052,11,50108,50108,11,50164,50164,11,50220,50220,11,50276,50276,11,50332,50332,11,50388,50388,11,50444,50444,11,50500,50500,11,50556,50556,11,50612,50612,11,50668,50668,11,50724,50724,11,50780,50780,11,50836,50836,11,50892,50892,11,50948,50948,11,51004,51004,11,51060,51060,11,51116,51116,11,51172,51172,11,51228,51228,11,51284,51284,11,51340,51340,11,51396,51396,11,51452,51452,11,51508,51508,11,51564,51564,11,51620,51620,11,51676,51676,11,51732,51732,11,51788,51788,11,51844,51844,11,51900,51900,11,51956,51956,11,52012,52012,11,52068,52068,11,52124,52124,11,52180,52180,11,52236,52236,11,52292,52292,11,52348,52348,11,52404,52404,11,52460,52460,11,52516,52516,11,52572,52572,11,52628,52628,11,52684,52684,11,52740,52740,11,52796,52796,11,52852,52852,11,52908,52908,11,52964,52964,11,53020,53020,11,53076,53076,11,53132,53132,11,53188,53188,11,53244,53244,11,53300,53300,11,53356,53356,11,53412,53412,11,53468,53468,11,53524,53524,11,53580,53580,11,53636,53636,11,53692,53692,11,53748,53748,11,53804,53804,11,53860,53860,11,53916,53916,11,53972,53972,11,54028,54028,11,54084,54084,11,54140,54140,11,54196,54196,11,54252,54252,11,54308,54308,11,54364,54364,11,54420,54420,11,54476,54476,11,54532,54532,11,54588,54588,11,54644,54644,11,54700,54700,11,54756,54756,11,54812,54812,11,54868,54868,11,54924,54924,11,54980,54980,11,55036,55036,11,55092,55092,11,55148,55148,11,55216,55238,9,65056,65071,5,65529,65531,4,68097,68099,5,68159,68159,5,69446,69456,5,69688,69702,5,69808,69810,7,69815,69816,7,69821,69821,1,69888,69890,5,69932,69932,7,69957,69958,7,70016,70017,5,70067,70069,7,70079,70080,7,70089,70092,5,70095,70095,5,70191,70193,5,70196,70196,5,70198,70199,5,70367,70367,5,70371,70378,5,70402,70403,7,70462,70462,5,70464,70464,5,70471,70472,7,70487,70487,5,70502,70508,5,70709,70711,7,70720,70721,7,70725,70725,7,70750,70750,5,70833,70834,7,70841,70841,7,70843,70844,7,70846,70846,7,70849,70849,7,71087,71087,5,71090,71093,5,71100,71101,5,71103,71104,5,71216,71218,7,71227,71228,7,71230,71230,7,71339,71339,5,71341,71341,5,71344,71349,5,71351,71351,5,71456,71457,7,71462,71462,7,71724,71726,7,71736,71736,7,71984,71984,5,71991,71992,7,71997,71997,7,71999,71999,1,72001,72001,1,72003,72003,5,72148,72151,5,72156,72159,7,72164,72164,7,72243,72248,5,72250,72250,1,72263,72263,5,72279,72280,7,72324,72329,1,72343,72343,7,72751,72751,7,72760,72765,5,72767,72767,5,72873,72873,7,72881,72881,7,72884,72884,7,73009,73014,5,73020,73021,5,73030,73030,1,73098,73102,7,73107,73108,7,73110,73110,7,73459,73460,5,78896,78904,4,92976,92982,5,94033,94087,7,94180,94180,5,113821,113822,5,119141,119141,5,119143,119145,5,119150,119154,5,119163,119170,5,119210,119213,5,121344,121398,5,121461,121461,5,121499,121503,5,122880,122886,5,122907,122913,5,122918,122922,5,123628,123631,5,125252,125258,5,126980,126980,14,127183,127183,14,127245,127247,14,127340,127343,14,127358,127359,14,127377,127386,14,127462,127487,6,127491,127503,14,127535,127535,14,127548,127551,14,127568,127569,14,127744,127777,14,127780,127891,14,127894,127895,14,127897,127899,14,127902,127984,14,127987,127989,14,127991,127994,14,128000,128253,14,128255,128317,14,128329,128334,14,128336,128359,14,128367,128368,14,128371,128377,14,128379,128390,14,128392,128393,14,128398,128399,14,128401,128404,14,128407,128419,14,128421,128421,14,128424,128424,14,128433,128434,14,128444,128444,14,128450,128452,14,128465,128467,14,128476,128478,14,128481,128481,14,128483,128483,14,128488,128488,14,128495,128495,14,128499,128499,14,128506,128591,14,128710,128714,14,128721,128722,14,128725,128725,14,128728,128735,14,128742,128744,14,128746,128746,14,128749,128751,14,128753,128754,14,128756,128758,14,128761,128761,14,128763,128764,14,128884,128895,14,128992,129003,14,129036,129039,14,129114,129119,14,129198,129279,14,129293,129295,14,129305,129310,14,129312,129319,14,129328,129328,14,129331,129338,14,129343,129343,14,129351,129355,14,129357,129359,14,129375,129387,14,129393,129393,14,129395,129398,14,129401,129401,14,129403,129403,14,129408,129412,14,129426,129431,14,129443,129444,14,129451,129453,14,129456,129465,14,129472,129472,14,129475,129482,14,129484,129484,14,129488,129510,14,129536,129647,14,129652,129652,14,129656,129658,14,129664,129666,14,129671,129679,14,129686,129704,14,129712,129718,14,129728,129730,14,129744,129750,14,917504,917504,4,917506,917535,4,917632,917759,4,918000,921599,4,0,9,4,11,12,4,14,31,4,169,169,14,174,174,14,1155,1159,5,1425,1469,5,1473,1474,5,1479,1479,5,1552,1562,5,1611,1631,5,1750,1756,5,1759,1764,5,1770,1773,5,1809,1809,5,1958,1968,5,2045,2045,5,2075,2083,5,2089,2093,5,2259,2273,5,2275,2306,5,2362,2362,5,2364,2364,5,2369,2376,5,2381,2381,5,2385,2391,5,2433,2433,5,2492,2492,5,2495,2496,7,2503,2504,7,2509,2509,5,2530,2531,5,2561,2562,5,2620,2620,5,2625,2626,5,2635,2637,5,2672,2673,5,2689,2690,5,2748,2748,5,2753,2757,5,2761,2761,7,2765,2765,5,2810,2815,5,2818,2819,7,2878,2878,5,2880,2880,7,2887,2888,7,2893,2893,5,2903,2903,5,2946,2946,5,3007,3007,7,3009,3010,7,3018,3020,7,3031,3031,5,3073,3075,7,3134,3136,5,3142,3144,5,3157,3158,5,3201,3201,5,3260,3260,5,3263,3263,5,3266,3266,5,3270,3270,5,3274,3275,7,3285,3286,5,3328,3329,5,3387,3388,5,3391,3392,7,3398,3400,7,3405,3405,5,3415,3415,5,3457,3457,5,3530,3530,5,3536,3537,7,3542,3542,5,3551,3551,5,3633,3633,5,3636,3642,5,3761,3761,5,3764,3772,5,3864,3865,5,3895,3895,5,3902,3903,7,3967,3967,7,3974,3975,5,3993,4028,5,4141,4144,5,4146,4151,5,4155,4156,7,4182,4183,7,4190,4192,5,4226,4226,5,4229,4230,5,4253,4253,5,4448,4519,9,4957,4959,5,5938,5940,5,6002,6003,5,6070,6070,7,6078,6085,7,6087,6088,7,6109,6109,5,6158,6158,4,6313,6313,5,6435,6438,7,6441,6443,7,6450,6450,5,6457,6459,5,6681,6682,7,6741,6741,7,6743,6743,7,6752,6752,5,6757,6764,5,6771,6780,5,6832,6845,5,6847,6848,5,6916,6916,7,6965,6965,5,6971,6971,7,6973,6977,7,6979,6980,7,7040,7041,5,7073,7073,7,7078,7079,7,7082,7082,7,7142,7142,5,7144,7145,5,7149,7149,5,7151,7153,5,7204,7211,7,7220,7221,7,7376,7378,5,7393,7393,7,7405,7405,5,7415,7415,7,7616,7673,5,8203,8203,4,8205,8205,13,8232,8232,4,8234,8238,4,8265,8265,14,8293,8293,4,8400,8412,5,8417,8417,5,8421,8432,5,8505,8505,14,8617,8618,14,9000,9000,14,9167,9167,14,9208,9210,14,9642,9643,14,9664,9664,14,9728,9732,14,9735,9741,14,9743,9744,14,9746,9746,14,9750,9751,14,9753,9756,14,9758,9759,14,9761,9761,14,9764,9765,14,9767,9769,14,9771,9773,14,9776,9783,14,9787,9791,14,9793,9793,14,9795,9799,14,9812,9822,14,9824,9824,14,9827,9827,14,9829,9830,14,9832,9832,14,9851,9851,14,9854,9854,14,9856,9861,14,9874,9876,14,9878,9879,14,9881,9881,14,9883,9884,14,9888,9889,14,9895,9895,14,9898,9899,14,9904,9905,14,9917,9918,14,9924,9925,14,9928,9928,14,9934,9935,14,9937,9937,14,9939,9940,14,9961,9962,14,9968,9973,14,9975,9978,14,9981,9981,14,9986,9986,14,9989,9989,14,9998,9998,14,10000,10001,14,10004,10004,14,10013,10013,14,10024,10024,14,10052,10052,14,10060,10060,14,10067,10069,14,10083,10084,14,10133,10135,14,10160,10160,14,10548,10549,14,11035,11036,14,11093,11093,14,11647,11647,5,12330,12333,5,12336,12336,14,12441,12442,5,12953,12953,14,42608,42610,5,42654,42655,5,43010,43010,5,43019,43019,5,43045,43046,5,43052,43052,5,43188,43203,7,43232,43249,5,43302,43309,5,43346,43347,7,43392,43394,5,43443,43443,5,43446,43449,5,43452,43453,5,43493,43493,5,43567,43568,7,43571,43572,7,43587,43587,5,43597,43597,7,43696,43696,5,43703,43704,5,43713,43713,5,43756,43757,5,43765,43765,7,44003,44004,7,44006,44007,7,44009,44010,7,44013,44013,5,44033,44059,12,44061,44087,12,44089,44115,12,44117,44143,12,44145,44171,12,44173,44199,12,44201,44227,12,44229,44255,12,44257,44283,12,44285,44311,12,44313,44339,12,44341,44367,12,44369,44395,12,44397,44423,12,44425,44451,12,44453,44479,12,44481,44507,12,44509,44535,12,44537,44563,12,44565,44591,12,44593,44619,12,44621,44647,12,44649,44675,12,44677,44703,12,44705,44731,12,44733,44759,12,44761,44787,12,44789,44815,12,44817,44843,12,44845,44871,12,44873,44899,12,44901,44927,12,44929,44955,12,44957,44983,12,44985,45011,12,45013,45039,12,45041,45067,12,45069,45095,12,45097,45123,12,45125,45151,12,45153,45179,12,45181,45207,12,45209,45235,12,45237,45263,12,45265,45291,12,45293,45319,12,45321,45347,12,45349,45375,12,45377,45403,12,45405,45431,12,45433,45459,12,45461,45487,12,45489,45515,12,45517,45543,12,45545,45571,12,45573,45599,12,45601,45627,12,45629,45655,12,45657,45683,12,45685,45711,12,45713,45739,12,45741,45767,12,45769,45795,12,45797,45823,12,45825,45851,12,45853,45879,12,45881,45907,12,45909,45935,12,45937,45963,12,45965,45991,12,45993,46019,12,46021,46047,12,46049,46075,12,46077,46103,12,46105,46131,12,46133,46159,12,46161,46187,12,46189,46215,12,46217,46243,12,46245,46271,12,46273,46299,12,46301,46327,12,46329,46355,12,46357,46383,12,46385,46411,12,46413,46439,12,46441,46467,12,46469,46495,12,46497,46523,12,46525,46551,12,46553,46579,12,46581,46607,12,46609,46635,12,46637,46663,12,46665,46691,12,46693,46719,12,46721,46747,12,46749,46775,12,46777,46803,12,46805,46831,12,46833,46859,12,46861,46887,12,46889,46915,12,46917,46943,12,46945,46971,12,46973,46999,12,47001,47027,12,47029,47055,12,47057,47083,12,47085,47111,12,47113,47139,12,47141,47167,12,47169,47195,12,47197,47223,12,47225,47251,12,47253,47279,12,47281,47307,12,47309,47335,12,47337,47363,12,47365,47391,12,47393,47419,12,47421,47447,12,47449,47475,12,47477,47503,12,47505,47531,12,47533,47559,12,47561,47587,12,47589,47615,12,47617,47643,12,47645,47671,12,47673,47699,12,47701,47727,12,47729,47755,12,47757,47783,12,47785,47811,12,47813,47839,12,47841,47867,12,47869,47895,12,47897,47923,12,47925,47951,12,47953,47979,12,47981,48007,12,48009,48035,12,48037,48063,12,48065,48091,12,48093,48119,12,48121,48147,12,48149,48175,12,48177,48203,12,48205,48231,12,48233,48259,12,48261,48287,12,48289,48315,12,48317,48343,12,48345,48371,12,48373,48399,12,48401,48427,12,48429,48455,12,48457,48483,12,48485,48511,12,48513,48539,12,48541,48567,12,48569,48595,12,48597,48623,12,48625,48651,12,48653,48679,12,48681,48707,12,48709,48735,12,48737,48763,12,48765,48791,12,48793,48819,12,48821,48847,12,48849,48875,12,48877,48903,12,48905,48931,12,48933,48959,12,48961,48987,12,48989,49015,12,49017,49043,12,49045,49071,12,49073,49099,12,49101,49127,12,49129,49155,12,49157,49183,12,49185,49211,12,49213,49239,12,49241,49267,12,49269,49295,12,49297,49323,12,49325,49351,12,49353,49379,12,49381,49407,12,49409,49435,12,49437,49463,12,49465,49491,12,49493,49519,12,49521,49547,12,49549,49575,12,49577,49603,12,49605,49631,12,49633,49659,12,49661,49687,12,49689,49715,12,49717,49743,12,49745,49771,12,49773,49799,12,49801,49827,12,49829,49855,12,49857,49883,12,49885,49911,12,49913,49939,12,49941,49967,12,49969,49995,12,49997,50023,12,50025,50051,12,50053,50079,12,50081,50107,12,50109,50135,12,50137,50163,12,50165,50191,12,50193,50219,12,50221,50247,12,50249,50275,12,50277,50303,12,50305,50331,12,50333,50359,12,50361,50387,12,50389,50415,12,50417,50443,12,50445,50471,12,50473,50499,12,50501,50527,12,50529,50555,12,50557,50583,12,50585,50611,12,50613,50639,12,50641,50667,12,50669,50695,12,50697,50723,12,50725,50751,12,50753,50779,12,50781,50807,12,50809,50835,12,50837,50863,12,50865,50891,12,50893,50919,12,50921,50947,12,50949,50975,12,50977,51003,12,51005,51031,12,51033,51059,12,51061,51087,12,51089,51115,12,51117,51143,12,51145,51171,12,51173,51199,12,51201,51227,12,51229,51255,12,51257,51283,12,51285,51311,12,51313,51339,12,51341,51367,12,51369,51395,12,51397,51423,12,51425,51451,12,51453,51479,12,51481,51507,12,51509,51535,12,51537,51563,12,51565,51591,12,51593,51619,12,51621,51647,12,51649,51675,12,51677,51703,12,51705,51731,12,51733,51759,12,51761,51787,12,51789,51815,12,51817,51843,12,51845,51871,12,51873,51899,12,51901,51927,12,51929,51955,12,51957,51983,12,51985,52011,12,52013,52039,12,52041,52067,12,52069,52095,12,52097,52123,12,52125,52151,12,52153,52179,12,52181,52207,12,52209,52235,12,52237,52263,12,52265,52291,12,52293,52319,12,52321,52347,12,52349,52375,12,52377,52403,12,52405,52431,12,52433,52459,12,52461,52487,12,52489,52515,12,52517,52543,12,52545,52571,12,52573,52599,12,52601,52627,12,52629,52655,12,52657,52683,12,52685,52711,12,52713,52739,12,52741,52767,12,52769,52795,12,52797,52823,12,52825,52851,12,52853,52879,12,52881,52907,12,52909,52935,12,52937,52963,12,52965,52991,12,52993,53019,12,53021,53047,12,53049,53075,12,53077,53103,12,53105,53131,12,53133,53159,12,53161,53187,12,53189,53215,12,53217,53243,12,53245,53271,12,53273,53299,12,53301,53327,12,53329,53355,12,53357,53383,12,53385,53411,12,53413,53439,12,53441,53467,12,53469,53495,12,53497,53523,12,53525,53551,12,53553,53579,12,53581,53607,12,53609,53635,12,53637,53663,12,53665,53691,12,53693,53719,12,53721,53747,12,53749,53775,12,53777,53803,12,53805,53831,12,53833,53859,12,53861,53887,12,53889,53915,12,53917,53943,12,53945,53971,12,53973,53999,12,54001,54027,12,54029,54055,12,54057,54083,12,54085,54111,12,54113,54139,12,54141,54167,12,54169,54195,12,54197,54223,12,54225,54251,12,54253,54279,12,54281,54307,12,54309,54335,12,54337,54363,12,54365,54391,12,54393,54419,12,54421,54447,12,54449,54475,12,54477,54503,12,54505,54531,12,54533,54559,12,54561,54587,12,54589,54615,12,54617,54643,12,54645,54671,12,54673,54699,12,54701,54727,12,54729,54755,12,54757,54783,12,54785,54811,12,54813,54839,12,54841,54867,12,54869,54895,12,54897,54923,12,54925,54951,12,54953,54979,12,54981,55007,12,55009,55035,12,55037,55063,12,55065,55091,12,55093,55119,12,55121,55147,12,55149,55175,12,55177,55203,12,55243,55291,10,65024,65039,5,65279,65279,4,65520,65528,4,66045,66045,5,66422,66426,5,68101,68102,5,68152,68154,5,68325,68326,5,69291,69292,5,69632,69632,7,69634,69634,7,69759,69761,5]'); - } - //#endregion - /** - * Computes the offset after performing a left delete on the given string, - * while considering unicode grapheme/emoji rules. - */ - function getLeftDeleteOffset(offset, str) { - if (offset === 0) { - return 0; - } - // Try to delete emoji part. - const emojiOffset = getOffsetBeforeLastEmojiComponent(offset, str); - if (emojiOffset !== undefined) { - return emojiOffset; - } - // Otherwise, just skip a single code point. - const codePoint = getPrevCodePoint(str, offset); - offset -= getUTF16Length(codePoint); - return offset; - } - exports.getLeftDeleteOffset = getLeftDeleteOffset; - function getOffsetBeforeLastEmojiComponent(offset, str) { - // See https://www.unicode.org/reports/tr51/tr51-14.html#EBNF_and_Regex for the - // structure of emojis. - let codePoint = getPrevCodePoint(str, offset); - offset -= getUTF16Length(codePoint); - // Skip modifiers - while ((isEmojiModifier(codePoint) || codePoint === 65039 /* emojiVariantSelector */ || codePoint === 8419 /* enclosingKeyCap */)) { - if (offset === 0) { - // Cannot skip modifier, no preceding emoji base. - return undefined; - } - codePoint = getPrevCodePoint(str, offset); - offset -= getUTF16Length(codePoint); - } - // Expect base emoji - if (!isEmojiImprecise(codePoint)) { - // Unexpected code point, not a valid emoji. - return undefined; - } - if (offset >= 0) { - // Skip optional ZWJ code points that combine multiple emojis. - // In theory, we should check if that ZWJ actually combines multiple emojis - // to prevent deleting ZWJs in situations we didn't account for. - const optionalZwjCodePoint = getPrevCodePoint(str, offset); - if (optionalZwjCodePoint === 8205 /* zwj */) { - offset -= getUTF16Length(optionalZwjCodePoint); - } - } - return offset; - } - function getUTF16Length(codePoint) { - return codePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1; - } - function isEmojiModifier(codePoint) { - return 0x1F3FB <= codePoint && codePoint <= 0x1F3FF; - } -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[103/*vs/base/common/buffer*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/]), function (require, exports, strings) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.writeUInt8 = exports.readUInt8 = exports.writeUInt32BE = exports.readUInt32BE = exports.writeUInt16LE = exports.readUInt16LE = exports.VSBuffer = void 0; - const hasBuffer = (typeof Buffer !== 'undefined'); - const hasTextDecoder = (typeof TextDecoder !== 'undefined'); - let textDecoder; - class VSBuffer { - constructor(buffer) { - this.buffer = buffer; - this.byteLength = this.buffer.byteLength; - } - static wrap(actual) { - if (hasBuffer && !(Buffer.isBuffer(actual))) { - // https://nodejs.org/dist/latest-v10.x/docs/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length - // Create a zero-copy Buffer wrapper around the ArrayBuffer pointed to by the Uint8Array - actual = Buffer.from(actual.buffer, actual.byteOffset, actual.byteLength); - } - return new VSBuffer(actual); - } - toString() { - if (hasBuffer) { - return this.buffer.toString(); - } - else if (hasTextDecoder) { - if (!textDecoder) { - textDecoder = new TextDecoder(); - } - return textDecoder.decode(this.buffer); - } - else { - return strings.decodeUTF8(this.buffer); - } - } - } - exports.VSBuffer = VSBuffer; - function readUInt16LE(source, offset) { - return (((source[offset + 0] << 0) >>> 0) | - ((source[offset + 1] << 8) >>> 0)); - } - exports.readUInt16LE = readUInt16LE; - function writeUInt16LE(destination, value, offset) { - destination[offset + 0] = (value & 0b11111111); - value = value >>> 8; - destination[offset + 1] = (value & 0b11111111); - } - exports.writeUInt16LE = writeUInt16LE; - function readUInt32BE(source, offset) { - return (source[offset] * Math.pow(2, 24) - + source[offset + 1] * Math.pow(2, 16) - + source[offset + 2] * Math.pow(2, 8) - + source[offset + 3]); - } - exports.readUInt32BE = readUInt32BE; - function writeUInt32BE(destination, value, offset) { - destination[offset + 3] = value; - value = value >>> 8; - destination[offset + 2] = value; - value = value >>> 8; - destination[offset + 1] = value; - value = value >>> 8; - destination[offset] = value; - } - exports.writeUInt32BE = writeUInt32BE; - function readUInt8(source, offset) { - return source[offset]; - } - exports.readUInt8 = readUInt8; - function writeUInt8(destination, value, offset) { - destination[offset] = value; - } - exports.writeUInt8 = writeUInt8; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/common/extpath*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/,8/*vs/base/common/strings*/,73/*vs/base/common/path*/]), function (require, exports, platform_1, strings_1, path_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.hasDriveLetter = exports.isRootOrDriveLetter = exports.isWindowsDriveLetter = exports.isEqualOrParent = exports.toPosixPath = exports.toSlashes = void 0; - /** - * Takes a Windows OS path and changes backward slashes to forward slashes. - * This should only be done for OS paths from Windows (or user provided paths potentially from Windows). - * Using it on a Linux or MaxOS path might change it. - */ - function toSlashes(osPath) { - return osPath.replace(/[\\/]/g, path_1.posix.sep); - } - exports.toSlashes = toSlashes; - /** - * Takes a Windows OS path (using backward or forward slashes) and turns it into a posix path: - * - turns backward slashes into forward slashes - * - makes it absolute if it starts with a drive letter - * This should only be done for OS paths from Windows (or user provided paths potentially from Windows). - * Using it on a Linux or MaxOS path might change it. - */ - function toPosixPath(osPath) { - if (osPath.indexOf('/') === -1) { - osPath = toSlashes(osPath); - } - if (/^[a-zA-Z]:(\/|$)/.test(osPath)) { // starts with a drive letter - osPath = '/' + osPath; - } - return osPath; - } - exports.toPosixPath = toPosixPath; - function isEqualOrParent(base, parentCandidate, ignoreCase, separator = path_1.sep) { - if (base === parentCandidate) { - return true; - } - if (!base || !parentCandidate) { - return false; - } - if (parentCandidate.length > base.length) { - return false; - } - if (ignoreCase) { - const beginsWith = (0, strings_1.startsWithIgnoreCase)(base, parentCandidate); - if (!beginsWith) { - return false; - } - if (parentCandidate.length === base.length) { - return true; // same path, different casing - } - let sepOffset = parentCandidate.length; - if (parentCandidate.charAt(parentCandidate.length - 1) === separator) { - sepOffset--; // adjust the expected sep offset in case our candidate already ends in separator character - } - return base.charAt(sepOffset) === separator; - } - if (parentCandidate.charAt(parentCandidate.length - 1) !== separator) { - parentCandidate += separator; - } - return base.indexOf(parentCandidate) === 0; - } - exports.isEqualOrParent = isEqualOrParent; - function isWindowsDriveLetter(char0) { - return char0 >= 65 /* A */ && char0 <= 90 /* Z */ || char0 >= 97 /* a */ && char0 <= 122 /* z */; - } - exports.isWindowsDriveLetter = isWindowsDriveLetter; - function isRootOrDriveLetter(path) { - const pathNormalized = (0, path_1.normalize)(path); - if (platform_1.isWindows) { - if (path.length > 3) { - return false; - } - return hasDriveLetter(pathNormalized) && - (path.length === 2 || pathNormalized.charCodeAt(2) === 92 /* Backslash */); - } - return pathNormalized === path_1.posix.sep; - } - exports.isRootOrDriveLetter = isRootOrDriveLetter; - function hasDriveLetter(path) { - if (platform_1.isWindows) { - return isWindowsDriveLetter(path.charCodeAt(0)) && path.charCodeAt(1) === 58 /* Colon */; - } - return false; - } - exports.hasDriveLetter = hasDriveLetter; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/common/hash*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/]), function (require, exports, strings) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.StringSHA1 = exports.toHexString = exports.stringHash = exports.doHash = exports.hash = void 0; - /** - * Return a hash value for an object. - */ - function hash(obj) { - return doHash(obj, 0); - } - exports.hash = hash; - function doHash(obj, hashVal) { - switch (typeof obj) { - case 'object': - if (obj === null) { - return numberHash(349, hashVal); - } - else if (Array.isArray(obj)) { - return arrayHash(obj, hashVal); - } - return objectHash(obj, hashVal); - case 'string': - return stringHash(obj, hashVal); - case 'boolean': - return booleanHash(obj, hashVal); - case 'number': - return numberHash(obj, hashVal); - case 'undefined': - return numberHash(937, hashVal); - default: - return numberHash(617, hashVal); - } - } - exports.doHash = doHash; - function numberHash(val, initialHashVal) { - return (((initialHashVal << 5) - initialHashVal) + val) | 0; // hashVal * 31 + ch, keep as int32 - } - function booleanHash(b, initialHashVal) { - return numberHash(b ? 433 : 863, initialHashVal); - } - function stringHash(s, hashVal) { - hashVal = numberHash(149417, hashVal); - for (let i = 0, length = s.length; i < length; i++) { - hashVal = numberHash(s.charCodeAt(i), hashVal); - } - return hashVal; - } - exports.stringHash = stringHash; - function arrayHash(arr, initialHashVal) { - initialHashVal = numberHash(104579, initialHashVal); - return arr.reduce((hashVal, item) => doHash(item, hashVal), initialHashVal); - } - function objectHash(obj, initialHashVal) { - initialHashVal = numberHash(181387, initialHashVal); - return Object.keys(obj).sort().reduce((hashVal, key) => { - hashVal = stringHash(key, hashVal); - return doHash(obj[key], hashVal); - }, initialHashVal); - } - function leftRotate(value, bits, totalBits = 32) { - // delta + bits = totalBits - const delta = totalBits - bits; - // All ones, expect `delta` zeros aligned to the right - const mask = ~((1 << delta) - 1); - // Join (value left-shifted `bits` bits) with (masked value right-shifted `delta` bits) - return ((value << bits) | ((mask & value) >>> delta)) >>> 0; - } - function fill(dest, index = 0, count = dest.byteLength, value = 0) { - for (let i = 0; i < count; i++) { - dest[index + i] = value; - } - } - function leftPad(value, length, char = '0') { - while (value.length < length) { - value = char + value; - } - return value; - } - function toHexString(bufferOrValue, bitsize = 32) { - if (bufferOrValue instanceof ArrayBuffer) { - return Array.from(new Uint8Array(bufferOrValue)).map(b => b.toString(16).padStart(2, '0')).join(''); - } - return leftPad((bufferOrValue >>> 0).toString(16), bitsize / 4); - } - exports.toHexString = toHexString; - /** - * A SHA1 implementation that works with strings and does not allocate. - */ - class StringSHA1 { - constructor() { - this._h0 = 0x67452301; - this._h1 = 0xEFCDAB89; - this._h2 = 0x98BADCFE; - this._h3 = 0x10325476; - this._h4 = 0xC3D2E1F0; - this._buff = new Uint8Array(64 /* BLOCK_SIZE */ + 3 /* to fit any utf-8 */); - this._buffDV = new DataView(this._buff.buffer); - this._buffLen = 0; - this._totalLen = 0; - this._leftoverHighSurrogate = 0; - this._finished = false; - } - update(str) { - const strLen = str.length; - if (strLen === 0) { - return; - } - const buff = this._buff; - let buffLen = this._buffLen; - let leftoverHighSurrogate = this._leftoverHighSurrogate; - let charCode; - let offset; - if (leftoverHighSurrogate !== 0) { - charCode = leftoverHighSurrogate; - offset = -1; - leftoverHighSurrogate = 0; - } - else { - charCode = str.charCodeAt(0); - offset = 0; - } - while (true) { - let codePoint = charCode; - if (strings.isHighSurrogate(charCode)) { - if (offset + 1 < strLen) { - const nextCharCode = str.charCodeAt(offset + 1); - if (strings.isLowSurrogate(nextCharCode)) { - offset++; - codePoint = strings.computeCodePoint(charCode, nextCharCode); - } - else { - // illegal => unicode replacement character - codePoint = 65533 /* UNICODE_REPLACEMENT */; - } - } - else { - // last character is a surrogate pair - leftoverHighSurrogate = charCode; - break; - } - } - else if (strings.isLowSurrogate(charCode)) { - // illegal => unicode replacement character - codePoint = 65533 /* UNICODE_REPLACEMENT */; - } - buffLen = this._push(buff, buffLen, codePoint); - offset++; - if (offset < strLen) { - charCode = str.charCodeAt(offset); - } - else { - break; - } - } - this._buffLen = buffLen; - this._leftoverHighSurrogate = leftoverHighSurrogate; - } - _push(buff, buffLen, codePoint) { - if (codePoint < 0x0080) { - buff[buffLen++] = codePoint; - } - else if (codePoint < 0x0800) { - buff[buffLen++] = 0b11000000 | ((codePoint & 0b00000000000000000000011111000000) >>> 6); - buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0); - } - else if (codePoint < 0x10000) { - buff[buffLen++] = 0b11100000 | ((codePoint & 0b00000000000000001111000000000000) >>> 12); - buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000111111000000) >>> 6); - buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0); - } - else { - buff[buffLen++] = 0b11110000 | ((codePoint & 0b00000000000111000000000000000000) >>> 18); - buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000111111000000000000) >>> 12); - buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000111111000000) >>> 6); - buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0); - } - if (buffLen >= 64 /* BLOCK_SIZE */) { - this._step(); - buffLen -= 64 /* BLOCK_SIZE */; - this._totalLen += 64 /* BLOCK_SIZE */; - // take last 3 in case of UTF8 overflow - buff[0] = buff[64 /* BLOCK_SIZE */ + 0]; - buff[1] = buff[64 /* BLOCK_SIZE */ + 1]; - buff[2] = buff[64 /* BLOCK_SIZE */ + 2]; - } - return buffLen; - } - digest() { - if (!this._finished) { - this._finished = true; - if (this._leftoverHighSurrogate) { - // illegal => unicode replacement character - this._leftoverHighSurrogate = 0; - this._buffLen = this._push(this._buff, this._buffLen, 65533 /* UNICODE_REPLACEMENT */); - } - this._totalLen += this._buffLen; - this._wrapUp(); - } - return toHexString(this._h0) + toHexString(this._h1) + toHexString(this._h2) + toHexString(this._h3) + toHexString(this._h4); - } - _wrapUp() { - this._buff[this._buffLen++] = 0x80; - fill(this._buff, this._buffLen); - if (this._buffLen > 56) { - this._step(); - fill(this._buff); - } - // this will fit because the mantissa can cover up to 52 bits - const ml = 8 * this._totalLen; - this._buffDV.setUint32(56, Math.floor(ml / 4294967296), false); - this._buffDV.setUint32(60, ml % 4294967296, false); - this._step(); - } - _step() { - const bigBlock32 = StringSHA1._bigBlock32; - const data = this._buffDV; - for (let j = 0; j < 64 /* 16*4 */; j += 4) { - bigBlock32.setUint32(j, data.getUint32(j, false), false); - } - for (let j = 64; j < 320 /* 80*4 */; j += 4) { - bigBlock32.setUint32(j, leftRotate((bigBlock32.getUint32(j - 12, false) ^ bigBlock32.getUint32(j - 32, false) ^ bigBlock32.getUint32(j - 56, false) ^ bigBlock32.getUint32(j - 64, false)), 1), false); - } - let a = this._h0; - let b = this._h1; - let c = this._h2; - let d = this._h3; - let e = this._h4; - let f, k; - let temp; - for (let j = 0; j < 80; j++) { - if (j < 20) { - f = (b & c) | ((~b) & d); - k = 0x5A827999; - } - else if (j < 40) { - f = b ^ c ^ d; - k = 0x6ED9EBA1; - } - else if (j < 60) { - f = (b & c) | (b & d) | (c & d); - k = 0x8F1BBCDC; - } - else { - f = b ^ c ^ d; - k = 0xCA62C1D6; - } - temp = (leftRotate(a, 5) + f + e + k + bigBlock32.getUint32(j * 4, false)) & 0xffffffff; - e = d; - d = c; - c = leftRotate(b, 30); - b = a; - a = temp; - } - this._h0 = (this._h0 + a) & 0xffffffff; - this._h1 = (this._h1 + b) & 0xffffffff; - this._h2 = (this._h2 + c) & 0xffffffff; - this._h3 = (this._h3 + d) & 0xffffffff; - this._h4 = (this._h4 + e) & 0xffffffff; - } - } - exports.StringSHA1 = StringSHA1; - StringSHA1._bigBlock32 = new DataView(new ArrayBuffer(320)); // 80 * 4 = 320 -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[128/*vs/base/common/diff/diff*/], __M([0/*require*/,1/*exports*/,285/*vs/base/common/diff/diffChange*/,92/*vs/base/common/hash*/]), function (require, exports, diffChange_1, hash_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.LcsDiff = exports.MyArray = exports.Debug = exports.stringDiff = exports.StringDiffSequence = void 0; - class StringDiffSequence { - constructor(source) { - this.source = source; - } - getElements() { - const source = this.source; - const characters = new Int32Array(source.length); - for (let i = 0, len = source.length; i < len; i++) { - characters[i] = source.charCodeAt(i); - } - return characters; - } - } - exports.StringDiffSequence = StringDiffSequence; - function stringDiff(original, modified, pretty) { - return new LcsDiff(new StringDiffSequence(original), new StringDiffSequence(modified)).ComputeDiff(pretty).changes; - } - exports.stringDiff = stringDiff; - // - // The code below has been ported from a C# implementation in VS - // - class Debug { - static Assert(condition, message) { - if (!condition) { - throw new Error(message); - } - } - } - exports.Debug = Debug; - class MyArray { - /** - * Copies a range of elements from an Array starting at the specified source index and pastes - * them to another Array starting at the specified destination index. The length and the indexes - * are specified as 64-bit integers. - * sourceArray: - * The Array that contains the data to copy. - * sourceIndex: - * A 64-bit integer that represents the index in the sourceArray at which copying begins. - * destinationArray: - * The Array that receives the data. - * destinationIndex: - * A 64-bit integer that represents the index in the destinationArray at which storing begins. - * length: - * A 64-bit integer that represents the number of elements to copy. - */ - static Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length) { - for (let i = 0; i < length; i++) { - destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i]; - } - } - static Copy2(sourceArray, sourceIndex, destinationArray, destinationIndex, length) { - for (let i = 0; i < length; i++) { - destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i]; - } - } - } - exports.MyArray = MyArray; - /** - * A utility class which helps to create the set of DiffChanges from - * a difference operation. This class accepts original DiffElements and - * modified DiffElements that are involved in a particular change. The - * MarktNextChange() method can be called to mark the separation between - * distinct changes. At the end, the Changes property can be called to retrieve - * the constructed changes. - */ - class DiffChangeHelper { - /** - * Constructs a new DiffChangeHelper for the given DiffSequences. - */ - constructor() { - this.m_changes = []; - this.m_originalStart = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; - this.m_modifiedStart = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; - this.m_originalCount = 0; - this.m_modifiedCount = 0; - } - /** - * Marks the beginning of the next change in the set of differences. - */ - MarkNextChange() { - // Only add to the list if there is something to add - if (this.m_originalCount > 0 || this.m_modifiedCount > 0) { - // Add the new change to our list - this.m_changes.push(new diffChange_1.DiffChange(this.m_originalStart, this.m_originalCount, this.m_modifiedStart, this.m_modifiedCount)); - } - // Reset for the next change - this.m_originalCount = 0; - this.m_modifiedCount = 0; - this.m_originalStart = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; - this.m_modifiedStart = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; - } - /** - * Adds the original element at the given position to the elements - * affected by the current change. The modified index gives context - * to the change position with respect to the original sequence. - * @param originalIndex The index of the original element to add. - * @param modifiedIndex The index of the modified element that provides corresponding position in the modified sequence. - */ - AddOriginalElement(originalIndex, modifiedIndex) { - // The 'true' start index is the smallest of the ones we've seen - this.m_originalStart = Math.min(this.m_originalStart, originalIndex); - this.m_modifiedStart = Math.min(this.m_modifiedStart, modifiedIndex); - this.m_originalCount++; - } - /** - * Adds the modified element at the given position to the elements - * affected by the current change. The original index gives context - * to the change position with respect to the modified sequence. - * @param originalIndex The index of the original element that provides corresponding position in the original sequence. - * @param modifiedIndex The index of the modified element to add. - */ - AddModifiedElement(originalIndex, modifiedIndex) { - // The 'true' start index is the smallest of the ones we've seen - this.m_originalStart = Math.min(this.m_originalStart, originalIndex); - this.m_modifiedStart = Math.min(this.m_modifiedStart, modifiedIndex); - this.m_modifiedCount++; - } - /** - * Retrieves all of the changes marked by the class. - */ - getChanges() { - if (this.m_originalCount > 0 || this.m_modifiedCount > 0) { - // Finish up on whatever is left - this.MarkNextChange(); - } - return this.m_changes; - } - /** - * Retrieves all of the changes marked by the class in the reverse order - */ - getReverseChanges() { - if (this.m_originalCount > 0 || this.m_modifiedCount > 0) { - // Finish up on whatever is left - this.MarkNextChange(); - } - this.m_changes.reverse(); - return this.m_changes; - } - } - /** - * An implementation of the difference algorithm described in - * "An O(ND) Difference Algorithm and its variations" by Eugene W. Myers - */ - class LcsDiff { - /** - * Constructs the DiffFinder - */ - constructor(originalSequence, modifiedSequence, continueProcessingPredicate = null) { - this.ContinueProcessingPredicate = continueProcessingPredicate; - this._originalSequence = originalSequence; - this._modifiedSequence = modifiedSequence; - const [originalStringElements, originalElementsOrHash, originalHasStrings] = LcsDiff._getElements(originalSequence); - const [modifiedStringElements, modifiedElementsOrHash, modifiedHasStrings] = LcsDiff._getElements(modifiedSequence); - this._hasStrings = (originalHasStrings && modifiedHasStrings); - this._originalStringElements = originalStringElements; - this._originalElementsOrHash = originalElementsOrHash; - this._modifiedStringElements = modifiedStringElements; - this._modifiedElementsOrHash = modifiedElementsOrHash; - this.m_forwardHistory = []; - this.m_reverseHistory = []; - } - static _isStringArray(arr) { - return (arr.length > 0 && typeof arr[0] === 'string'); - } - static _getElements(sequence) { - const elements = sequence.getElements(); - if (LcsDiff._isStringArray(elements)) { - const hashes = new Int32Array(elements.length); - for (let i = 0, len = elements.length; i < len; i++) { - hashes[i] = (0, hash_1.stringHash)(elements[i], 0); - } - return [elements, hashes, true]; - } - if (elements instanceof Int32Array) { - return [[], elements, false]; - } - return [[], new Int32Array(elements), false]; - } - ElementsAreEqual(originalIndex, newIndex) { - if (this._originalElementsOrHash[originalIndex] !== this._modifiedElementsOrHash[newIndex]) { - return false; - } - return (this._hasStrings ? this._originalStringElements[originalIndex] === this._modifiedStringElements[newIndex] : true); - } - ElementsAreStrictEqual(originalIndex, newIndex) { - if (!this.ElementsAreEqual(originalIndex, newIndex)) { - return false; - } - const originalElement = LcsDiff._getStrictElement(this._originalSequence, originalIndex); - const modifiedElement = LcsDiff._getStrictElement(this._modifiedSequence, newIndex); - return (originalElement === modifiedElement); - } - static _getStrictElement(sequence, index) { - if (typeof sequence.getStrictElement === 'function') { - return sequence.getStrictElement(index); - } - return null; - } - OriginalElementsAreEqual(index1, index2) { - if (this._originalElementsOrHash[index1] !== this._originalElementsOrHash[index2]) { - return false; - } - return (this._hasStrings ? this._originalStringElements[index1] === this._originalStringElements[index2] : true); - } - ModifiedElementsAreEqual(index1, index2) { - if (this._modifiedElementsOrHash[index1] !== this._modifiedElementsOrHash[index2]) { - return false; - } - return (this._hasStrings ? this._modifiedStringElements[index1] === this._modifiedStringElements[index2] : true); - } - ComputeDiff(pretty) { - return this._ComputeDiff(0, this._originalElementsOrHash.length - 1, 0, this._modifiedElementsOrHash.length - 1, pretty); - } - /** - * Computes the differences between the original and modified input - * sequences on the bounded range. - * @returns An array of the differences between the two input sequences. - */ - _ComputeDiff(originalStart, originalEnd, modifiedStart, modifiedEnd, pretty) { - const quitEarlyArr = [false]; - let changes = this.ComputeDiffRecursive(originalStart, originalEnd, modifiedStart, modifiedEnd, quitEarlyArr); - if (pretty) { - // We have to clean up the computed diff to be more intuitive - // but it turns out this cannot be done correctly until the entire set - // of diffs have been computed - changes = this.PrettifyChanges(changes); - } - return { - quitEarly: quitEarlyArr[0], - changes: changes - }; - } - /** - * Private helper method which computes the differences on the bounded range - * recursively. - * @returns An array of the differences between the two input sequences. - */ - ComputeDiffRecursive(originalStart, originalEnd, modifiedStart, modifiedEnd, quitEarlyArr) { - quitEarlyArr[0] = false; - // Find the start of the differences - while (originalStart <= originalEnd && modifiedStart <= modifiedEnd && this.ElementsAreEqual(originalStart, modifiedStart)) { - originalStart++; - modifiedStart++; - } - // Find the end of the differences - while (originalEnd >= originalStart && modifiedEnd >= modifiedStart && this.ElementsAreEqual(originalEnd, modifiedEnd)) { - originalEnd--; - modifiedEnd--; - } - // In the special case where we either have all insertions or all deletions or the sequences are identical - if (originalStart > originalEnd || modifiedStart > modifiedEnd) { - let changes; - if (modifiedStart <= modifiedEnd) { - Debug.Assert(originalStart === originalEnd + 1, 'originalStart should only be one more than originalEnd'); - // All insertions - changes = [ - new diffChange_1.DiffChange(originalStart, 0, modifiedStart, modifiedEnd - modifiedStart + 1) - ]; - } - else if (originalStart <= originalEnd) { - Debug.Assert(modifiedStart === modifiedEnd + 1, 'modifiedStart should only be one more than modifiedEnd'); - // All deletions - changes = [ - new diffChange_1.DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, 0) - ]; - } - else { - Debug.Assert(originalStart === originalEnd + 1, 'originalStart should only be one more than originalEnd'); - Debug.Assert(modifiedStart === modifiedEnd + 1, 'modifiedStart should only be one more than modifiedEnd'); - // Identical sequences - No differences - changes = []; - } - return changes; - } - // This problem can be solved using the Divide-And-Conquer technique. - const midOriginalArr = [0]; - const midModifiedArr = [0]; - const result = this.ComputeRecursionPoint(originalStart, originalEnd, modifiedStart, modifiedEnd, midOriginalArr, midModifiedArr, quitEarlyArr); - const midOriginal = midOriginalArr[0]; - const midModified = midModifiedArr[0]; - if (result !== null) { - // Result is not-null when there was enough memory to compute the changes while - // searching for the recursion point - return result; - } - else if (!quitEarlyArr[0]) { - // We can break the problem down recursively by finding the changes in the - // First Half: (originalStart, modifiedStart) to (midOriginal, midModified) - // Second Half: (midOriginal + 1, minModified + 1) to (originalEnd, modifiedEnd) - // NOTE: ComputeDiff() is inclusive, therefore the second range starts on the next point - const leftChanges = this.ComputeDiffRecursive(originalStart, midOriginal, modifiedStart, midModified, quitEarlyArr); - let rightChanges = []; - if (!quitEarlyArr[0]) { - rightChanges = this.ComputeDiffRecursive(midOriginal + 1, originalEnd, midModified + 1, modifiedEnd, quitEarlyArr); - } - else { - // We did't have time to finish the first half, so we don't have time to compute this half. - // Consider the entire rest of the sequence different. - rightChanges = [ - new diffChange_1.DiffChange(midOriginal + 1, originalEnd - (midOriginal + 1) + 1, midModified + 1, modifiedEnd - (midModified + 1) + 1) - ]; - } - return this.ConcatenateChanges(leftChanges, rightChanges); - } - // If we hit here, we quit early, and so can't return anything meaningful - return [ - new diffChange_1.DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1) - ]; - } - WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr) { - let forwardChanges = null; - let reverseChanges = null; - // First, walk backward through the forward diagonals history - let changeHelper = new DiffChangeHelper(); - let diagonalMin = diagonalForwardStart; - let diagonalMax = diagonalForwardEnd; - let diagonalRelative = (midOriginalArr[0] - midModifiedArr[0]) - diagonalForwardOffset; - let lastOriginalIndex = -1073741824 /* MIN_SAFE_SMALL_INTEGER */; - let historyIndex = this.m_forwardHistory.length - 1; - do { - // Get the diagonal index from the relative diagonal number - const diagonal = diagonalRelative + diagonalForwardBase; - // Figure out where we came from - if (diagonal === diagonalMin || (diagonal < diagonalMax && forwardPoints[diagonal - 1] < forwardPoints[diagonal + 1])) { - // Vertical line (the element is an insert) - originalIndex = forwardPoints[diagonal + 1]; - modifiedIndex = originalIndex - diagonalRelative - diagonalForwardOffset; - if (originalIndex < lastOriginalIndex) { - changeHelper.MarkNextChange(); - } - lastOriginalIndex = originalIndex; - changeHelper.AddModifiedElement(originalIndex + 1, modifiedIndex); - diagonalRelative = (diagonal + 1) - diagonalForwardBase; //Setup for the next iteration - } - else { - // Horizontal line (the element is a deletion) - originalIndex = forwardPoints[diagonal - 1] + 1; - modifiedIndex = originalIndex - diagonalRelative - diagonalForwardOffset; - if (originalIndex < lastOriginalIndex) { - changeHelper.MarkNextChange(); - } - lastOriginalIndex = originalIndex - 1; - changeHelper.AddOriginalElement(originalIndex, modifiedIndex + 1); - diagonalRelative = (diagonal - 1) - diagonalForwardBase; //Setup for the next iteration - } - if (historyIndex >= 0) { - forwardPoints = this.m_forwardHistory[historyIndex]; - diagonalForwardBase = forwardPoints[0]; //We stored this in the first spot - diagonalMin = 1; - diagonalMax = forwardPoints.length - 1; - } - } while (--historyIndex >= -1); - // Ironically, we get the forward changes as the reverse of the - // order we added them since we technically added them backwards - forwardChanges = changeHelper.getReverseChanges(); - if (quitEarlyArr[0]) { - // TODO: Calculate a partial from the reverse diagonals. - // For now, just assume everything after the midOriginal/midModified point is a diff - let originalStartPoint = midOriginalArr[0] + 1; - let modifiedStartPoint = midModifiedArr[0] + 1; - if (forwardChanges !== null && forwardChanges.length > 0) { - const lastForwardChange = forwardChanges[forwardChanges.length - 1]; - originalStartPoint = Math.max(originalStartPoint, lastForwardChange.getOriginalEnd()); - modifiedStartPoint = Math.max(modifiedStartPoint, lastForwardChange.getModifiedEnd()); - } - reverseChanges = [ - new diffChange_1.DiffChange(originalStartPoint, originalEnd - originalStartPoint + 1, modifiedStartPoint, modifiedEnd - modifiedStartPoint + 1) - ]; - } - else { - // Now walk backward through the reverse diagonals history - changeHelper = new DiffChangeHelper(); - diagonalMin = diagonalReverseStart; - diagonalMax = diagonalReverseEnd; - diagonalRelative = (midOriginalArr[0] - midModifiedArr[0]) - diagonalReverseOffset; - lastOriginalIndex = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; - historyIndex = (deltaIsEven) ? this.m_reverseHistory.length - 1 : this.m_reverseHistory.length - 2; - do { - // Get the diagonal index from the relative diagonal number - const diagonal = diagonalRelative + diagonalReverseBase; - // Figure out where we came from - if (diagonal === diagonalMin || (diagonal < diagonalMax && reversePoints[diagonal - 1] >= reversePoints[diagonal + 1])) { - // Horizontal line (the element is a deletion)) - originalIndex = reversePoints[diagonal + 1] - 1; - modifiedIndex = originalIndex - diagonalRelative - diagonalReverseOffset; - if (originalIndex > lastOriginalIndex) { - changeHelper.MarkNextChange(); - } - lastOriginalIndex = originalIndex + 1; - changeHelper.AddOriginalElement(originalIndex + 1, modifiedIndex + 1); - diagonalRelative = (diagonal + 1) - diagonalReverseBase; //Setup for the next iteration - } - else { - // Vertical line (the element is an insertion) - originalIndex = reversePoints[diagonal - 1]; - modifiedIndex = originalIndex - diagonalRelative - diagonalReverseOffset; - if (originalIndex > lastOriginalIndex) { - changeHelper.MarkNextChange(); - } - lastOriginalIndex = originalIndex; - changeHelper.AddModifiedElement(originalIndex + 1, modifiedIndex + 1); - diagonalRelative = (diagonal - 1) - diagonalReverseBase; //Setup for the next iteration - } - if (historyIndex >= 0) { - reversePoints = this.m_reverseHistory[historyIndex]; - diagonalReverseBase = reversePoints[0]; //We stored this in the first spot - diagonalMin = 1; - diagonalMax = reversePoints.length - 1; - } - } while (--historyIndex >= -1); - // There are cases where the reverse history will find diffs that - // are correct, but not intuitive, so we need shift them. - reverseChanges = changeHelper.getChanges(); - } - return this.ConcatenateChanges(forwardChanges, reverseChanges); - } - /** - * Given the range to compute the diff on, this method finds the point: - * (midOriginal, midModified) - * that exists in the middle of the LCS of the two sequences and - * is the point at which the LCS problem may be broken down recursively. - * This method will try to keep the LCS trace in memory. If the LCS recursion - * point is calculated and the full trace is available in memory, then this method - * will return the change list. - * @param originalStart The start bound of the original sequence range - * @param originalEnd The end bound of the original sequence range - * @param modifiedStart The start bound of the modified sequence range - * @param modifiedEnd The end bound of the modified sequence range - * @param midOriginal The middle point of the original sequence range - * @param midModified The middle point of the modified sequence range - * @returns The diff changes, if available, otherwise null - */ - ComputeRecursionPoint(originalStart, originalEnd, modifiedStart, modifiedEnd, midOriginalArr, midModifiedArr, quitEarlyArr) { - let originalIndex = 0, modifiedIndex = 0; - let diagonalForwardStart = 0, diagonalForwardEnd = 0; - let diagonalReverseStart = 0, diagonalReverseEnd = 0; - // To traverse the edit graph and produce the proper LCS, our actual - // start position is just outside the given boundary - originalStart--; - modifiedStart--; - // We set these up to make the compiler happy, but they will - // be replaced before we return with the actual recursion point - midOriginalArr[0] = 0; - midModifiedArr[0] = 0; - // Clear out the history - this.m_forwardHistory = []; - this.m_reverseHistory = []; - // Each cell in the two arrays corresponds to a diagonal in the edit graph. - // The integer value in the cell represents the originalIndex of the furthest - // reaching point found so far that ends in that diagonal. - // The modifiedIndex can be computed mathematically from the originalIndex and the diagonal number. - const maxDifferences = (originalEnd - originalStart) + (modifiedEnd - modifiedStart); - const numDiagonals = maxDifferences + 1; - const forwardPoints = new Int32Array(numDiagonals); - const reversePoints = new Int32Array(numDiagonals); - // diagonalForwardBase: Index into forwardPoints of the diagonal which passes through (originalStart, modifiedStart) - // diagonalReverseBase: Index into reversePoints of the diagonal which passes through (originalEnd, modifiedEnd) - const diagonalForwardBase = (modifiedEnd - modifiedStart); - const diagonalReverseBase = (originalEnd - originalStart); - // diagonalForwardOffset: Geometric offset which allows modifiedIndex to be computed from originalIndex and the - // diagonal number (relative to diagonalForwardBase) - // diagonalReverseOffset: Geometric offset which allows modifiedIndex to be computed from originalIndex and the - // diagonal number (relative to diagonalReverseBase) - const diagonalForwardOffset = (originalStart - modifiedStart); - const diagonalReverseOffset = (originalEnd - modifiedEnd); - // delta: The difference between the end diagonal and the start diagonal. This is used to relate diagonal numbers - // relative to the start diagonal with diagonal numbers relative to the end diagonal. - // The Even/Oddn-ness of this delta is important for determining when we should check for overlap - const delta = diagonalReverseBase - diagonalForwardBase; - const deltaIsEven = (delta % 2 === 0); - // Here we set up the start and end points as the furthest points found so far - // in both the forward and reverse directions, respectively - forwardPoints[diagonalForwardBase] = originalStart; - reversePoints[diagonalReverseBase] = originalEnd; - // Remember if we quit early, and thus need to do a best-effort result instead of a real result. - quitEarlyArr[0] = false; - // A couple of points: - // --With this method, we iterate on the number of differences between the two sequences. - // The more differences there actually are, the longer this will take. - // --Also, as the number of differences increases, we have to search on diagonals further - // away from the reference diagonal (which is diagonalForwardBase for forward, diagonalReverseBase for reverse). - // --We extend on even diagonals (relative to the reference diagonal) only when numDifferences - // is even and odd diagonals only when numDifferences is odd. - for (let numDifferences = 1; numDifferences <= (maxDifferences / 2) + 1; numDifferences++) { - let furthestOriginalIndex = 0; - let furthestModifiedIndex = 0; - // Run the algorithm in the forward direction - diagonalForwardStart = this.ClipDiagonalBound(diagonalForwardBase - numDifferences, numDifferences, diagonalForwardBase, numDiagonals); - diagonalForwardEnd = this.ClipDiagonalBound(diagonalForwardBase + numDifferences, numDifferences, diagonalForwardBase, numDiagonals); - for (let diagonal = diagonalForwardStart; diagonal <= diagonalForwardEnd; diagonal += 2) { - // STEP 1: We extend the furthest reaching point in the present diagonal - // by looking at the diagonals above and below and picking the one whose point - // is further away from the start point (originalStart, modifiedStart) - if (diagonal === diagonalForwardStart || (diagonal < diagonalForwardEnd && forwardPoints[diagonal - 1] < forwardPoints[diagonal + 1])) { - originalIndex = forwardPoints[diagonal + 1]; - } - else { - originalIndex = forwardPoints[diagonal - 1] + 1; - } - modifiedIndex = originalIndex - (diagonal - diagonalForwardBase) - diagonalForwardOffset; - // Save the current originalIndex so we can test for false overlap in step 3 - const tempOriginalIndex = originalIndex; - // STEP 2: We can continue to extend the furthest reaching point in the present diagonal - // so long as the elements are equal. - while (originalIndex < originalEnd && modifiedIndex < modifiedEnd && this.ElementsAreEqual(originalIndex + 1, modifiedIndex + 1)) { - originalIndex++; - modifiedIndex++; - } - forwardPoints[diagonal] = originalIndex; - if (originalIndex + modifiedIndex > furthestOriginalIndex + furthestModifiedIndex) { - furthestOriginalIndex = originalIndex; - furthestModifiedIndex = modifiedIndex; - } - // STEP 3: If delta is odd (overlap first happens on forward when delta is odd) - // and diagonal is in the range of reverse diagonals computed for numDifferences-1 - // (the previous iteration; we haven't computed reverse diagonals for numDifferences yet) - // then check for overlap. - if (!deltaIsEven && Math.abs(diagonal - diagonalReverseBase) <= (numDifferences - 1)) { - if (originalIndex >= reversePoints[diagonal]) { - midOriginalArr[0] = originalIndex; - midModifiedArr[0] = modifiedIndex; - if (tempOriginalIndex <= reversePoints[diagonal] && 1447 /* MaxDifferencesHistory */ > 0 && numDifferences <= (1447 /* MaxDifferencesHistory */ + 1)) { - // BINGO! We overlapped, and we have the full trace in memory! - return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr); - } - else { - // Either false overlap, or we didn't have enough memory for the full trace - // Just return the recursion point - return null; - } - } - } - } - // Check to see if we should be quitting early, before moving on to the next iteration. - const matchLengthOfLongest = ((furthestOriginalIndex - originalStart) + (furthestModifiedIndex - modifiedStart) - numDifferences) / 2; - if (this.ContinueProcessingPredicate !== null && !this.ContinueProcessingPredicate(furthestOriginalIndex, matchLengthOfLongest)) { - // We can't finish, so skip ahead to generating a result from what we have. - quitEarlyArr[0] = true; - // Use the furthest distance we got in the forward direction. - midOriginalArr[0] = furthestOriginalIndex; - midModifiedArr[0] = furthestModifiedIndex; - if (matchLengthOfLongest > 0 && 1447 /* MaxDifferencesHistory */ > 0 && numDifferences <= (1447 /* MaxDifferencesHistory */ + 1)) { - // Enough of the history is in memory to walk it backwards - return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr); - } - else { - // We didn't actually remember enough of the history. - //Since we are quiting the diff early, we need to shift back the originalStart and modified start - //back into the boundary limits since we decremented their value above beyond the boundary limit. - originalStart++; - modifiedStart++; - return [ - new diffChange_1.DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1) - ]; - } - } - // Run the algorithm in the reverse direction - diagonalReverseStart = this.ClipDiagonalBound(diagonalReverseBase - numDifferences, numDifferences, diagonalReverseBase, numDiagonals); - diagonalReverseEnd = this.ClipDiagonalBound(diagonalReverseBase + numDifferences, numDifferences, diagonalReverseBase, numDiagonals); - for (let diagonal = diagonalReverseStart; diagonal <= diagonalReverseEnd; diagonal += 2) { - // STEP 1: We extend the furthest reaching point in the present diagonal - // by looking at the diagonals above and below and picking the one whose point - // is further away from the start point (originalEnd, modifiedEnd) - if (diagonal === diagonalReverseStart || (diagonal < diagonalReverseEnd && reversePoints[diagonal - 1] >= reversePoints[diagonal + 1])) { - originalIndex = reversePoints[diagonal + 1] - 1; - } - else { - originalIndex = reversePoints[diagonal - 1]; - } - modifiedIndex = originalIndex - (diagonal - diagonalReverseBase) - diagonalReverseOffset; - // Save the current originalIndex so we can test for false overlap - const tempOriginalIndex = originalIndex; - // STEP 2: We can continue to extend the furthest reaching point in the present diagonal - // as long as the elements are equal. - while (originalIndex > originalStart && modifiedIndex > modifiedStart && this.ElementsAreEqual(originalIndex, modifiedIndex)) { - originalIndex--; - modifiedIndex--; - } - reversePoints[diagonal] = originalIndex; - // STEP 4: If delta is even (overlap first happens on reverse when delta is even) - // and diagonal is in the range of forward diagonals computed for numDifferences - // then check for overlap. - if (deltaIsEven && Math.abs(diagonal - diagonalForwardBase) <= numDifferences) { - if (originalIndex <= forwardPoints[diagonal]) { - midOriginalArr[0] = originalIndex; - midModifiedArr[0] = modifiedIndex; - if (tempOriginalIndex >= forwardPoints[diagonal] && 1447 /* MaxDifferencesHistory */ > 0 && numDifferences <= (1447 /* MaxDifferencesHistory */ + 1)) { - // BINGO! We overlapped, and we have the full trace in memory! - return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr); - } - else { - // Either false overlap, or we didn't have enough memory for the full trace - // Just return the recursion point - return null; - } - } - } - } - // Save current vectors to history before the next iteration - if (numDifferences <= 1447 /* MaxDifferencesHistory */) { - // We are allocating space for one extra int, which we fill with - // the index of the diagonal base index - let temp = new Int32Array(diagonalForwardEnd - diagonalForwardStart + 2); - temp[0] = diagonalForwardBase - diagonalForwardStart + 1; - MyArray.Copy2(forwardPoints, diagonalForwardStart, temp, 1, diagonalForwardEnd - diagonalForwardStart + 1); - this.m_forwardHistory.push(temp); - temp = new Int32Array(diagonalReverseEnd - diagonalReverseStart + 2); - temp[0] = diagonalReverseBase - diagonalReverseStart + 1; - MyArray.Copy2(reversePoints, diagonalReverseStart, temp, 1, diagonalReverseEnd - diagonalReverseStart + 1); - this.m_reverseHistory.push(temp); - } - } - // If we got here, then we have the full trace in history. We just have to convert it to a change list - // NOTE: This part is a bit messy - return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr); - } - /** - * Shifts the given changes to provide a more intuitive diff. - * While the first element in a diff matches the first element after the diff, - * we shift the diff down. - * - * @param changes The list of changes to shift - * @returns The shifted changes - */ - PrettifyChanges(changes) { - // Shift all the changes down first - for (let i = 0; i < changes.length; i++) { - const change = changes[i]; - const originalStop = (i < changes.length - 1) ? changes[i + 1].originalStart : this._originalElementsOrHash.length; - const modifiedStop = (i < changes.length - 1) ? changes[i + 1].modifiedStart : this._modifiedElementsOrHash.length; - const checkOriginal = change.originalLength > 0; - const checkModified = change.modifiedLength > 0; - while (change.originalStart + change.originalLength < originalStop - && change.modifiedStart + change.modifiedLength < modifiedStop - && (!checkOriginal || this.OriginalElementsAreEqual(change.originalStart, change.originalStart + change.originalLength)) - && (!checkModified || this.ModifiedElementsAreEqual(change.modifiedStart, change.modifiedStart + change.modifiedLength))) { - const startStrictEqual = this.ElementsAreStrictEqual(change.originalStart, change.modifiedStart); - const endStrictEqual = this.ElementsAreStrictEqual(change.originalStart + change.originalLength, change.modifiedStart + change.modifiedLength); - if (endStrictEqual && !startStrictEqual) { - // moving the change down would create an equal change, but the elements are not strict equal - break; - } - change.originalStart++; - change.modifiedStart++; - } - let mergedChangeArr = [null]; - if (i < changes.length - 1 && this.ChangesOverlap(changes[i], changes[i + 1], mergedChangeArr)) { - changes[i] = mergedChangeArr[0]; - changes.splice(i + 1, 1); - i--; - continue; - } - } - // Shift changes back up until we hit empty or whitespace-only lines - for (let i = changes.length - 1; i >= 0; i--) { - const change = changes[i]; - let originalStop = 0; - let modifiedStop = 0; - if (i > 0) { - const prevChange = changes[i - 1]; - originalStop = prevChange.originalStart + prevChange.originalLength; - modifiedStop = prevChange.modifiedStart + prevChange.modifiedLength; - } - const checkOriginal = change.originalLength > 0; - const checkModified = change.modifiedLength > 0; - let bestDelta = 0; - let bestScore = this._boundaryScore(change.originalStart, change.originalLength, change.modifiedStart, change.modifiedLength); - for (let delta = 1;; delta++) { - const originalStart = change.originalStart - delta; - const modifiedStart = change.modifiedStart - delta; - if (originalStart < originalStop || modifiedStart < modifiedStop) { - break; - } - if (checkOriginal && !this.OriginalElementsAreEqual(originalStart, originalStart + change.originalLength)) { - break; - } - if (checkModified && !this.ModifiedElementsAreEqual(modifiedStart, modifiedStart + change.modifiedLength)) { - break; - } - const touchingPreviousChange = (originalStart === originalStop && modifiedStart === modifiedStop); - const score = ((touchingPreviousChange ? 5 : 0) - + this._boundaryScore(originalStart, change.originalLength, modifiedStart, change.modifiedLength)); - if (score > bestScore) { - bestScore = score; - bestDelta = delta; - } - } - change.originalStart -= bestDelta; - change.modifiedStart -= bestDelta; - const mergedChangeArr = [null]; - if (i > 0 && this.ChangesOverlap(changes[i - 1], changes[i], mergedChangeArr)) { - changes[i - 1] = mergedChangeArr[0]; - changes.splice(i, 1); - i++; - continue; - } - } - // There could be multiple longest common substrings. - // Give preference to the ones containing longer lines - if (this._hasStrings) { - for (let i = 1, len = changes.length; i < len; i++) { - const aChange = changes[i - 1]; - const bChange = changes[i]; - const matchedLength = bChange.originalStart - aChange.originalStart - aChange.originalLength; - const aOriginalStart = aChange.originalStart; - const bOriginalEnd = bChange.originalStart + bChange.originalLength; - const abOriginalLength = bOriginalEnd - aOriginalStart; - const aModifiedStart = aChange.modifiedStart; - const bModifiedEnd = bChange.modifiedStart + bChange.modifiedLength; - const abModifiedLength = bModifiedEnd - aModifiedStart; - // Avoid wasting a lot of time with these searches - if (matchedLength < 5 && abOriginalLength < 20 && abModifiedLength < 20) { - const t = this._findBetterContiguousSequence(aOriginalStart, abOriginalLength, aModifiedStart, abModifiedLength, matchedLength); - if (t) { - const [originalMatchStart, modifiedMatchStart] = t; - if (originalMatchStart !== aChange.originalStart + aChange.originalLength || modifiedMatchStart !== aChange.modifiedStart + aChange.modifiedLength) { - // switch to another sequence that has a better score - aChange.originalLength = originalMatchStart - aChange.originalStart; - aChange.modifiedLength = modifiedMatchStart - aChange.modifiedStart; - bChange.originalStart = originalMatchStart + matchedLength; - bChange.modifiedStart = modifiedMatchStart + matchedLength; - bChange.originalLength = bOriginalEnd - bChange.originalStart; - bChange.modifiedLength = bModifiedEnd - bChange.modifiedStart; - } - } - } - } - } - return changes; - } - _findBetterContiguousSequence(originalStart, originalLength, modifiedStart, modifiedLength, desiredLength) { - if (originalLength < desiredLength || modifiedLength < desiredLength) { - return null; - } - const originalMax = originalStart + originalLength - desiredLength + 1; - const modifiedMax = modifiedStart + modifiedLength - desiredLength + 1; - let bestScore = 0; - let bestOriginalStart = 0; - let bestModifiedStart = 0; - for (let i = originalStart; i < originalMax; i++) { - for (let j = modifiedStart; j < modifiedMax; j++) { - const score = this._contiguousSequenceScore(i, j, desiredLength); - if (score > 0 && score > bestScore) { - bestScore = score; - bestOriginalStart = i; - bestModifiedStart = j; - } - } - } - if (bestScore > 0) { - return [bestOriginalStart, bestModifiedStart]; - } - return null; - } - _contiguousSequenceScore(originalStart, modifiedStart, length) { - let score = 0; - for (let l = 0; l < length; l++) { - if (!this.ElementsAreEqual(originalStart + l, modifiedStart + l)) { - return 0; - } - score += this._originalStringElements[originalStart + l].length; - } - return score; - } - _OriginalIsBoundary(index) { - if (index <= 0 || index >= this._originalElementsOrHash.length - 1) { - return true; - } - return (this._hasStrings && /^\s*$/.test(this._originalStringElements[index])); - } - _OriginalRegionIsBoundary(originalStart, originalLength) { - if (this._OriginalIsBoundary(originalStart) || this._OriginalIsBoundary(originalStart - 1)) { - return true; - } - if (originalLength > 0) { - const originalEnd = originalStart + originalLength; - if (this._OriginalIsBoundary(originalEnd - 1) || this._OriginalIsBoundary(originalEnd)) { - return true; - } - } - return false; - } - _ModifiedIsBoundary(index) { - if (index <= 0 || index >= this._modifiedElementsOrHash.length - 1) { - return true; - } - return (this._hasStrings && /^\s*$/.test(this._modifiedStringElements[index])); - } - _ModifiedRegionIsBoundary(modifiedStart, modifiedLength) { - if (this._ModifiedIsBoundary(modifiedStart) || this._ModifiedIsBoundary(modifiedStart - 1)) { - return true; - } - if (modifiedLength > 0) { - const modifiedEnd = modifiedStart + modifiedLength; - if (this._ModifiedIsBoundary(modifiedEnd - 1) || this._ModifiedIsBoundary(modifiedEnd)) { - return true; - } - } - return false; - } - _boundaryScore(originalStart, originalLength, modifiedStart, modifiedLength) { - const originalScore = (this._OriginalRegionIsBoundary(originalStart, originalLength) ? 1 : 0); - const modifiedScore = (this._ModifiedRegionIsBoundary(modifiedStart, modifiedLength) ? 1 : 0); - return (originalScore + modifiedScore); - } - /** - * Concatenates the two input DiffChange lists and returns the resulting - * list. - * @param The left changes - * @param The right changes - * @returns The concatenated list - */ - ConcatenateChanges(left, right) { - let mergedChangeArr = []; - if (left.length === 0 || right.length === 0) { - return (right.length > 0) ? right : left; - } - else if (this.ChangesOverlap(left[left.length - 1], right[0], mergedChangeArr)) { - // Since we break the problem down recursively, it is possible that we - // might recurse in the middle of a change thereby splitting it into - // two changes. Here in the combining stage, we detect and fuse those - // changes back together - const result = new Array(left.length + right.length - 1); - MyArray.Copy(left, 0, result, 0, left.length - 1); - result[left.length - 1] = mergedChangeArr[0]; - MyArray.Copy(right, 1, result, left.length, right.length - 1); - return result; - } - else { - const result = new Array(left.length + right.length); - MyArray.Copy(left, 0, result, 0, left.length); - MyArray.Copy(right, 0, result, left.length, right.length); - return result; - } - } - /** - * Returns true if the two changes overlap and can be merged into a single - * change - * @param left The left change - * @param right The right change - * @param mergedChange The merged change if the two overlap, null otherwise - * @returns True if the two changes overlap - */ - ChangesOverlap(left, right, mergedChangeArr) { - Debug.Assert(left.originalStart <= right.originalStart, 'Left change is not less than or equal to right change'); - Debug.Assert(left.modifiedStart <= right.modifiedStart, 'Left change is not less than or equal to right change'); - if (left.originalStart + left.originalLength >= right.originalStart || left.modifiedStart + left.modifiedLength >= right.modifiedStart) { - const originalStart = left.originalStart; - let originalLength = left.originalLength; - const modifiedStart = left.modifiedStart; - let modifiedLength = left.modifiedLength; - if (left.originalStart + left.originalLength >= right.originalStart) { - originalLength = right.originalStart + right.originalLength - left.originalStart; - } - if (left.modifiedStart + left.modifiedLength >= right.modifiedStart) { - modifiedLength = right.modifiedStart + right.modifiedLength - left.modifiedStart; - } - mergedChangeArr[0] = new diffChange_1.DiffChange(originalStart, originalLength, modifiedStart, modifiedLength); - return true; - } - else { - mergedChangeArr[0] = null; - return false; - } - } - /** - * Helper method used to clip a diagonal index to the range of valid - * diagonals. This also decides whether or not the diagonal index, - * if it exceeds the boundary, should be clipped to the boundary or clipped - * one inside the boundary depending on the Even/Odd status of the boundary - * and numDifferences. - * @param diagonal The index of the diagonal to clip. - * @param numDifferences The current number of differences being iterated upon. - * @param diagonalBaseIndex The base reference diagonal. - * @param numDiagonals The total number of diagonals. - * @returns The clipped diagonal index. - */ - ClipDiagonalBound(diagonal, numDifferences, diagonalBaseIndex, numDiagonals) { - if (diagonal >= 0 && diagonal < numDiagonals) { - // Nothing to clip, its in range - return diagonal; - } - // diagonalsBelow: The number of diagonals below the reference diagonal - // diagonalsAbove: The number of diagonals above the reference diagonal - const diagonalsBelow = diagonalBaseIndex; - const diagonalsAbove = numDiagonals - diagonalBaseIndex - 1; - const diffEven = (numDifferences % 2 === 0); - if (diagonal < 0) { - const lowerBoundEven = (diagonalsBelow % 2 === 0); - return (diffEven === lowerBoundEven) ? 0 : 1; - } - else { - const upperBoundEven = (diagonalsAbove % 2 === 0); - return (diffEven === upperBoundEven) ? numDiagonals - 1 : numDiagonals - 2; - } - } - } - exports.LcsDiff = LcsDiff; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/browser/ui/tree/indexTreeModel*/], __M([0/*require*/,1/*exports*/,101/*vs/base/browser/ui/tree/tree*/,19/*vs/base/common/arrays*/,128/*vs/base/common/diff/diff*/,6/*vs/base/common/event*/,54/*vs/base/common/iterator*/]), function (require, exports, tree_1, arrays_1, diff_1, event_1, iterator_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.IndexTreeModel = exports.getVisibleState = exports.isFilterResult = void 0; - function isFilterResult(obj) { - return typeof obj === 'object' && 'visibility' in obj && 'data' in obj; - } - exports.isFilterResult = isFilterResult; - function getVisibleState(visibility) { - switch (visibility) { - case true: return 1 /* Visible */; - case false: return 0 /* Hidden */; - default: return visibility; - } - } - exports.getVisibleState = getVisibleState; - function isCollapsibleStateUpdate(update) { - return typeof update.collapsible === 'boolean'; - } - class IndexTreeModel { - constructor(user, list, rootElement, options = {}) { - this.user = user; - this.list = list; - this.rootRef = []; - this.eventBufferer = new event_1.EventBufferer(); - this._onDidChangeCollapseState = new event_1.Emitter(); - this.onDidChangeCollapseState = this.eventBufferer.wrapEvent(this._onDidChangeCollapseState.event); - this._onDidChangeRenderNodeCount = new event_1.Emitter(); - this.onDidChangeRenderNodeCount = this.eventBufferer.wrapEvent(this._onDidChangeRenderNodeCount.event); - this._onDidSplice = new event_1.Emitter(); - this.onDidSplice = this._onDidSplice.event; - this.collapseByDefault = typeof options.collapseByDefault === 'undefined' ? false : options.collapseByDefault; - this.filter = options.filter; - this.autoExpandSingleChildren = typeof options.autoExpandSingleChildren === 'undefined' ? false : options.autoExpandSingleChildren; - this.root = { - parent: undefined, - element: rootElement, - children: [], - depth: 0, - visibleChildrenCount: 0, - visibleChildIndex: -1, - collapsible: false, - collapsed: false, - renderNodeCount: 0, - visibility: 1 /* Visible */, - visible: true, - filterData: undefined - }; - } - splice(location, deleteCount, toInsert = iterator_1.Iterable.empty(), options = {}) { - if (location.length === 0) { - throw new tree_1.TreeError(this.user, 'Invalid tree location'); - } - if (options.diffIdentityProvider) { - this.spliceSmart(options.diffIdentityProvider, location, deleteCount, toInsert, options); - } - else { - this.spliceSimple(location, deleteCount, toInsert, options); - } - } - spliceSmart(identity, location, deleteCount, toInsertIterable, options, recurseLevels) { - var _a; - if (toInsertIterable === void 0) { toInsertIterable = iterator_1.Iterable.empty(); } - if (recurseLevels === void 0) { recurseLevels = (_a = options.diffDepth) !== null && _a !== void 0 ? _a : 0; } - const { parentNode } = this.getParentNodeWithListIndex(location); - const toInsert = [...toInsertIterable]; - const index = location[location.length - 1]; - const diff = new diff_1.LcsDiff({ getElements: () => parentNode.children.map(e => identity.getId(e.element).toString()) }, { - getElements: () => [ - ...parentNode.children.slice(0, index), - ...toInsert, - ...parentNode.children.slice(index + deleteCount), - ].map(e => identity.getId(e.element).toString()) - }).ComputeDiff(false); - // if we were given a 'best effort' diff, use default behavior - if (diff.quitEarly) { - return this.spliceSimple(location, deleteCount, toInsert, options); - } - const locationPrefix = location.slice(0, -1); - const recurseSplice = (fromOriginal, fromModified, count) => { - if (recurseLevels > 0) { - for (let i = 0; i < count; i++) { - fromOriginal--; - fromModified--; - this.spliceSmart(identity, [...locationPrefix, fromOriginal, 0], Number.MAX_SAFE_INTEGER, toInsert[fromModified].children, options, recurseLevels - 1); - } - } - }; - let lastStartO = Math.min(parentNode.children.length, index + deleteCount); - let lastStartM = toInsert.length; - for (const change of diff.changes.sort((a, b) => b.originalStart - a.originalStart)) { - recurseSplice(lastStartO, lastStartM, lastStartO - (change.originalStart + change.originalLength)); - lastStartO = change.originalStart; - lastStartM = change.modifiedStart - index; - this.spliceSimple([...locationPrefix, lastStartO], change.originalLength, iterator_1.Iterable.slice(toInsert, lastStartM, lastStartM + change.modifiedLength), options); - } - // at this point, startO === startM === count since any remaining prefix should match - recurseSplice(lastStartO, lastStartM, lastStartO); - } - spliceSimple(location, deleteCount, toInsert = iterator_1.Iterable.empty(), { onDidCreateNode, onDidDeleteNode }) { - const { parentNode, listIndex, revealed, visible } = this.getParentNodeWithListIndex(location); - const treeListElementsToInsert = []; - const nodesToInsertIterator = iterator_1.Iterable.map(toInsert, el => this.createTreeNode(el, parentNode, parentNode.visible ? 1 /* Visible */ : 0 /* Hidden */, revealed, treeListElementsToInsert, onDidCreateNode)); - const lastIndex = location[location.length - 1]; - const lastHadChildren = parentNode.children.length > 0; - // figure out what's the visible child start index right before the - // splice point - let visibleChildStartIndex = 0; - for (let i = lastIndex; i >= 0 && i < parentNode.children.length; i--) { - const child = parentNode.children[i]; - if (child.visible) { - visibleChildStartIndex = child.visibleChildIndex; - break; - } - } - const nodesToInsert = []; - let insertedVisibleChildrenCount = 0; - let renderNodeCount = 0; - for (const child of nodesToInsertIterator) { - nodesToInsert.push(child); - renderNodeCount += child.renderNodeCount; - if (child.visible) { - child.visibleChildIndex = visibleChildStartIndex + insertedVisibleChildrenCount++; - } - } - const deletedNodes = (0, arrays_1.splice)(parentNode.children, lastIndex, deleteCount, nodesToInsert); - // figure out what is the count of deleted visible children - let deletedVisibleChildrenCount = 0; - for (const child of deletedNodes) { - if (child.visible) { - deletedVisibleChildrenCount++; - } - } - // and adjust for all visible children after the splice point - if (deletedVisibleChildrenCount !== 0) { - for (let i = lastIndex + nodesToInsert.length; i < parentNode.children.length; i++) { - const child = parentNode.children[i]; - if (child.visible) { - child.visibleChildIndex -= deletedVisibleChildrenCount; - } - } - } - // update parent's visible children count - parentNode.visibleChildrenCount += insertedVisibleChildrenCount - deletedVisibleChildrenCount; - if (revealed && visible) { - const visibleDeleteCount = deletedNodes.reduce((r, node) => r + (node.visible ? node.renderNodeCount : 0), 0); - this._updateAncestorsRenderNodeCount(parentNode, renderNodeCount - visibleDeleteCount); - this.list.splice(listIndex, visibleDeleteCount, treeListElementsToInsert); - } - if (deletedNodes.length > 0 && onDidDeleteNode) { - const visit = (node) => { - onDidDeleteNode(node); - node.children.forEach(visit); - }; - deletedNodes.forEach(visit); - } - const currentlyHasChildren = parentNode.children.length > 0; - if (lastHadChildren !== currentlyHasChildren) { - this.setCollapsible(location.slice(0, -1), currentlyHasChildren); - } - this._onDidSplice.fire({ insertedNodes: nodesToInsert, deletedNodes }); - let node = parentNode; - while (node) { - if (node.visibility === 2 /* Recurse */) { - this.refilter(); - break; - } - node = node.parent; - } - } - rerender(location) { - if (location.length === 0) { - throw new tree_1.TreeError(this.user, 'Invalid tree location'); - } - const { node, listIndex, revealed } = this.getTreeNodeWithListIndex(location); - if (node.visible && revealed) { - this.list.splice(listIndex, 1, [node]); - } - } - has(location) { - return this.hasTreeNode(location); - } - getListIndex(location) { - const { listIndex, visible, revealed } = this.getTreeNodeWithListIndex(location); - return visible && revealed ? listIndex : -1; - } - getListRenderCount(location) { - return this.getTreeNode(location).renderNodeCount; - } - isCollapsible(location) { - return this.getTreeNode(location).collapsible; - } - setCollapsible(location, collapsible) { - const node = this.getTreeNode(location); - if (typeof collapsible === 'undefined') { - collapsible = !node.collapsible; - } - const update = { collapsible }; - return this.eventBufferer.bufferEvents(() => this._setCollapseState(location, update)); - } - isCollapsed(location) { - return this.getTreeNode(location).collapsed; - } - setCollapsed(location, collapsed, recursive) { - const node = this.getTreeNode(location); - if (typeof collapsed === 'undefined') { - collapsed = !node.collapsed; - } - const update = { collapsed, recursive: recursive || false }; - return this.eventBufferer.bufferEvents(() => this._setCollapseState(location, update)); - } - _setCollapseState(location, update) { - const { node, listIndex, revealed } = this.getTreeNodeWithListIndex(location); - const result = this._setListNodeCollapseState(node, listIndex, revealed, update); - if (node !== this.root && this.autoExpandSingleChildren && result && !isCollapsibleStateUpdate(update) && node.collapsible && !node.collapsed && !update.recursive) { - let onlyVisibleChildIndex = -1; - for (let i = 0; i < node.children.length; i++) { - const child = node.children[i]; - if (child.visible) { - if (onlyVisibleChildIndex > -1) { - onlyVisibleChildIndex = -1; - break; - } - else { - onlyVisibleChildIndex = i; - } - } - } - if (onlyVisibleChildIndex > -1) { - this._setCollapseState([...location, onlyVisibleChildIndex], update); - } - } - return result; - } - _setListNodeCollapseState(node, listIndex, revealed, update) { - const result = this._setNodeCollapseState(node, update, false); - if (!revealed || !node.visible || !result) { - return result; - } - const previousRenderNodeCount = node.renderNodeCount; - const toInsert = this.updateNodeAfterCollapseChange(node); - const deleteCount = previousRenderNodeCount - (listIndex === -1 ? 0 : 1); - this.list.splice(listIndex + 1, deleteCount, toInsert.slice(1)); - return result; - } - _setNodeCollapseState(node, update, deep) { - let result; - if (node === this.root) { - result = false; - } - else { - if (isCollapsibleStateUpdate(update)) { - result = node.collapsible !== update.collapsible; - node.collapsible = update.collapsible; - } - else if (!node.collapsible) { - result = false; - } - else { - result = node.collapsed !== update.collapsed; - node.collapsed = update.collapsed; - } - if (result) { - this._onDidChangeCollapseState.fire({ node, deep }); - } - } - if (!isCollapsibleStateUpdate(update) && update.recursive) { - for (const child of node.children) { - result = this._setNodeCollapseState(child, update, true) || result; - } - } - return result; - } - expandTo(location) { - this.eventBufferer.bufferEvents(() => { - let node = this.getTreeNode(location); - while (node.parent) { - node = node.parent; - location = location.slice(0, location.length - 1); - if (node.collapsed) { - this._setCollapseState(location, { collapsed: false, recursive: false }); - } - } - }); - } - refilter() { - const previousRenderNodeCount = this.root.renderNodeCount; - const toInsert = this.updateNodeAfterFilterChange(this.root); - this.list.splice(0, previousRenderNodeCount, toInsert); - } - createTreeNode(treeElement, parent, parentVisibility, revealed, treeListElements, onDidCreateNode) { - const node = { - parent, - element: treeElement.element, - children: [], - depth: parent.depth + 1, - visibleChildrenCount: 0, - visibleChildIndex: -1, - collapsible: typeof treeElement.collapsible === 'boolean' ? treeElement.collapsible : (typeof treeElement.collapsed !== 'undefined'), - collapsed: typeof treeElement.collapsed === 'undefined' ? this.collapseByDefault : treeElement.collapsed, - renderNodeCount: 1, - visibility: 1 /* Visible */, - visible: true, - filterData: undefined - }; - const visibility = this._filterNode(node, parentVisibility); - node.visibility = visibility; - if (revealed) { - treeListElements.push(node); - } - const childElements = treeElement.children || iterator_1.Iterable.empty(); - const childRevealed = revealed && visibility !== 0 /* Hidden */ && !node.collapsed; - const childNodes = iterator_1.Iterable.map(childElements, el => this.createTreeNode(el, node, visibility, childRevealed, treeListElements, onDidCreateNode)); - let visibleChildrenCount = 0; - let renderNodeCount = 1; - for (const child of childNodes) { - node.children.push(child); - renderNodeCount += child.renderNodeCount; - if (child.visible) { - child.visibleChildIndex = visibleChildrenCount++; - } - } - node.collapsible = node.collapsible || node.children.length > 0; - node.visibleChildrenCount = visibleChildrenCount; - node.visible = visibility === 2 /* Recurse */ ? visibleChildrenCount > 0 : (visibility === 1 /* Visible */); - if (!node.visible) { - node.renderNodeCount = 0; - if (revealed) { - treeListElements.pop(); - } - } - else if (!node.collapsed) { - node.renderNodeCount = renderNodeCount; - } - if (onDidCreateNode) { - onDidCreateNode(node); - } - return node; - } - updateNodeAfterCollapseChange(node) { - const previousRenderNodeCount = node.renderNodeCount; - const result = []; - this._updateNodeAfterCollapseChange(node, result); - this._updateAncestorsRenderNodeCount(node.parent, result.length - previousRenderNodeCount); - return result; - } - _updateNodeAfterCollapseChange(node, result) { - if (node.visible === false) { - return 0; - } - result.push(node); - node.renderNodeCount = 1; - if (!node.collapsed) { - for (const child of node.children) { - node.renderNodeCount += this._updateNodeAfterCollapseChange(child, result); - } - } - this._onDidChangeRenderNodeCount.fire(node); - return node.renderNodeCount; - } - updateNodeAfterFilterChange(node) { - const previousRenderNodeCount = node.renderNodeCount; - const result = []; - this._updateNodeAfterFilterChange(node, node.visible ? 1 /* Visible */ : 0 /* Hidden */, result); - this._updateAncestorsRenderNodeCount(node.parent, result.length - previousRenderNodeCount); - return result; - } - _updateNodeAfterFilterChange(node, parentVisibility, result, revealed = true) { - let visibility; - if (node !== this.root) { - visibility = this._filterNode(node, parentVisibility); - if (visibility === 0 /* Hidden */) { - node.visible = false; - node.renderNodeCount = 0; - return false; - } - if (revealed) { - result.push(node); - } - } - const resultStartLength = result.length; - node.renderNodeCount = node === this.root ? 0 : 1; - let hasVisibleDescendants = false; - if (!node.collapsed || visibility !== 0 /* Hidden */) { - let visibleChildIndex = 0; - for (const child of node.children) { - hasVisibleDescendants = this._updateNodeAfterFilterChange(child, visibility, result, revealed && !node.collapsed) || hasVisibleDescendants; - if (child.visible) { - child.visibleChildIndex = visibleChildIndex++; - } - } - node.visibleChildrenCount = visibleChildIndex; - } - else { - node.visibleChildrenCount = 0; - } - if (node !== this.root) { - node.visible = visibility === 2 /* Recurse */ ? hasVisibleDescendants : (visibility === 1 /* Visible */); - } - if (!node.visible) { - node.renderNodeCount = 0; - if (revealed) { - result.pop(); - } - } - else if (!node.collapsed) { - node.renderNodeCount += result.length - resultStartLength; - } - this._onDidChangeRenderNodeCount.fire(node); - return node.visible; - } - _updateAncestorsRenderNodeCount(node, diff) { - if (diff === 0) { - return; - } - while (node) { - node.renderNodeCount += diff; - this._onDidChangeRenderNodeCount.fire(node); - node = node.parent; - } - } - _filterNode(node, parentVisibility) { - const result = this.filter ? this.filter.filter(node.element, parentVisibility) : 1 /* Visible */; - if (typeof result === 'boolean') { - node.filterData = undefined; - return result ? 1 /* Visible */ : 0 /* Hidden */; - } - else if (isFilterResult(result)) { - node.filterData = result.data; - return getVisibleState(result.visibility); - } - else { - node.filterData = undefined; - return getVisibleState(result); - } - } - // cheap - hasTreeNode(location, node = this.root) { - if (!location || location.length === 0) { - return true; - } - const [index, ...rest] = location; - if (index < 0 || index > node.children.length) { - return false; - } - return this.hasTreeNode(rest, node.children[index]); - } - // cheap - getTreeNode(location, node = this.root) { - if (!location || location.length === 0) { - return node; - } - const [index, ...rest] = location; - if (index < 0 || index > node.children.length) { - throw new tree_1.TreeError(this.user, 'Invalid tree location'); - } - return this.getTreeNode(rest, node.children[index]); - } - // expensive - getTreeNodeWithListIndex(location) { - if (location.length === 0) { - return { node: this.root, listIndex: -1, revealed: true, visible: false }; - } - const { parentNode, listIndex, revealed, visible } = this.getParentNodeWithListIndex(location); - const index = location[location.length - 1]; - if (index < 0 || index > parentNode.children.length) { - throw new tree_1.TreeError(this.user, 'Invalid tree location'); - } - const node = parentNode.children[index]; - return { node, listIndex, revealed, visible: visible && node.visible }; - } - getParentNodeWithListIndex(location, node = this.root, listIndex = 0, revealed = true, visible = true) { - const [index, ...rest] = location; - if (index < 0 || index > node.children.length) { - throw new tree_1.TreeError(this.user, 'Invalid tree location'); - } - // TODO@joao perf! - for (let i = 0; i < index; i++) { - listIndex += node.children[i].renderNodeCount; - } - revealed = revealed && !node.collapsed; - visible = visible && node.visible; - if (rest.length === 0) { - return { parentNode: node, listIndex, revealed, visible }; - } - return this.getParentNodeWithListIndex(rest, node.children[index], listIndex + 1, revealed, visible); - } - getNode(location = []) { - return this.getTreeNode(location); - } - // TODO@joao perf! - getNodeLocation(node) { - const location = []; - let indexTreeNode = node; // typing woes - while (indexTreeNode.parent) { - location.push(indexTreeNode.parent.children.indexOf(indexTreeNode)); - indexTreeNode = indexTreeNode.parent; - } - return location.reverse(); - } - getParentNodeLocation(location) { - if (location.length === 0) { - return undefined; - } - else if (location.length === 1) { - return []; - } - else { - return (0, arrays_1.tail2)(location)[0]; - } - } - } - exports.IndexTreeModel = IndexTreeModel; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/browser/ui/tree/objectTreeModel*/], __M([0/*require*/,1/*exports*/,54/*vs/base/common/iterator*/,158/*vs/base/browser/ui/tree/indexTreeModel*/,101/*vs/base/browser/ui/tree/tree*/]), function (require, exports, iterator_1, indexTreeModel_1, tree_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ObjectTreeModel = void 0; - class ObjectTreeModel { - constructor(user, list, options = {}) { - this.user = user; - this.rootRef = null; - this.nodes = new Map(); - this.nodesByIdentity = new Map(); - this.model = new indexTreeModel_1.IndexTreeModel(user, list, null, options); - this.onDidSplice = this.model.onDidSplice; - this.onDidChangeCollapseState = this.model.onDidChangeCollapseState; - this.onDidChangeRenderNodeCount = this.model.onDidChangeRenderNodeCount; - if (options.sorter) { - this.sorter = { - compare(a, b) { - return options.sorter.compare(a.element, b.element); - } - }; - } - this.identityProvider = options.identityProvider; - } - setChildren(element, children = iterator_1.Iterable.empty(), options = {}) { - const location = this.getElementLocation(element); - this._setChildren(location, this.preserveCollapseState(children), options); - } - _setChildren(location, children = iterator_1.Iterable.empty(), options) { - const insertedElements = new Set(); - const insertedElementIds = new Set(); - const onDidCreateNode = (node) => { - var _a; - if (node.element === null) { - return; - } - const tnode = node; - insertedElements.add(tnode.element); - this.nodes.set(tnode.element, tnode); - if (this.identityProvider) { - const id = this.identityProvider.getId(tnode.element).toString(); - insertedElementIds.add(id); - this.nodesByIdentity.set(id, tnode); - } - (_a = options.onDidCreateNode) === null || _a === void 0 ? void 0 : _a.call(options, tnode); - }; - const onDidDeleteNode = (node) => { - var _a; - if (node.element === null) { - return; - } - const tnode = node; - if (!insertedElements.has(tnode.element)) { - this.nodes.delete(tnode.element); - } - if (this.identityProvider) { - const id = this.identityProvider.getId(tnode.element).toString(); - if (!insertedElementIds.has(id)) { - this.nodesByIdentity.delete(id); - } - } - (_a = options.onDidDeleteNode) === null || _a === void 0 ? void 0 : _a.call(options, tnode); - }; - this.model.splice([...location, 0], Number.MAX_VALUE, children, Object.assign(Object.assign({}, options), { onDidCreateNode, onDidDeleteNode })); - } - preserveCollapseState(elements = iterator_1.Iterable.empty()) { - if (this.sorter) { - elements = [...elements].sort(this.sorter.compare.bind(this.sorter)); - } - return iterator_1.Iterable.map(elements, treeElement => { - let node = this.nodes.get(treeElement.element); - if (!node && this.identityProvider) { - const id = this.identityProvider.getId(treeElement.element).toString(); - node = this.nodesByIdentity.get(id); - } - if (!node) { - return Object.assign(Object.assign({}, treeElement), { children: this.preserveCollapseState(treeElement.children) }); - } - const collapsible = typeof treeElement.collapsible === 'boolean' ? treeElement.collapsible : node.collapsible; - const collapsed = typeof treeElement.collapsed !== 'undefined' ? treeElement.collapsed : node.collapsed; - return Object.assign(Object.assign({}, treeElement), { collapsible, - collapsed, children: this.preserveCollapseState(treeElement.children) }); - }); - } - rerender(element) { - const location = this.getElementLocation(element); - this.model.rerender(location); - } - has(element) { - return this.nodes.has(element); - } - getListIndex(element) { - const location = this.getElementLocation(element); - return this.model.getListIndex(location); - } - getListRenderCount(element) { - const location = this.getElementLocation(element); - return this.model.getListRenderCount(location); - } - isCollapsible(element) { - const location = this.getElementLocation(element); - return this.model.isCollapsible(location); - } - setCollapsible(element, collapsible) { - const location = this.getElementLocation(element); - return this.model.setCollapsible(location, collapsible); - } - isCollapsed(element) { - const location = this.getElementLocation(element); - return this.model.isCollapsed(location); - } - setCollapsed(element, collapsed, recursive) { - const location = this.getElementLocation(element); - return this.model.setCollapsed(location, collapsed, recursive); - } - expandTo(element) { - const location = this.getElementLocation(element); - this.model.expandTo(location); - } - refilter() { - this.model.refilter(); - } - getNode(element = null) { - if (element === null) { - return this.model.getNode(this.model.rootRef); - } - const node = this.nodes.get(element); - if (!node) { - throw new tree_1.TreeError(this.user, `Tree element not found: ${element}`); - } - return node; - } - getNodeLocation(node) { - return node.element; - } - getParentNodeLocation(element) { - if (element === null) { - throw new tree_1.TreeError(this.user, `Invalid getParentNodeLocation call`); - } - const node = this.nodes.get(element); - if (!node) { - throw new tree_1.TreeError(this.user, `Tree element not found: ${element}`); - } - const location = this.model.getNodeLocation(node); - const parentLocation = this.model.getParentNodeLocation(location); - const parent = this.model.getNode(parentLocation); - return parent.element; - } - getElementLocation(element) { - if (element === null) { - return []; - } - const node = this.nodes.get(element); - if (!node) { - throw new tree_1.TreeError(this.user, `Tree element not found: ${element}`); - } - return this.model.getNodeLocation(node); - } - } - exports.ObjectTreeModel = ObjectTreeModel; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[292/*vs/base/browser/ui/tree/compressedObjectTreeModel*/], __M([0/*require*/,1/*exports*/,54/*vs/base/common/iterator*/,6/*vs/base/common/event*/,101/*vs/base/browser/ui/tree/tree*/,159/*vs/base/browser/ui/tree/objectTreeModel*/]), function (require, exports, iterator_1, event_1, tree_1, objectTreeModel_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CompressibleObjectTreeModel = exports.DefaultElementMapper = exports.CompressedObjectTreeModel = exports.decompress = exports.compress = void 0; - function noCompress(element) { - const elements = [element.element]; - const incompressible = element.incompressible || false; - return { - element: { elements, incompressible }, - children: iterator_1.Iterable.map(iterator_1.Iterable.from(element.children), noCompress), - collapsible: element.collapsible, - collapsed: element.collapsed - }; - } - // Exported only for test reasons, do not use directly - function compress(element) { - const elements = [element.element]; - const incompressible = element.incompressible || false; - let childrenIterator; - let children; - while (true) { - [children, childrenIterator] = iterator_1.Iterable.consume(iterator_1.Iterable.from(element.children), 2); - if (children.length !== 1) { - break; - } - if (children[0].incompressible) { - break; - } - element = children[0]; - elements.push(element.element); - } - return { - element: { elements, incompressible }, - children: iterator_1.Iterable.map(iterator_1.Iterable.concat(children, childrenIterator), compress), - collapsible: element.collapsible, - collapsed: element.collapsed - }; - } - exports.compress = compress; - function _decompress(element, index = 0) { - let children; - if (index < element.element.elements.length - 1) { - children = [_decompress(element, index + 1)]; - } - else { - children = iterator_1.Iterable.map(iterator_1.Iterable.from(element.children), el => _decompress(el, 0)); - } - if (index === 0 && element.element.incompressible) { - return { - element: element.element.elements[index], - children, - incompressible: true, - collapsible: element.collapsible, - collapsed: element.collapsed - }; - } - return { - element: element.element.elements[index], - children, - collapsible: element.collapsible, - collapsed: element.collapsed - }; - } - // Exported only for test reasons, do not use directly - function decompress(element) { - return _decompress(element, 0); - } - exports.decompress = decompress; - function splice(treeElement, element, children) { - if (treeElement.element === element) { - return Object.assign(Object.assign({}, treeElement), { children }); - } - return Object.assign(Object.assign({}, treeElement), { children: iterator_1.Iterable.map(iterator_1.Iterable.from(treeElement.children), e => splice(e, element, children)) }); - } - const wrapIdentityProvider = (base) => ({ - getId(node) { - return node.elements.map(e => base.getId(e).toString()).join('\0'); - } - }); - // Exported only for test reasons, do not use directly - class CompressedObjectTreeModel { - constructor(user, list, options = {}) { - this.user = user; - this.rootRef = null; - this.nodes = new Map(); - this.model = new objectTreeModel_1.ObjectTreeModel(user, list, options); - this.enabled = typeof options.compressionEnabled === 'undefined' ? true : options.compressionEnabled; - this.identityProvider = options.identityProvider; - } - get onDidSplice() { return this.model.onDidSplice; } - get onDidChangeCollapseState() { return this.model.onDidChangeCollapseState; } - get onDidChangeRenderNodeCount() { return this.model.onDidChangeRenderNodeCount; } - setChildren(element, children = iterator_1.Iterable.empty(), options) { - // Diffs must be deem, since the compression can affect nested elements. - // @see https://github.com/microsoft/vscode/pull/114237#issuecomment-759425034 - const diffIdentityProvider = options.diffIdentityProvider && wrapIdentityProvider(options.diffIdentityProvider); - if (element === null) { - const compressedChildren = iterator_1.Iterable.map(children, this.enabled ? compress : noCompress); - this._setChildren(null, compressedChildren, { diffIdentityProvider, diffDepth: Infinity }); - return; - } - const compressedNode = this.nodes.get(element); - if (!compressedNode) { - throw new Error('Unknown compressed tree node'); - } - const node = this.model.getNode(compressedNode); - const compressedParentNode = this.model.getParentNodeLocation(compressedNode); - const parent = this.model.getNode(compressedParentNode); - const decompressedElement = decompress(node); - const splicedElement = splice(decompressedElement, element, children); - const recompressedElement = (this.enabled ? compress : noCompress)(splicedElement); - const parentChildren = parent.children - .map(child => child === node ? recompressedElement : child); - this._setChildren(parent.element, parentChildren, { - diffIdentityProvider, - diffDepth: node.depth - parent.depth, - }); - } - setCompressionEnabled(enabled) { - if (enabled === this.enabled) { - return; - } - this.enabled = enabled; - const root = this.model.getNode(); - const rootChildren = root.children; - const decompressedRootChildren = iterator_1.Iterable.map(rootChildren, decompress); - const recompressedRootChildren = iterator_1.Iterable.map(decompressedRootChildren, enabled ? compress : noCompress); - // it should be safe to always use deep diff mode here if an identity - // provider is available, since we know the raw nodes are unchanged. - this._setChildren(null, recompressedRootChildren, { - diffIdentityProvider: this.identityProvider, - diffDepth: Infinity, - }); - } - _setChildren(node, children, options) { - const insertedElements = new Set(); - const onDidCreateNode = (node) => { - for (const element of node.element.elements) { - insertedElements.add(element); - this.nodes.set(element, node.element); - } - }; - const onDidDeleteNode = (node) => { - for (const element of node.element.elements) { - if (!insertedElements.has(element)) { - this.nodes.delete(element); - } - } - }; - this.model.setChildren(node, children, Object.assign(Object.assign({}, options), { onDidCreateNode, onDidDeleteNode })); - } - has(element) { - return this.nodes.has(element); - } - getListIndex(location) { - const node = this.getCompressedNode(location); - return this.model.getListIndex(node); - } - getListRenderCount(location) { - const node = this.getCompressedNode(location); - return this.model.getListRenderCount(node); - } - getNode(location) { - if (typeof location === 'undefined') { - return this.model.getNode(); - } - const node = this.getCompressedNode(location); - return this.model.getNode(node); - } - // TODO: review this - getNodeLocation(node) { - const compressedNode = this.model.getNodeLocation(node); - if (compressedNode === null) { - return null; - } - return compressedNode.elements[compressedNode.elements.length - 1]; - } - // TODO: review this - getParentNodeLocation(location) { - const compressedNode = this.getCompressedNode(location); - const parentNode = this.model.getParentNodeLocation(compressedNode); - if (parentNode === null) { - return null; - } - return parentNode.elements[parentNode.elements.length - 1]; - } - isCollapsible(location) { - const compressedNode = this.getCompressedNode(location); - return this.model.isCollapsible(compressedNode); - } - setCollapsible(location, collapsible) { - const compressedNode = this.getCompressedNode(location); - return this.model.setCollapsible(compressedNode, collapsible); - } - isCollapsed(location) { - const compressedNode = this.getCompressedNode(location); - return this.model.isCollapsed(compressedNode); - } - setCollapsed(location, collapsed, recursive) { - const compressedNode = this.getCompressedNode(location); - return this.model.setCollapsed(compressedNode, collapsed, recursive); - } - expandTo(location) { - const compressedNode = this.getCompressedNode(location); - this.model.expandTo(compressedNode); - } - rerender(location) { - const compressedNode = this.getCompressedNode(location); - this.model.rerender(compressedNode); - } - refilter() { - this.model.refilter(); - } - getCompressedNode(element) { - if (element === null) { - return null; - } - const node = this.nodes.get(element); - if (!node) { - throw new tree_1.TreeError(this.user, `Tree element not found: ${element}`); - } - return node; - } - } - exports.CompressedObjectTreeModel = CompressedObjectTreeModel; - const DefaultElementMapper = elements => elements[elements.length - 1]; - exports.DefaultElementMapper = DefaultElementMapper; - class CompressedTreeNodeWrapper { - constructor(unwrapper, node) { - this.unwrapper = unwrapper; - this.node = node; - } - get element() { return this.node.element === null ? null : this.unwrapper(this.node.element); } - get children() { return this.node.children.map(node => new CompressedTreeNodeWrapper(this.unwrapper, node)); } - get depth() { return this.node.depth; } - get visibleChildrenCount() { return this.node.visibleChildrenCount; } - get visibleChildIndex() { return this.node.visibleChildIndex; } - get collapsible() { return this.node.collapsible; } - get collapsed() { return this.node.collapsed; } - get visible() { return this.node.visible; } - get filterData() { return this.node.filterData; } - } - function mapList(nodeMapper, list) { - return { - splice(start, deleteCount, toInsert) { - list.splice(start, deleteCount, toInsert.map(node => nodeMapper.map(node))); - }, - updateElementHeight(index, height) { - list.updateElementHeight(index, height); - } - }; - } - function mapOptions(compressedNodeUnwrapper, options) { - return Object.assign(Object.assign({}, options), { identityProvider: options.identityProvider && { - getId(node) { - return options.identityProvider.getId(compressedNodeUnwrapper(node)); - } - }, sorter: options.sorter && { - compare(node, otherNode) { - return options.sorter.compare(node.elements[0], otherNode.elements[0]); - } - }, filter: options.filter && { - filter(node, parentVisibility) { - return options.filter.filter(compressedNodeUnwrapper(node), parentVisibility); - } - } }); - } - class CompressibleObjectTreeModel { - constructor(user, list, options = {}) { - this.rootRef = null; - this.elementMapper = options.elementMapper || exports.DefaultElementMapper; - const compressedNodeUnwrapper = node => this.elementMapper(node.elements); - this.nodeMapper = new tree_1.WeakMapper(node => new CompressedTreeNodeWrapper(compressedNodeUnwrapper, node)); - this.model = new CompressedObjectTreeModel(user, mapList(this.nodeMapper, list), mapOptions(compressedNodeUnwrapper, options)); - } - get onDidSplice() { - return event_1.Event.map(this.model.onDidSplice, ({ insertedNodes, deletedNodes }) => ({ - insertedNodes: insertedNodes.map(node => this.nodeMapper.map(node)), - deletedNodes: deletedNodes.map(node => this.nodeMapper.map(node)), - })); - } - get onDidChangeCollapseState() { - return event_1.Event.map(this.model.onDidChangeCollapseState, ({ node, deep }) => ({ - node: this.nodeMapper.map(node), - deep - })); - } - get onDidChangeRenderNodeCount() { - return event_1.Event.map(this.model.onDidChangeRenderNodeCount, node => this.nodeMapper.map(node)); - } - setChildren(element, children = iterator_1.Iterable.empty(), options = {}) { - this.model.setChildren(element, children, options); - } - setCompressionEnabled(enabled) { - this.model.setCompressionEnabled(enabled); - } - has(location) { - return this.model.has(location); - } - getListIndex(location) { - return this.model.getListIndex(location); - } - getListRenderCount(location) { - return this.model.getListRenderCount(location); - } - getNode(location) { - return this.nodeMapper.map(this.model.getNode(location)); - } - getNodeLocation(node) { - return node.element; - } - getParentNodeLocation(location) { - return this.model.getParentNodeLocation(location); - } - isCollapsible(location) { - return this.model.isCollapsible(location); - } - setCollapsible(location, collapsed) { - return this.model.setCollapsible(location, collapsed); - } - isCollapsed(location) { - return this.model.isCollapsed(location); - } - setCollapsed(location, collapsed, recursive) { - return this.model.setCollapsed(location, collapsed, recursive); - } - expandTo(location) { - return this.model.expandTo(location); - } - rerender(location) { - return this.model.rerender(location); - } - refilter() { - return this.model.refilter(); - } - getCompressedTreeNode(location = null) { - return this.model.getNode(location); - } - } - exports.CompressibleObjectTreeModel = CompressibleObjectTreeModel; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[293/*vs/base/common/search*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/]), function (require, exports, strings) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.buildReplaceStringWithCasePreserved = void 0; - function buildReplaceStringWithCasePreserved(matches, pattern) { - if (matches && (matches[0] !== '')) { - const containsHyphens = validateSpecificSpecialCharacter(matches, pattern, '-'); - const containsUnderscores = validateSpecificSpecialCharacter(matches, pattern, '_'); - if (containsHyphens && !containsUnderscores) { - return buildReplaceStringForSpecificSpecialCharacter(matches, pattern, '-'); - } - else if (!containsHyphens && containsUnderscores) { - return buildReplaceStringForSpecificSpecialCharacter(matches, pattern, '_'); - } - if (matches[0].toUpperCase() === matches[0]) { - return pattern.toUpperCase(); - } - else if (matches[0].toLowerCase() === matches[0]) { - return pattern.toLowerCase(); - } - else if (strings.containsUppercaseCharacter(matches[0][0]) && pattern.length > 0) { - return pattern[0].toUpperCase() + pattern.substr(1); - } - else if (matches[0][0].toUpperCase() !== matches[0][0] && pattern.length > 0) { - return pattern[0].toLowerCase() + pattern.substr(1); - } - else { - // we don't understand its pattern yet. - return pattern; - } - } - else { - return pattern; - } - } - exports.buildReplaceStringWithCasePreserved = buildReplaceStringWithCasePreserved; - function validateSpecificSpecialCharacter(matches, pattern, specialCharacter) { - const doesContainSpecialCharacter = matches[0].indexOf(specialCharacter) !== -1 && pattern.indexOf(specialCharacter) !== -1; - return doesContainSpecialCharacter && matches[0].split(specialCharacter).length === pattern.split(specialCharacter).length; - } - function buildReplaceStringForSpecificSpecialCharacter(matches, pattern, specialCharacter) { - const splitPatternAtSpecialCharacter = pattern.split(specialCharacter); - const splitMatchAtSpecialCharacter = matches[0].split(specialCharacter); - let replaceString = ''; - splitPatternAtSpecialCharacter.forEach((splitValue, index) => { - replaceString += buildReplaceStringWithCasePreserved([splitMatchAtSpecialCharacter[index]], splitValue) + specialCharacter; - }); - return replaceString.slice(0, -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[74/*vs/base/common/severity*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/]), function (require, exports, 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) { - const _error = 'error'; - const _warning = 'warning'; - const _warn = 'warn'; - const _info = 'info'; - const _ignore = 'ignore'; - /** - * 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; - function toString(severity) { - switch (severity) { - case Severity.Error: return _error; - case Severity.Warning: return _warning; - case Severity.Info: return _info; - default: return _ignore; - } - } - Severity.toString = toString; - })(Severity || (Severity = {})); - exports.default = Severity; -}); - -define(__m[20/*vs/base/common/types*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.assertNever = exports.withNullAsUndefined = exports.createProxyObject = exports.getAllMethodNames = exports.getAllPropertyNames = exports.validateConstraint = exports.validateConstraints = exports.isFunction = exports.assertIsDefined = exports.assertType = exports.isUndefinedOrNull = exports.isUndefined = exports.isBoolean = exports.isNumber = exports.isObject = exports.isString = exports.isArray = void 0; - /** - * @returns whether the provided parameter is a JavaScript Array or not. - */ - function isArray(array) { - return Array.isArray(array); - } - exports.isArray = isArray; - /** - * @returns whether the provided parameter is a JavaScript String or not. - */ - function isString(str) { - return (typeof str === 'string'); - } - exports.isString = isString; - /** - * - * @returns whether the provided parameter is of type `object` but **not** - * `null`, an `array`, a `regexp`, nor a `date`. - */ - function isObject(obj) { - // The method can't do a type cast since there are type (like strings) which - // are subclasses of any put not positvely matched by the function. Hence type - // narrowing results in wrong results. - return typeof obj === 'object' - && obj !== null - && !Array.isArray(obj) - && !(obj instanceof RegExp) - && !(obj instanceof Date); - } - exports.isObject = isObject; - /** - * In **contrast** to just checking `typeof` this will return `false` for `NaN`. - * @returns whether the provided parameter is a JavaScript Number or not. - */ - function isNumber(obj) { - return (typeof obj === 'number' && !isNaN(obj)); - } - exports.isNumber = isNumber; - /** - * @returns whether the provided parameter is a JavaScript Boolean or not. - */ - function isBoolean(obj) { - return (obj === true || obj === false); - } - exports.isBoolean = isBoolean; - /** - * @returns whether the provided parameter is undefined. - */ - function isUndefined(obj) { - return (typeof obj === 'undefined'); - } - exports.isUndefined = isUndefined; - /** - * @returns whether the provided parameter is undefined or null. - */ - function isUndefinedOrNull(obj) { - return (isUndefined(obj) || obj === null); - } - exports.isUndefinedOrNull = isUndefinedOrNull; - function assertType(condition, type) { - if (!condition) { - throw new Error(type ? `Unexpected type, expected '${type}'` : 'Unexpected type'); - } - } - exports.assertType = assertType; - /** - * Asserts that the argument passed in is neither undefined nor null. - */ - function assertIsDefined(arg) { - if (isUndefinedOrNull(arg)) { - throw new Error('Assertion Failed: argument is undefined or null'); - } - return arg; - } - exports.assertIsDefined = assertIsDefined; - /** - * @returns whether the provided parameter is a JavaScript Function or not. - */ - function isFunction(obj) { - return (typeof obj === 'function'); - } - exports.isFunction = isFunction; - function validateConstraints(args, constraints) { - const len = Math.min(args.length, constraints.length); - for (let i = 0; i < len; i++) { - validateConstraint(args[i], constraints[i]); - } - } - exports.validateConstraints = validateConstraints; - function validateConstraint(arg, constraint) { - if (isString(constraint)) { - if (typeof arg !== constraint) { - throw new Error(`argument does not match constraint: typeof ${constraint}`); - } - } - else if (isFunction(constraint)) { - try { - if (arg instanceof constraint) { - return; - } - } - catch (_a) { - // ignore - } - if (!isUndefinedOrNull(arg) && arg.constructor === constraint) { - return; - } - if (constraint.length === 1 && constraint.call(undefined, arg) === true) { - return; - } - throw new Error(`argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true`); - } - } - exports.validateConstraint = validateConstraint; - function getAllPropertyNames(obj) { - let res = []; - let proto = Object.getPrototypeOf(obj); - while (Object.prototype !== proto) { - res = res.concat(Object.getOwnPropertyNames(proto)); - proto = Object.getPrototypeOf(proto); - } - return res; - } - exports.getAllPropertyNames = getAllPropertyNames; - function getAllMethodNames(obj) { - const methods = []; - for (const prop of getAllPropertyNames(obj)) { - if (typeof obj[prop] === 'function') { - methods.push(prop); - } - } - return methods; - } - exports.getAllMethodNames = getAllMethodNames; - function createProxyObject(methodNames, invoke) { - const createProxyMethod = (method) => { - return function () { - const args = Array.prototype.slice.call(arguments, 0); - return invoke(method, args); - }; - }; - let result = {}; - for (const methodName of methodNames) { - result[methodName] = createProxyMethod(methodName); - } - return result; - } - exports.createProxyObject = createProxyObject; - /** - * Converts null to undefined, passes all other values through. - */ - function withNullAsUndefined(x) { - return x === null ? undefined : x; - } - exports.withNullAsUndefined = withNullAsUndefined; - function assertNever(value, message = 'Unreachable') { - throw new Error(message); - } - exports.assertNever = assertNever; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/common/objects*/], __M([0/*require*/,1/*exports*/,20/*vs/base/common/types*/]), function (require, exports, types_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getOrDefault = exports.equals = exports.mixin = exports.cloneAndChange = exports.deepFreeze = exports.deepClone = void 0; - function deepClone(obj) { - if (!obj || typeof obj !== 'object') { - return obj; - } - if (obj instanceof RegExp) { - // See https://github.com/microsoft/TypeScript/issues/10990 - return obj; - } - const result = Array.isArray(obj) ? [] : {}; - Object.keys(obj).forEach((key) => { - if (obj[key] && typeof obj[key] === 'object') { - result[key] = deepClone(obj[key]); - } - else { - result[key] = obj[key]; - } - }); - return result; - } - exports.deepClone = deepClone; - function deepFreeze(obj) { - if (!obj || typeof obj !== 'object') { - return obj; - } - const stack = [obj]; - while (stack.length > 0) { - const obj = stack.shift(); - Object.freeze(obj); - for (const key in obj) { - if (_hasOwnProperty.call(obj, key)) { - const prop = obj[key]; - if (typeof prop === 'object' && !Object.isFrozen(prop)) { - stack.push(prop); - } - } - } - } - return obj; - } - exports.deepFreeze = deepFreeze; - const _hasOwnProperty = Object.prototype.hasOwnProperty; - function cloneAndChange(obj, changer) { - return _cloneAndChange(obj, changer, new Set()); - } - exports.cloneAndChange = cloneAndChange; - function _cloneAndChange(obj, changer, seen) { - if ((0, types_1.isUndefinedOrNull)(obj)) { - return obj; - } - const changed = changer(obj); - if (typeof changed !== 'undefined') { - return changed; - } - if ((0, types_1.isArray)(obj)) { - const r1 = []; - for (const e of obj) { - r1.push(_cloneAndChange(e, changer, seen)); - } - return r1; - } - if ((0, types_1.isObject)(obj)) { - if (seen.has(obj)) { - throw new Error('Cannot clone recursive data-structure'); - } - seen.add(obj); - const r2 = {}; - for (let i2 in obj) { - if (_hasOwnProperty.call(obj, i2)) { - r2[i2] = _cloneAndChange(obj[i2], changer, seen); - } - } - seen.delete(obj); - return r2; - } - return obj; - } - /** - * Copies all properties of source into destination. The optional parameter "overwrite" allows to control - * if existing properties on the destination should be overwritten or not. Defaults to true (overwrite). - */ - function mixin(destination, source, overwrite = true) { - if (!(0, types_1.isObject)(destination)) { - return source; - } - if ((0, types_1.isObject)(source)) { - Object.keys(source).forEach(key => { - if (key in destination) { - if (overwrite) { - if ((0, types_1.isObject)(destination[key]) && (0, types_1.isObject)(source[key])) { - mixin(destination[key], source[key], overwrite); - } - else { - destination[key] = source[key]; - } - } - } - else { - destination[key] = source[key]; - } - }); - } - return destination; - } - exports.mixin = mixin; - function equals(one, other) { - if (one === other) { - return true; - } - if (one === null || one === undefined || other === null || other === undefined) { - return false; - } - if (typeof one !== typeof other) { - return false; - } - if (typeof one !== 'object') { - return false; - } - if ((Array.isArray(one)) !== (Array.isArray(other))) { - return false; - } - let i; - let key; - if (Array.isArray(one)) { - if (one.length !== other.length) { - return false; - } - for (i = 0; i < one.length; i++) { - if (!equals(one[i], other[i])) { - return false; - } - } - } - else { - const oneKeys = []; - for (key in one) { - oneKeys.push(key); - } - oneKeys.sort(); - const otherKeys = []; - for (key in other) { - otherKeys.push(key); - } - otherKeys.sort(); - if (!equals(oneKeys, otherKeys)) { - return false; - } - for (i = 0; i < oneKeys.length; i++) { - if (!equals(one[oneKeys[i]], other[oneKeys[i]])) { - return false; - } - } - } - return true; - } - exports.equals = equals; - function getOrDefault(obj, fn, defaultValue) { - const result = fn(obj); - return typeof result === 'undefined' ? defaultValue : result; - } - exports.getOrDefault = getOrDefault; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[129/*vs/base/common/uint*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.toUint32 = exports.toUint8 = void 0; - function toUint8(v) { - if (v < 0) { - return 0; - } - if (v > 255 /* MAX_UINT_8 */) { - return 255 /* MAX_UINT_8 */; - } - return v | 0; - } - exports.toUint8 = toUint8; - function toUint32(v) { - if (v < 0) { - return 0; - } - if (v > 4294967295 /* MAX_UINT_32 */) { - return 4294967295 /* MAX_UINT_32 */; - } - return v | 0; - } - exports.toUint32 = toUint32; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[24/*vs/base/common/uri*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/,73/*vs/base/common/path*/]), function (require, exports, platform_1, paths) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.uriToFsPath = exports.URI = void 0; - const _schemePattern = /^\w[\w\d+.-]*$/; - const _singleSlashStart = /^\//; - const _doubleSlashStart = /^\/\//; - function _validateUri(ret, _strict) { - // scheme, must be set - if (!ret.scheme && _strict) { - throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${ret.authority}", path: "${ret.path}", query: "${ret.query}", fragment: "${ret.fragment}"}`); - } - // scheme, https://tools.ietf.org/html/rfc3986#section-3.1 - // ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) - if (ret.scheme && !_schemePattern.test(ret.scheme)) { - throw new Error('[UriError]: Scheme contains illegal characters.'); - } - // path, http://tools.ietf.org/html/rfc3986#section-3.3 - // If a URI contains an authority component, then the path component - // must either be empty or begin with a slash ("/") character. If a URI - // does not contain an authority component, then the path cannot begin - // with two slash characters ("//"). - if (ret.path) { - if (ret.authority) { - if (!_singleSlashStart.test(ret.path)) { - throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character'); - } - } - else { - if (_doubleSlashStart.test(ret.path)) { - throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")'); - } - } - } - } - // for a while we allowed uris *without* schemes and this is the migration - // for them, e.g. an uri without scheme and without strict-mode warns and falls - // back to the file-scheme. that should cause the least carnage and still be a - // clear warning - function _schemeFix(scheme, _strict) { - if (!scheme && !_strict) { - return 'file'; - } - return scheme; - } - // implements a bit of https://tools.ietf.org/html/rfc3986#section-5 - function _referenceResolution(scheme, path) { - // the slash-character is our 'default base' as we don't - // support constructing URIs relative to other URIs. This - // also means that we alter and potentially break paths. - // see https://tools.ietf.org/html/rfc3986#section-5.1.4 - switch (scheme) { - case 'https': - case 'http': - case 'file': - if (!path) { - path = _slash; - } - else if (path[0] !== _slash) { - path = _slash + path; - } - break; - } - return path; - } - const _empty = ''; - const _slash = '/'; - const _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/; - /** - * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986. - * This class is a simple parser which creates the basic component parts - * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation - * and encoding. - * - * ```txt - * foo://example.com:8042/over/there?name=ferret#nose - * \_/ \______________/\_________/ \_________/ \__/ - * | | | | | - * scheme authority path query fragment - * | _____________________|__ - * / \ / \ - * urn:example:animal:ferret:nose - * ``` - */ - class URI { - /** - * @internal - */ - constructor(schemeOrData, authority, path, query, fragment, _strict = false) { - if (typeof schemeOrData === 'object') { - this.scheme = schemeOrData.scheme || _empty; - this.authority = schemeOrData.authority || _empty; - this.path = schemeOrData.path || _empty; - this.query = schemeOrData.query || _empty; - this.fragment = schemeOrData.fragment || _empty; - // no validation because it's this URI - // that creates uri components. - // _validateUri(this); - } - else { - this.scheme = _schemeFix(schemeOrData, _strict); - this.authority = authority || _empty; - this.path = _referenceResolution(this.scheme, path || _empty); - this.query = query || _empty; - this.fragment = fragment || _empty; - _validateUri(this, _strict); - } - } - static isUri(thing) { - if (thing instanceof URI) { - return true; - } - if (!thing) { - return false; - } - return typeof thing.authority === 'string' - && typeof thing.fragment === 'string' - && typeof thing.path === 'string' - && typeof thing.query === 'string' - && typeof thing.scheme === 'string' - && typeof thing.fsPath === 'string' - && typeof thing.with === 'function' - && typeof thing.toString === 'function'; - } - // ---- filesystem path ----------------------- - /** - * Returns a string representing the corresponding file system path of this URI. - * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the - * platform specific path separator. - * - * * Will *not* validate the path for invalid characters and semantics. - * * Will *not* look at the scheme of this URI. - * * The result shall *not* be used for display purposes but for accessing a file on disk. - * - * - * The *difference* to `URI#path` is the use of the platform specific separator and the handling - * of UNC paths. See the below sample of a file-uri with an authority (UNC path). - * - * ```ts - const u = URI.parse('file://server/c$/folder/file.txt') - u.authority === 'server' - u.path === '/shares/c$/file.txt' - u.fsPath === '\\server\c$\folder\file.txt' - ``` - * - * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path, - * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working - * with URIs that represent files on disk (`file` scheme). - */ - get fsPath() { - // if (this.scheme !== 'file') { - // console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`); - // } - return uriToFsPath(this, false); - } - // ---- modify to new ------------------------- - with(change) { - if (!change) { - return this; - } - let { scheme, authority, path, query, fragment } = change; - if (scheme === undefined) { - scheme = this.scheme; - } - else if (scheme === null) { - scheme = _empty; - } - if (authority === undefined) { - authority = this.authority; - } - else if (authority === null) { - authority = _empty; - } - if (path === undefined) { - path = this.path; - } - else if (path === null) { - path = _empty; - } - if (query === undefined) { - query = this.query; - } - else if (query === null) { - query = _empty; - } - if (fragment === undefined) { - fragment = this.fragment; - } - else if (fragment === null) { - fragment = _empty; - } - if (scheme === this.scheme - && authority === this.authority - && path === this.path - && query === this.query - && fragment === this.fragment) { - return this; - } - return new Uri(scheme, authority, path, query, fragment); - } - // ---- parse & validate ------------------------ - /** - * Creates a new URI from a string, e.g. `http://www.msft.com/some/path`, - * `file:///usr/home`, or `scheme:with/path`. - * - * @param value A string which represents an URI (see `URI#toString`). - */ - static parse(value, _strict = false) { - const match = _regexp.exec(value); - if (!match) { - return new Uri(_empty, _empty, _empty, _empty, _empty); - } - return new Uri(match[2] || _empty, percentDecode(match[4] || _empty), percentDecode(match[5] || _empty), percentDecode(match[7] || _empty), percentDecode(match[9] || _empty), _strict); - } - /** - * Creates a new URI from a file system path, e.g. `c:\my\files`, - * `/usr/home`, or `\\server\share\some\path`. - * - * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument - * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as** - * `URI.parse('file://' + path)` because the path might contain characters that are - * interpreted (# and ?). See the following sample: - * ```ts - const good = URI.file('/coding/c#/project1'); - good.scheme === 'file'; - good.path === '/coding/c#/project1'; - good.fragment === ''; - const bad = URI.parse('file://' + '/coding/c#/project1'); - bad.scheme === 'file'; - bad.path === '/coding/c'; // path is now broken - bad.fragment === '/project1'; - ``` - * - * @param path A file system path (see `URI#fsPath`) - */ - static file(path) { - let authority = _empty; - // normalize to fwd-slashes on windows, - // on other systems bwd-slashes are valid - // filename character, eg /f\oo/ba\r.txt - if (platform_1.isWindows) { - path = path.replace(/\\/g, _slash); - } - // check for authority as used in UNC shares - // or use the path as given - if (path[0] === _slash && path[1] === _slash) { - const idx = path.indexOf(_slash, 2); - if (idx === -1) { - authority = path.substring(2); - path = _slash; - } - else { - authority = path.substring(2, idx); - path = path.substring(idx) || _slash; - } - } - return new Uri('file', authority, path, _empty, _empty); - } - static from(components) { - const result = new Uri(components.scheme, components.authority, components.path, components.query, components.fragment); - _validateUri(result, true); - return result; - } - /** - * Join a URI path with path fragments and normalizes the resulting path. - * - * @param uri The input URI. - * @param pathFragment The path fragment to add to the URI path. - * @returns The resulting URI. - */ - static joinPath(uri, ...pathFragment) { - if (!uri.path) { - throw new Error(`[UriError]: cannot call joinPath on URI without path`); - } - let newPath; - if (platform_1.isWindows && uri.scheme === 'file') { - newPath = URI.file(paths.win32.join(uriToFsPath(uri, true), ...pathFragment)).path; - } - else { - newPath = paths.posix.join(uri.path, ...pathFragment); - } - return uri.with({ path: newPath }); - } - // ---- printing/externalize --------------------------- - /** - * Creates a string representation for this URI. It's guaranteed that calling - * `URI.parse` with the result of this function creates an URI which is equal - * to this URI. - * - * * The result shall *not* be used for display purposes but for externalization or transport. - * * The result will be encoded using the percentage encoding and encoding happens mostly - * ignore the scheme-specific encoding rules. - * - * @param skipEncoding Do not encode the result, default is `false` - */ - toString(skipEncoding = false) { - return _asFormatted(this, skipEncoding); - } - toJSON() { - return this; - } - static revive(data) { - if (!data) { - return data; - } - else if (data instanceof URI) { - return data; - } - else { - const result = new Uri(data); - result._formatted = data.external; - result._fsPath = data._sep === _pathSepMarker ? data.fsPath : null; - return result; - } - } - } - exports.URI = URI; - const _pathSepMarker = platform_1.isWindows ? 1 : undefined; - // This class exists so that URI is compatibile with vscode.Uri (API). - class Uri extends URI { - constructor() { - super(...arguments); - this._formatted = null; - this._fsPath = null; - } - get fsPath() { - if (!this._fsPath) { - this._fsPath = uriToFsPath(this, false); - } - return this._fsPath; - } - toString(skipEncoding = false) { - if (!skipEncoding) { - if (!this._formatted) { - this._formatted = _asFormatted(this, false); - } - return this._formatted; - } - else { - // we don't cache that - return _asFormatted(this, true); - } - } - toJSON() { - const res = { - $mid: 1 /* Uri */ - }; - // cached state - if (this._fsPath) { - res.fsPath = this._fsPath; - res._sep = _pathSepMarker; - } - if (this._formatted) { - res.external = this._formatted; - } - // uri components - if (this.path) { - res.path = this.path; - } - if (this.scheme) { - res.scheme = this.scheme; - } - if (this.authority) { - res.authority = this.authority; - } - if (this.query) { - res.query = this.query; - } - if (this.fragment) { - res.fragment = this.fragment; - } - return res; - } - } - // reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2 - const encodeTable = { - [58 /* Colon */]: '%3A', - [47 /* Slash */]: '%2F', - [63 /* QuestionMark */]: '%3F', - [35 /* Hash */]: '%23', - [91 /* OpenSquareBracket */]: '%5B', - [93 /* CloseSquareBracket */]: '%5D', - [64 /* AtSign */]: '%40', - [33 /* ExclamationMark */]: '%21', - [36 /* DollarSign */]: '%24', - [38 /* Ampersand */]: '%26', - [39 /* SingleQuote */]: '%27', - [40 /* OpenParen */]: '%28', - [41 /* CloseParen */]: '%29', - [42 /* Asterisk */]: '%2A', - [43 /* Plus */]: '%2B', - [44 /* Comma */]: '%2C', - [59 /* Semicolon */]: '%3B', - [61 /* Equals */]: '%3D', - [32 /* Space */]: '%20', - }; - function encodeURIComponentFast(uriComponent, allowSlash) { - let res = undefined; - let nativeEncodePos = -1; - for (let pos = 0; pos < uriComponent.length; pos++) { - const code = uriComponent.charCodeAt(pos); - // unreserved characters: https://tools.ietf.org/html/rfc3986#section-2.3 - if ((code >= 97 /* a */ && code <= 122 /* z */) - || (code >= 65 /* A */ && code <= 90 /* Z */) - || (code >= 48 /* Digit0 */ && code <= 57 /* Digit9 */) - || code === 45 /* Dash */ - || code === 46 /* Period */ - || code === 95 /* Underline */ - || code === 126 /* Tilde */ - || (allowSlash && code === 47 /* Slash */)) { - // check if we are delaying native encode - if (nativeEncodePos !== -1) { - res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos)); - nativeEncodePos = -1; - } - // check if we write into a new string (by default we try to return the param) - if (res !== undefined) { - res += uriComponent.charAt(pos); - } - } - else { - // encoding needed, we need to allocate a new string - if (res === undefined) { - res = uriComponent.substr(0, pos); - } - // check with default table first - const escaped = encodeTable[code]; - if (escaped !== undefined) { - // check if we are delaying native encode - if (nativeEncodePos !== -1) { - res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos)); - nativeEncodePos = -1; - } - // append escaped variant to result - res += escaped; - } - else if (nativeEncodePos === -1) { - // use native encode only when needed - nativeEncodePos = pos; - } - } - } - if (nativeEncodePos !== -1) { - res += encodeURIComponent(uriComponent.substring(nativeEncodePos)); - } - return res !== undefined ? res : uriComponent; - } - function encodeURIComponentMinimal(path) { - let res = undefined; - for (let pos = 0; pos < path.length; pos++) { - const code = path.charCodeAt(pos); - if (code === 35 /* Hash */ || code === 63 /* QuestionMark */) { - if (res === undefined) { - res = path.substr(0, pos); - } - res += encodeTable[code]; - } - else { - if (res !== undefined) { - res += path[pos]; - } - } - } - return res !== undefined ? res : path; - } - /** - * Compute `fsPath` for the given uri - */ - function uriToFsPath(uri, keepDriveLetterCasing) { - let value; - if (uri.authority && uri.path.length > 1 && uri.scheme === 'file') { - // unc path: file://shares/c$/far/boo - value = `//${uri.authority}${uri.path}`; - } - else if (uri.path.charCodeAt(0) === 47 /* Slash */ - && (uri.path.charCodeAt(1) >= 65 /* A */ && uri.path.charCodeAt(1) <= 90 /* Z */ || uri.path.charCodeAt(1) >= 97 /* a */ && uri.path.charCodeAt(1) <= 122 /* z */) - && uri.path.charCodeAt(2) === 58 /* Colon */) { - if (!keepDriveLetterCasing) { - // windows drive letter: file:///c:/far/boo - value = uri.path[1].toLowerCase() + uri.path.substr(2); - } - else { - value = uri.path.substr(1); - } - } - else { - // other path - value = uri.path; - } - if (platform_1.isWindows) { - value = value.replace(/\//g, '\\'); - } - return value; - } - exports.uriToFsPath = uriToFsPath; - /** - * Create the external version of a uri - */ - function _asFormatted(uri, skipEncoding) { - const encoder = !skipEncoding - ? encodeURIComponentFast - : encodeURIComponentMinimal; - let res = ''; - let { scheme, authority, path, query, fragment } = uri; - if (scheme) { - res += scheme; - res += ':'; - } - if (authority || scheme === 'file') { - res += _slash; - res += _slash; - } - if (authority) { - let idx = authority.indexOf('@'); - if (idx !== -1) { - // @ - const userinfo = authority.substr(0, idx); - authority = authority.substr(idx + 1); - idx = userinfo.indexOf(':'); - if (idx === -1) { - res += encoder(userinfo, false); - } - else { - // :@ - res += encoder(userinfo.substr(0, idx), false); - res += ':'; - res += encoder(userinfo.substr(idx + 1), false); - } - res += '@'; - } - authority = authority.toLowerCase(); - idx = authority.indexOf(':'); - if (idx === -1) { - res += encoder(authority, false); - } - else { - // : - res += encoder(authority.substr(0, idx), false); - res += authority.substr(idx); - } - } - if (path) { - // lower-case windows drive letters in /C:/fff or C:/fff - if (path.length >= 3 && path.charCodeAt(0) === 47 /* Slash */ && path.charCodeAt(2) === 58 /* Colon */) { - const code = path.charCodeAt(1); - if (code >= 65 /* A */ && code <= 90 /* Z */) { - path = `/${String.fromCharCode(code + 32)}:${path.substr(3)}`; // "/c:".length === 3 - } - } - else if (path.length >= 2 && path.charCodeAt(1) === 58 /* Colon */) { - const code = path.charCodeAt(0); - if (code >= 65 /* A */ && code <= 90 /* Z */) { - path = `${String.fromCharCode(code + 32)}:${path.substr(2)}`; // "/c:".length === 3 - } - } - // encode the rest of the path - res += encoder(path, true); - } - if (query) { - res += '?'; - res += encoder(query, false); - } - if (fragment) { - res += '#'; - res += !skipEncoding ? encodeURIComponentFast(fragment, false) : fragment; - } - return res; - } - // --- decode - function decodeURIComponentGraceful(str) { - try { - return decodeURIComponent(str); - } - catch (_a) { - if (str.length > 3) { - return str.substr(0, 3) + decodeURIComponentGraceful(str.substr(3)); - } - else { - return str; - } - } - } - const _rEncodedAsHex = /(%[0-9A-Za-z][0-9A-Za-z])+/g; - function percentDecode(str) { - if (!str.match(_rEncodedAsHex)) { - return str; - } - return str.replace(_rEncodedAsHex, (match) => decodeURIComponentGraceful(match)); - } -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/common/map*/], __M([0/*require*/,1/*exports*/,24/*vs/base/common/uri*/,8/*vs/base/common/strings*/]), function (require, exports, uri_1, strings_1) { - "use strict"; - var _a, _b; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.LRUCache = exports.LinkedMap = exports.ResourceMap = exports.TernarySearchTree = exports.UriIterator = exports.PathIterator = exports.ConfigKeysIterator = exports.StringIterator = void 0; - class StringIterator { - constructor() { - this._value = ''; - this._pos = 0; - } - reset(key) { - this._value = key; - this._pos = 0; - return this; - } - next() { - this._pos += 1; - return this; - } - hasNext() { - return this._pos < this._value.length - 1; - } - cmp(a) { - const aCode = a.charCodeAt(0); - const thisCode = this._value.charCodeAt(this._pos); - return aCode - thisCode; - } - value() { - return this._value[this._pos]; - } - } - exports.StringIterator = StringIterator; - class ConfigKeysIterator { - constructor(_caseSensitive = true) { - this._caseSensitive = _caseSensitive; - } - reset(key) { - this._value = key; - this._from = 0; - this._to = 0; - return this.next(); - } - hasNext() { - return this._to < this._value.length; - } - next() { - // this._data = key.split(/[\\/]/).filter(s => !!s); - this._from = this._to; - let justSeps = true; - for (; this._to < this._value.length; this._to++) { - const ch = this._value.charCodeAt(this._to); - if (ch === 46 /* Period */) { - if (justSeps) { - this._from++; - } - else { - break; - } - } - else { - justSeps = false; - } - } - return this; - } - cmp(a) { - return this._caseSensitive - ? (0, strings_1.compareSubstring)(a, this._value, 0, a.length, this._from, this._to) - : (0, strings_1.compareSubstringIgnoreCase)(a, this._value, 0, a.length, this._from, this._to); - } - value() { - return this._value.substring(this._from, this._to); - } - } - exports.ConfigKeysIterator = ConfigKeysIterator; - class PathIterator { - constructor(_splitOnBackslash = true, _caseSensitive = true) { - this._splitOnBackslash = _splitOnBackslash; - this._caseSensitive = _caseSensitive; - } - reset(key) { - this._value = key.replace(/\\$|\/$/, ''); - this._from = 0; - this._to = 0; - return this.next(); - } - hasNext() { - return this._to < this._value.length; - } - next() { - // this._data = key.split(/[\\/]/).filter(s => !!s); - this._from = this._to; - let justSeps = true; - for (; this._to < this._value.length; this._to++) { - const ch = this._value.charCodeAt(this._to); - if (ch === 47 /* Slash */ || this._splitOnBackslash && ch === 92 /* Backslash */) { - if (justSeps) { - this._from++; - } - else { - break; - } - } - else { - justSeps = false; - } - } - return this; - } - cmp(a) { - return this._caseSensitive - ? (0, strings_1.compareSubstring)(a, this._value, 0, a.length, this._from, this._to) - : (0, strings_1.compareSubstringIgnoreCase)(a, this._value, 0, a.length, this._from, this._to); - } - value() { - return this._value.substring(this._from, this._to); - } - } - exports.PathIterator = PathIterator; - class UriIterator { - constructor(_ignorePathCasing) { - this._ignorePathCasing = _ignorePathCasing; - this._states = []; - this._stateIdx = 0; - } - reset(key) { - this._value = key; - this._states = []; - if (this._value.scheme) { - this._states.push(1 /* Scheme */); - } - if (this._value.authority) { - this._states.push(2 /* Authority */); - } - if (this._value.path) { - this._pathIterator = new PathIterator(false, !this._ignorePathCasing(key)); - this._pathIterator.reset(key.path); - if (this._pathIterator.value()) { - this._states.push(3 /* Path */); - } - } - if (this._value.query) { - this._states.push(4 /* Query */); - } - if (this._value.fragment) { - this._states.push(5 /* Fragment */); - } - this._stateIdx = 0; - return this; - } - next() { - if (this._states[this._stateIdx] === 3 /* Path */ && this._pathIterator.hasNext()) { - this._pathIterator.next(); - } - else { - this._stateIdx += 1; - } - return this; - } - hasNext() { - return (this._states[this._stateIdx] === 3 /* Path */ && this._pathIterator.hasNext()) - || this._stateIdx < this._states.length - 1; - } - cmp(a) { - if (this._states[this._stateIdx] === 1 /* Scheme */) { - return (0, strings_1.compareIgnoreCase)(a, this._value.scheme); - } - else if (this._states[this._stateIdx] === 2 /* Authority */) { - return (0, strings_1.compareIgnoreCase)(a, this._value.authority); - } - else if (this._states[this._stateIdx] === 3 /* Path */) { - return this._pathIterator.cmp(a); - } - else if (this._states[this._stateIdx] === 4 /* Query */) { - return (0, strings_1.compare)(a, this._value.query); - } - else if (this._states[this._stateIdx] === 5 /* Fragment */) { - return (0, strings_1.compare)(a, this._value.fragment); - } - throw new Error(); - } - value() { - if (this._states[this._stateIdx] === 1 /* Scheme */) { - return this._value.scheme; - } - else if (this._states[this._stateIdx] === 2 /* Authority */) { - return this._value.authority; - } - else if (this._states[this._stateIdx] === 3 /* Path */) { - return this._pathIterator.value(); - } - else if (this._states[this._stateIdx] === 4 /* Query */) { - return this._value.query; - } - else if (this._states[this._stateIdx] === 5 /* Fragment */) { - return this._value.fragment; - } - throw new Error(); - } - } - exports.UriIterator = UriIterator; - class TernarySearchTreeNode { - isEmpty() { - return !this.left && !this.mid && !this.right && !this.value; - } - } - class TernarySearchTree { - constructor(segments) { - this._iter = segments; - } - static forUris(ignorePathCasing = () => false) { - return new TernarySearchTree(new UriIterator(ignorePathCasing)); - } - static forStrings() { - return new TernarySearchTree(new StringIterator()); - } - static forConfigKeys() { - return new TernarySearchTree(new ConfigKeysIterator()); - } - clear() { - this._root = undefined; - } - set(key, element) { - const iter = this._iter.reset(key); - let node; - if (!this._root) { - this._root = new TernarySearchTreeNode(); - this._root.segment = iter.value(); - } - node = this._root; - while (true) { - const val = iter.cmp(node.segment); - if (val > 0) { - // left - if (!node.left) { - node.left = new TernarySearchTreeNode(); - node.left.segment = iter.value(); - } - node = node.left; - } - else if (val < 0) { - // right - if (!node.right) { - node.right = new TernarySearchTreeNode(); - node.right.segment = iter.value(); - } - node = node.right; - } - else if (iter.hasNext()) { - // mid - iter.next(); - if (!node.mid) { - node.mid = new TernarySearchTreeNode(); - node.mid.segment = iter.value(); - } - node = node.mid; - } - else { - break; - } - } - const oldElement = node.value; - node.value = element; - node.key = key; - return oldElement; - } - get(key) { - var _c; - return (_c = this._getNode(key)) === null || _c === void 0 ? void 0 : _c.value; - } - _getNode(key) { - const iter = this._iter.reset(key); - let node = this._root; - while (node) { - const val = iter.cmp(node.segment); - if (val > 0) { - // left - node = node.left; - } - else if (val < 0) { - // right - node = node.right; - } - else if (iter.hasNext()) { - // mid - iter.next(); - node = node.mid; - } - else { - break; - } - } - return node; - } - has(key) { - const node = this._getNode(key); - return !((node === null || node === void 0 ? void 0 : node.value) === undefined && (node === null || node === void 0 ? void 0 : node.mid) === undefined); - } - delete(key) { - return this._delete(key, false); - } - deleteSuperstr(key) { - return this._delete(key, true); - } - _delete(key, superStr) { - const iter = this._iter.reset(key); - const stack = []; - let node = this._root; - // find and unset node - while (node) { - const val = iter.cmp(node.segment); - if (val > 0) { - // left - stack.push([1, node]); - node = node.left; - } - else if (val < 0) { - // right - stack.push([-1, node]); - node = node.right; - } - else if (iter.hasNext()) { - // mid - iter.next(); - stack.push([0, node]); - node = node.mid; - } - else { - if (superStr) { - // remove children - node.left = undefined; - node.mid = undefined; - node.right = undefined; - } - else { - // remove element - node.value = undefined; - } - // clean up empty nodes - while (stack.length > 0 && node.isEmpty()) { - let [dir, parent] = stack.pop(); - switch (dir) { - case 1: - parent.left = undefined; - break; - case 0: - parent.mid = undefined; - break; - case -1: - parent.right = undefined; - break; - } - node = parent; - } - break; - } - } - } - findSubstr(key) { - const iter = this._iter.reset(key); - let node = this._root; - let candidate = undefined; - while (node) { - const val = iter.cmp(node.segment); - if (val > 0) { - // left - node = node.left; - } - else if (val < 0) { - // right - node = node.right; - } - else if (iter.hasNext()) { - // mid - iter.next(); - candidate = node.value || candidate; - node = node.mid; - } - else { - break; - } - } - return node && node.value || candidate; - } - findSuperstr(key) { - const iter = this._iter.reset(key); - let node = this._root; - while (node) { - const val = iter.cmp(node.segment); - if (val > 0) { - // left - node = node.left; - } - else if (val < 0) { - // right - node = node.right; - } - else if (iter.hasNext()) { - // mid - iter.next(); - node = node.mid; - } - else { - // collect - if (!node.mid) { - return undefined; - } - else { - return this._entries(node.mid); - } - } - } - return undefined; - } - forEach(callback) { - for (const [key, value] of this) { - callback(value, key); - } - } - *[Symbol.iterator]() { - yield* this._entries(this._root); - } - *_entries(node) { - // DFS - if (!node) { - return; - } - const stack = [node]; - while (stack.length > 0) { - const node = stack.pop(); - if (node) { - if (node.value) { - yield [node.key, node.value]; - } - if (node.left) { - stack.push(node.left); - } - if (node.mid) { - stack.push(node.mid); - } - if (node.right) { - stack.push(node.right); - } - } - } - } - } - exports.TernarySearchTree = TernarySearchTree; - class ResourceMap { - constructor(mapOrKeyFn, toKey) { - this[_a] = 'ResourceMap'; - if (mapOrKeyFn instanceof ResourceMap) { - this.map = new Map(mapOrKeyFn.map); - this.toKey = toKey !== null && toKey !== void 0 ? toKey : ResourceMap.defaultToKey; - } - else { - this.map = new Map(); - this.toKey = mapOrKeyFn !== null && mapOrKeyFn !== void 0 ? mapOrKeyFn : ResourceMap.defaultToKey; - } - } - set(resource, value) { - this.map.set(this.toKey(resource), value); - return this; - } - get(resource) { - return this.map.get(this.toKey(resource)); - } - has(resource) { - return this.map.has(this.toKey(resource)); - } - get size() { - return this.map.size; - } - clear() { - this.map.clear(); - } - delete(resource) { - return this.map.delete(this.toKey(resource)); - } - forEach(clb, thisArg) { - if (typeof thisArg !== 'undefined') { - clb = clb.bind(thisArg); - } - for (let [index, value] of this.map) { - clb(value, uri_1.URI.parse(index), this); - } - } - values() { - return this.map.values(); - } - *keys() { - for (let key of this.map.keys()) { - yield uri_1.URI.parse(key); - } - } - *entries() { - for (let tuple of this.map.entries()) { - yield [uri_1.URI.parse(tuple[0]), tuple[1]]; - } - } - *[(_a = Symbol.toStringTag, Symbol.iterator)]() { - for (let item of this.map) { - yield [uri_1.URI.parse(item[0]), item[1]]; - } - } - } - exports.ResourceMap = ResourceMap; - ResourceMap.defaultToKey = (resource) => resource.toString(); - class LinkedMap { - constructor() { - this[_b] = 'LinkedMap'; - this._map = new Map(); - this._head = undefined; - this._tail = undefined; - this._size = 0; - this._state = 0; - } - clear() { - this._map.clear(); - this._head = undefined; - this._tail = undefined; - this._size = 0; - this._state++; - } - isEmpty() { - return !this._head && !this._tail; - } - get size() { - return this._size; - } - get first() { - var _c; - return (_c = this._head) === null || _c === void 0 ? void 0 : _c.value; - } - get last() { - var _c; - return (_c = this._tail) === null || _c === void 0 ? void 0 : _c.value; - } - has(key) { - return this._map.has(key); - } - get(key, touch = 0 /* None */) { - const item = this._map.get(key); - if (!item) { - return undefined; - } - if (touch !== 0 /* None */) { - this.touch(item, touch); - } - return item.value; - } - set(key, value, touch = 0 /* None */) { - let item = this._map.get(key); - if (item) { - item.value = value; - if (touch !== 0 /* None */) { - this.touch(item, touch); - } - } - else { - item = { key, value, next: undefined, previous: undefined }; - switch (touch) { - case 0 /* None */: - this.addItemLast(item); - break; - case 1 /* AsOld */: - this.addItemFirst(item); - break; - case 2 /* AsNew */: - this.addItemLast(item); - break; - default: - this.addItemLast(item); - break; - } - this._map.set(key, item); - this._size++; - } - return this; - } - delete(key) { - return !!this.remove(key); - } - remove(key) { - const item = this._map.get(key); - if (!item) { - return undefined; - } - this._map.delete(key); - this.removeItem(item); - this._size--; - return item.value; - } - shift() { - if (!this._head && !this._tail) { - return undefined; - } - if (!this._head || !this._tail) { - throw new Error('Invalid list'); - } - const item = this._head; - this._map.delete(item.key); - this.removeItem(item); - this._size--; - return item.value; - } - forEach(callbackfn, thisArg) { - const state = this._state; - let current = this._head; - while (current) { - if (thisArg) { - callbackfn.bind(thisArg)(current.value, current.key, this); - } - else { - callbackfn(current.value, current.key, this); - } - if (this._state !== state) { - throw new Error(`LinkedMap got modified during iteration.`); - } - current = current.next; - } - } - keys() { - const map = this; - const state = this._state; - let current = this._head; - const iterator = { - [Symbol.iterator]() { - return iterator; - }, - next() { - if (map._state !== state) { - throw new Error(`LinkedMap got modified during iteration.`); - } - if (current) { - const result = { value: current.key, done: false }; - current = current.next; - return result; - } - else { - return { value: undefined, done: true }; - } - } - }; - return iterator; - } - values() { - const map = this; - const state = this._state; - let current = this._head; - const iterator = { - [Symbol.iterator]() { - return iterator; - }, - next() { - if (map._state !== state) { - throw new Error(`LinkedMap got modified during iteration.`); - } - if (current) { - const result = { value: current.value, done: false }; - current = current.next; - return result; - } - else { - return { value: undefined, done: true }; - } - } - }; - return iterator; - } - entries() { - const map = this; - const state = this._state; - let current = this._head; - const iterator = { - [Symbol.iterator]() { - return iterator; - }, - next() { - if (map._state !== state) { - throw new Error(`LinkedMap got modified during iteration.`); - } - if (current) { - const result = { value: [current.key, current.value], done: false }; - current = current.next; - return result; - } - else { - return { value: undefined, done: true }; - } - } - }; - return iterator; - } - [(_b = Symbol.toStringTag, Symbol.iterator)]() { - return this.entries(); - } - trimOld(newSize) { - if (newSize >= this.size) { - return; - } - if (newSize === 0) { - this.clear(); - return; - } - let current = this._head; - let currentSize = this.size; - while (current && currentSize > newSize) { - this._map.delete(current.key); - current = current.next; - currentSize--; - } - this._head = current; - this._size = currentSize; - if (current) { - current.previous = undefined; - } - this._state++; - } - addItemFirst(item) { - // First time Insert - if (!this._head && !this._tail) { - this._tail = item; - } - else if (!this._head) { - throw new Error('Invalid list'); - } - else { - item.next = this._head; - this._head.previous = item; - } - this._head = item; - this._state++; - } - addItemLast(item) { - // First time Insert - if (!this._head && !this._tail) { - this._head = item; - } - else if (!this._tail) { - throw new Error('Invalid list'); - } - else { - item.previous = this._tail; - this._tail.next = item; - } - this._tail = item; - this._state++; - } - removeItem(item) { - if (item === this._head && item === this._tail) { - this._head = undefined; - this._tail = undefined; - } - else if (item === this._head) { - // This can only happen if size === 1 which is handled - // by the case above. - if (!item.next) { - throw new Error('Invalid list'); - } - item.next.previous = undefined; - this._head = item.next; - } - else if (item === this._tail) { - // This can only happen if size === 1 which is handled - // by the case above. - if (!item.previous) { - throw new Error('Invalid list'); - } - item.previous.next = undefined; - this._tail = item.previous; - } - else { - const next = item.next; - const previous = item.previous; - if (!next || !previous) { - throw new Error('Invalid list'); - } - next.previous = previous; - previous.next = next; - } - item.next = undefined; - item.previous = undefined; - this._state++; - } - touch(item, touch) { - if (!this._head || !this._tail) { - throw new Error('Invalid list'); - } - if ((touch !== 1 /* AsOld */ && touch !== 2 /* AsNew */)) { - return; - } - if (touch === 1 /* AsOld */) { - if (item === this._head) { - return; - } - const next = item.next; - const previous = item.previous; - // Unlink the item - if (item === this._tail) { - // previous must be defined since item was not head but is tail - // So there are more than on item in the map - previous.next = undefined; - this._tail = previous; - } - else { - // Both next and previous are not undefined since item was neither head nor tail. - next.previous = previous; - previous.next = next; - } - // Insert the node at head - item.previous = undefined; - item.next = this._head; - this._head.previous = item; - this._head = item; - this._state++; - } - else if (touch === 2 /* AsNew */) { - if (item === this._tail) { - return; - } - const next = item.next; - const previous = item.previous; - // Unlink the item. - if (item === this._head) { - // next must be defined since item was not tail but is head - // So there are more than on item in the map - next.previous = undefined; - this._head = next; - } - else { - // Both next and previous are not undefined since item was neither head nor tail. - next.previous = previous; - previous.next = next; - } - item.next = undefined; - item.previous = this._tail; - this._tail.next = item; - this._tail = item; - this._state++; - } - } - toJSON() { - const data = []; - this.forEach((value, key) => { - data.push([key, value]); - }); - return data; - } - fromJSON(data) { - this.clear(); - for (const [key, value] of data) { - this.set(key, value); - } - } - } - exports.LinkedMap = LinkedMap; - class LRUCache extends LinkedMap { - constructor(limit, ratio = 1) { - super(); - this._limit = limit; - this._ratio = Math.min(Math.max(0, ratio), 1); - } - get limit() { - return this._limit; - } - set limit(limit) { - this._limit = limit; - this.checkTrim(); - } - get(key, touch = 2 /* AsNew */) { - return super.get(key, touch); - } - peek(key) { - return super.get(key, 0 /* None */); - } - set(key, value) { - super.set(key, value, 2 /* AsNew */); - this.checkTrim(); - return this; - } - checkTrim() { - if (this.size > this._limit) { - this.trimOld(Math.round(this._limit * this._ratio)); - } - } - } - exports.LRUCache = LRUCache; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[67/*vs/base/common/filters*/], __M([0/*require*/,1/*exports*/,49/*vs/base/common/map*/,8/*vs/base/common/strings*/]), function (require, exports, map_1, strings) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.fuzzyScoreGracefulAggressive = exports.fuzzyScore = exports.FuzzyScore = exports.isPatternInWord = exports.createMatches = exports.anyScore = exports.matchesFuzzy = exports.matchesWords = exports.matchesCamelCase = exports.isUpper = exports.matchesSubString = exports.matchesContiguousSubString = exports.matchesPrefix = exports.or = void 0; - // Combined filters - /** - * @returns A filter which combines the provided set - * of filters with an or. The *first* filters that - * matches defined the return value of the returned - * filter. - */ - function or(...filter) { - return function (word, wordToMatchAgainst) { - for (let i = 0, len = filter.length; i < len; i++) { - const match = filter[i](word, wordToMatchAgainst); - if (match) { - return match; - } - } - return null; - }; - } - exports.or = or; - exports.matchesPrefix = _matchesPrefix.bind(undefined, true); - function _matchesPrefix(ignoreCase, word, wordToMatchAgainst) { - if (!wordToMatchAgainst || wordToMatchAgainst.length < word.length) { - return null; - } - let matches; - if (ignoreCase) { - matches = strings.startsWithIgnoreCase(wordToMatchAgainst, word); - } - else { - matches = wordToMatchAgainst.indexOf(word) === 0; - } - if (!matches) { - return null; - } - return word.length > 0 ? [{ start: 0, end: word.length }] : []; - } - // Contiguous Substring - function matchesContiguousSubString(word, wordToMatchAgainst) { - const index = wordToMatchAgainst.toLowerCase().indexOf(word.toLowerCase()); - if (index === -1) { - return null; - } - return [{ start: index, end: index + word.length }]; - } - exports.matchesContiguousSubString = matchesContiguousSubString; - // Substring - function matchesSubString(word, wordToMatchAgainst) { - return _matchesSubString(word.toLowerCase(), wordToMatchAgainst.toLowerCase(), 0, 0); - } - exports.matchesSubString = matchesSubString; - function _matchesSubString(word, wordToMatchAgainst, i, j) { - if (i === word.length) { - return []; - } - else if (j === wordToMatchAgainst.length) { - return null; - } - else { - if (word[i] === wordToMatchAgainst[j]) { - let result = null; - if (result = _matchesSubString(word, wordToMatchAgainst, i + 1, j + 1)) { - return join({ start: j, end: j + 1 }, result); - } - return null; - } - return _matchesSubString(word, wordToMatchAgainst, i, j + 1); - } - } - // CamelCase - function isLower(code) { - return 97 /* a */ <= code && code <= 122 /* z */; - } - function isUpper(code) { - return 65 /* A */ <= code && code <= 90 /* Z */; - } - exports.isUpper = isUpper; - function isNumber(code) { - return 48 /* Digit0 */ <= code && code <= 57 /* Digit9 */; - } - function isWhitespace(code) { - return (code === 32 /* Space */ - || code === 9 /* Tab */ - || code === 10 /* LineFeed */ - || code === 13 /* CarriageReturn */); - } - const wordSeparators = new Set(); - '`~!@#$%^&*()-=+[{]}\\|;:\'",.<>/?' - .split('') - .forEach(s => wordSeparators.add(s.charCodeAt(0))); - function isWordSeparator(code) { - return isWhitespace(code) || wordSeparators.has(code); - } - function charactersMatch(codeA, codeB) { - return (codeA === codeB) || (isWordSeparator(codeA) && isWordSeparator(codeB)); - } - function isAlphanumeric(code) { - return isLower(code) || isUpper(code) || isNumber(code); - } - function join(head, tail) { - if (tail.length === 0) { - tail = [head]; - } - else if (head.end === tail[0].start) { - tail[0].start = head.start; - } - else { - tail.unshift(head); - } - return tail; - } - function nextAnchor(camelCaseWord, start) { - for (let i = start; i < camelCaseWord.length; i++) { - const c = camelCaseWord.charCodeAt(i); - if (isUpper(c) || isNumber(c) || (i > 0 && !isAlphanumeric(camelCaseWord.charCodeAt(i - 1)))) { - return i; - } - } - return camelCaseWord.length; - } - function _matchesCamelCase(word, camelCaseWord, i, j) { - if (i === word.length) { - return []; - } - else if (j === camelCaseWord.length) { - return null; - } - else if (word[i] !== camelCaseWord[j].toLowerCase()) { - return null; - } - else { - let result = null; - let nextUpperIndex = j + 1; - result = _matchesCamelCase(word, camelCaseWord, i + 1, j + 1); - while (!result && (nextUpperIndex = nextAnchor(camelCaseWord, nextUpperIndex)) < camelCaseWord.length) { - result = _matchesCamelCase(word, camelCaseWord, i + 1, nextUpperIndex); - nextUpperIndex++; - } - return result === null ? null : join({ start: j, end: j + 1 }, result); - } - } - // Heuristic to avoid computing camel case matcher for words that don't - // look like camelCaseWords. - function analyzeCamelCaseWord(word) { - let upper = 0, lower = 0, alpha = 0, numeric = 0, code = 0; - for (let i = 0; i < word.length; i++) { - code = word.charCodeAt(i); - if (isUpper(code)) { - upper++; - } - if (isLower(code)) { - lower++; - } - if (isAlphanumeric(code)) { - alpha++; - } - if (isNumber(code)) { - numeric++; - } - } - const upperPercent = upper / word.length; - const lowerPercent = lower / word.length; - const alphaPercent = alpha / word.length; - const numericPercent = numeric / word.length; - return { upperPercent, lowerPercent, alphaPercent, numericPercent }; - } - function isUpperCaseWord(analysis) { - const { upperPercent, lowerPercent } = analysis; - return lowerPercent === 0 && upperPercent > 0.6; - } - function isCamelCaseWord(analysis) { - const { upperPercent, lowerPercent, alphaPercent, numericPercent } = analysis; - return lowerPercent > 0.2 && upperPercent < 0.8 && alphaPercent > 0.6 && numericPercent < 0.2; - } - // Heuristic to avoid computing camel case matcher for words that don't - // look like camel case patterns. - function isCamelCasePattern(word) { - let upper = 0, lower = 0, code = 0, whitespace = 0; - for (let i = 0; i < word.length; i++) { - code = word.charCodeAt(i); - if (isUpper(code)) { - upper++; - } - if (isLower(code)) { - lower++; - } - if (isWhitespace(code)) { - whitespace++; - } - } - if ((upper === 0 || lower === 0) && whitespace === 0) { - return word.length <= 30; - } - else { - return upper <= 5; - } - } - function matchesCamelCase(word, camelCaseWord) { - if (!camelCaseWord) { - return null; - } - camelCaseWord = camelCaseWord.trim(); - if (camelCaseWord.length === 0) { - return null; - } - if (!isCamelCasePattern(word)) { - return null; - } - if (camelCaseWord.length > 60) { - return null; - } - const analysis = analyzeCamelCaseWord(camelCaseWord); - if (!isCamelCaseWord(analysis)) { - if (!isUpperCaseWord(analysis)) { - return null; - } - camelCaseWord = camelCaseWord.toLowerCase(); - } - let result = null; - let i = 0; - word = word.toLowerCase(); - while (i < camelCaseWord.length && (result = _matchesCamelCase(word, camelCaseWord, 0, i)) === null) { - i = nextAnchor(camelCaseWord, i + 1); - } - return result; - } - exports.matchesCamelCase = matchesCamelCase; - // Matches beginning of words supporting non-ASCII languages - // If `contiguous` is true then matches word with beginnings of the words in the target. E.g. "pul" will match "Git: Pull" - // Otherwise also matches sub string of the word with beginnings of the words in the target. E.g. "gp" or "g p" will match "Git: Pull" - // Useful in cases where the target is words (e.g. command labels) - function matchesWords(word, target, contiguous = false) { - if (!target || target.length === 0) { - return null; - } - let result = null; - let i = 0; - word = word.toLowerCase(); - target = target.toLowerCase(); - while (i < target.length && (result = _matchesWords(word, target, 0, i, contiguous)) === null) { - i = nextWord(target, i + 1); - } - return result; - } - exports.matchesWords = matchesWords; - function _matchesWords(word, target, i, j, contiguous) { - if (i === word.length) { - return []; - } - else if (j === target.length) { - return null; - } - else if (!charactersMatch(word.charCodeAt(i), target.charCodeAt(j))) { - return null; - } - else { - let result = null; - let nextWordIndex = j + 1; - result = _matchesWords(word, target, i + 1, j + 1, contiguous); - if (!contiguous) { - while (!result && (nextWordIndex = nextWord(target, nextWordIndex)) < target.length) { - result = _matchesWords(word, target, i + 1, nextWordIndex, contiguous); - nextWordIndex++; - } - } - return result === null ? null : join({ start: j, end: j + 1 }, result); - } - } - function nextWord(word, start) { - for (let i = start; i < word.length; i++) { - if (isWordSeparator(word.charCodeAt(i)) || - (i > 0 && isWordSeparator(word.charCodeAt(i - 1)))) { - return i; - } - } - return word.length; - } - // Fuzzy - const fuzzyContiguousFilter = or(exports.matchesPrefix, matchesCamelCase, matchesContiguousSubString); - const fuzzySeparateFilter = or(exports.matchesPrefix, matchesCamelCase, matchesSubString); - const fuzzyRegExpCache = new map_1.LRUCache(10000); // bounded to 10000 elements - function matchesFuzzy(word, wordToMatchAgainst, enableSeparateSubstringMatching = false) { - if (typeof word !== 'string' || typeof wordToMatchAgainst !== 'string') { - return null; // return early for invalid input - } - // Form RegExp for wildcard matches - let regexp = fuzzyRegExpCache.get(word); - if (!regexp) { - regexp = new RegExp(strings.convertSimple2RegExpPattern(word), 'i'); - fuzzyRegExpCache.set(word, regexp); - } - // RegExp Filter - const match = regexp.exec(wordToMatchAgainst); - if (match) { - return [{ start: match.index, end: match.index + match[0].length }]; - } - // Default Filter - return enableSeparateSubstringMatching ? fuzzySeparateFilter(word, wordToMatchAgainst) : fuzzyContiguousFilter(word, wordToMatchAgainst); - } - exports.matchesFuzzy = matchesFuzzy; - function anyScore(pattern, lowPattern, patternPos, word, lowWord, wordPos) { - const max = Math.min(13, pattern.length); - for (; patternPos < max; patternPos++) { - const result = fuzzyScore(pattern, lowPattern, patternPos, word, lowWord, wordPos, false); - if (result) { - return result; - } - } - return [0, wordPos]; - } - exports.anyScore = anyScore; - //#region --- fuzzyScore --- - function createMatches(score) { - if (typeof score === 'undefined') { - return []; - } - const res = []; - const wordPos = score[1]; - for (let i = score.length - 1; i > 1; i--) { - const pos = score[i] + wordPos; - const last = res[res.length - 1]; - if (last && last.end === pos) { - last.end = pos + 1; - } - else { - res.push({ start: pos, end: pos + 1 }); - } - } - return res; - } - exports.createMatches = createMatches; - const _maxLen = 128; - function initTable() { - const table = []; - const row = []; - for (let i = 0; i <= _maxLen; i++) { - row[i] = 0; - } - for (let i = 0; i <= _maxLen; i++) { - table.push(row.slice(0)); - } - return table; - } - function initArr(maxLen) { - const row = []; - for (let i = 0; i <= maxLen; i++) { - row[i] = 0; - } - return row; - } - const _minWordMatchPos = initArr(2 * _maxLen); // min word position for a certain pattern position - const _maxWordMatchPos = initArr(2 * _maxLen); // max word position for a certain pattern position - const _diag = initTable(); // the length of a contiguous diagonal match - const _table = initTable(); - const _arrows = initTable(); - const _debug = false; - function printTable(table, pattern, patternLen, word, wordLen) { - function pad(s, n, pad = ' ') { - while (s.length < n) { - s = pad + s; - } - return s; - } - let ret = ` | |${word.split('').map(c => pad(c, 3)).join('|')}\n`; - for (let i = 0; i <= patternLen; i++) { - if (i === 0) { - ret += ' |'; - } - else { - ret += `${pattern[i - 1]}|`; - } - ret += table[i].slice(0, wordLen + 1).map(n => pad(n.toString(), 3)).join('|') + '\n'; - } - return ret; - } - function printTables(pattern, patternStart, word, wordStart) { - pattern = pattern.substr(patternStart); - word = word.substr(wordStart); - console.log(printTable(_table, pattern, pattern.length, word, word.length)); - console.log(printTable(_arrows, pattern, pattern.length, word, word.length)); - console.log(printTable(_diag, pattern, pattern.length, word, word.length)); - } - function isSeparatorAtPos(value, index) { - if (index < 0 || index >= value.length) { - return false; - } - const code = value.codePointAt(index); - switch (code) { - case 95 /* Underline */: - case 45 /* Dash */: - case 46 /* Period */: - case 32 /* Space */: - case 47 /* Slash */: - case 92 /* Backslash */: - case 39 /* SingleQuote */: - case 34 /* DoubleQuote */: - case 58 /* Colon */: - case 36 /* DollarSign */: - case 60 /* LessThan */: - case 40 /* OpenParen */: - case 91 /* OpenSquareBracket */: - return true; - case undefined: - return false; - default: - if (strings.isEmojiImprecise(code)) { - return true; - } - return false; - } - } - function isWhitespaceAtPos(value, index) { - if (index < 0 || index >= value.length) { - return false; - } - const code = value.charCodeAt(index); - switch (code) { - case 32 /* Space */: - case 9 /* Tab */: - return true; - default: - return false; - } - } - function isUpperCaseAtPos(pos, word, wordLow) { - return word[pos] !== wordLow[pos]; - } - function isPatternInWord(patternLow, patternPos, patternLen, wordLow, wordPos, wordLen, fillMinWordPosArr = false) { - while (patternPos < patternLen && wordPos < wordLen) { - if (patternLow[patternPos] === wordLow[wordPos]) { - if (fillMinWordPosArr) { - // Remember the min word position for each pattern position - _minWordMatchPos[patternPos] = wordPos; - } - patternPos += 1; - } - wordPos += 1; - } - return patternPos === patternLen; // pattern must be exhausted - } - exports.isPatternInWord = isPatternInWord; - var FuzzyScore; - (function (FuzzyScore) { - /** - * No matches and value `-100` - */ - FuzzyScore.Default = ([-100, 0]); - function isDefault(score) { - return !score || (score.length === 2 && score[0] === -100 && score[1] === 0); - } - FuzzyScore.isDefault = isDefault; - })(FuzzyScore = exports.FuzzyScore || (exports.FuzzyScore = {})); - function fuzzyScore(pattern, patternLow, patternStart, word, wordLow, wordStart, firstMatchCanBeWeak) { - const patternLen = pattern.length > _maxLen ? _maxLen : pattern.length; - const wordLen = word.length > _maxLen ? _maxLen : word.length; - if (patternStart >= patternLen || wordStart >= wordLen || (patternLen - patternStart) > (wordLen - wordStart)) { - return undefined; - } - // Run a simple check if the characters of pattern occur - // (in order) at all in word. If that isn't the case we - // stop because no match will be possible - if (!isPatternInWord(patternLow, patternStart, patternLen, wordLow, wordStart, wordLen, true)) { - return undefined; - } - // Find the max matching word position for each pattern position - // NOTE: the min matching word position was filled in above, in the `isPatternInWord` call - _fillInMaxWordMatchPos(patternLen, wordLen, patternStart, wordStart, patternLow, wordLow); - let row = 1; - let column = 1; - let patternPos = patternStart; - let wordPos = wordStart; - const hasStrongFirstMatch = [false]; - // There will be a match, fill in tables - for (row = 1, patternPos = patternStart; patternPos < patternLen; row++, patternPos++) { - // Reduce search space to possible matching word positions and to possible access from next row - const minWordMatchPos = _minWordMatchPos[patternPos]; - const maxWordMatchPos = _maxWordMatchPos[patternPos]; - const nextMaxWordMatchPos = (patternPos + 1 < patternLen ? _maxWordMatchPos[patternPos + 1] : wordLen); - for (column = minWordMatchPos - wordStart + 1, wordPos = minWordMatchPos; wordPos < nextMaxWordMatchPos; column++, wordPos++) { - let score = Number.MIN_SAFE_INTEGER; - let canComeDiag = false; - if (wordPos <= maxWordMatchPos) { - score = _doScore(pattern, patternLow, patternPos, patternStart, word, wordLow, wordPos, wordLen, wordStart, _diag[row - 1][column - 1] === 0, hasStrongFirstMatch); - } - let diagScore = 0; - if (score !== Number.MAX_SAFE_INTEGER) { - canComeDiag = true; - diagScore = score + _table[row - 1][column - 1]; - } - const canComeLeft = wordPos > minWordMatchPos; - const leftScore = canComeLeft ? _table[row][column - 1] + (_diag[row][column - 1] > 0 ? -5 : 0) : 0; // penalty for a gap start - const canComeLeftLeft = wordPos > minWordMatchPos + 1 && _diag[row][column - 1] > 0; - const leftLeftScore = canComeLeftLeft ? _table[row][column - 2] + (_diag[row][column - 2] > 0 ? -5 : 0) : 0; // penalty for a gap start - if (canComeLeftLeft && (!canComeLeft || leftLeftScore >= leftScore) && (!canComeDiag || leftLeftScore >= diagScore)) { - // always prefer choosing left left to jump over a diagonal because that means a match is earlier in the word - _table[row][column] = leftLeftScore; - _arrows[row][column] = 3 /* LeftLeft */; - _diag[row][column] = 0; - } - else if (canComeLeft && (!canComeDiag || leftScore >= diagScore)) { - // always prefer choosing left since that means a match is earlier in the word - _table[row][column] = leftScore; - _arrows[row][column] = 2 /* Left */; - _diag[row][column] = 0; - } - else if (canComeDiag) { - _table[row][column] = diagScore; - _arrows[row][column] = 1 /* Diag */; - _diag[row][column] = _diag[row - 1][column - 1] + 1; - } - else { - throw new Error(`not possible`); - } - } - } - if (_debug) { - printTables(pattern, patternStart, word, wordStart); - } - if (!hasStrongFirstMatch[0] && !firstMatchCanBeWeak) { - return undefined; - } - row--; - column--; - const result = [_table[row][column], wordStart]; - let backwardsDiagLength = 0; - let maxMatchColumn = 0; - while (row >= 1) { - // Find the column where we go diagonally up - let diagColumn = column; - do { - const arrow = _arrows[row][diagColumn]; - if (arrow === 3 /* LeftLeft */) { - diagColumn = diagColumn - 2; - } - else if (arrow === 2 /* Left */) { - diagColumn = diagColumn - 1; - } - else { - // found the diagonal - break; - } - } while (diagColumn >= 1); - // Overturn the "forwards" decision if keeping the "backwards" diagonal would give a better match - if (backwardsDiagLength > 1 // only if we would have a contiguous match of 3 characters - && patternLow[patternStart + row - 1] === wordLow[wordStart + column - 1] // only if we can do a contiguous match diagonally - && !isUpperCaseAtPos(diagColumn + wordStart - 1, word, wordLow) // only if the forwards chose diagonal is not an uppercase - && backwardsDiagLength + 1 > _diag[row][diagColumn] // only if our contiguous match would be longer than the "forwards" contiguous match - ) { - diagColumn = column; - } - if (diagColumn === column) { - // this is a contiguous match - backwardsDiagLength++; - } - else { - backwardsDiagLength = 1; - } - if (!maxMatchColumn) { - // remember the last matched column - maxMatchColumn = diagColumn; - } - row--; - column = diagColumn - 1; - result.push(column); - } - if (wordLen === patternLen) { - // the word matches the pattern with all characters! - // giving the score a total match boost (to come up ahead other words) - result[0] += 2; - } - // Add 1 penalty for each skipped character in the word - const skippedCharsCount = maxMatchColumn - patternLen; - result[0] -= skippedCharsCount; - return result; - } - exports.fuzzyScore = fuzzyScore; - function _fillInMaxWordMatchPos(patternLen, wordLen, patternStart, wordStart, patternLow, wordLow) { - let patternPos = patternLen - 1; - let wordPos = wordLen - 1; - while (patternPos >= patternStart && wordPos >= wordStart) { - if (patternLow[patternPos] === wordLow[wordPos]) { - _maxWordMatchPos[patternPos] = wordPos; - patternPos--; - } - wordPos--; - } - } - function _doScore(pattern, patternLow, patternPos, patternStart, word, wordLow, wordPos, wordLen, wordStart, newMatchStart, outFirstMatchStrong) { - if (patternLow[patternPos] !== wordLow[wordPos]) { - return Number.MIN_SAFE_INTEGER; - } - let score = 1; - let isGapLocation = false; - if (wordPos === (patternPos - patternStart)) { - // common prefix: `foobar <-> foobaz` - // ^^^^^ - score = pattern[patternPos] === word[wordPos] ? 7 : 5; - } - else if (isUpperCaseAtPos(wordPos, word, wordLow) && (wordPos === 0 || !isUpperCaseAtPos(wordPos - 1, word, wordLow))) { - // hitting upper-case: `foo <-> forOthers` - // ^^ ^ - score = pattern[patternPos] === word[wordPos] ? 7 : 5; - isGapLocation = true; - } - else if (isSeparatorAtPos(wordLow, wordPos) && (wordPos === 0 || !isSeparatorAtPos(wordLow, wordPos - 1))) { - // hitting a separator: `. <-> foo.bar` - // ^ - score = 5; - } - else if (isSeparatorAtPos(wordLow, wordPos - 1) || isWhitespaceAtPos(wordLow, wordPos - 1)) { - // post separator: `foo <-> bar_foo` - // ^^^ - score = 5; - isGapLocation = true; - } - if (score > 1 && patternPos === patternStart) { - outFirstMatchStrong[0] = true; - } - if (!isGapLocation) { - isGapLocation = isUpperCaseAtPos(wordPos, word, wordLow) || isSeparatorAtPos(wordLow, wordPos - 1) || isWhitespaceAtPos(wordLow, wordPos - 1); - } - // - if (patternPos === patternStart) { // first character in pattern - if (wordPos > wordStart) { - // the first pattern character would match a word character that is not at the word start - // so introduce a penalty to account for the gap preceding this match - score -= isGapLocation ? 3 : 5; - } - } - else { - if (newMatchStart) { - // this would be the beginning of a new match (i.e. there would be a gap before this location) - score += isGapLocation ? 2 : 0; - } - else { - // this is part of a contiguous match, so give it a slight bonus, but do so only if it would not be a prefered gap location - score += isGapLocation ? 0 : 1; - } - } - if (wordPos + 1 === wordLen) { - // we always penalize gaps, but this gives unfair advantages to a match that would match the last character in the word - // so pretend there is a gap after the last character in the word to normalize things - score -= isGapLocation ? 3 : 5; - } - return score; - } - //#endregion - //#region --- graceful --- - function fuzzyScoreGracefulAggressive(pattern, lowPattern, patternPos, word, lowWord, wordPos, firstMatchCanBeWeak) { - return fuzzyScoreWithPermutations(pattern, lowPattern, patternPos, word, lowWord, wordPos, true, firstMatchCanBeWeak); - } - exports.fuzzyScoreGracefulAggressive = fuzzyScoreGracefulAggressive; - function fuzzyScoreWithPermutations(pattern, lowPattern, patternPos, word, lowWord, wordPos, aggressive, firstMatchCanBeWeak) { - let top = fuzzyScore(pattern, lowPattern, patternPos, word, lowWord, wordPos, firstMatchCanBeWeak); - if (top && !aggressive) { - // when using the original pattern yield a result we` - // return it unless we are aggressive and try to find - // a better alignment, e.g. `cno` -> `^co^ns^ole` or `^c^o^nsole`. - return top; - } - if (pattern.length >= 3) { - // When the pattern is long enough then try a few (max 7) - // permutations of the pattern to find a better match. The - // permutations only swap neighbouring characters, e.g - // `cnoso` becomes `conso`, `cnsoo`, `cnoos`. - const tries = Math.min(7, pattern.length - 1); - for (let movingPatternPos = patternPos + 1; movingPatternPos < tries; movingPatternPos++) { - const newPattern = nextTypoPermutation(pattern, movingPatternPos); - if (newPattern) { - const candidate = fuzzyScore(newPattern, newPattern.toLowerCase(), patternPos, word, lowWord, wordPos, firstMatchCanBeWeak); - if (candidate) { - candidate[0] -= 3; // permutation penalty - if (!top || candidate[0] > top[0]) { - top = candidate; - } - } - } - } - } - return top; - } - function nextTypoPermutation(pattern, patternPos) { - if (patternPos + 1 >= pattern.length) { - return undefined; - } - const swap1 = pattern[patternPos]; - const swap2 = pattern[patternPos + 1]; - if (swap1 === swap2) { - return undefined; - } - return pattern.slice(0, patternPos) - + swap2 - + swap1 - + pattern.slice(patternPos + 2); - } -}); -//#endregion - -define(__m[294/*vs/base/common/fuzzyScorer*/], __M([0/*require*/,1/*exports*/,67/*vs/base/common/filters*/,73/*vs/base/common/path*/,17/*vs/base/common/platform*/,8/*vs/base/common/strings*/]), function (require, exports, filters_1, path_1, platform_1, strings_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.pieceToQuery = exports.prepareQuery = exports.scoreFuzzy2 = void 0; - const NO_SCORE2 = [undefined, []]; - function scoreFuzzy2(target, query, patternStart = 0, wordStart = 0) { - // Score: multiple inputs - const preparedQuery = query; - if (preparedQuery.values && preparedQuery.values.length > 1) { - return doScoreFuzzy2Multiple(target, preparedQuery.values, patternStart, wordStart); - } - // Score: single input - return doScoreFuzzy2Single(target, query, patternStart, wordStart); - } - exports.scoreFuzzy2 = scoreFuzzy2; - function doScoreFuzzy2Multiple(target, query, patternStart, wordStart) { - let totalScore = 0; - const totalMatches = []; - for (const queryPiece of query) { - const [score, matches] = doScoreFuzzy2Single(target, queryPiece, patternStart, wordStart); - if (typeof score !== 'number') { - // if a single query value does not match, return with - // no score entirely, we require all queries to match - return NO_SCORE2; - } - totalScore += score; - totalMatches.push(...matches); - } - // if we have a score, ensure that the positions are - // sorted in ascending order and distinct - return [totalScore, normalizeMatches(totalMatches)]; - } - function doScoreFuzzy2Single(target, query, patternStart, wordStart) { - const score = (0, filters_1.fuzzyScore)(query.original, query.originalLowercase, patternStart, target, target.toLowerCase(), wordStart, true); - if (!score) { - return NO_SCORE2; - } - return [score[0], (0, filters_1.createMatches)(score)]; - } - function normalizeMatches(matches) { - // sort matches by start to be able to normalize - const sortedMatches = matches.sort((matchA, matchB) => { - return matchA.start - matchB.start; - }); - // merge matches that overlap - const normalizedMatches = []; - let currentMatch = undefined; - for (const match of sortedMatches) { - // if we have no current match or the matches - // do not overlap, we take it as is and remember - // it for future merging - if (!currentMatch || !matchOverlaps(currentMatch, match)) { - currentMatch = match; - normalizedMatches.push(match); - } - // otherwise we merge the matches - else { - currentMatch.start = Math.min(currentMatch.start, match.start); - currentMatch.end = Math.max(currentMatch.end, match.end); - } - } - return normalizedMatches; - } - function matchOverlaps(matchA, matchB) { - if (matchA.end < matchB.start) { - return false; // A ends before B starts - } - if (matchB.end < matchA.start) { - return false; // B ends before A starts - } - return true; - } - /** - * Helper function to prepare a search value for scoring by removing unwanted characters - * and allowing to score on multiple pieces separated by whitespace character. - */ - const MULTIPLE_QUERY_VALUES_SEPARATOR = ' '; - function prepareQuery(original) { - if (typeof original !== 'string') { - original = ''; - } - const originalLowercase = original.toLowerCase(); - const { pathNormalized, normalized, normalizedLowercase } = normalizeQuery(original); - const containsPathSeparator = pathNormalized.indexOf(path_1.sep) >= 0; - let values = undefined; - const originalSplit = original.split(MULTIPLE_QUERY_VALUES_SEPARATOR); - if (originalSplit.length > 1) { - for (const originalPiece of originalSplit) { - const { pathNormalized: pathNormalizedPiece, normalized: normalizedPiece, normalizedLowercase: normalizedLowercasePiece } = normalizeQuery(originalPiece); - if (normalizedPiece) { - if (!values) { - values = []; - } - values.push({ - original: originalPiece, - originalLowercase: originalPiece.toLowerCase(), - pathNormalized: pathNormalizedPiece, - normalized: normalizedPiece, - normalizedLowercase: normalizedLowercasePiece - }); - } - } - } - return { original, originalLowercase, pathNormalized, normalized, normalizedLowercase, values, containsPathSeparator }; - } - exports.prepareQuery = prepareQuery; - function normalizeQuery(original) { - let pathNormalized; - if (platform_1.isWindows) { - pathNormalized = original.replace(/\//g, path_1.sep); // Help Windows users to search for paths when using slash - } - else { - pathNormalized = original.replace(/\\/g, path_1.sep); // Help macOS/Linux users to search for paths when using backslash - } - const normalized = (0, strings_1.stripWildcards)(pathNormalized).replace(/\s/g, ''); - return { - pathNormalized, - normalized, - normalizedLowercase: normalized.toLowerCase() - }; - } - function pieceToQuery(arg1) { - if (Array.isArray(arg1)) { - return prepareQuery(arg1.map(piece => piece.original).join(MULTIPLE_QUERY_VALUES_SEPARATOR)); - } - return prepareQuery(arg1.original); - } - exports.pieceToQuery = pieceToQuery; -}); -//#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[201/*vs/base/common/glob*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,157/*vs/base/common/extpath*/,73/*vs/base/common/path*/,49/*vs/base/common/map*/,15/*vs/base/common/async*/]), function (require, exports, strings, extpath, paths, map_1, async_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.isRelativePattern = exports.parse = exports.match = exports.splitGlobAware = void 0; - const GLOBSTAR = '**'; - const GLOB_SPLIT = '/'; - const PATH_REGEX = '[/\\\\]'; // any slash or backslash - const NO_PATH_REGEX = '[^/\\\\]'; // any non-slash and non-backslash - const ALL_FORWARD_SLASHES = /\//g; - function starsToRegExp(starCount) { - switch (starCount) { - case 0: - return ''; - case 1: - return `${NO_PATH_REGEX}*?`; // 1 star matches any number of characters except path separator (/ and \) - non greedy (?) - default: - // Matches: (Path Sep OR Path Val followed by Path Sep OR Path Sep followed by Path Val) 0-many times - // Group is non capturing because we don't need to capture at all (?:...) - // Overall we use non-greedy matching because it could be that we match too much - return `(?:${PATH_REGEX}|${NO_PATH_REGEX}+${PATH_REGEX}|${PATH_REGEX}${NO_PATH_REGEX}+)*?`; - } - } - function splitGlobAware(pattern, splitChar) { - if (!pattern) { - return []; - } - const segments = []; - let inBraces = false; - let inBrackets = false; - let curVal = ''; - for (const char of pattern) { - switch (char) { - case splitChar: - if (!inBraces && !inBrackets) { - segments.push(curVal); - curVal = ''; - continue; - } - break; - case '{': - inBraces = true; - break; - case '}': - inBraces = false; - break; - case '[': - inBrackets = true; - break; - case ']': - inBrackets = false; - break; - } - curVal += char; - } - // Tail - if (curVal) { - segments.push(curVal); - } - return segments; - } - exports.splitGlobAware = splitGlobAware; - function parseRegExp(pattern) { - if (!pattern) { - return ''; - } - let regEx = ''; - // Split up into segments for each slash found - const segments = splitGlobAware(pattern, GLOB_SPLIT); - // Special case where we only have globstars - if (segments.every(s => s === GLOBSTAR)) { - regEx = '.*'; - } - // Build regex over segments - else { - let previousSegmentWasGlobStar = false; - segments.forEach((segment, index) => { - // Globstar is special - if (segment === GLOBSTAR) { - // if we have more than one globstar after another, just ignore it - if (!previousSegmentWasGlobStar) { - regEx += starsToRegExp(2); - previousSegmentWasGlobStar = true; - } - return; - } - // States - let inBraces = false; - let braceVal = ''; - let inBrackets = false; - let bracketVal = ''; - for (const char of segment) { - // Support brace expansion - if (char !== '}' && inBraces) { - braceVal += char; - continue; - } - // Support brackets - if (inBrackets && (char !== ']' || !bracketVal) /* ] is literally only allowed as first character in brackets to match it */) { - let res; - // range operator - if (char === '-') { - res = char; - } - // negation operator (only valid on first index in bracket) - else if ((char === '^' || char === '!') && !bracketVal) { - res = '^'; - } - // glob split matching is not allowed within character ranges - // see http://man7.org/linux/man-pages/man7/glob.7.html - else if (char === GLOB_SPLIT) { - res = ''; - } - // anything else gets escaped - else { - res = strings.escapeRegExpCharacters(char); - } - bracketVal += res; - continue; - } - switch (char) { - case '{': - inBraces = true; - continue; - case '[': - inBrackets = true; - continue; - case '}': - const choices = splitGlobAware(braceVal, ','); - // Converts {foo,bar} => [foo|bar] - const braceRegExp = `(?:${choices.map(c => parseRegExp(c)).join('|')})`; - regEx += braceRegExp; - inBraces = false; - braceVal = ''; - break; - case ']': - regEx += ('[' + bracketVal + ']'); - inBrackets = false; - bracketVal = ''; - break; - case '?': - regEx += NO_PATH_REGEX; // 1 ? matches any single character except path separator (/ and \) - continue; - case '*': - regEx += starsToRegExp(1); - continue; - default: - regEx += strings.escapeRegExpCharacters(char); - } - } - // Tail: Add the slash we had split on if there is more to come and the remaining pattern is not a globstar - // For example if pattern: some/**/*.js we want the "/" after some to be included in the RegEx to prevent - // a folder called "something" to match as well. - // However, if pattern: some/**, we tolerate that we also match on "something" because our globstar behaviour - // is to match 0-N segments. - if (index < segments.length - 1 && (segments[index + 1] !== GLOBSTAR || index + 2 < segments.length)) { - regEx += PATH_REGEX; - } - // reset state - previousSegmentWasGlobStar = false; - }); - } - return regEx; - } - // regexes to check for trival glob patterns that just check for String#endsWith - const T1 = /^\*\*\/\*\.[\w\.-]+$/; // **/*.something - const T2 = /^\*\*\/([\w\.-]+)\/?$/; // **/something - const T3 = /^{\*\*\/[\*\.]?[\w\.-]+\/?(,\*\*\/[\*\.]?[\w\.-]+\/?)*}$/; // {**/*.something,**/*.else} or {**/package.json,**/project.json} - const T3_2 = /^{\*\*\/[\*\.]?[\w\.-]+(\/(\*\*)?)?(,\*\*\/[\*\.]?[\w\.-]+(\/(\*\*)?)?)*}$/; // Like T3, with optional trailing /** - const T4 = /^\*\*((\/[\w\.-]+)+)\/?$/; // **/something/else - const T5 = /^([\w\.-]+(\/[\w\.-]+)*)\/?$/; // something/else - const CACHE = new map_1.LRUCache(10000); // bounded to 10000 elements - const FALSE = function () { - return false; - }; - const NULL = function () { - return null; - }; - function parsePattern(arg1, options) { - if (!arg1) { - return NULL; - } - // Handle IRelativePattern - let pattern; - if (typeof arg1 !== 'string') { - pattern = arg1.pattern; - } - else { - pattern = arg1; - } - // Whitespace trimming - pattern = pattern.trim(); - // Check cache - const patternKey = `${pattern}_${!!options.trimForExclusions}`; - let parsedPattern = CACHE.get(patternKey); - if (parsedPattern) { - return wrapRelativePattern(parsedPattern, arg1); - } - // Check for Trivias - let match; - if (T1.test(pattern)) { // common pattern: **/*.txt just need endsWith check - const base = pattern.substr(4); // '**/*'.length === 4 - parsedPattern = function (path, basename) { - return typeof path === 'string' && path.endsWith(base) ? pattern : null; - }; - } - else if (match = T2.exec(trimForExclusions(pattern, options))) { // common pattern: **/some.txt just need basename check - parsedPattern = trivia2(match[1], pattern); - } - else if ((options.trimForExclusions ? T3_2 : T3).test(pattern)) { // repetition of common patterns (see above) {**/*.txt,**/*.png} - parsedPattern = trivia3(pattern, options); - } - else if (match = T4.exec(trimForExclusions(pattern, options))) { // common pattern: **/something/else just need endsWith check - parsedPattern = trivia4and5(match[1].substr(1), pattern, true); - } - else if (match = T5.exec(trimForExclusions(pattern, options))) { // common pattern: something/else just need equals check - parsedPattern = trivia4and5(match[1], pattern, false); - } - // Otherwise convert to pattern - else { - parsedPattern = toRegExp(pattern); - } - // Cache - CACHE.set(patternKey, parsedPattern); - return wrapRelativePattern(parsedPattern, arg1); - } - function wrapRelativePattern(parsedPattern, arg2) { - if (typeof arg2 === 'string') { - return parsedPattern; - } - return function (path, basename) { - if (!extpath.isEqualOrParent(path, arg2.base)) { - return null; - } - return parsedPattern(paths.relative(arg2.base, path), basename); - }; - } - function trimForExclusions(pattern, options) { - return options.trimForExclusions && pattern.endsWith('/**') ? pattern.substr(0, pattern.length - 2) : pattern; // dropping **, tailing / is dropped later - } - // common pattern: **/some.txt just need basename check - function trivia2(base, originalPattern) { - const slashBase = `/${base}`; - const backslashBase = `\\${base}`; - const parsedPattern = function (path, basename) { - if (typeof path !== 'string') { - return null; - } - if (basename) { - return basename === base ? originalPattern : null; - } - return path === base || path.endsWith(slashBase) || path.endsWith(backslashBase) ? originalPattern : null; - }; - const basenames = [base]; - parsedPattern.basenames = basenames; - parsedPattern.patterns = [originalPattern]; - parsedPattern.allBasenames = basenames; - return parsedPattern; - } - // repetition of common patterns (see above) {**/*.txt,**/*.png} - function trivia3(pattern, options) { - const parsedPatterns = aggregateBasenameMatches(pattern.slice(1, -1).split(',') - .map(pattern => parsePattern(pattern, options)) - .filter(pattern => pattern !== NULL), pattern); - const n = parsedPatterns.length; - if (!n) { - return NULL; - } - if (n === 1) { - return parsedPatterns[0]; - } - const parsedPattern = function (path, basename) { - for (let i = 0, n = parsedPatterns.length; i < n; i++) { - if (parsedPatterns[i](path, basename)) { - return pattern; - } - } - return null; - }; - const withBasenames = parsedPatterns.find(pattern => !!pattern.allBasenames); - if (withBasenames) { - parsedPattern.allBasenames = withBasenames.allBasenames; - } - const allPaths = parsedPatterns.reduce((all, current) => current.allPaths ? all.concat(current.allPaths) : all, []); - if (allPaths.length) { - parsedPattern.allPaths = allPaths; - } - return parsedPattern; - } - // common patterns: **/something/else just need endsWith check, something/else just needs and equals check - function trivia4and5(targetPath, pattern, matchPathEnds) { - const usingPosixSep = paths.sep === paths.posix.sep; - const nativePath = usingPosixSep ? targetPath : targetPath.replace(ALL_FORWARD_SLASHES, paths.sep); - const nativePathEnd = paths.sep + nativePath; - const targetPathEnd = paths.posix.sep + targetPath; - const parsedPattern = matchPathEnds ? function (testPath, basename) { - return typeof testPath === 'string' && - ((testPath === nativePath || testPath.endsWith(nativePathEnd)) - || !usingPosixSep && (testPath === targetPath || testPath.endsWith(targetPathEnd))) - ? pattern : null; - } : function (testPath, basename) { - return typeof testPath === 'string' && - (testPath === nativePath - || (!usingPosixSep && testPath === targetPath)) - ? pattern : null; - }; - parsedPattern.allPaths = [(matchPathEnds ? '*/' : './') + targetPath]; - return parsedPattern; - } - function toRegExp(pattern) { - try { - const regExp = new RegExp(`^${parseRegExp(pattern)}$`); - return function (path) { - regExp.lastIndex = 0; // reset RegExp to its initial state to reuse it! - return typeof path === 'string' && regExp.test(path) ? pattern : null; - }; - } - catch (error) { - return NULL; - } - } - function match(arg1, path, hasSibling) { - if (!arg1 || typeof path !== 'string') { - return false; - } - return parse(arg1)(path, undefined, hasSibling); - } - exports.match = match; - function parse(arg1, options = {}) { - if (!arg1) { - return FALSE; - } - // Glob with String - if (typeof arg1 === 'string' || isRelativePattern(arg1)) { - const parsedPattern = parsePattern(arg1, options); - if (parsedPattern === NULL) { - return FALSE; - } - const resultPattern = function (path, basename) { - return !!parsedPattern(path, basename); - }; - if (parsedPattern.allBasenames) { - resultPattern.allBasenames = parsedPattern.allBasenames; - } - if (parsedPattern.allPaths) { - resultPattern.allPaths = parsedPattern.allPaths; - } - return resultPattern; - } - // Glob with Expression - return parsedExpression(arg1, options); - } - exports.parse = parse; - function isRelativePattern(obj) { - const rp = obj; - return rp && typeof rp.base === 'string' && typeof rp.pattern === 'string'; - } - exports.isRelativePattern = isRelativePattern; - function parsedExpression(expression, options) { - const parsedPatterns = aggregateBasenameMatches(Object.getOwnPropertyNames(expression) - .map(pattern => parseExpressionPattern(pattern, expression[pattern], options)) - .filter(pattern => pattern !== NULL)); - const n = parsedPatterns.length; - if (!n) { - return NULL; - } - if (!parsedPatterns.some(parsedPattern => !!parsedPattern.requiresSiblings)) { - if (n === 1) { - return parsedPatterns[0]; - } - const resultExpression = function (path, basename) { - for (let i = 0, n = parsedPatterns.length; i < n; i++) { - // Pattern matches path - const result = parsedPatterns[i](path, basename); - if (result) { - return result; - } - } - return null; - }; - const withBasenames = parsedPatterns.find(pattern => !!pattern.allBasenames); - if (withBasenames) { - resultExpression.allBasenames = withBasenames.allBasenames; - } - const allPaths = parsedPatterns.reduce((all, current) => current.allPaths ? all.concat(current.allPaths) : all, []); - if (allPaths.length) { - resultExpression.allPaths = allPaths; - } - return resultExpression; - } - const resultExpression = function (path, basename, hasSibling) { - let name = undefined; - for (let i = 0, n = parsedPatterns.length; i < n; i++) { - // Pattern matches path - const parsedPattern = parsedPatterns[i]; - if (parsedPattern.requiresSiblings && hasSibling) { - if (!basename) { - basename = paths.basename(path); - } - if (!name) { - name = basename.substr(0, basename.length - paths.extname(path).length); - } - } - const result = parsedPattern(path, basename, name, hasSibling); - if (result) { - return result; - } - } - return null; - }; - const withBasenames = parsedPatterns.find(pattern => !!pattern.allBasenames); - if (withBasenames) { - resultExpression.allBasenames = withBasenames.allBasenames; - } - const allPaths = parsedPatterns.reduce((all, current) => current.allPaths ? all.concat(current.allPaths) : all, []); - if (allPaths.length) { - resultExpression.allPaths = allPaths; - } - return resultExpression; - } - function parseExpressionPattern(pattern, value, options) { - if (value === false) { - return NULL; // pattern is disabled - } - const parsedPattern = parsePattern(pattern, options); - if (parsedPattern === NULL) { - return NULL; - } - // Expression Pattern is - if (typeof value === 'boolean') { - return parsedPattern; - } - // Expression Pattern is - if (value) { - const when = value.when; - if (typeof when === 'string') { - const result = (path, basename, name, hasSibling) => { - if (!hasSibling || !parsedPattern(path, basename)) { - return null; - } - const clausePattern = when.replace('$(basename)', name); - const matched = hasSibling(clausePattern); - return (0, async_1.isThenable)(matched) ? - matched.then(m => m ? pattern : null) : - matched ? pattern : null; - }; - result.requiresSiblings = true; - return result; - } - } - // Expression is Anything - return parsedPattern; - } - function aggregateBasenameMatches(parsedPatterns, result) { - const basenamePatterns = parsedPatterns.filter(parsedPattern => !!parsedPattern.basenames); - if (basenamePatterns.length < 2) { - return parsedPatterns; - } - const basenames = basenamePatterns.reduce((all, current) => { - const basenames = current.basenames; - return basenames ? all.concat(basenames) : all; - }, []); - let patterns; - if (result) { - patterns = []; - for (let i = 0, n = basenames.length; i < n; i++) { - patterns.push(result); - } - } - else { - patterns = basenamePatterns.reduce((all, current) => { - const patterns = current.patterns; - return patterns ? all.concat(patterns) : all; - }, []); - } - const aggregate = function (path, basename) { - if (typeof path !== 'string') { - return null; - } - if (!basename) { - let i; - for (i = path.length; i > 0; i--) { - const ch = path.charCodeAt(i - 1); - if (ch === 47 /* Slash */ || ch === 92 /* Backslash */) { - break; - } - } - basename = path.substr(i); - } - const index = basenames.indexOf(basename); - return index !== -1 ? patterns[index] : null; - }; - aggregate.basenames = basenames; - aggregate.patterns = patterns; - aggregate.allBasenames = basenames; - const aggregatedPatterns = parsedPatterns.filter(parsedPattern => !parsedPattern.basenames); - aggregatedPatterns.push(aggregate); - return aggregatedPatterns; - } -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[104/*vs/base/common/iconLabels*/], __M([0/*require*/,1/*exports*/,27/*vs/base/common/codicons*/,67/*vs/base/common/filters*/,8/*vs/base/common/strings*/]), function (require, exports, codicons_1, filters_1, strings_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.matchesFuzzyIconAware = exports.parseLabelWithIcons = exports.stripIcons = exports.markdownEscapeEscapedIcons = exports.escapeIcons = exports.iconStartMarker = void 0; - exports.iconStartMarker = '$('; - const iconsRegex = new RegExp(`\\$\\(${codicons_1.CSSIcon.iconNameExpression}(?:${codicons_1.CSSIcon.iconModifierExpression})?\\)`, 'g'); // no capturing groups - const escapeIconsRegex = new RegExp(`(\\\\)?${iconsRegex.source}`, 'g'); - function escapeIcons(text) { - return text.replace(escapeIconsRegex, (match, escaped) => escaped ? match : `\\${match}`); - } - exports.escapeIcons = escapeIcons; - const markdownEscapedIconsRegex = new RegExp(`\\\\${iconsRegex.source}`, 'g'); - function markdownEscapeEscapedIcons(text) { - // Need to add an extra \ for escaping in markdown - return text.replace(markdownEscapedIconsRegex, match => `\\${match}`); - } - exports.markdownEscapeEscapedIcons = markdownEscapeEscapedIcons; - const stripIconsRegex = new RegExp(`(\\s)?(\\\\)?${iconsRegex.source}(\\s)?`, 'g'); - function stripIcons(text) { - if (text.indexOf(exports.iconStartMarker) === -1) { - return text; - } - return text.replace(stripIconsRegex, (match, preWhitespace, escaped, postWhitespace) => escaped ? match : preWhitespace || postWhitespace || ''); - } - exports.stripIcons = stripIcons; - function parseLabelWithIcons(text) { - const firstIconIndex = text.indexOf(exports.iconStartMarker); - if (firstIconIndex === -1) { - return { text }; // return early if the word does not include an icon - } - return doParseLabelWithIcons(text, firstIconIndex); - } - exports.parseLabelWithIcons = parseLabelWithIcons; - function doParseLabelWithIcons(text, firstIconIndex) { - const iconOffsets = []; - let textWithoutIcons = ''; - function appendChars(chars) { - if (chars) { - textWithoutIcons += chars; - for (const _ of chars) { - iconOffsets.push(iconsOffset); // make sure to fill in icon offsets - } - } - } - let currentIconStart = -1; - let currentIconValue = ''; - let iconsOffset = 0; - let char; - let nextChar; - let offset = firstIconIndex; - const length = text.length; - // Append all characters until the first icon - appendChars(text.substr(0, firstIconIndex)); - // example: $(file-symlink-file) my cool $(other-icon) entry - while (offset < length) { - char = text[offset]; - nextChar = text[offset + 1]; - // beginning of icon: some value $( <-- - if (char === exports.iconStartMarker[0] && nextChar === exports.iconStartMarker[1]) { - currentIconStart = offset; - // if we had a previous potential icon value without - // the closing ')', it was actually not an icon and - // so we have to add it to the actual value - appendChars(currentIconValue); - currentIconValue = exports.iconStartMarker; - offset++; // jump over '(' - } - // end of icon: some value $(some-icon) <-- - else if (char === ')' && currentIconStart !== -1) { - const currentIconLength = offset - currentIconStart + 1; // +1 to include the closing ')' - iconsOffset += currentIconLength; - currentIconStart = -1; - currentIconValue = ''; - } - // within icon - else if (currentIconStart !== -1) { - // Make sure this is a real icon name - if (/^[a-z0-9\-]$/i.test(char)) { - currentIconValue += char; - } - else { - // This is not a real icon, treat it as text - appendChars(currentIconValue); - currentIconStart = -1; - currentIconValue = ''; - } - } - // any value outside of icon - else { - appendChars(char); - } - offset++; - } - // if we had a previous potential icon value without - // the closing ')', it was actually not an icon and - // so we have to add it to the actual value - appendChars(currentIconValue); - return { text: textWithoutIcons, iconOffsets }; - } - function matchesFuzzyIconAware(query, target, enableSeparateSubstringMatching = false) { - const { text, iconOffsets } = target; - // Return early if there are no icon markers in the word to match against - if (!iconOffsets || iconOffsets.length === 0) { - return (0, filters_1.matchesFuzzy)(query, text, enableSeparateSubstringMatching); - } - // Trim the word to match against because it could have leading - // whitespace now if the word started with an icon - const wordToMatchAgainstWithoutIconsTrimmed = (0, strings_1.ltrim)(text, ' '); - const leadingWhitespaceOffset = text.length - wordToMatchAgainstWithoutIconsTrimmed.length; - // match on value without icon - const matches = (0, filters_1.matchesFuzzy)(query, wordToMatchAgainstWithoutIconsTrimmed, enableSeparateSubstringMatching); - // Map matches back to offsets with icon and trimming - if (matches) { - for (const match of matches) { - const iconOffset = iconOffsets[match.start + leadingWhitespaceOffset] /* icon offsets at index */ + leadingWhitespaceOffset /* overall leading whitespace offset */; - match.start += iconOffset; - match.end += iconOffset; - } - } - return matches; - } - exports.matchesFuzzyIconAware = matchesFuzzyIconAware; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/common/htmlContent*/], __M([0/*require*/,1/*exports*/,104/*vs/base/common/iconLabels*/,12/*vs/base/common/errors*/]), function (require, exports, iconLabels_1, errors_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.parseHrefAndDimensions = exports.removeMarkdownEscapes = exports.escapeMarkdownSyntaxTokens = exports.isMarkdownString = exports.isEmptyMarkdownString = exports.MarkdownString = void 0; - class MarkdownString { - constructor(value = '', isTrustedOrOptions = false) { - var _a, _b; - this.value = value; - if (typeof this.value !== 'string') { - throw (0, errors_1.illegalArgument)('value'); - } - if (typeof isTrustedOrOptions === 'boolean') { - this.isTrusted = isTrustedOrOptions; - this.supportThemeIcons = false; - } - else { - this.isTrusted = (_a = isTrustedOrOptions.isTrusted) !== null && _a !== void 0 ? _a : undefined; - this.supportThemeIcons = (_b = isTrustedOrOptions.supportThemeIcons) !== null && _b !== void 0 ? _b : false; - } - } - appendText(value, newlineStyle = 0 /* Paragraph */) { - this.value += escapeMarkdownSyntaxTokens(this.supportThemeIcons ? (0, iconLabels_1.escapeIcons)(value) : value) - .replace(/([ \t]+)/g, (_match, g1) => ' '.repeat(g1.length)) - .replace(/^>/gm, '\\>') - .replace(/\n/g, newlineStyle === 1 /* Break */ ? '\\\n' : '\n\n'); - return this; - } - appendMarkdown(value) { - this.value += value; - return this; - } - appendCodeblock(langId, code) { - this.value += '\n```'; - this.value += langId; - this.value += '\n'; - this.value += code; - this.value += '\n```\n'; - return this; - } - } - exports.MarkdownString = MarkdownString; - function isEmptyMarkdownString(oneOrMany) { - if (isMarkdownString(oneOrMany)) { - return !oneOrMany.value; - } - else if (Array.isArray(oneOrMany)) { - return oneOrMany.every(isEmptyMarkdownString); - } - else { - return true; - } - } - exports.isEmptyMarkdownString = isEmptyMarkdownString; - function isMarkdownString(thing) { - if (thing instanceof MarkdownString) { - return true; - } - else if (thing && typeof thing === 'object') { - return typeof thing.value === 'string' - && (typeof thing.isTrusted === 'boolean' || thing.isTrusted === undefined) - && (typeof thing.supportThemeIcons === 'boolean' || thing.supportThemeIcons === undefined); - } - return false; - } - exports.isMarkdownString = isMarkdownString; - function escapeMarkdownSyntaxTokens(text) { - // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash - return text.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); - } - exports.escapeMarkdownSyntaxTokens = escapeMarkdownSyntaxTokens; - function removeMarkdownEscapes(text) { - if (!text) { - return text; - } - return text.replace(/\\([\\`*_{}[\]()#+\-.!])/g, '$1'); - } - exports.removeMarkdownEscapes = removeMarkdownEscapes; - function parseHrefAndDimensions(href) { - const dimensions = []; - const splitted = href.split('|').map(s => s.trim()); - href = splitted[0]; - const parameters = splitted[1]; - if (parameters) { - const heightFromParams = /height=(\d+)/.exec(parameters); - const widthFromParams = /width=(\d+)/.exec(parameters); - const height = heightFromParams ? heightFromParams[1] : ''; - const width = widthFromParams ? widthFromParams[1] : ''; - const widthIsFinite = isFinite(parseInt(width)); - const heightIsFinite = isFinite(parseInt(height)); - if (widthIsFinite) { - dimensions.push(`width="${width}"`); - } - if (heightIsFinite) { - dimensions.push(`height="${height}"`); - } - } - return { href, dimensions }; - } - exports.parseHrefAndDimensions = parseHrefAndDimensions; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/common/marshalling*/], __M([0/*require*/,1/*exports*/,103/*vs/base/common/buffer*/,24/*vs/base/common/uri*/]), function (require, exports, buffer_1, uri_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.revive = exports.parse = void 0; - function parse(text) { - let data = JSON.parse(text); - data = revive(data); - return data; - } - exports.parse = parse; - function revive(obj, depth = 0) { - if (!obj || depth > 200) { - return obj; - } - if (typeof obj === 'object') { - switch (obj.$mid) { - case 1 /* Uri */: return uri_1.URI.revive(obj); - case 2 /* Regexp */: return new RegExp(obj.source, obj.flags); - } - if (obj instanceof buffer_1.VSBuffer - || obj instanceof Uint8Array) { - return obj; - } - if (Array.isArray(obj)) { - for (let i = 0; i < obj.length; ++i) { - obj[i] = revive(obj[i], depth + 1); - } - } - else { - // walk object - for (const key in obj) { - if (Object.hasOwnProperty.call(obj, key)) { - obj[key] = revive(obj[key], depth + 1); - } - } - } - } - return obj; - } - exports.revive = revive; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[46/*vs/base/common/network*/], __M([0/*require*/,1/*exports*/,24/*vs/base/common/uri*/,17/*vs/base/common/platform*/]), function (require, exports, uri_1, platform) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.FileAccess = exports.RemoteAuthorities = exports.Schemas = void 0; - var Schemas; - (function (Schemas) { - /** - * A schema that is used for models that exist in memory - * only and that have no correspondence on a server or such. - */ - Schemas.inMemory = 'inmemory'; - /** - * A schema that is used for setting files - */ - Schemas.vscode = 'vscode'; - /** - * A schema that is used for internal private files - */ - Schemas.internal = 'private'; - /** - * A walk-through document. - */ - Schemas.walkThrough = 'walkThrough'; - /** - * An embedded code snippet. - */ - Schemas.walkThroughSnippet = 'walkThroughSnippet'; - Schemas.http = 'http'; - Schemas.https = 'https'; - Schemas.file = 'file'; - Schemas.mailto = 'mailto'; - Schemas.untitled = 'untitled'; - Schemas.data = 'data'; - Schemas.command = 'command'; - Schemas.vscodeRemote = 'vscode-remote'; - Schemas.vscodeRemoteResource = 'vscode-remote-resource'; - Schemas.userData = 'vscode-userdata'; - Schemas.vscodeCustomEditor = 'vscode-custom-editor'; - Schemas.vscodeNotebook = 'vscode-notebook'; - Schemas.vscodeNotebookCell = 'vscode-notebook-cell'; - Schemas.vscodeNotebookCellMetadata = 'vscode-notebook-cell-metadata'; - Schemas.vscodeNotebookCellOutput = 'vscode-notebook-cell-output'; - Schemas.vscodeInteractive = 'vscode-interactive'; - Schemas.vscodeInteractiveInput = 'vscode-interactive-input'; - Schemas.vscodeSettings = 'vscode-settings'; - Schemas.vscodeWorkspaceTrust = 'vscode-workspace-trust'; - Schemas.vscodeTerminal = 'vscode-terminal'; - Schemas.webviewPanel = 'webview-panel'; - /** - * Scheme used for loading the wrapper html and script in webviews. - */ - Schemas.vscodeWebview = 'vscode-webview'; - /** - * Scheme used for extension pages - */ - Schemas.extension = 'extension'; - /** - * Scheme used as a replacement of `file` scheme to load - * files with our custom protocol handler (desktop only). - */ - Schemas.vscodeFileResource = 'vscode-file'; - /** - * Scheme used for temporary resources - */ - Schemas.tmp = 'tmp'; - })(Schemas = exports.Schemas || (exports.Schemas = {})); - class RemoteAuthoritiesImpl { - constructor() { - this._hosts = Object.create(null); - this._ports = Object.create(null); - this._connectionTokens = Object.create(null); - this._preferredWebSchema = 'http'; - this._delegate = null; - } - setPreferredWebSchema(schema) { - this._preferredWebSchema = schema; - } - rewrite(uri) { - if (this._delegate) { - return this._delegate(uri); - } - const authority = uri.authority; - let host = this._hosts[authority]; - if (host && host.indexOf(':') !== -1) { - host = `[${host}]`; - } - const port = this._ports[authority]; - const connectionToken = this._connectionTokens[authority]; - let query = `path=${encodeURIComponent(uri.path)}`; - if (typeof connectionToken === 'string') { - query += `&tkn=${encodeURIComponent(connectionToken)}`; - } - return uri_1.URI.from({ - scheme: platform.isWeb ? this._preferredWebSchema : Schemas.vscodeRemoteResource, - authority: `${host}:${port}`, - path: `/vscode-remote-resource`, - query - }); - } - } - exports.RemoteAuthorities = new RemoteAuthoritiesImpl(); - class FileAccessImpl { - constructor() { - this.FALLBACK_AUTHORITY = 'vscode-app'; - } - asBrowserUri(uriOrModule, moduleIdToUrl, __forceCodeFileUri) { - const uri = this.toUri(uriOrModule, moduleIdToUrl); - // Handle remote URIs via `RemoteAuthorities` - if (uri.scheme === Schemas.vscodeRemote) { - return exports.RemoteAuthorities.rewrite(uri); - } - let convertToVSCodeFileResource = false; - // Only convert the URI if we are in a native context and it has `file:` scheme - // and we have explicitly enabled the conversion (sandbox, or VSCODE_BROWSER_CODE_LOADING) - if (platform.isNative && (__forceCodeFileUri || platform.isPreferringBrowserCodeLoad) && uri.scheme === Schemas.file) { - convertToVSCodeFileResource = true; - } - // Also convert `file:` URIs in the web worker extension host (running in desktop) case - if (uri.scheme === Schemas.file && typeof platform.globals.importScripts === 'function' && platform.globals.origin === 'vscode-file://vscode-app') { - convertToVSCodeFileResource = true; - } - if (convertToVSCodeFileResource) { - return uri.with({ - scheme: Schemas.vscodeFileResource, - // We need to provide an authority here so that it can serve - // as origin for network and loading matters in chromium. - // If the URI is not coming with an authority already, we - // add our own - authority: uri.authority || this.FALLBACK_AUTHORITY, - query: null, - fragment: null - }); - } - return uri; - } - toUri(uriOrModule, moduleIdToUrl) { - if (uri_1.URI.isUri(uriOrModule)) { - return uriOrModule; - } - return uri_1.URI.parse(moduleIdToUrl.toUrl(uriOrModule)); - } - } - exports.FileAccess = new FileAccessImpl(); -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[7/*vs/base/browser/dom*/], __M([0/*require*/,1/*exports*/,39/*vs/base/browser/browser*/,51/*vs/base/browser/keyboardEvent*/,55/*vs/base/browser/mouseEvent*/,15/*vs/base/common/async*/,12/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,46/*vs/base/common/network*/,156/*vs/base/browser/canIUse*/]), function (require, exports, browser, keyboardEvent_1, mouseEvent_1, async_1, errors_1, event_1, lifecycle_1, platform, network_1, canIUse_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.addMatchMediaChangeListener = exports.ModifierKeyEmitter = exports.asCSSPropertyValue = exports.asCSSUrl = exports.animate = exports.windowOpenNoOpener = exports.computeScreenAwareSize = exports.getElementsByTagName = exports.hide = exports.show = exports.$ = exports.Namespace = exports.reset = exports.prepend = exports.append = exports.trackFocus = exports.restoreParentsScrollTop = exports.saveParentsScrollTop = exports.EventHelper = exports.EventType = exports.isHTMLElement = exports.removeCSSRulesContainingSelector = exports.createCSSRule = exports.createStyleSheet = exports.getActiveElement = exports.getShadowRoot = exports.isInShadowDOM = exports.isShadowRoot = exports.hasParentWithClass = exports.findParentWithClass = exports.isAncestor = exports.getTotalHeight = exports.getContentHeight = exports.getContentWidth = exports.getTotalWidth = exports.StandardWindow = exports.getDomNodePagePosition = exports.size = exports.getTopLeftOffset = exports.Dimension = exports.getClientArea = exports.getComputedStyle = exports.addDisposableThrottledListener = exports.scheduleAtNextAnimationFrame = exports.runAtThisOrScheduleAtNextAnimationFrame = exports.addDisposableNonBubblingPointerOutListener = exports.addDisposableNonBubblingMouseOutListener = exports.addDisposableGenericMouseUpListner = exports.addDisposableGenericMouseDownListner = exports.addStandardDisposableGenericMouseDownListner = exports.addStandardDisposableListener = exports.addDisposableListener = exports.isInDOM = exports.clearNode = void 0; - function clearNode(node) { - while (node.firstChild) { - node.firstChild.remove(); - } - } - exports.clearNode = clearNode; - /** - * @deprecated Use node.isConnected directly - */ - function isInDOM(node) { - var _a; - return (_a = node === null || node === void 0 ? void 0 : node.isConnected) !== null && _a !== void 0 ? _a : false; - } - exports.isInDOM = isInDOM; - class DomListener { - constructor(node, type, handler, options) { - this._node = node; - this._type = type; - this._handler = handler; - this._options = (options || false); - this._node.addEventListener(this._type, this._handler, this._options); - } - dispose() { - if (!this._handler) { - // Already disposed - return; - } - this._node.removeEventListener(this._type, this._handler, this._options); - // Prevent leakers from holding on to the dom or handler func - this._node = null; - this._handler = null; - } - } - function addDisposableListener(node, type, handler, useCaptureOrOptions) { - return new DomListener(node, type, handler, useCaptureOrOptions); - } - exports.addDisposableListener = addDisposableListener; - function _wrapAsStandardMouseEvent(handler) { - return function (e) { - return handler(new mouseEvent_1.StandardMouseEvent(e)); - }; - } - function _wrapAsStandardKeyboardEvent(handler) { - return function (e) { - return handler(new keyboardEvent_1.StandardKeyboardEvent(e)); - }; - } - let addStandardDisposableListener = function addStandardDisposableListener(node, type, handler, useCapture) { - let wrapHandler = handler; - if (type === 'click' || type === 'mousedown') { - wrapHandler = _wrapAsStandardMouseEvent(handler); - } - else if (type === 'keydown' || type === 'keypress' || type === 'keyup') { - wrapHandler = _wrapAsStandardKeyboardEvent(handler); - } - return addDisposableListener(node, type, wrapHandler, useCapture); - }; - exports.addStandardDisposableListener = addStandardDisposableListener; - let addStandardDisposableGenericMouseDownListner = function addStandardDisposableListener(node, handler, useCapture) { - let wrapHandler = _wrapAsStandardMouseEvent(handler); - return addDisposableGenericMouseDownListner(node, wrapHandler, useCapture); - }; - exports.addStandardDisposableGenericMouseDownListner = addStandardDisposableGenericMouseDownListner; - function addDisposableGenericMouseDownListner(node, handler, useCapture) { - return addDisposableListener(node, platform.isIOS && canIUse_1.BrowserFeatures.pointerEvents ? exports.EventType.POINTER_DOWN : exports.EventType.MOUSE_DOWN, handler, useCapture); - } - exports.addDisposableGenericMouseDownListner = addDisposableGenericMouseDownListner; - function addDisposableGenericMouseUpListner(node, handler, useCapture) { - return addDisposableListener(node, platform.isIOS && canIUse_1.BrowserFeatures.pointerEvents ? exports.EventType.POINTER_UP : exports.EventType.MOUSE_UP, handler, useCapture); - } - exports.addDisposableGenericMouseUpListner = addDisposableGenericMouseUpListner; - function addDisposableNonBubblingMouseOutListener(node, handler) { - return addDisposableListener(node, 'mouseout', (e) => { - // Mouse out bubbles, so this is an attempt to ignore faux mouse outs coming from children elements - let toElement = (e.relatedTarget); - while (toElement && toElement !== node) { - toElement = toElement.parentNode; - } - if (toElement === node) { - return; - } - handler(e); - }); - } - exports.addDisposableNonBubblingMouseOutListener = addDisposableNonBubblingMouseOutListener; - function addDisposableNonBubblingPointerOutListener(node, handler) { - return addDisposableListener(node, 'pointerout', (e) => { - // Mouse out bubbles, so this is an attempt to ignore faux mouse outs coming from children elements - let toElement = (e.relatedTarget); - while (toElement && toElement !== node) { - toElement = toElement.parentNode; - } - if (toElement === node) { - return; - } - handler(e); - }); - } - exports.addDisposableNonBubblingPointerOutListener = addDisposableNonBubblingPointerOutListener; - let _animationFrame = null; - function doRequestAnimationFrame(callback) { - if (!_animationFrame) { - const emulatedRequestAnimationFrame = (callback) => { - return setTimeout(() => callback(new Date().getTime()), 0); - }; - _animationFrame = (self.requestAnimationFrame - || self.msRequestAnimationFrame - || self.webkitRequestAnimationFrame - || self.mozRequestAnimationFrame - || self.oRequestAnimationFrame - || emulatedRequestAnimationFrame); - } - return _animationFrame.call(self, callback); - } - class AnimationFrameQueueItem { - constructor(runner, priority = 0) { - this._runner = runner; - this.priority = priority; - this._canceled = false; - } - dispose() { - this._canceled = true; - } - execute() { - if (this._canceled) { - return; - } - try { - this._runner(); - } - catch (e) { - (0, errors_1.onUnexpectedError)(e); - } - } - // Sort by priority (largest to lowest) - static sort(a, b) { - return b.priority - a.priority; - } - } - (function () { - /** - * The runners scheduled at the next animation frame - */ - let NEXT_QUEUE = []; - /** - * The runners scheduled at the current animation frame - */ - let CURRENT_QUEUE = null; - /** - * A flag to keep track if the native requestAnimationFrame was already called - */ - let animFrameRequested = false; - /** - * A flag to indicate if currently handling a native requestAnimationFrame callback - */ - let inAnimationFrameRunner = false; - let animationFrameRunner = () => { - animFrameRequested = false; - CURRENT_QUEUE = NEXT_QUEUE; - NEXT_QUEUE = []; - inAnimationFrameRunner = true; - while (CURRENT_QUEUE.length > 0) { - CURRENT_QUEUE.sort(AnimationFrameQueueItem.sort); - let top = CURRENT_QUEUE.shift(); - top.execute(); - } - inAnimationFrameRunner = false; - }; - exports.scheduleAtNextAnimationFrame = (runner, priority = 0) => { - let item = new AnimationFrameQueueItem(runner, priority); - NEXT_QUEUE.push(item); - if (!animFrameRequested) { - animFrameRequested = true; - doRequestAnimationFrame(animationFrameRunner); - } - return item; - }; - exports.runAtThisOrScheduleAtNextAnimationFrame = (runner, priority) => { - if (inAnimationFrameRunner) { - let item = new AnimationFrameQueueItem(runner, priority); - CURRENT_QUEUE.push(item); - return item; - } - else { - return (0, exports.scheduleAtNextAnimationFrame)(runner, priority); - } - }; - })(); - const MINIMUM_TIME_MS = 8; - const DEFAULT_EVENT_MERGER = function (lastEvent, currentEvent) { - return currentEvent; - }; - class TimeoutThrottledDomListener extends lifecycle_1.Disposable { - constructor(node, type, handler, eventMerger = DEFAULT_EVENT_MERGER, minimumTimeMs = MINIMUM_TIME_MS) { - super(); - let lastEvent = null; - let lastHandlerTime = 0; - let timeout = this._register(new async_1.TimeoutTimer()); - let invokeHandler = () => { - lastHandlerTime = (new Date()).getTime(); - handler(lastEvent); - lastEvent = null; - }; - this._register(addDisposableListener(node, type, (e) => { - lastEvent = eventMerger(lastEvent, e); - let elapsedTime = (new Date()).getTime() - lastHandlerTime; - if (elapsedTime >= minimumTimeMs) { - timeout.cancel(); - invokeHandler(); - } - else { - timeout.setIfNotSet(invokeHandler, minimumTimeMs - elapsedTime); - } - })); - } - } - function addDisposableThrottledListener(node, type, handler, eventMerger, minimumTimeMs) { - return new TimeoutThrottledDomListener(node, type, handler, eventMerger, minimumTimeMs); - } - exports.addDisposableThrottledListener = addDisposableThrottledListener; - function getComputedStyle(el) { - return document.defaultView.getComputedStyle(el, null); - } - exports.getComputedStyle = getComputedStyle; - function getClientArea(element) { - // Try with DOM clientWidth / clientHeight - if (element !== document.body) { - return new Dimension(element.clientWidth, element.clientHeight); - } - // If visual view port exits and it's on mobile, it should be used instead of window innerWidth / innerHeight, or document.body.clientWidth / document.body.clientHeight - if (platform.isIOS && window.visualViewport) { - return new Dimension(window.visualViewport.width, window.visualViewport.height); - } - // Try innerWidth / innerHeight - if (window.innerWidth && window.innerHeight) { - return new Dimension(window.innerWidth, window.innerHeight); - } - // Try with document.body.clientWidth / document.body.clientHeight - if (document.body && document.body.clientWidth && document.body.clientHeight) { - return new Dimension(document.body.clientWidth, document.body.clientHeight); - } - // Try with document.documentElement.clientWidth / document.documentElement.clientHeight - if (document.documentElement && document.documentElement.clientWidth && document.documentElement.clientHeight) { - return new Dimension(document.documentElement.clientWidth, document.documentElement.clientHeight); - } - throw new Error('Unable to figure out browser width and height'); - } - exports.getClientArea = getClientArea; - class SizeUtils { - // Adapted from WinJS - // Converts a CSS positioning string for the specified element to pixels. - static convertToPixels(element, value) { - return parseFloat(value) || 0; - } - static getDimension(element, cssPropertyName, jsPropertyName) { - let computedStyle = getComputedStyle(element); - let value = '0'; - if (computedStyle) { - if (computedStyle.getPropertyValue) { - value = computedStyle.getPropertyValue(cssPropertyName); - } - else { - // IE8 - value = computedStyle.getAttribute(jsPropertyName); - } - } - return SizeUtils.convertToPixels(element, value); - } - static getBorderLeftWidth(element) { - return SizeUtils.getDimension(element, 'border-left-width', 'borderLeftWidth'); - } - static getBorderRightWidth(element) { - return SizeUtils.getDimension(element, 'border-right-width', 'borderRightWidth'); - } - static getBorderTopWidth(element) { - return SizeUtils.getDimension(element, 'border-top-width', 'borderTopWidth'); - } - static getBorderBottomWidth(element) { - return SizeUtils.getDimension(element, 'border-bottom-width', 'borderBottomWidth'); - } - static getPaddingLeft(element) { - return SizeUtils.getDimension(element, 'padding-left', 'paddingLeft'); - } - static getPaddingRight(element) { - return SizeUtils.getDimension(element, 'padding-right', 'paddingRight'); - } - static getPaddingTop(element) { - return SizeUtils.getDimension(element, 'padding-top', 'paddingTop'); - } - static getPaddingBottom(element) { - return SizeUtils.getDimension(element, 'padding-bottom', 'paddingBottom'); - } - static getMarginLeft(element) { - return SizeUtils.getDimension(element, 'margin-left', 'marginLeft'); - } - static getMarginTop(element) { - return SizeUtils.getDimension(element, 'margin-top', 'marginTop'); - } - static getMarginRight(element) { - return SizeUtils.getDimension(element, 'margin-right', 'marginRight'); - } - static getMarginBottom(element) { - return SizeUtils.getDimension(element, 'margin-bottom', 'marginBottom'); - } - } - class Dimension { - constructor(width, height) { - this.width = width; - this.height = height; - } - with(width = this.width, height = this.height) { - if (width !== this.width || height !== this.height) { - return new Dimension(width, height); - } - else { - return this; - } - } - static is(obj) { - return typeof obj === 'object' && typeof obj.height === 'number' && typeof obj.width === 'number'; - } - static lift(obj) { - if (obj instanceof Dimension) { - return obj; - } - else { - return new Dimension(obj.width, obj.height); - } - } - static equals(a, b) { - if (a === b) { - return true; - } - if (!a || !b) { - return false; - } - return a.width === b.width && a.height === b.height; - } - } - exports.Dimension = Dimension; - function getTopLeftOffset(element) { - // Adapted from WinJS.Utilities.getPosition - // and added borders to the mix - let offsetParent = element.offsetParent; - let top = element.offsetTop; - let left = element.offsetLeft; - while ((element = element.parentNode) !== null - && element !== document.body - && element !== document.documentElement) { - top -= element.scrollTop; - const c = isShadowRoot(element) ? null : getComputedStyle(element); - if (c) { - left -= c.direction !== 'rtl' ? element.scrollLeft : -element.scrollLeft; - } - if (element === offsetParent) { - left += SizeUtils.getBorderLeftWidth(element); - top += SizeUtils.getBorderTopWidth(element); - top += element.offsetTop; - left += element.offsetLeft; - offsetParent = element.offsetParent; - } - } - return { - left: left, - top: top - }; - } - exports.getTopLeftOffset = getTopLeftOffset; - function size(element, width, height) { - if (typeof width === 'number') { - element.style.width = `${width}px`; - } - if (typeof height === 'number') { - element.style.height = `${height}px`; - } - } - exports.size = size; - /** - * Returns the position of a dom node relative to the entire page. - */ - function getDomNodePagePosition(domNode) { - let bb = domNode.getBoundingClientRect(); - return { - left: bb.left + exports.StandardWindow.scrollX, - top: bb.top + exports.StandardWindow.scrollY, - width: bb.width, - height: bb.height - }; - } - exports.getDomNodePagePosition = getDomNodePagePosition; - exports.StandardWindow = new class { - get scrollX() { - if (typeof window.scrollX === 'number') { - // modern browsers - return window.scrollX; - } - else { - return document.body.scrollLeft + document.documentElement.scrollLeft; - } - } - get scrollY() { - if (typeof window.scrollY === 'number') { - // modern browsers - return window.scrollY; - } - else { - return document.body.scrollTop + document.documentElement.scrollTop; - } - } - }; - // Adapted from WinJS - // Gets the width of the element, including margins. - function getTotalWidth(element) { - let margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element); - return element.offsetWidth + margin; - } - exports.getTotalWidth = getTotalWidth; - function getContentWidth(element) { - let border = SizeUtils.getBorderLeftWidth(element) + SizeUtils.getBorderRightWidth(element); - let padding = SizeUtils.getPaddingLeft(element) + SizeUtils.getPaddingRight(element); - return element.offsetWidth - border - padding; - } - exports.getContentWidth = getContentWidth; - // Adapted from WinJS - // Gets the height of the content of the specified element. The content height does not include borders or padding. - function getContentHeight(element) { - let border = SizeUtils.getBorderTopWidth(element) + SizeUtils.getBorderBottomWidth(element); - let padding = SizeUtils.getPaddingTop(element) + SizeUtils.getPaddingBottom(element); - return element.offsetHeight - border - padding; - } - exports.getContentHeight = getContentHeight; - // Adapted from WinJS - // Gets the height of the element, including its margins. - function getTotalHeight(element) { - let margin = SizeUtils.getMarginTop(element) + SizeUtils.getMarginBottom(element); - return element.offsetHeight + margin; - } - exports.getTotalHeight = getTotalHeight; - // ---------------------------------------------------------------------------------------- - function isAncestor(testChild, testAncestor) { - while (testChild) { - if (testChild === testAncestor) { - return true; - } - testChild = testChild.parentNode; - } - return false; - } - exports.isAncestor = isAncestor; - function findParentWithClass(node, clazz, stopAtClazzOrNode) { - while (node && node.nodeType === node.ELEMENT_NODE) { - if (node.classList.contains(clazz)) { - return node; - } - if (stopAtClazzOrNode) { - if (typeof stopAtClazzOrNode === 'string') { - if (node.classList.contains(stopAtClazzOrNode)) { - return null; - } - } - else { - if (node === stopAtClazzOrNode) { - return null; - } - } - } - node = node.parentNode; - } - return null; - } - exports.findParentWithClass = findParentWithClass; - function hasParentWithClass(node, clazz, stopAtClazzOrNode) { - return !!findParentWithClass(node, clazz, stopAtClazzOrNode); - } - exports.hasParentWithClass = hasParentWithClass; - function isShadowRoot(node) { - return (node && !!node.host && !!node.mode); - } - exports.isShadowRoot = isShadowRoot; - function isInShadowDOM(domNode) { - return !!getShadowRoot(domNode); - } - exports.isInShadowDOM = isInShadowDOM; - function getShadowRoot(domNode) { - while (domNode.parentNode) { - if (domNode === document.body) { - // reached the body - return null; - } - domNode = domNode.parentNode; - } - return isShadowRoot(domNode) ? domNode : null; - } - exports.getShadowRoot = getShadowRoot; - function getActiveElement() { - let result = document.activeElement; - while (result === null || result === void 0 ? void 0 : result.shadowRoot) { - result = result.shadowRoot.activeElement; - } - return result; - } - exports.getActiveElement = getActiveElement; - function createStyleSheet(container = document.getElementsByTagName('head')[0]) { - let style = document.createElement('style'); - style.type = 'text/css'; - style.media = 'screen'; - container.appendChild(style); - return style; - } - exports.createStyleSheet = createStyleSheet; - let _sharedStyleSheet = null; - function getSharedStyleSheet() { - if (!_sharedStyleSheet) { - _sharedStyleSheet = createStyleSheet(); - } - return _sharedStyleSheet; - } - function getDynamicStyleSheetRules(style) { - var _a, _b; - if ((_a = style === null || style === void 0 ? void 0 : style.sheet) === null || _a === void 0 ? void 0 : _a.rules) { - // Chrome, IE - return style.sheet.rules; - } - if ((_b = style === null || style === void 0 ? void 0 : style.sheet) === null || _b === void 0 ? void 0 : _b.cssRules) { - // FF - return style.sheet.cssRules; - } - return []; - } - function createCSSRule(selector, cssText, style = getSharedStyleSheet()) { - if (!style || !cssText) { - return; - } - style.sheet.insertRule(selector + '{' + cssText + '}', 0); - } - exports.createCSSRule = createCSSRule; - function removeCSSRulesContainingSelector(ruleName, style = getSharedStyleSheet()) { - if (!style) { - return; - } - let rules = getDynamicStyleSheetRules(style); - let toDelete = []; - for (let i = 0; i < rules.length; i++) { - let rule = rules[i]; - if (rule.selectorText.indexOf(ruleName) !== -1) { - toDelete.push(i); - } - } - for (let i = toDelete.length - 1; i >= 0; i--) { - style.sheet.deleteRule(toDelete[i]); - } - } - exports.removeCSSRulesContainingSelector = removeCSSRulesContainingSelector; - function isHTMLElement(o) { - if (typeof HTMLElement === 'object') { - return o instanceof HTMLElement; - } - return o && typeof o === 'object' && o.nodeType === 1 && typeof o.nodeName === 'string'; - } - exports.isHTMLElement = isHTMLElement; - exports.EventType = { - // Mouse - CLICK: 'click', - AUXCLICK: 'auxclick', - DBLCLICK: 'dblclick', - MOUSE_UP: 'mouseup', - MOUSE_DOWN: 'mousedown', - MOUSE_OVER: 'mouseover', - MOUSE_MOVE: 'mousemove', - MOUSE_OUT: 'mouseout', - MOUSE_ENTER: 'mouseenter', - MOUSE_LEAVE: 'mouseleave', - MOUSE_WHEEL: 'wheel', - POINTER_UP: 'pointerup', - POINTER_DOWN: 'pointerdown', - POINTER_MOVE: 'pointermove', - CONTEXT_MENU: 'contextmenu', - WHEEL: 'wheel', - // Keyboard - KEY_DOWN: 'keydown', - KEY_PRESS: 'keypress', - KEY_UP: 'keyup', - // HTML Document - LOAD: 'load', - BEFORE_UNLOAD: 'beforeunload', - UNLOAD: 'unload', - ABORT: 'abort', - ERROR: 'error', - RESIZE: 'resize', - SCROLL: 'scroll', - FULLSCREEN_CHANGE: 'fullscreenchange', - WK_FULLSCREEN_CHANGE: 'webkitfullscreenchange', - // Form - SELECT: 'select', - CHANGE: 'change', - SUBMIT: 'submit', - RESET: 'reset', - FOCUS: 'focus', - FOCUS_IN: 'focusin', - FOCUS_OUT: 'focusout', - BLUR: 'blur', - INPUT: 'input', - // Local Storage - STORAGE: 'storage', - // Drag - DRAG_START: 'dragstart', - DRAG: 'drag', - DRAG_ENTER: 'dragenter', - DRAG_LEAVE: 'dragleave', - DRAG_OVER: 'dragover', - DROP: 'drop', - DRAG_END: 'dragend', - // Animation - ANIMATION_START: browser.isWebKit ? 'webkitAnimationStart' : 'animationstart', - ANIMATION_END: browser.isWebKit ? 'webkitAnimationEnd' : 'animationend', - ANIMATION_ITERATION: browser.isWebKit ? 'webkitAnimationIteration' : 'animationiteration' - }; - exports.EventHelper = { - stop: function (e, cancelBubble) { - if (e.preventDefault) { - e.preventDefault(); - } - else { - // IE8 - e.returnValue = false; - } - if (cancelBubble) { - if (e.stopPropagation) { - e.stopPropagation(); - } - else { - // IE8 - e.cancelBubble = true; - } - } - } - }; - function saveParentsScrollTop(node) { - let r = []; - for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) { - r[i] = node.scrollTop; - node = node.parentNode; - } - return r; - } - exports.saveParentsScrollTop = saveParentsScrollTop; - function restoreParentsScrollTop(node, state) { - for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) { - if (node.scrollTop !== state[i]) { - node.scrollTop = state[i]; - } - node = node.parentNode; - } - } - exports.restoreParentsScrollTop = restoreParentsScrollTop; - class FocusTracker extends lifecycle_1.Disposable { - constructor(element) { - super(); - this._onDidFocus = this._register(new event_1.Emitter()); - this.onDidFocus = this._onDidFocus.event; - this._onDidBlur = this._register(new event_1.Emitter()); - this.onDidBlur = this._onDidBlur.event; - let hasFocus = isAncestor(document.activeElement, element); - let loosingFocus = false; - const onFocus = () => { - loosingFocus = false; - if (!hasFocus) { - hasFocus = true; - this._onDidFocus.fire(); - } - }; - const onBlur = () => { - if (hasFocus) { - loosingFocus = true; - window.setTimeout(() => { - if (loosingFocus) { - loosingFocus = false; - hasFocus = false; - this._onDidBlur.fire(); - } - }, 0); - } - }; - this._refreshStateHandler = () => { - let currentNodeHasFocus = isAncestor(document.activeElement, element); - if (currentNodeHasFocus !== hasFocus) { - if (hasFocus) { - onBlur(); - } - else { - onFocus(); - } - } - }; - this._register(addDisposableListener(element, exports.EventType.FOCUS, onFocus, true)); - this._register(addDisposableListener(element, exports.EventType.BLUR, onBlur, true)); - } - } - function trackFocus(element) { - return new FocusTracker(element); - } - exports.trackFocus = trackFocus; - function append(parent, ...children) { - parent.append(...children); - if (children.length === 1 && typeof children[0] !== 'string') { - return children[0]; - } - } - exports.append = append; - function prepend(parent, child) { - parent.insertBefore(child, parent.firstChild); - return child; - } - exports.prepend = prepend; - /** - * Removes all children from `parent` and appends `children` - */ - function reset(parent, ...children) { - parent.innerText = ''; - append(parent, ...children); - } - exports.reset = reset; - const SELECTOR_REGEX = /([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/; - var Namespace; - (function (Namespace) { - Namespace["HTML"] = "http://www.w3.org/1999/xhtml"; - Namespace["SVG"] = "http://www.w3.org/2000/svg"; - })(Namespace = exports.Namespace || (exports.Namespace = {})); - function _$(namespace, description, attrs, ...children) { - let match = SELECTOR_REGEX.exec(description); - if (!match) { - throw new Error('Bad use of emmet'); - } - attrs = Object.assign({}, (attrs || {})); - let tagName = match[1] || 'div'; - let result; - if (namespace !== Namespace.HTML) { - result = document.createElementNS(namespace, tagName); - } - else { - result = document.createElement(tagName); - } - if (match[3]) { - result.id = match[3]; - } - if (match[4]) { - result.className = match[4].replace(/\./g, ' ').trim(); - } - Object.keys(attrs).forEach(name => { - const value = attrs[name]; - if (typeof value === 'undefined') { - return; - } - if (/^on\w+$/.test(name)) { - result[name] = value; - } - else if (name === 'selected') { - if (value) { - result.setAttribute(name, 'true'); - } - } - else { - result.setAttribute(name, value); - } - }); - result.append(...children); - return result; - } - function $(description, attrs, ...children) { - return _$(Namespace.HTML, description, attrs, ...children); - } - exports.$ = $; - $.SVG = function (description, attrs, ...children) { - return _$(Namespace.SVG, description, attrs, ...children); - }; - function show(...elements) { - for (let element of elements) { - element.style.display = ''; - element.removeAttribute('aria-hidden'); - } - } - exports.show = show; - function hide(...elements) { - for (let element of elements) { - element.style.display = 'none'; - element.setAttribute('aria-hidden', 'true'); - } - } - exports.hide = hide; - function getElementsByTagName(tag) { - return Array.prototype.slice.call(document.getElementsByTagName(tag), 0); - } - exports.getElementsByTagName = getElementsByTagName; - /** - * Find a value usable for a dom node size such that the likelihood that it would be - * displayed with constant screen pixels size is as high as possible. - * - * e.g. We would desire for the cursors to be 2px (CSS px) wide. Under a devicePixelRatio - * of 1.25, the cursor will be 2.5 screen pixels wide. Depending on how the dom node aligns/"snaps" - * with the screen pixels, it will sometimes be rendered with 2 screen pixels, and sometimes with 3 screen pixels. - */ - function computeScreenAwareSize(cssPx) { - const screenPx = window.devicePixelRatio * cssPx; - return Math.max(1, Math.floor(screenPx)) / window.devicePixelRatio; - } - exports.computeScreenAwareSize = computeScreenAwareSize; - /** - * Open safely a new window. This is the best way to do so, but you cannot tell - * if the window was opened or if it was blocked by the brower's popup blocker. - * If you want to tell if the browser blocked the new window, use `windowOpenNoOpenerWithSuccess`. - * - * See https://github.com/microsoft/monaco-editor/issues/601 - * To protect against malicious code in the linked site, particularly phishing attempts, - * the window.opener should be set to null to prevent the linked site from having access - * to change the location of the current page. - * See https://mathiasbynens.github.io/rel-noopener/ - */ - function windowOpenNoOpener(url) { - // By using 'noopener' in the `windowFeatures` argument, the newly created window will - // not be able to use `window.opener` to reach back to the current page. - // See https://stackoverflow.com/a/46958731 - // See https://developer.mozilla.org/en-US/docs/Web/API/Window/open#noopener - // However, this also doesn't allow us to realize if the browser blocked - // the creation of the window. - window.open(url, '_blank', 'noopener'); - } - exports.windowOpenNoOpener = windowOpenNoOpener; - function animate(fn) { - const step = () => { - fn(); - stepDisposable = (0, exports.scheduleAtNextAnimationFrame)(step); - }; - let stepDisposable = (0, exports.scheduleAtNextAnimationFrame)(step); - return (0, lifecycle_1.toDisposable)(() => stepDisposable.dispose()); - } - exports.animate = animate; - network_1.RemoteAuthorities.setPreferredWebSchema(/^https:/.test(window.location.href) ? 'https' : 'http'); - /** - * returns url('...') - */ - function asCSSUrl(uri) { - if (!uri) { - return `url('')`; - } - return `url('${network_1.FileAccess.asBrowserUri(uri).toString(true).replace(/'/g, '%27')}')`; - } - exports.asCSSUrl = asCSSUrl; - function asCSSPropertyValue(value) { - return `'${value.replace(/'/g, '%27')}'`; - } - exports.asCSSPropertyValue = asCSSPropertyValue; - class ModifierKeyEmitter extends event_1.Emitter { - constructor() { - super(); - this._subscriptions = new lifecycle_1.DisposableStore(); - this._keyStatus = { - altKey: false, - shiftKey: false, - ctrlKey: false, - metaKey: false - }; - this._subscriptions.add(addDisposableListener(window, 'keydown', e => { - if (e.defaultPrevented) { - return; - } - const event = new keyboardEvent_1.StandardKeyboardEvent(e); - // If Alt-key keydown event is repeated, ignore it #112347 - // Only known to be necessary for Alt-Key at the moment #115810 - if (event.keyCode === 6 /* Alt */ && e.repeat) { - return; - } - if (e.altKey && !this._keyStatus.altKey) { - this._keyStatus.lastKeyPressed = 'alt'; - } - else if (e.ctrlKey && !this._keyStatus.ctrlKey) { - this._keyStatus.lastKeyPressed = 'ctrl'; - } - else if (e.metaKey && !this._keyStatus.metaKey) { - this._keyStatus.lastKeyPressed = 'meta'; - } - else if (e.shiftKey && !this._keyStatus.shiftKey) { - this._keyStatus.lastKeyPressed = 'shift'; - } - else if (event.keyCode !== 6 /* Alt */) { - this._keyStatus.lastKeyPressed = undefined; - } - else { - return; - } - this._keyStatus.altKey = e.altKey; - this._keyStatus.ctrlKey = e.ctrlKey; - this._keyStatus.metaKey = e.metaKey; - this._keyStatus.shiftKey = e.shiftKey; - if (this._keyStatus.lastKeyPressed) { - this._keyStatus.event = e; - this.fire(this._keyStatus); - } - }, true)); - this._subscriptions.add(addDisposableListener(window, 'keyup', e => { - if (e.defaultPrevented) { - return; - } - if (!e.altKey && this._keyStatus.altKey) { - this._keyStatus.lastKeyReleased = 'alt'; - } - else if (!e.ctrlKey && this._keyStatus.ctrlKey) { - this._keyStatus.lastKeyReleased = 'ctrl'; - } - else if (!e.metaKey && this._keyStatus.metaKey) { - this._keyStatus.lastKeyReleased = 'meta'; - } - else if (!e.shiftKey && this._keyStatus.shiftKey) { - this._keyStatus.lastKeyReleased = 'shift'; - } - else { - this._keyStatus.lastKeyReleased = undefined; - } - if (this._keyStatus.lastKeyPressed !== this._keyStatus.lastKeyReleased) { - this._keyStatus.lastKeyPressed = undefined; - } - this._keyStatus.altKey = e.altKey; - this._keyStatus.ctrlKey = e.ctrlKey; - this._keyStatus.metaKey = e.metaKey; - this._keyStatus.shiftKey = e.shiftKey; - if (this._keyStatus.lastKeyReleased) { - this._keyStatus.event = e; - this.fire(this._keyStatus); - } - }, true)); - this._subscriptions.add(addDisposableListener(document.body, 'mousedown', () => { - this._keyStatus.lastKeyPressed = undefined; - }, true)); - this._subscriptions.add(addDisposableListener(document.body, 'mouseup', () => { - this._keyStatus.lastKeyPressed = undefined; - }, true)); - this._subscriptions.add(addDisposableListener(document.body, 'mousemove', e => { - if (e.buttons) { - this._keyStatus.lastKeyPressed = undefined; - } - }, true)); - this._subscriptions.add(addDisposableListener(window, 'blur', () => { - this.resetKeyStatus(); - })); - } - get keyStatus() { - return this._keyStatus; - } - /** - * Allows to explicitly reset the key status based on more knowledge (#109062) - */ - resetKeyStatus() { - this.doResetKeyStatus(); - this.fire(this._keyStatus); - } - doResetKeyStatus() { - this._keyStatus = { - altKey: false, - shiftKey: false, - ctrlKey: false, - metaKey: false - }; - } - static getInstance() { - if (!ModifierKeyEmitter.instance) { - ModifierKeyEmitter.instance = new ModifierKeyEmitter(); - } - return ModifierKeyEmitter.instance; - } - dispose() { - super.dispose(); - this._subscriptions.dispose(); - } - } - exports.ModifierKeyEmitter = ModifierKeyEmitter; - function addMatchMediaChangeListener(query, callback) { - const mediaQueryList = window.matchMedia(query); - if (typeof mediaQueryList.addEventListener === 'function') { - mediaQueryList.addEventListener('change', callback); - } - else { - // Safari 13.x - mediaQueryList.addListener(callback); - } - } - exports.addMatchMediaChangeListener = addMatchMediaChangeListener; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/browser/formattedTextRenderer*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/]), function (require, exports, DOM) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.createElement = exports.renderFormattedText = exports.renderText = void 0; - function renderText(text, options = {}) { - const element = createElement(options); - element.textContent = text; - return element; - } - exports.renderText = renderText; - function renderFormattedText(formattedText, options = {}) { - const element = createElement(options); - _renderFormattedText(element, parseFormattedText(formattedText, !!options.renderCodeSegements), options.actionHandler, options.renderCodeSegements); - return element; - } - exports.renderFormattedText = renderFormattedText; - function createElement(options) { - const tagName = options.inline ? 'span' : 'div'; - const element = document.createElement(tagName); - if (options.className) { - element.className = options.className; - } - return element; - } - exports.createElement = createElement; - class StringStream { - constructor(source) { - this.source = source; - this.index = 0; - } - eos() { - return this.index >= this.source.length; - } - next() { - const next = this.peek(); - this.advance(); - return next; - } - peek() { - return this.source[this.index]; - } - advance() { - this.index++; - } - } - function _renderFormattedText(element, treeNode, actionHandler, renderCodeSegements) { - let child; - if (treeNode.type === 2 /* Text */) { - child = document.createTextNode(treeNode.content || ''); - } - else if (treeNode.type === 3 /* Bold */) { - child = document.createElement('b'); - } - else if (treeNode.type === 4 /* Italics */) { - child = document.createElement('i'); - } - else if (treeNode.type === 7 /* Code */ && renderCodeSegements) { - child = document.createElement('code'); - } - else if (treeNode.type === 5 /* Action */ && actionHandler) { - const a = document.createElement('a'); - a.href = '#'; - actionHandler.disposeables.add(DOM.addStandardDisposableListener(a, 'click', (event) => { - actionHandler.callback(String(treeNode.index), event); - })); - child = a; - } - else if (treeNode.type === 8 /* NewLine */) { - child = document.createElement('br'); - } - else if (treeNode.type === 1 /* Root */) { - child = element; - } - if (child && element !== child) { - element.appendChild(child); - } - if (child && Array.isArray(treeNode.children)) { - treeNode.children.forEach((nodeChild) => { - _renderFormattedText(child, nodeChild, actionHandler, renderCodeSegements); - }); - } - } - function parseFormattedText(content, parseCodeSegments) { - const root = { - type: 1 /* Root */, - children: [] - }; - let actionViewItemIndex = 0; - let current = root; - const stack = []; - const stream = new StringStream(content); - while (!stream.eos()) { - let next = stream.next(); - const isEscapedFormatType = (next === '\\' && formatTagType(stream.peek(), parseCodeSegments) !== 0 /* Invalid */); - if (isEscapedFormatType) { - next = stream.next(); // unread the backslash if it escapes a format tag type - } - if (!isEscapedFormatType && isFormatTag(next, parseCodeSegments) && next === stream.peek()) { - stream.advance(); - if (current.type === 2 /* Text */) { - current = stack.pop(); - } - const type = formatTagType(next, parseCodeSegments); - if (current.type === type || (current.type === 5 /* Action */ && type === 6 /* ActionClose */)) { - current = stack.pop(); - } - else { - const newCurrent = { - type: type, - children: [] - }; - if (type === 5 /* Action */) { - newCurrent.index = actionViewItemIndex; - actionViewItemIndex++; - } - current.children.push(newCurrent); - stack.push(current); - current = newCurrent; - } - } - else if (next === '\n') { - if (current.type === 2 /* Text */) { - current = stack.pop(); - } - current.children.push({ - type: 8 /* NewLine */ - }); - } - else { - if (current.type !== 2 /* Text */) { - const textCurrent = { - type: 2 /* Text */, - content: next - }; - current.children.push(textCurrent); - stack.push(current); - current = textCurrent; - } - else { - current.content += next; - } - } - } - if (current.type === 2 /* Text */) { - current = stack.pop(); - } - if (stack.length) { - // incorrectly formatted string literal - } - return root; - } - function isFormatTag(char, supportCodeSegments) { - return formatTagType(char, supportCodeSegments) !== 0 /* Invalid */; - } - function formatTagType(char, supportCodeSegments) { - switch (char) { - case '*': - return 3 /* Bold */; - case '_': - return 4 /* Italics */; - case '[': - return 5 /* Action */; - case ']': - return 6 /* ActionClose */; - case '`': - return supportCodeSegments ? 7 /* Code */ : 0 /* Invalid */; - default: - return 0 /* Invalid */; - } - } -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/browser/globalMouseMoveMonitor*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,196/*vs/base/browser/iframe*/,55/*vs/base/browser/mouseEvent*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/]), function (require, exports, dom, iframe_1, mouseEvent_1, lifecycle_1, platform_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.GlobalMouseMoveMonitor = exports.standardMouseMoveMerger = void 0; - function standardMouseMoveMerger(lastEvent, currentEvent) { - let ev = new mouseEvent_1.StandardMouseEvent(currentEvent); - ev.preventDefault(); - return { - leftButton: ev.leftButton, - buttons: ev.buttons, - posx: ev.posx, - posy: ev.posy - }; - } - exports.standardMouseMoveMerger = standardMouseMoveMerger; - class GlobalMouseMoveMonitor { - constructor() { - this._hooks = new lifecycle_1.DisposableStore(); - this._mouseMoveEventMerger = null; - this._mouseMoveCallback = null; - this._onStopCallback = null; - } - dispose() { - this.stopMonitoring(false); - this._hooks.dispose(); - } - stopMonitoring(invokeStopCallback, browserEvent) { - if (!this.isMonitoring()) { - // Not monitoring - return; - } - // Unhook - this._hooks.clear(); - this._mouseMoveEventMerger = null; - this._mouseMoveCallback = null; - const onStopCallback = this._onStopCallback; - this._onStopCallback = null; - if (invokeStopCallback && onStopCallback) { - onStopCallback(browserEvent); - } - } - isMonitoring() { - return !!this._mouseMoveEventMerger; - } - startMonitoring(initialElement, initialButtons, mouseMoveEventMerger, mouseMoveCallback, onStopCallback) { - if (this.isMonitoring()) { - // I am already hooked - return; - } - this._mouseMoveEventMerger = mouseMoveEventMerger; - this._mouseMoveCallback = mouseMoveCallback; - this._onStopCallback = onStopCallback; - const windowChain = iframe_1.IframeUtils.getSameOriginWindowChain(); - const mouseMove = platform_1.isIOS ? 'pointermove' : 'mousemove'; // Safari sends wrong event, workaround for #122653 - const mouseUp = 'mouseup'; - const listenTo = windowChain.map(element => element.window.document); - const shadowRoot = dom.getShadowRoot(initialElement); - if (shadowRoot) { - listenTo.unshift(shadowRoot); - } - for (const element of listenTo) { - this._hooks.add(dom.addDisposableThrottledListener(element, mouseMove, (data) => { - if (data.buttons !== initialButtons) { - // Buttons state has changed in the meantime - this.stopMonitoring(true); - return; - } - this._mouseMoveCallback(data); - }, (lastEvent, currentEvent) => this._mouseMoveEventMerger(lastEvent, currentEvent))); - this._hooks.add(dom.addDisposableListener(element, mouseUp, (e) => this.stopMonitoring(true))); - } - if (iframe_1.IframeUtils.hasDifferentOriginAncestor()) { - let lastSameOriginAncestor = windowChain[windowChain.length - 1]; - // We might miss a mouse up if it happens outside the iframe - // This one is for Chrome - this._hooks.add(dom.addDisposableListener(lastSameOriginAncestor.window.document, 'mouseout', (browserEvent) => { - let e = new mouseEvent_1.StandardMouseEvent(browserEvent); - if (e.target.tagName.toLowerCase() === 'html') { - this.stopMonitoring(true); - } - })); - // This one is for FF - this._hooks.add(dom.addDisposableListener(lastSameOriginAncestor.window.document, 'mouseover', (browserEvent) => { - let e = new mouseEvent_1.StandardMouseEvent(browserEvent); - if (e.target.tagName.toLowerCase() === 'html') { - this.stopMonitoring(true); - } - })); - // This one is for IE - this._hooks.add(dom.addDisposableListener(lastSameOriginAncestor.window.document.body, 'mouseleave', (browserEvent) => { - this.stopMonitoring(true); - })); - } - } - } - exports.GlobalMouseMoveMonitor = GlobalMouseMoveMonitor; -}); - -/*--------------------------------------------------------------------------------------------- - * 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[60/*vs/base/browser/touch*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/,7/*vs/base/browser/dom*/,90/*vs/base/common/decorators*/]), function (require, exports, arrays, lifecycle_1, DomUtils, decorators_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Gesture = exports.EventType = void 0; - 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 = {})); - class Gesture extends lifecycle_1.Disposable { - constructor() { - super(); - this.dispatched = false; - this.activeTouches = {}; - this.handle = null; - this.targets = []; - this.ignoreTargets = []; - this._lastSetTapCountTime = 0; - this._register(DomUtils.addDisposableListener(document, 'touchstart', (e) => this.onTouchStart(e), { passive: false })); - this._register(DomUtils.addDisposableListener(document, 'touchend', (e) => this.onTouchEnd(e))); - this._register(DomUtils.addDisposableListener(document, 'touchmove', (e) => this.onTouchMove(e), { passive: false })); - } - static addTarget(element) { - if (!Gesture.isTouchDevice()) { - return lifecycle_1.Disposable.None; - } - if (!Gesture.INSTANCE) { - Gesture.INSTANCE = new Gesture(); - } - Gesture.INSTANCE.targets.push(element); - return { - dispose: () => { - Gesture.INSTANCE.targets = Gesture.INSTANCE.targets.filter(t => t !== element); - } - }; - } - static ignoreTarget(element) { - if (!Gesture.isTouchDevice()) { - return lifecycle_1.Disposable.None; - } - if (!Gesture.INSTANCE) { - Gesture.INSTANCE = new Gesture(); - } - Gesture.INSTANCE.ignoreTargets.push(element); - return { - dispose: () => { - Gesture.INSTANCE.ignoreTargets = Gesture.INSTANCE.ignoreTargets.filter(t => t !== element); - } - }; - } - static isTouchDevice() { - // `'ontouchstart' in window` always evaluates to true with typescript's modern typings. This causes `window` to be - // `never` later in `window.navigator`. That's why we need the explicit `window as Window` cast - return 'ontouchstart' in window || navigator.maxTouchPoints > 0; - } - dispose() { - if (this.handle) { - this.handle.dispose(); - this.handle = null; - } - super.dispose(); - } - onTouchStart(e) { - let 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 (let i = 0, len = e.targetTouches.length; i < len; i++) { - let 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] - }; - let 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; - } - } - onTouchEnd(e) { - let timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based. - let activeTouchCount = Object.keys(this.activeTouches).length; - for (let i = 0, len = e.changedTouches.length; i < len; i++) { - let touch = e.changedTouches.item(i); - if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) { - console.warn('move of an UNKNOWN touch', touch); - continue; - } - let data = this.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) { - let evt = this.newGestureEvent(EventType.Tap, data.initialTarget); - evt.pageX = arrays.tail(data.rollingPageX); - evt.pageY = arrays.tail(data.rollingPageY); - this.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) { - let evt = this.newGestureEvent(EventType.Contextmenu, data.initialTarget); - evt.pageX = arrays.tail(data.rollingPageX); - evt.pageY = arrays.tail(data.rollingPageY); - this.dispatchEvent(evt); - } - else if (activeTouchCount === 1) { - let finalX = arrays.tail(data.rollingPageX); - let finalY = arrays.tail(data.rollingPageY); - let deltaT = arrays.tail(data.rollingTimestamps) - data.rollingTimestamps[0]; - let deltaX = finalX - data.rollingPageX[0]; - let deltaY = finalY - data.rollingPageY[0]; - // We need to get all the dispatch targets on the start of the inertia event - const dispatchTo = this.targets.filter(t => data.initialTarget instanceof Node && t.contains(data.initialTarget)); - this.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.dispatchEvent(this.newGestureEvent(EventType.End, data.initialTarget)); - // forget about this touch - delete this.activeTouches[touch.identifier]; - } - if (this.dispatched) { - e.preventDefault(); - e.stopPropagation(); - this.dispatched = false; - } - } - newGestureEvent(type, initialTarget) { - let event = document.createEvent('CustomEvent'); - event.initEvent(type, false, true); - event.initialTarget = initialTarget; - event.tapCount = 0; - return event; - } - dispatchEvent(event) { - if (event.type === EventType.Tap) { - const currentTime = (new Date()).getTime(); - let 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 (let i = 0; i < this.ignoreTargets.length; i++) { - if (event.initialTarget instanceof Node && this.ignoreTargets[i].contains(event.initialTarget)) { - return; - } - } - this.targets.forEach(target => { - if (event.initialTarget instanceof Node && target.contains(event.initialTarget)) { - target.dispatchEvent(event); - this.dispatched = true; - } - }); - } - inertia(dispatchTo, t1, vX, dirX, x, vY, dirY, y) { - this.handle = DomUtils.scheduleAtNextAnimationFrame(() => { - let now = Date.now(); - // velocity: old speed + accel_over_time - let 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 - let evt = this.newGestureEvent(EventType.Change); - evt.translationX = delta_pos_x; - evt.translationY = delta_pos_y; - dispatchTo.forEach(d => d.dispatchEvent(evt)); - if (!stopped) { - this.inertia(dispatchTo, now, vX, dirX, x + delta_pos_x, vY, dirY, y + delta_pos_y); - } - }); - } - onTouchMove(e) { - let timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based. - for (let i = 0, len = e.changedTouches.length; i < len; i++) { - let touch = e.changedTouches.item(i); - if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) { - console.warn('end of an UNKNOWN touch', touch); - continue; - } - let data = this.activeTouches[touch.identifier]; - let 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); - 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[105/*vs/base/browser/ui/iconLabel/iconLabels*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,27/*vs/base/common/codicons*/]), function (require, exports, dom, codicons_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.renderIcon = exports.renderLabelWithIcons = void 0; - const labelWithIconsRegex = new RegExp(`(\\\\)?\\$\\((${codicons_1.CSSIcon.iconNameExpression}(?:${codicons_1.CSSIcon.iconModifierExpression})?)\\)`, 'g'); - function renderLabelWithIcons(text) { - const elements = new Array(); - let match; - let textStart = 0, textStop = 0; - while ((match = labelWithIconsRegex.exec(text)) !== null) { - textStop = match.index || 0; - elements.push(text.substring(textStart, textStop)); - textStart = (match.index || 0) + match[0].length; - const [, escaped, codicon] = match; - elements.push(escaped ? `$(${codicon})` : renderIcon({ id: codicon })); - } - if (textStart < text.length) { - elements.push(text.substring(textStart)); - } - return elements; - } - exports.renderLabelWithIcons = renderLabelWithIcons; - function renderIcon(icon) { - const node = dom.$(`span`); - node.classList.add(...codicons_1.CSSIcon.asClassNameArray(icon)); - return node; - } - exports.renderIcon = renderIcon; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/browser/ui/highlightedlabel/highlightedLabel*/], __M([0/*require*/,1/*exports*/,42/*vs/base/common/objects*/,7/*vs/base/browser/dom*/,105/*vs/base/browser/ui/iconLabel/iconLabels*/]), function (require, exports, objects, dom, iconLabels_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.HighlightedLabel = void 0; - class HighlightedLabel { - constructor(container, supportIcons) { - this.supportIcons = supportIcons; - this.text = ''; - this.title = ''; - this.highlights = []; - this.didEverRender = false; - this.domNode = document.createElement('span'); - this.domNode.className = 'monaco-highlighted-label'; - container.appendChild(this.domNode); - } - get element() { - return this.domNode; - } - set(text, highlights = [], title = '', escapeNewLines) { - if (!text) { - text = ''; - } - if (escapeNewLines) { - // adjusts highlights inplace - text = HighlightedLabel.escapeNewLines(text, highlights); - } - if (this.didEverRender && this.text === text && this.title === title && objects.equals(this.highlights, highlights)) { - return; - } - this.text = text; - this.title = title; - this.highlights = highlights; - this.render(); - } - render() { - const children = []; - let pos = 0; - for (const highlight of this.highlights) { - if (highlight.end === highlight.start) { - continue; - } - if (pos < highlight.start) { - const substring = this.text.substring(pos, highlight.start); - children.push(dom.$('span', undefined, ...this.supportIcons ? (0, iconLabels_1.renderLabelWithIcons)(substring) : [substring])); - pos = highlight.end; - } - const substring = this.text.substring(highlight.start, highlight.end); - const element = dom.$('span.highlight', undefined, ...this.supportIcons ? (0, iconLabels_1.renderLabelWithIcons)(substring) : [substring]); - if (highlight.extraClasses) { - element.classList.add(highlight.extraClasses); - } - children.push(element); - pos = highlight.end; - } - if (pos < this.text.length) { - const substring = this.text.substring(pos); - children.push(dom.$('span', undefined, ...this.supportIcons ? (0, iconLabels_1.renderLabelWithIcons)(substring) : [substring])); - } - dom.reset(this.domNode, ...children); - if (this.title) { - this.domNode.title = this.title; - } - else { - this.domNode.removeAttribute('title'); - } - this.didEverRender = true; - } - static escapeNewLines(text, highlights) { - let total = 0; - let extra = 0; - return text.replace(/\r\n|\r|\n/g, (match, offset) => { - extra = match === '\r\n' ? -1 : 0; - offset += total; - for (const highlight of highlights) { - if (highlight.end <= offset) { - continue; - } - if (highlight.start >= offset) { - highlight.start += extra; - } - if (highlight.end >= offset) { - highlight.end += extra; - } - } - total += extra; - return '\u23CE'; - }); - } - } - exports.HighlightedLabel = HighlightedLabel; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[295/*vs/base/browser/ui/list/rowCache*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/]), function (require, exports, dom_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.RowCache = void 0; - 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 - } - } - class RowCache { - constructor(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. - */ - alloc(templateId) { - let result = this.getTemplateCache(templateId).pop(); - if (!result) { - const domNode = (0, dom_1.$)('.monaco-list-row'); - const renderer = this.getRenderer(templateId); - const templateData = renderer.renderTemplate(domNode); - result = { domNode, templateId, templateData }; - } - return result; - } - /** - * Releases the row for eventual reuse. - */ - release(row) { - if (!row) { - return; - } - this.releaseRow(row); - } - releaseRow(row) { - const { domNode, templateId } = row; - if (domNode) { - domNode.classList.remove('scrolling'); - removeFromParent(domNode); - } - const cache = this.getTemplateCache(templateId); - cache.push(row); - } - getTemplateCache(templateId) { - let result = this.cache.get(templateId); - if (!result) { - result = []; - this.cache.set(templateId, result); - } - return result; - } - dispose() { - this.cache.forEach((cachedRows, templateId) => { - for (const cachedRow of cachedRows) { - const renderer = this.getRenderer(templateId); - renderer.disposeTemplate(cachedRow.templateData); - cachedRow.templateData = null; - } - }); - this.cache.clear(); - } - getRenderer(templateId) { - const renderer = this.renderers.get(templateId); - if (!renderer) { - throw new Error(`No renderer found for ${templateId}`); - } - return renderer; - } - } - 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[52/*vs/base/browser/ui/widget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,51/*vs/base/browser/keyboardEvent*/,55/*vs/base/browser/mouseEvent*/,2/*vs/base/common/lifecycle*/,60/*vs/base/browser/touch*/]), function (require, exports, dom, keyboardEvent_1, mouseEvent_1, lifecycle_1, touch_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Widget = void 0; - class Widget extends lifecycle_1.Disposable { - onclick(domNode, listener) { - this._register(dom.addDisposableListener(domNode, dom.EventType.CLICK, (e) => listener(new mouseEvent_1.StandardMouseEvent(e)))); - } - onmousedown(domNode, listener) { - this._register(dom.addDisposableListener(domNode, dom.EventType.MOUSE_DOWN, (e) => listener(new mouseEvent_1.StandardMouseEvent(e)))); - } - onmouseover(domNode, listener) { - this._register(dom.addDisposableListener(domNode, dom.EventType.MOUSE_OVER, (e) => listener(new mouseEvent_1.StandardMouseEvent(e)))); - } - onnonbubblingmouseout(domNode, listener) { - this._register(dom.addDisposableNonBubblingMouseOutListener(domNode, (e) => listener(new mouseEvent_1.StandardMouseEvent(e)))); - } - onkeydown(domNode, listener) { - this._register(dom.addDisposableListener(domNode, dom.EventType.KEY_DOWN, (e) => listener(new keyboardEvent_1.StandardKeyboardEvent(e)))); - } - onkeyup(domNode, listener) { - this._register(dom.addDisposableListener(domNode, dom.EventType.KEY_UP, (e) => listener(new keyboardEvent_1.StandardKeyboardEvent(e)))); - } - oninput(domNode, listener) { - this._register(dom.addDisposableListener(domNode, dom.EventType.INPUT, listener)); - } - onblur(domNode, listener) { - this._register(dom.addDisposableListener(domNode, dom.EventType.BLUR, listener)); - } - onfocus(domNode, listener) { - this._register(dom.addDisposableListener(domNode, dom.EventType.FOCUS, listener)); - } - ignoreGesture(domNode) { - touch_1.Gesture.ignoreTarget(domNode); - } - } - 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[162/*vs/base/browser/ui/scrollbar/scrollbarArrow*/], __M([0/*require*/,1/*exports*/,93/*vs/base/browser/globalMouseMoveMonitor*/,52/*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 }); - exports.ScrollbarArrow = exports.ARROW_IMG_SIZE = void 0; - /** - * The arrow image size. - */ - exports.ARROW_IMG_SIZE = 11; - class ScrollbarArrow extends widget_1.Widget { - constructor(opts) { - super(); - 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.classList.add(...opts.icon.classNamesArray); - 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, (e) => this._arrowMouseDown(e)); - this.onmousedown(this.domNode, (e) => this._arrowMouseDown(e)); - this._mousedownRepeatTimer = this._register(new async_1.IntervalTimer()); - this._mousedownScheduleRepeatTimer = this._register(new async_1.TimeoutTimer()); - } - _arrowMouseDown(e) { - const scheduleRepeater = () => { - this._mousedownRepeatTimer.cancelAndSet(() => this._onActivate(), 1000 / 24); - }; - this._onActivate(); - this._mousedownRepeatTimer.cancel(); - this._mousedownScheduleRepeatTimer.cancelAndSet(scheduleRepeater, 200); - this._mouseMoveMonitor.startMonitoring(e.target, e.buttons, globalMouseMoveMonitor_1.standardMouseMoveMerger, (mouseMoveData) => { - /* Intentional empty */ - }, () => { - this._mousedownRepeatTimer.cancel(); - this._mousedownScheduleRepeatTimer.cancel(); - }); - e.preventDefault(); - } - } - 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[203/*vs/base/browser/ui/scrollbar/abstractScrollbar*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,30/*vs/base/browser/fastDomNode*/,93/*vs/base/browser/globalMouseMoveMonitor*/,162/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,290/*vs/base/browser/ui/scrollbar/scrollbarVisibilityController*/,52/*vs/base/browser/ui/widget*/,17/*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 }); - exports.AbstractScrollbar = void 0; - /** - * The orthogonal distance to the slider at which dragging "resets". This implements "snapping" - */ - const MOUSE_DRAG_RESET_DISTANCE = 140; - class AbstractScrollbar extends widget_1.Widget { - constructor(opts) { - super(); - this._lazyRender = opts.lazyRender; - this._host = opts.host; - this._scrollable = opts.scrollable; - this._scrollByPage = opts.scrollByPage; - 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 = (0, 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, (e) => this._domNodeMouseDown(e)); - } - // ----------------- creation - /** - * Creates the dom node for an arrow & adds it to the container - */ - _createArrow(opts) { - const 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 - */ - _createSlider(top, left, width, height) { - this.slider = (0, 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, (e) => { - if (e.leftButton) { - e.preventDefault(); - this._sliderMouseDown(e, () => { }); - } - }); - this.onclick(this.slider.domNode, e => { - if (e.leftButton) { - e.stopPropagation(); - } - }); - } - // ----------------- Update state - _onElementSize(visibleSize) { - if (this._scrollbarState.setVisibleSize(visibleSize)) { - this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()); - this._shouldRender = true; - if (!this._lazyRender) { - this.render(); - } - } - return this._shouldRender; - } - _onElementScrollSize(elementScrollSize) { - if (this._scrollbarState.setScrollSize(elementScrollSize)) { - this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()); - this._shouldRender = true; - if (!this._lazyRender) { - this.render(); - } - } - return this._shouldRender; - } - _onElementScrollPosition(elementScrollPosition) { - if (this._scrollbarState.setScrollPosition(elementScrollPosition)) { - this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()); - this._shouldRender = true; - if (!this._lazyRender) { - this.render(); - } - } - return this._shouldRender; - } - // ----------------- rendering - beginReveal() { - this._visibilityController.setShouldBeVisible(true); - } - beginHide() { - this._visibilityController.setShouldBeVisible(false); - } - render() { - 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 - _domNodeMouseDown(e) { - if (e.target !== this.domNode.domNode) { - return; - } - this._onMouseDown(e); - } - delegateMouseDown(e) { - const domTop = this.domNode.domNode.getClientRects()[0].top; - const sliderStart = domTop + this._scrollbarState.getSliderPosition(); - const sliderStop = domTop + this._scrollbarState.getSliderPosition() + this._scrollbarState.getSliderSize(); - const 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, () => { }); - } - } - else { - // Act as if it was a mouse down on the scrollbar - this._onMouseDown(e); - } - } - _onMouseDown(e) { - let offsetX; - let 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 { - const domNodePosition = dom.getDomNodePagePosition(this.domNode.domNode); - offsetX = e.posx - domNodePosition.left; - offsetY = e.posy - domNodePosition.top; - } - const offset = this._mouseDownRelativePosition(offsetX, offsetY); - this._setDesiredScrollPositionNow(this._scrollByPage - ? this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(offset) - : this._scrollbarState.getDesiredScrollPositionFromOffset(offset)); - if (e.leftButton) { - e.preventDefault(); - this._sliderMouseDown(e, () => { }); - } - } - _sliderMouseDown(e, onDragFinished) { - const initialMousePosition = this._sliderMousePosition(e); - const initialMouseOrthogonalPosition = this._sliderOrthogonalMousePosition(e); - const initialScrollbarState = this._scrollbarState.clone(); - this.slider.toggleClassName('active', true); - this._mouseMoveMonitor.startMonitoring(e.target, e.buttons, globalMouseMoveMonitor_1.standardMouseMoveMerger, (mouseMoveData) => { - const mouseOrthogonalPosition = this._sliderOrthogonalMousePosition(mouseMoveData); - const 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; - } - const mousePosition = this._sliderMousePosition(mouseMoveData); - const mouseDelta = mousePosition - initialMousePosition; - this._setDesiredScrollPositionNow(initialScrollbarState.getDesiredScrollPositionFromDelta(mouseDelta)); - }, () => { - this.slider.toggleClassName('active', false); - this._host.onDragEnd(); - onDragFinished(); - }); - this._host.onDragStart(); - } - _setDesiredScrollPositionNow(_desiredScrollPosition) { - const desiredScrollPosition = {}; - this.writeScrollPosition(desiredScrollPosition, _desiredScrollPosition); - this._scrollable.setScrollPositionNow(desiredScrollPosition); - } - updateScrollbarSize(scrollbarSize) { - this._updateScrollbarSize(scrollbarSize); - this._scrollbarState.setScrollbarSize(scrollbarSize); - this._shouldRender = true; - if (!this._lazyRender) { - this.render(); - } - } - isNeeded() { - return this._scrollbarState.isNeeded(); - } - } - 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[296/*vs/base/browser/ui/scrollbar/horizontalScrollbar*/], __M([0/*require*/,1/*exports*/,55/*vs/base/browser/mouseEvent*/,203/*vs/base/browser/ui/scrollbar/abstractScrollbar*/,162/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,197/*vs/base/browser/ui/scrollbar/scrollbarState*/,27/*vs/base/common/codicons*/]), function (require, exports, mouseEvent_1, abstractScrollbar_1, scrollbarArrow_1, scrollbarState_1, codicons_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.HorizontalScrollbar = void 0; - const scrollbarButtonLeftIcon = (0, codicons_1.registerCodicon)('scrollbar-button-left', codicons_1.Codicon.triangleLeft); - const scrollbarButtonRightIcon = (0, codicons_1.registerCodicon)('scrollbar-button-right', codicons_1.Codicon.triangleRight); - class HorizontalScrollbar extends abstractScrollbar_1.AbstractScrollbar { - constructor(scrollable, options, host) { - const scrollDimensions = scrollable.getScrollDimensions(); - const scrollPosition = scrollable.getCurrentScrollPosition(); - super({ - 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, - scrollByPage: options.scrollByPage - }); - if (options.horizontalHasArrows) { - const arrowDelta = (options.arrowSize - scrollbarArrow_1.ARROW_IMG_SIZE) / 2; - const scrollbarDelta = (options.horizontalScrollbarSize - scrollbarArrow_1.ARROW_IMG_SIZE) / 2; - this._createArrow({ - className: 'scra', - icon: scrollbarButtonLeftIcon, - top: scrollbarDelta, - left: arrowDelta, - bottom: undefined, - right: undefined, - bgWidth: options.arrowSize, - bgHeight: options.horizontalScrollbarSize, - onActivate: () => this._host.onMouseWheel(new mouseEvent_1.StandardWheelEvent(null, 1, 0)), - }); - this._createArrow({ - className: 'scra', - icon: scrollbarButtonRightIcon, - top: scrollbarDelta, - left: undefined, - bottom: undefined, - right: arrowDelta, - bgWidth: options.arrowSize, - bgHeight: options.horizontalScrollbarSize, - onActivate: () => this._host.onMouseWheel(new mouseEvent_1.StandardWheelEvent(null, -1, 0)), - }); - } - this._createSlider(Math.floor((options.horizontalScrollbarSize - options.horizontalSliderSize) / 2), 0, undefined, options.horizontalSliderSize); - } - _updateSlider(sliderSize, sliderPosition) { - this.slider.setWidth(sliderSize); - this.slider.setLeft(sliderPosition); - } - _renderDomNode(largeSize, smallSize) { - this.domNode.setWidth(largeSize); - this.domNode.setHeight(smallSize); - this.domNode.setLeft(0); - this.domNode.setBottom(0); - } - onDidScroll(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; - } - _mouseDownRelativePosition(offsetX, offsetY) { - return offsetX; - } - _sliderMousePosition(e) { - return e.posx; - } - _sliderOrthogonalMousePosition(e) { - return e.posy; - } - _updateScrollbarSize(size) { - this.slider.setHeight(size); - } - writeScrollPosition(target, scrollPosition) { - target.scrollLeft = scrollPosition; - } - updateOptions(options) { - this.updateScrollbarSize(options.horizontal === 2 /* Hidden */ ? 0 : options.horizontalScrollbarSize); - this._scrollbarState.setOppositeScrollbarSize(options.vertical === 2 /* Hidden */ ? 0 : options.verticalScrollbarSize); - this._visibilityController.setVisibility(options.horizontal); - this._scrollByPage = options.scrollByPage; - } - } - 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[297/*vs/base/browser/ui/scrollbar/verticalScrollbar*/], __M([0/*require*/,1/*exports*/,55/*vs/base/browser/mouseEvent*/,203/*vs/base/browser/ui/scrollbar/abstractScrollbar*/,162/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,197/*vs/base/browser/ui/scrollbar/scrollbarState*/,27/*vs/base/common/codicons*/]), function (require, exports, mouseEvent_1, abstractScrollbar_1, scrollbarArrow_1, scrollbarState_1, codicons_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.VerticalScrollbar = void 0; - const scrollbarButtonUpIcon = (0, codicons_1.registerCodicon)('scrollbar-button-up', codicons_1.Codicon.triangleUp); - const scrollbarButtonDownIcon = (0, codicons_1.registerCodicon)('scrollbar-button-down', codicons_1.Codicon.triangleDown); - class VerticalScrollbar extends abstractScrollbar_1.AbstractScrollbar { - constructor(scrollable, options, host) { - const scrollDimensions = scrollable.getScrollDimensions(); - const scrollPosition = scrollable.getCurrentScrollPosition(); - super({ - 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, - scrollByPage: options.scrollByPage - }); - if (options.verticalHasArrows) { - const arrowDelta = (options.arrowSize - scrollbarArrow_1.ARROW_IMG_SIZE) / 2; - const scrollbarDelta = (options.verticalScrollbarSize - scrollbarArrow_1.ARROW_IMG_SIZE) / 2; - this._createArrow({ - className: 'scra', - icon: scrollbarButtonUpIcon, - top: arrowDelta, - left: scrollbarDelta, - bottom: undefined, - right: undefined, - bgWidth: options.verticalScrollbarSize, - bgHeight: options.arrowSize, - onActivate: () => this._host.onMouseWheel(new mouseEvent_1.StandardWheelEvent(null, 0, 1)), - }); - this._createArrow({ - className: 'scra', - icon: scrollbarButtonDownIcon, - top: undefined, - left: scrollbarDelta, - bottom: arrowDelta, - right: undefined, - bgWidth: options.verticalScrollbarSize, - bgHeight: options.arrowSize, - onActivate: () => this._host.onMouseWheel(new mouseEvent_1.StandardWheelEvent(null, 0, -1)), - }); - } - this._createSlider(0, Math.floor((options.verticalScrollbarSize - options.verticalSliderSize) / 2), options.verticalSliderSize, undefined); - } - _updateSlider(sliderSize, sliderPosition) { - this.slider.setHeight(sliderSize); - this.slider.setTop(sliderPosition); - } - _renderDomNode(largeSize, smallSize) { - this.domNode.setWidth(smallSize); - this.domNode.setHeight(largeSize); - this.domNode.setRight(0); - this.domNode.setTop(0); - } - onDidScroll(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; - } - _mouseDownRelativePosition(offsetX, offsetY) { - return offsetY; - } - _sliderMousePosition(e) { - return e.posy; - } - _sliderOrthogonalMousePosition(e) { - return e.posx; - } - _updateScrollbarSize(size) { - this.slider.setWidth(size); - } - writeScrollPosition(target, scrollPosition) { - target.scrollTop = scrollPosition; - } - updateOptions(options) { - this.updateScrollbarSize(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 - this._scrollbarState.setOppositeScrollbarSize(0); - this._visibilityController.setVisibility(options.vertical); - this._scrollByPage = options.scrollByPage; - } - } - 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. - *--------------------------------------------------------------------------------------------*/ -define(__m[43/*vs/base/common/resources*/], __M([0/*require*/,1/*exports*/,157/*vs/base/common/extpath*/,73/*vs/base/common/path*/,24/*vs/base/common/uri*/,8/*vs/base/common/strings*/,46/*vs/base/common/network*/]), function (require, exports, extpath, paths, uri_1, strings_1, network_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DataUri = exports.resolvePath = exports.normalizePath = exports.joinPath = exports.dirname = exports.basename = exports.basenameOrAuthority = exports.isEqual = exports.extUri = exports.ExtUri = exports.originalFSPath = void 0; - function originalFSPath(uri) { - return (0, uri_1.uriToFsPath)(uri, true); - } - exports.originalFSPath = originalFSPath; - class ExtUri { - constructor(_ignorePathCasing) { - this._ignorePathCasing = _ignorePathCasing; - } - compare(uri1, uri2, ignoreFragment = false) { - if (uri1 === uri2) { - return 0; - } - return (0, strings_1.compare)(this.getComparisonKey(uri1, ignoreFragment), this.getComparisonKey(uri2, ignoreFragment)); - } - isEqual(uri1, uri2, ignoreFragment = false) { - if (uri1 === uri2) { - return true; - } - if (!uri1 || !uri2) { - return false; - } - return this.getComparisonKey(uri1, ignoreFragment) === this.getComparisonKey(uri2, ignoreFragment); - } - getComparisonKey(uri, ignoreFragment = false) { - return uri.with({ - path: this._ignorePathCasing(uri) ? uri.path.toLowerCase() : undefined, - fragment: ignoreFragment ? null : undefined - }).toString(); - } - // --- path math - joinPath(resource, ...pathFragment) { - return uri_1.URI.joinPath(resource, ...pathFragment); - } - basenameOrAuthority(resource) { - return (0, exports.basename)(resource) || resource.authority; - } - basename(resource) { - return paths.posix.basename(resource.path); - } - dirname(resource) { - if (resource.path.length === 0) { - return resource; - } - let dirname; - if (resource.scheme === network_1.Schemas.file) { - dirname = uri_1.URI.file(paths.dirname(originalFSPath(resource))).path; - } - else { - 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 - }); - } - normalizePath(resource) { - if (!resource.path.length) { - return resource; - } - let 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 - }); - } - resolvePath(base, path) { - if (base.scheme === network_1.Schemas.file) { - const newURI = uri_1.URI.file(paths.resolve(originalFSPath(base), path)); - return base.with({ - authority: newURI.authority, - path: newURI.path - }); - } - path = extpath.toPosixPath(path); // we allow path to be a windows path - return base.with({ - path: paths.posix.resolve(base.path, path) - }); - } - } - exports.ExtUri = ExtUri; - /** - * Unbiased utility that takes uris "as they are". This means it can be interchanged with - * uri#toString() usages. The following is true - * ``` - * assertEqual(aUri.toString() === bUri.toString(), exturi.isEqual(aUri, bUri)) - * ``` - */ - exports.extUri = new ExtUri(() => false); - exports.isEqual = exports.extUri.isEqual.bind(exports.extUri); - exports.basenameOrAuthority = exports.extUri.basenameOrAuthority.bind(exports.extUri); - exports.basename = exports.extUri.basename.bind(exports.extUri); - exports.dirname = exports.extUri.dirname.bind(exports.extUri); - exports.joinPath = exports.extUri.joinPath.bind(exports.extUri); - exports.normalizePath = exports.extUri.normalizePath.bind(exports.extUri); - exports.resolvePath = exports.extUri.resolvePath.bind(exports.extUri); - /** - * 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) { - const 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 - const meta = dataUri.path.substring(dataUri.path.indexOf(';') + 1, dataUri.path.lastIndexOf(';')); - meta.split(';').forEach(property => { - const [key, value] = property.split(':'); - 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 - const 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[298/*vs/base/browser/markdownRenderer*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,160/*vs/base/browser/formattedTextRenderer*/,12/*vs/base/common/errors*/,82/*vs/base/common/htmlContent*/,125/*vs/base/common/idGenerator*/,700/*vs/base/common/marked/marked*/,701/*vs/base/common/insane/insane*/,202/*vs/base/common/marshalling*/,42/*vs/base/common/objects*/,8/*vs/base/common/strings*/,24/*vs/base/common/uri*/,46/*vs/base/common/network*/,104/*vs/base/common/iconLabels*/,43/*vs/base/common/resources*/,55/*vs/base/browser/mouseEvent*/,105/*vs/base/browser/ui/iconLabel/iconLabels*/,6/*vs/base/common/event*/,91/*vs/base/browser/event*/]), function (require, exports, DOM, formattedTextRenderer_1, errors_1, htmlContent_1, idGenerator_1, marked, insane_1, marshalling_1, objects_1, strings_1, uri_1, network_1, iconLabels_1, resources_1, mouseEvent_1, iconLabels_2, event_1, event_2) { - "use strict"; - var _a; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.renderMarkdown = void 0; - const _ttpInsane = (_a = window.trustedTypes) === null || _a === void 0 ? void 0 : _a.createPolicy('insane', { - createHTML(value, options) { - return (0, insane_1.insane)(value, options); - } - }); - /** - * Low-level way create a html element from a markdown string. - * - * **Note** that for most cases you should be using [`MarkdownRenderer`](./src/vs/editor/browser/core/markdownRenderer.ts) - * which comes with support for pretty code block rendering and which uses the default way of handling links. - */ - function renderMarkdown(markdown, options = {}, markedOptions = {}) { - var _a; - const element = (0, formattedTextRenderer_1.createElement)(options); - const _uriMassage = function (part) { - let data; - try { - data = (0, marshalling_1.parse)(decodeURIComponent(part)); - } - catch (e) { - // ignore - } - if (!data) { - return part; - } - data = (0, objects_1.cloneAndChange)(data, value => { - if (markdown.uris && markdown.uris[value]) { - return uri_1.URI.revive(markdown.uris[value]); - } - else { - return undefined; - } - }); - return encodeURIComponent(JSON.stringify(data)); - }; - const _href = function (href, isDomUri) { - const data = markdown.uris && markdown.uris[href]; - if (!data) { - return href; // no uri exists - } - let uri = uri_1.URI.revive(data); - if (uri_1.URI.parse(href).toString() === uri.toString()) { - return href; // no tranformation performed - } - if (isDomUri) { - // this URI will end up as "src"-attribute of a dom node - // and because of that special rewriting needs to be done - // so that the URI uses a protocol that's understood by - // browsers (like http or https) - return network_1.FileAccess.asBrowserUri(uri).toString(true); - } - if (uri.query) { - uri = uri.with({ query: _uriMassage(uri.query) }); - } - return uri.toString(); - }; - // signal to code-block render that the - // element has been created - let signalInnerHTML; - const withInnerHTML = new Promise(c => signalInnerHTML = c); - const renderer = new marked.Renderer(); - renderer.image = (href, title, text) => { - let dimensions = []; - let attributes = []; - if (href) { - ({ href, dimensions } = (0, htmlContent_1.parseHrefAndDimensions)(href)); - href = _href(href, true); - try { - const hrefAsUri = uri_1.URI.parse(href); - if (options.baseUrl && hrefAsUri.scheme === network_1.Schemas.file) { // absolute or relative local path, or file: uri - href = (0, resources_1.resolvePath)(options.baseUrl, href).toString(); - } - } - catch (err) { } - attributes.push(`src="${href}"`); - } - if (text) { - attributes.push(`alt="${text}"`); - } - if (title) { - attributes.push(`title="${title}"`); - } - if (dimensions.length) { - attributes = attributes.concat(dimensions); - } - return ''; - }; - renderer.link = (href, title, text) => { - // Remove markdown escapes. Workaround for https://github.com/chjj/marked/issues/829 - if (href === text) { // raw link case - text = (0, htmlContent_1.removeMarkdownEscapes)(text); - } - href = _href(href, false); - if (options.baseUrl) { - const hasScheme = /^\w[\w\d+.-]*:/.test(href); - if (!hasScheme) { - href = (0, resources_1.resolvePath)(options.baseUrl, href).toString(); - } - } - title = (0, htmlContent_1.removeMarkdownEscapes)(title); - href = (0, htmlContent_1.removeMarkdownEscapes)(href); - if (!href - || href.match(/^data:|javascript:/i) - || (href.match(/^command:/i) && !markdown.isTrusted) - || href.match(/^command:(\/\/\/)?_workbench\.downloadResource/i)) { - // drop the link - return text; - } - else { - // HTML Encode href - href = href.replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') - .replace(/'/g, '''); - return `
    ${text}`; - } - }; - renderer.paragraph = (text) => { - if (markdown.supportThemeIcons) { - const elements = (0, iconLabels_2.renderLabelWithIcons)(text); - text = elements.map(e => typeof e === 'string' ? e : e.outerHTML).join(''); - } - return `

    ${text}

    `; - }; - if (options.codeBlockRenderer) { - renderer.code = (code, lang) => { - const value = options.codeBlockRenderer(lang, code); - // when code-block rendering is async we return sync - // but update the node with the real result later. - const id = idGenerator_1.defaultGenerator.nextId(); - const promise = Promise.all([value, withInnerHTML]).then(values => { - const span = element.querySelector(`div[data-code="${id}"]`); - if (span) { - DOM.reset(span, values[0]); - } - }).catch(_err => { - // ignore - }); - if (options.asyncRenderCallback) { - promise.then(options.asyncRenderCallback); - } - return `
    ${(0, strings_1.escape)(code)}
    `; - }; - } - if (options.actionHandler) { - const onClick = options.actionHandler.disposeables.add(new event_2.DomEmitter(element, 'click')); - const onAuxClick = options.actionHandler.disposeables.add(new event_2.DomEmitter(element, 'auxclick')); - options.actionHandler.disposeables.add(event_1.Event.any(onClick.event, onAuxClick.event)(e => { - const mouseEvent = new mouseEvent_1.StandardMouseEvent(e); - if (!mouseEvent.leftButton && !mouseEvent.middleButton) { - return; - } - let target = mouseEvent.target; - if (target.tagName !== 'A') { - target = target.parentElement; - if (!target || target.tagName !== 'A') { - return; - } - } - try { - const href = target.dataset['href']; - if (href) { - options.actionHandler.callback(href, mouseEvent); - } - } - catch (err) { - (0, errors_1.onUnexpectedError)(err); - } - finally { - mouseEvent.preventDefault(); - } - })); - } - // Use our own sanitizer so that we can let through only spans. - // Otherwise, we'd be letting all html be rendered. - // If we want to allow markdown permitted tags, then we can delete sanitizer and sanitize. - // We always pass the output through insane after this so that we don't rely on - // marked for sanitization. - markedOptions.sanitizer = (html) => { - const match = markdown.isTrusted ? html.match(/^(]+>)|(<\/\s*span>)$/) : undefined; - return match ? html : ''; - }; - markedOptions.sanitize = true; - markedOptions.silent = true; - markedOptions.renderer = renderer; - // values that are too long will freeze the UI - let value = (_a = markdown.value) !== null && _a !== void 0 ? _a : ''; - if (value.length > 100000) { - value = `${value.substr(0, 100000)}…`; - } - // escape theme icons - if (markdown.supportThemeIcons) { - value = (0, iconLabels_1.markdownEscapeEscapedIcons)(value); - } - const renderedMarkdown = marked.parse(value, markedOptions); - // sanitize with insane - element.innerHTML = sanitizeRenderedMarkdown(markdown, renderedMarkdown); - // signal that async code blocks can be now be inserted - signalInnerHTML(); - // signal size changes for image tags - if (options.asyncRenderCallback) { - for (const img of element.getElementsByTagName('img')) { - const listener = DOM.addDisposableListener(img, 'load', () => { - listener.dispose(); - options.asyncRenderCallback(); - }); - } - } - return element; - } - exports.renderMarkdown = renderMarkdown; - function sanitizeRenderedMarkdown(options, renderedMarkdown) { - var _a; - const insaneOptions = getInsaneOptions(options); - return (_a = _ttpInsane === null || _ttpInsane === void 0 ? void 0 : _ttpInsane.createHTML(renderedMarkdown, insaneOptions)) !== null && _a !== void 0 ? _a : (0, insane_1.insane)(renderedMarkdown, insaneOptions); - } - function getInsaneOptions(options) { - const 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 (options.isTrusted) { - allowedSchemes.push(network_1.Schemas.command); - } - return { - allowedSchemes, - // allowedTags should included everything that markdown renders to. - // Since we have our own sanitize function for marked, it's possible we missed some tag so let insane make sure. - // HTML tags that can result from markdown are from reading https://spec.commonmark.org/0.29/ - // HTML table tags that can result from markdown are from https://github.github.com/gfm/#tables-extension- - allowedTags: ['ul', 'li', 'p', 'code', 'blockquote', 'ol', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'em', 'pre', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'div', 'del', 'a', 'strong', 'br', 'img', 'span'], - allowedAttributes: { - 'a': ['href', 'name', 'target', 'data-href'], - 'img': ['src', 'title', 'alt', 'width', 'height'], - 'div': ['class', 'data-code'], - 'span': ['class', 'style'], - // https://github.com/microsoft/vscode/issues/95937 - 'th': ['align'], - 'td': ['align'] - }, - filter(token) { - if (token.tag === 'span' && options.isTrusted) { - if (token.attrs['style'] && (Object.keys(token.attrs).length === 1)) { - return !!token.attrs['style'].match(/^(color\:#[0-9a-fA-F]+;)?(background-color\:#[0-9a-fA-F]+;)?$/); - } - else if (token.attrs['class']) { - // The class should match codicon rendering in src\vs\base\common\codicons.ts - return !!token.attrs['class'].match(/^codicon codicon-[a-z\-]+( codicon-modifier-[a-z\-]+)?$/); - } - return false; - } - return 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[163/*vs/base/common/labels*/], __M([0/*require*/,1/*exports*/,24/*vs/base/common/uri*/,46/*vs/base/common/network*/,17/*vs/base/common/platform*/,43/*vs/base/common/resources*/,157/*vs/base/common/extpath*/]), function (require, exports, uri_1, network_1, platform_1, resources_1, extpath_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.normalizeDriveLetter = exports.getBaseLabel = void 0; - function getBaseLabel(resource) { - if (!resource) { - return undefined; - } - if (typeof resource === 'string') { - resource = uri_1.URI.file(resource); - } - const base = (0, 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 (platform_1.isWindows && (0, extpath_1.isRootOrDriveLetter)(base)) { - return normalizeDriveLetter(base); - } - return base; - } - exports.getBaseLabel = getBaseLabel; - function normalizeDriveLetter(path) { - if ((0, extpath_1.hasDriveLetter)(path)) { - return path.charAt(0).toUpperCase() + path.slice(1); - } - return path; - } - exports.normalizeDriveLetter = normalizeDriveLetter; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/common/mime*/], __M([0/*require*/,1/*exports*/,73/*vs/base/common/path*/,8/*vs/base/common/strings*/,201/*vs/base/common/glob*/,46/*vs/base/common/network*/,43/*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.guessMimeTypes = exports.registerTextMime = exports.Mimes = void 0; - var Mimes; - (function (Mimes) { - Mimes.text = 'text/plain'; - Mimes.binary = 'application/octet-stream'; - Mimes.unknown = 'application/unknown'; - Mimes.markdown = 'text/markdown'; - })(Mimes = exports.Mimes || (exports.Mimes = {})); - let registeredAssociations = []; - let nonUserRegisteredAssociations = []; - let userRegisteredAssociations = []; - /** - * Associate a text mime to the registry. - */ - function registerTextMime(association, warnOnOverwrite = false) { - // Register - const 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(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) { - let path; - if (resource) { - switch (resource.scheme) { - case network_1.Schemas.file: - path = resource.fsPath; - break; - case network_1.Schemas.data: - const metadata = resources_1.DataUri.parseMetaData(resource); - path = metadata.get(resources_1.DataUri.META_DATA_LABEL); - break; - default: - path = resource.path; - } - } - if (!path) { - return [Mimes.unknown]; - } - path = path.toLowerCase(); - const filename = (0, path_1.basename)(path); - // 1.) User configured mappings have highest priority - const configuredMime = guessMimeTypeByPath(path, filename, userRegisteredAssociations); - if (configuredMime) { - return [configuredMime, Mimes.text]; - } - // 2.) Registered mappings have middle priority - const registeredMime = guessMimeTypeByPath(path, filename, nonUserRegisteredAssociations); - if (registeredMime) { - return [registeredMime, Mimes.text]; - } - // 3.) Firstline has lowest priority - if (firstLine) { - const firstlineMime = guessMimeTypeByFirstline(firstLine); - if (firstlineMime) { - return [firstlineMime, Mimes.text]; - } - } - return [Mimes.unknown]; - } - exports.guessMimeTypes = guessMimeTypes; - function guessMimeTypeByPath(path, filename, associations) { - let filenameMatch = null; - let patternMatch = null; - let 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 (let i = associations.length - 1; i >= 0; i--) { - const 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) { - const target = association.filepatternOnPath ? path : filename; // match on full path if pattern contains path separator - if ((0, glob_1.match)(association.filepatternLowercase, target)) { - patternMatch = association; - } - } - } - // Longest extension match - if (association.extension) { - if (!extensionMatch || association.extension.length > extensionMatch.extension.length) { - if (filename.endsWith(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 ((0, 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 (let i = registeredAssociations.length - 1; i >= 0; i--) { - const association = registeredAssociations[i]; - if (!association.firstline) { - continue; - } - const matches = firstLine.match(association.firstline); - if (matches && matches.length > 0) { - return association.mime; - } - } - } - return null; - } -}); - -define(__m[164/*vs/base/browser/dnd*/], __M([0/*require*/,1/*exports*/,106/*vs/base/common/mime*/]), function (require, exports, mime_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.StaticDND = exports.DragAndDropData = exports.DataTransfers = void 0; - // Common data transfers - exports.DataTransfers = { - /** - * Application specific resource transfer type - */ - RESOURCES: 'ResourceURLs', - /** - * Browser specific transfer type to download - */ - DOWNLOAD_URL: 'DownloadURL', - /** - * Browser specific transfer type for files - */ - FILES: 'Files', - /** - * Typically transfer type for copy/paste transfers. - */ - TEXT: mime_1.Mimes.text, - /** - * Application specific terminal transfer type. - */ - TERMINALS: 'Terminals' - }; - class DragAndDropData { - constructor(data) { - this.data = data; - } - update() { - // noop - } - getData() { - return this.data; - } - } - exports.DragAndDropData = DragAndDropData; - exports.StaticDND = { - CurrentDragAndDropData: undefined - }; -}); - -define(__m[299/*vs/base/common/uuid*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.generateUuid = void 0; - // prep-work - const _data = new Uint8Array(16); - const _hex = []; - for (let i = 0; i < 256; i++) { - _hex.push(i.toString(16).padStart(2, '0')); - } - // todo@jrieken - with node@15 crypto#getRandomBytes is available everywhere, https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#browser_compatibility - let _fillRandomValues; - if (typeof crypto === 'object' && typeof crypto.getRandomValues === 'function') { - // browser - _fillRandomValues = crypto.getRandomValues.bind(crypto); - } - else { - _fillRandomValues = function (bucket) { - for (let i = 0; i < bucket.length; i++) { - bucket[i] = Math.floor(Math.random() * 256); - } - return bucket; - }; - } - function generateUuid() { - // get data - _fillRandomValues(_data); - // set version bits - _data[6] = (_data[6] & 0x0f) | 0x40; - _data[8] = (_data[8] & 0x3f) | 0x80; - // print as string - let i = 0; - let result = ''; - result += _hex[_data[i++]]; - result += _hex[_data[i++]]; - result += _hex[_data[i++]]; - result += _hex[_data[i++]]; - result += '-'; - result += _hex[_data[i++]]; - result += _hex[_data[i++]]; - result += '-'; - result += _hex[_data[i++]]; - result += _hex[_data[i++]]; - result += '-'; - result += _hex[_data[i++]]; - result += _hex[_data[i++]]; - result += '-'; - result += _hex[_data[i++]]; - result += _hex[_data[i++]]; - result += _hex[_data[i++]]; - result += _hex[_data[i++]]; - result += _hex[_data[i++]]; - result += _hex[_data[i++]]; - return result; - } - exports.generateUuid = generateUuid; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/common/worker/simpleWorker*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,20/*vs/base/common/types*/]), function (require, exports, errors_1, lifecycle_1, platform_1, types) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.create = exports.SimpleWorkerServer = exports.SimpleWorkerClient = exports.logOnceWebWorkerWarning = void 0; - const INITIALIZE = '$initialize'; - let 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; - class SimpleWorkerProtocol { - constructor(handler) { - this._workerId = -1; - this._handler = handler; - this._lastSentReq = 0; - this._pendingReplies = Object.create(null); - } - setWorkerId(workerId) { - this._workerId = workerId; - } - sendMessage(method, args) { - let req = String(++this._lastSentReq); - return new Promise((resolve, reject) => { - this._pendingReplies[req] = { - resolve: resolve, - reject: reject - }; - this._send({ - vsWorker: this._workerId, - req: req, - method: method, - args: args - }); - }); - } - handleMessage(message) { - if (!message || !message.vsWorker) { - return; - } - if (this._workerId !== -1 && message.vsWorker !== this._workerId) { - return; - } - this._handleMessage(message); - } - _handleMessage(msg) { - if (msg.seq) { - let replyMessage = msg; - if (!this._pendingReplies[replyMessage.seq]) { - console.warn('Got reply to unknown seq'); - return; - } - let reply = this._pendingReplies[replyMessage.seq]; - delete this._pendingReplies[replyMessage.seq]; - if (replyMessage.err) { - let 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; - } - let requestMessage = msg; - let req = requestMessage.req; - let result = this._handler.handleMessage(requestMessage.method, requestMessage.args); - result.then((r) => { - this._send({ - vsWorker: this._workerId, - seq: req, - res: r, - err: undefined - }); - }, (e) => { - if (e.detail instanceof Error) { - // Loading errors have a detail property that points to the actual error - e.detail = (0, errors_1.transformErrorForSerialization)(e.detail); - } - this._send({ - vsWorker: this._workerId, - seq: req, - res: undefined, - err: (0, errors_1.transformErrorForSerialization)(e) - }); - }); - } - _send(msg) { - let transfer = []; - if (msg.req) { - const m = msg; - for (let i = 0; i < m.args.length; i++) { - if (m.args[i] instanceof ArrayBuffer) { - transfer.push(m.args[i]); - } - } - } - else { - const m = msg; - if (m.res instanceof ArrayBuffer) { - transfer.push(m.res); - } - } - this._handler.sendMessage(msg, transfer); - } - } - /** - * Main thread side - */ - class SimpleWorkerClient extends lifecycle_1.Disposable { - constructor(workerFactory, moduleId, host) { - super(); - let lazyProxyReject = null; - this._worker = this._register(workerFactory.create('vs/base/common/worker/simpleWorker', (msg) => { - this._protocol.handleMessage(msg); - }, (err) => { - // in Firefox, web workers fail lazily :( - // we will reject the proxy - if (lazyProxyReject) { - lazyProxyReject(err); - } - })); - this._protocol = new SimpleWorkerProtocol({ - sendMessage: (msg, transfer) => { - this._worker.postMessage(msg, transfer); - }, - handleMessage: (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 - let 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; - } - const 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 - const proxyMethodRequest = (method, args) => { - return this._request(method, args); - }; - this._lazyProxy = new Promise((resolve, reject) => { - lazyProxyReject = reject; - this._onModuleLoaded.then((availableMethods) => { - resolve(types.createProxyObject(availableMethods, proxyMethodRequest)); - }, (e) => { - reject(e); - this._onError('Worker failed to load ' + moduleId, e); - }); - }); - } - getProxyObject() { - return this._lazyProxy; - } - _request(method, args) { - return new Promise((resolve, reject) => { - this._onModuleLoaded.then(() => { - this._protocol.sendMessage(method, args).then(resolve, reject); - }, reject); - }); - } - _onError(message, error) { - console.error(message); - console.info(error); - } - } - exports.SimpleWorkerClient = SimpleWorkerClient; - /** - * Worker side - */ - class SimpleWorkerServer { - constructor(postMessage, requestHandlerFactory) { - this._requestHandlerFactory = requestHandlerFactory; - this._requestHandler = null; - this._protocol = new SimpleWorkerProtocol({ - sendMessage: (msg, transfer) => { - postMessage(msg, transfer); - }, - handleMessage: (method, args) => this._handleMessage(method, args) - }); - } - onmessage(msg) { - this._protocol.handleMessage(msg); - } - _handleMessage(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); - } - } - initialize(workerId, loaderConfig, moduleId, hostMethods) { - this._protocol.setWorkerId(workerId); - const proxyMethodRequest = (method, args) => { - return this._protocol.sendMessage(method, args); - }; - const 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']; - } - } - if (typeof loaderConfig.trustedTypesPolicy !== undefined) { - // don't use, it has been destroyed during serialize - delete loaderConfig['trustedTypesPolicy']; - } - // Since this is in a web worker, enable catching errors - loaderConfig.catchError = true; - self.require.config(loaderConfig); - } - return new Promise((resolve, reject) => { - // Use the global require to be sure to get the global config - self.require([moduleId], (module) => { - this._requestHandler = module.create(hostProxy); - if (!this._requestHandler) { - reject(new Error(`No RequestHandler!`)); - return; - } - resolve(types.getAllMethodNames(this._requestHandler)); - }, reject); - }); - } - } - 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[205/*vs/base/parts/quickinput/common/quickInput*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ItemActivation = exports.QuickInputHideReason = exports.NO_KEY_MODS = void 0; - exports.NO_KEY_MODS = { ctrlCmd: false, alt: false }; - var QuickInputHideReason; - (function (QuickInputHideReason) { - /** - * Focus moved away from the quick input. - */ - QuickInputHideReason[QuickInputHideReason["Blur"] = 1] = "Blur"; - /** - * An explicit user gesture, e.g. pressing Escape key. - */ - QuickInputHideReason[QuickInputHideReason["Gesture"] = 2] = "Gesture"; - /** - * Anything else. - */ - QuickInputHideReason[QuickInputHideReason["Other"] = 3] = "Other"; - })(QuickInputHideReason = exports.QuickInputHideReason || (exports.QuickInputHideReason = {})); - var ItemActivation; - (function (ItemActivation) { - ItemActivation[ItemActivation["NONE"] = 0] = "NONE"; - ItemActivation[ItemActivation["FIRST"] = 1] = "FIRST"; - ItemActivation[ItemActivation["SECOND"] = 2] = "SECOND"; - ItemActivation[ItemActivation["LAST"] = 3] = "LAST"; - })(ItemActivation = exports.ItemActivation || (exports.ItemActivation = {})); -}); -//#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[300/*vs/base/parts/storage/common/storage*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,6/*vs/base/common/event*/,15/*vs/base/common/async*/,20/*vs/base/common/types*/]), function (require, exports, lifecycle_1, event_1, async_1, types_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.InMemoryStorageDatabase = exports.Storage = void 0; - var StorageState; - (function (StorageState) { - StorageState[StorageState["None"] = 0] = "None"; - StorageState[StorageState["Initialized"] = 1] = "Initialized"; - StorageState[StorageState["Closed"] = 2] = "Closed"; - })(StorageState || (StorageState = {})); - class Storage extends lifecycle_1.Disposable { - constructor(database, options = Object.create(null)) { - super(); - this.database = database; - this.options = options; - this._onDidChangeStorage = this._register(new event_1.Emitter()); - this.onDidChangeStorage = this._onDidChangeStorage.event; - this.state = StorageState.None; - this.cache = new Map(); - this.flushDelayer = new async_1.ThrottledDelayer(Storage.DEFAULT_FLUSH_DELAY); - this.pendingDeletes = new Set(); - this.pendingInserts = new Map(); - this.whenFlushedCallbacks = []; - this.registerListeners(); - } - registerListeners() { - this._register(this.database.onDidChangeItemsExternal(e => this.onDidChangeItemsExternal(e))); - } - onDidChangeItemsExternal(e) { - var _a, _b; - // items that change external require us to update our - // caches with the values. we just accept the value and - // emit an event if there is a change. - (_a = e.changed) === null || _a === void 0 ? void 0 : _a.forEach((value, key) => this.accept(key, value)); - (_b = e.deleted) === null || _b === void 0 ? void 0 : _b.forEach(key => this.accept(key, undefined)); - } - accept(key, value) { - if (this.state === StorageState.Closed) { - return; // Return early if we are already closed - } - let changed = false; - // Item got removed, check for deletion - if ((0, types_1.isUndefinedOrNull)(value)) { - changed = this.cache.delete(key); - } - // Item got updated, check for change - else { - const currentValue = this.cache.get(key); - if (currentValue !== value) { - this.cache.set(key, value); - changed = true; - } - } - // Signal to outside listeners - if (changed) { - this._onDidChangeStorage.fire(key); - } - } - get(key, fallbackValue) { - const value = this.cache.get(key); - if ((0, types_1.isUndefinedOrNull)(value)) { - return fallbackValue; - } - return value; - } - getBoolean(key, fallbackValue) { - const value = this.get(key); - if ((0, types_1.isUndefinedOrNull)(value)) { - return fallbackValue; - } - return value === 'true'; - } - getNumber(key, fallbackValue) { - const value = this.get(key); - if ((0, types_1.isUndefinedOrNull)(value)) { - return fallbackValue; - } - return parseInt(value, 10); - } - set(key, value) { - return __awaiter(this, void 0, void 0, function* () { - if (this.state === StorageState.Closed) { - return; // Return early if we are already closed - } - // We remove the key for undefined/null values - if ((0, types_1.isUndefinedOrNull)(value)) { - return this.delete(key); - } - // Otherwise, convert to String and store - const valueStr = String(value); - // Return early if value already set - const currentValue = this.cache.get(key); - if (currentValue === valueStr) { - return; - } - // Update in cache and pending - this.cache.set(key, valueStr); - this.pendingInserts.set(key, valueStr); - this.pendingDeletes.delete(key); - // Event - this._onDidChangeStorage.fire(key); - // Accumulate work by scheduling after timeout - return this.flushDelayer.trigger(() => this.flushPending()); - }); - } - delete(key) { - return __awaiter(this, void 0, void 0, function* () { - if (this.state === StorageState.Closed) { - return; // Return early if we are already closed - } - // Remove from cache and add to pending - const wasDeleted = this.cache.delete(key); - if (!wasDeleted) { - return; // Return early if value already deleted - } - if (!this.pendingDeletes.has(key)) { - this.pendingDeletes.add(key); - } - this.pendingInserts.delete(key); - // Event - this._onDidChangeStorage.fire(key); - // Accumulate work by scheduling after timeout - return this.flushDelayer.trigger(() => this.flushPending()); - }); - } - get hasPending() { - return this.pendingInserts.size > 0 || this.pendingDeletes.size > 0; - } - flushPending() { - return __awaiter(this, void 0, void 0, function* () { - if (!this.hasPending) { - return; // return early if nothing to do - } - // Get pending data - const updateRequest = { insert: this.pendingInserts, delete: this.pendingDeletes }; - // Reset pending data for next run - this.pendingDeletes = new Set(); - this.pendingInserts = new Map(); - // Update in storage and release any - // waiters we have once done - return this.database.updateItems(updateRequest).finally(() => { - var _a; - if (!this.hasPending) { - while (this.whenFlushedCallbacks.length) { - (_a = this.whenFlushedCallbacks.pop()) === null || _a === void 0 ? void 0 : _a(); - } - } - }); - }); - } - dispose() { - this.flushDelayer.dispose(); - super.dispose(); - } - } - exports.Storage = Storage; - Storage.DEFAULT_FLUSH_DELAY = 100; - class InMemoryStorageDatabase { - constructor() { - this.onDidChangeItemsExternal = event_1.Event.None; - this.items = new Map(); - } - updateItems(request) { - return __awaiter(this, void 0, void 0, function* () { - if (request.insert) { - request.insert.forEach((value, key) => this.items.set(key, value)); - } - if (request.delete) { - request.delete.forEach(key => this.items.delete(key)); - } - }); - } - } - exports.InMemoryStorageDatabase = InMemoryStorageDatabase; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[301/*vs/base/worker/defaultWorkerFactory*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/,204/*vs/base/common/worker/simpleWorker*/]), function (require, exports, platform_1, simpleWorker_1) { - "use strict"; - var _a; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DefaultWorkerFactory = exports.getWorkerBootstrapUrl = void 0; - const ttPolicy = (_a = window.trustedTypes) === null || _a === void 0 ? void 0 : _a.createPolicy('defaultWorkerFactory', { createScriptURL: value => value }); - 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') { - const wokerUrl = platform_1.globals.MonacoEnvironment.getWorkerUrl(workerId, label); - return new Worker(ttPolicy ? ttPolicy.createScriptURL(wokerUrl) : wokerUrl, { name: label }); - } - } - // ESM-comment-begin - if (typeof require === 'function') { - // check if the JS lives on a different origin - const workerMain = require.toUrl('./' + workerId); // explicitly using require.toUrl(), see https://github.com/microsoft/vscode/issues/107440#issuecomment-698982321 - const workerUrl = getWorkerBootstrapUrl(workerMain, label); - return new Worker(ttPolicy ? ttPolicy.createScriptURL(workerUrl) : 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) && scriptPath.substring(0, self.origin.length) !== self.origin) { - // this is the cross-origin case - // i.e. the webpage is running at a different origin than where the scripts are loaded from - const myPath = 'vs/base/worker/defaultWorkerFactory.js'; - const workerBaseUrl = require.toUrl(myPath).slice(0, -myPath.length); // explicitly using require.toUrl(), see https://github.com/microsoft/vscode/issues/107440#issuecomment-698982321 - const js = `/*${label}*/self.MonacoEnvironment={baseUrl: '${workerBaseUrl}'};const ttPolicy = self.trustedTypes?.createPolicy('defaultWorkerFactory', { createScriptURL: value => value });importScripts(ttPolicy?.createScriptURL('${scriptPath}') ?? '${scriptPath}');/*${label}*/`; - const blob = new Blob([js], { type: 'application/javascript' }); - return URL.createObjectURL(blob); - } - 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. - */ - class WebWorker { - constructor(moduleId, id, label, onMessageCallback, onErrorCallback) { - this.id = id; - const workerOrPromise = getWorker('workerMain.js', label); - if (isPromiseLike(workerOrPromise)) { - this.worker = workerOrPromise; - } - else { - this.worker = Promise.resolve(workerOrPromise); - } - this.postMessage(moduleId, []); - this.worker.then((w) => { - w.onmessage = function (ev) { - onMessageCallback(ev.data); - }; - w.onmessageerror = onErrorCallback; - if (typeof w.addEventListener === 'function') { - w.addEventListener('error', onErrorCallback); - } - }); - } - getId() { - return this.id; - } - postMessage(message, transfer) { - if (this.worker) { - this.worker.then(w => w.postMessage(message, transfer)); - } - } - dispose() { - if (this.worker) { - this.worker.then(w => w.terminate()); - } - this.worker = null; - } - } - class DefaultWorkerFactory { - constructor(label) { - this._label = label; - this._webWorkerFailedBeforeError = false; - } - create(moduleId, onMessageCallback, onErrorCallback) { - let workerId = (++DefaultWorkerFactory.LAST_WORKER_ID); - if (this._webWorkerFailedBeforeError) { - throw this._webWorkerFailedBeforeError; - } - return new WebWorker(moduleId, workerId, this._label || 'anonymous' + workerId, onMessageCallback, (err) => { - (0, simpleWorker_1.logOnceWebWorkerWarning)(err); - this._webWorkerFailedBeforeError = err; - onErrorCallback(err); - }); - } - } - exports.DefaultWorkerFactory = DefaultWorkerFactory; - DefaultWorkerFactory.LAST_WORKER_ID = 0; -}); - -define(__m[206/*vs/css!vs/base/browser/ui/actionbar/actionbar*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[302/*vs/css!vs/base/browser/ui/aria/aria*/], __M([10/*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[44/*vs/base/browser/ui/aria/aria*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/,7/*vs/base/browser/dom*/,302/*vs/css!vs/base/browser/ui/aria/aria*/]), function (require, exports, platform_1, dom) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.status = exports.alert = exports.setARIAContainer = void 0; - // Use a max length since we are inserting the whole msg in the DOM and that can cause browsers to freeze for long messages #94233 - const MAX_MESSAGE_LENGTH = 20000; - let ariaContainer; - let alertContainer; - let alertContainer2; - let statusContainer; - let statusContainer2; - function setARIAContainer(parent) { - ariaContainer = document.createElement('div'); - ariaContainer.className = 'monaco-aria-container'; - const createAlertContainer = () => { - const element = document.createElement('div'); - element.className = 'monaco-alert'; - element.setAttribute('role', 'alert'); - element.setAttribute('aria-atomic', 'true'); - ariaContainer.appendChild(element); - return element; - }; - alertContainer = createAlertContainer(); - alertContainer2 = createAlertContainer(); - const createStatusContainer = () => { - const element = document.createElement('div'); - element.className = 'monaco-status'; - element.setAttribute('role', 'complementary'); - element.setAttribute('aria-live', 'polite'); - element.setAttribute('aria-atomic', 'true'); - ariaContainer.appendChild(element); - return element; - }; - statusContainer = createStatusContainer(); - statusContainer2 = createStatusContainer(); - 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) { - if (!ariaContainer) { - return; - } - // Use alternate containers such that duplicated messages get read out by screen readers #99466 - if (alertContainer.textContent !== msg) { - dom.clearNode(alertContainer2); - insertMessage(alertContainer, msg); - } - else { - dom.clearNode(alertContainer); - insertMessage(alertContainer2, msg); - } - } - exports.alert = alert; - /** - * Given the provided message, will make sure that it is read as status to screen readers. - */ - function status(msg) { - if (!ariaContainer) { - return; - } - if (platform_1.isMacintosh) { - alert(msg); // VoiceOver does not seem to support status role - } - else { - if (statusContainer.textContent !== msg) { - dom.clearNode(statusContainer2); - insertMessage(statusContainer, msg); - } - else { - dom.clearNode(statusContainer); - insertMessage(statusContainer2, msg); - } - } - } - exports.status = status; - function insertMessage(target, msg) { - dom.clearNode(target); - if (msg.length > MAX_MESSAGE_LENGTH) { - msg = msg.substr(0, MAX_MESSAGE_LENGTH); - } - 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[303/*vs/css!vs/base/browser/ui/button/button*/], __M([10/*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[304/*vs/base/browser/ui/button/button*/], __M([0/*require*/,1/*exports*/,51/*vs/base/browser/keyboardEvent*/,29/*vs/base/common/color*/,42/*vs/base/common/objects*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,60/*vs/base/browser/touch*/,105/*vs/base/browser/ui/iconLabel/iconLabels*/,7/*vs/base/browser/dom*/,303/*vs/css!vs/base/browser/ui/button/button*/]), function (require, exports, keyboardEvent_1, color_1, objects_1, event_1, lifecycle_1, touch_1, iconLabels_1, dom_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Button = void 0; - const defaultOptions = { - buttonBackground: color_1.Color.fromHex('#0E639C'), - buttonHoverBackground: color_1.Color.fromHex('#006BB3'), - buttonForeground: color_1.Color.white - }; - class Button extends lifecycle_1.Disposable { - constructor(container, options) { - super(); - this._onDidClick = this._register(new event_1.Emitter()); - this.options = options || Object.create(null); - (0, objects_1.mixin)(this.options, defaultOptions, false); - this.buttonForeground = this.options.buttonForeground; - this.buttonBackground = this.options.buttonBackground; - this.buttonHoverBackground = this.options.buttonHoverBackground; - this.buttonSecondaryForeground = this.options.buttonSecondaryForeground; - this.buttonSecondaryBackground = this.options.buttonSecondaryBackground; - this.buttonSecondaryHoverBackground = this.options.buttonSecondaryHoverBackground; - this.buttonBorder = this.options.buttonBorder; - this._element = document.createElement('a'); - this._element.classList.add('monaco-button'); - this._element.tabIndex = 0; - this._element.setAttribute('role', 'button'); - container.appendChild(this._element); - this._register(touch_1.Gesture.addTarget(this._element)); - [dom_1.EventType.CLICK, touch_1.EventType.Tap].forEach(eventType => { - this._register((0, dom_1.addDisposableListener)(this._element, eventType, e => { - if (!this.enabled) { - dom_1.EventHelper.stop(e); - return; - } - this._onDidClick.fire(e); - })); - }); - this._register((0, dom_1.addDisposableListener)(this._element, dom_1.EventType.KEY_DOWN, e => { - const event = new keyboardEvent_1.StandardKeyboardEvent(e); - let eventHandled = false; - if (this.enabled && (event.equals(3 /* Enter */) || event.equals(10 /* Space */))) { - this._onDidClick.fire(e); - eventHandled = true; - } - else if (event.equals(9 /* Escape */)) { - this._element.blur(); - eventHandled = true; - } - if (eventHandled) { - dom_1.EventHelper.stop(event, true); - } - })); - this._register((0, dom_1.addDisposableListener)(this._element, dom_1.EventType.MOUSE_OVER, e => { - if (!this._element.classList.contains('disabled')) { - this.setHoverBackground(); - } - })); - this._register((0, dom_1.addDisposableListener)(this._element, dom_1.EventType.MOUSE_OUT, e => { - this.applyStyles(); // restore standard styles - })); - // Also set hover background when button is focused for feedback - this.focusTracker = this._register((0, dom_1.trackFocus)(this._element)); - this._register(this.focusTracker.onDidFocus(() => this.setHoverBackground())); - this._register(this.focusTracker.onDidBlur(() => this.applyStyles())); // restore standard styles - this.applyStyles(); - } - get onDidClick() { return this._onDidClick.event; } - setHoverBackground() { - let hoverBackground; - if (this.options.secondary) { - hoverBackground = this.buttonSecondaryHoverBackground ? this.buttonSecondaryHoverBackground.toString() : null; - } - else { - hoverBackground = this.buttonHoverBackground ? this.buttonHoverBackground.toString() : null; - } - if (hoverBackground) { - this._element.style.backgroundColor = hoverBackground; - } - } - style(styles) { - this.buttonForeground = styles.buttonForeground; - this.buttonBackground = styles.buttonBackground; - this.buttonHoverBackground = styles.buttonHoverBackground; - this.buttonSecondaryForeground = styles.buttonSecondaryForeground; - this.buttonSecondaryBackground = styles.buttonSecondaryBackground; - this.buttonSecondaryHoverBackground = styles.buttonSecondaryHoverBackground; - this.buttonBorder = styles.buttonBorder; - this.applyStyles(); - } - applyStyles() { - if (this._element) { - let background, foreground; - if (this.options.secondary) { - foreground = this.buttonSecondaryForeground ? this.buttonSecondaryForeground.toString() : ''; - background = this.buttonSecondaryBackground ? this.buttonSecondaryBackground.toString() : ''; - } - else { - foreground = this.buttonForeground ? this.buttonForeground.toString() : ''; - background = this.buttonBackground ? this.buttonBackground.toString() : ''; - } - const border = this.buttonBorder ? this.buttonBorder.toString() : ''; - this._element.style.color = foreground; - this._element.style.backgroundColor = background; - this._element.style.borderWidth = border ? '1px' : ''; - this._element.style.borderStyle = border ? 'solid' : ''; - this._element.style.borderColor = border; - } - } - get element() { - return this._element; - } - set label(value) { - this._element.classList.add('monaco-text-button'); - if (this.options.supportIcons) { - (0, dom_1.reset)(this._element, ...(0, iconLabels_1.renderLabelWithIcons)(value)); - } - else { - this._element.textContent = value; - } - if (typeof this.options.title === 'string') { - this._element.title = this.options.title; - } - else if (this.options.title) { - this._element.title = value; - } - } - set enabled(value) { - if (value) { - this._element.classList.remove('disabled'); - this._element.setAttribute('aria-disabled', String(false)); - this._element.tabIndex = 0; - } - else { - this._element.classList.add('disabled'); - this._element.setAttribute('aria-disabled', String(true)); - } - } - get enabled() { - return !this._element.classList.contains('disabled'); - } - } - exports.Button = Button; -}); - -define(__m[305/*vs/css!vs/base/browser/ui/checkbox/checkbox*/], __M([10/*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[165/*vs/base/browser/ui/checkbox/checkbox*/], __M([0/*require*/,1/*exports*/,52/*vs/base/browser/ui/widget*/,29/*vs/base/common/color*/,6/*vs/base/common/event*/,27/*vs/base/common/codicons*/,305/*vs/css!vs/base/browser/ui/checkbox/checkbox*/]), function (require, exports, widget_1, color_1, event_1, codicons_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Checkbox = void 0; - const defaultOpts = { - inputActiveOptionBorder: color_1.Color.fromHex('#007ACC00'), - inputActiveOptionForeground: color_1.Color.fromHex('#FFFFFF'), - inputActiveOptionBackground: color_1.Color.fromHex('#0E639C50') - }; - class Checkbox extends widget_1.Widget { - constructor(opts) { - super(); - 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 = Object.assign(Object.assign({}, defaultOpts), opts); - this._checked = this._opts.isChecked; - const classes = ['monaco-custom-checkbox']; - if (this._opts.icon) { - classes.push(...codicons_1.CSSIcon.asClassNameArray(this._opts.icon)); - } - if (this._opts.actionClassName) { - classes.push(...this._opts.actionClassName.split(' ')); - } - if (this._checked) { - classes.push('checked'); - } - this.domNode = document.createElement('div'); - this.domNode.title = this._opts.title; - this.domNode.classList.add(...classes); - if (!this._opts.notFocusable) { - 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, (ev) => { - this.checked = !this._checked; - this._onChange.fire(false); - ev.preventDefault(); - }); - this.ignoreGesture(this.domNode); - this.onkeydown(this.domNode, (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); - }); - } - get enabled() { - return this.domNode.getAttribute('aria-disabled') !== 'true'; - } - focus() { - this.domNode.focus(); - } - get checked() { - return this._checked; - } - set checked(newIsChecked) { - this._checked = newIsChecked; - this.domNode.setAttribute('aria-checked', String(this._checked)); - this.domNode.classList.toggle('checked', this._checked); - this.applyStyles(); - } - width() { - return 2 /*marginleft*/ + 2 /*border*/ + 2 /*padding*/ + 16 /* icon width */; - } - style(styles) { - if (styles.inputActiveOptionBorder) { - this._opts.inputActiveOptionBorder = styles.inputActiveOptionBorder; - } - if (styles.inputActiveOptionForeground) { - this._opts.inputActiveOptionForeground = styles.inputActiveOptionForeground; - } - if (styles.inputActiveOptionBackground) { - this._opts.inputActiveOptionBackground = styles.inputActiveOptionBackground; - } - this.applyStyles(); - } - applyStyles() { - if (this.domNode) { - this.domNode.style.borderColor = this._checked && this._opts.inputActiveOptionBorder ? this._opts.inputActiveOptionBorder.toString() : 'transparent'; - this.domNode.style.color = this._checked && this._opts.inputActiveOptionForeground ? this._opts.inputActiveOptionForeground.toString() : 'inherit'; - this.domNode.style.backgroundColor = this._checked && this._opts.inputActiveOptionBackground ? this._opts.inputActiveOptionBackground.toString() : 'transparent'; - } - } - enable() { - this.domNode.setAttribute('aria-disabled', String(false)); - } - disable() { - this.domNode.setAttribute('aria-disabled', String(true)); - } - } - exports.Checkbox = Checkbox; -}); - -define(__m[306/*vs/css!vs/base/browser/ui/codicons/codicon/codicon*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[307/*vs/css!vs/base/browser/ui/codicons/codicon/codicon-modifiers*/], __M([10/*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[130/*vs/base/browser/ui/codicons/codiconStyles*/], __M([0/*require*/,1/*exports*/,27/*vs/base/common/codicons*/,306/*vs/css!vs/base/browser/ui/codicons/codicon/codicon*/,307/*vs/css!vs/base/browser/ui/codicons/codicon/codicon-modifiers*/]), function (require, exports, codicons_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.formatRule = void 0; - function formatRule(c) { - let def = c.definition; - while (def instanceof codicons_1.Codicon) { - def = def.definition; - } - return `.codicon-${c.id}:before { content: '${def.fontCharacter}'; }`; - } - exports.formatRule = formatRule; -}); - -define(__m[308/*vs/css!vs/base/browser/ui/contextview/contextview*/], __M([10/*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[207/*vs/base/browser/ui/contextview/contextview*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,17/*vs/base/common/platform*/,2/*vs/base/common/lifecycle*/,126/*vs/base/common/range*/,156/*vs/base/browser/canIUse*/,308/*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 }); - exports.ContextView = exports.layout = exports.LayoutAnchorMode = void 0; - var LayoutAnchorMode; - (function (LayoutAnchorMode) { - LayoutAnchorMode[LayoutAnchorMode["AVOID"] = 0] = "AVOID"; - LayoutAnchorMode[LayoutAnchorMode["ALIGN"] = 1] = "ALIGN"; - })(LayoutAnchorMode = exports.LayoutAnchorMode || (exports.LayoutAnchorMode = {})); - /** - * 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) { - const layoutAfterAnchorBoundary = anchor.mode === LayoutAnchorMode.ALIGN ? anchor.offset : anchor.offset + anchor.size; - const layoutBeforeAnchorBoundary = anchor.mode === LayoutAnchorMode.ALIGN ? anchor.offset + anchor.size : anchor.offset; - if (anchor.position === 0 /* Before */) { - if (viewSize <= viewportSize - layoutAfterAnchorBoundary) { - return layoutAfterAnchorBoundary; // happy case, lay it out after the anchor - } - if (viewSize <= layoutBeforeAnchorBoundary) { - return layoutBeforeAnchorBoundary - 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 <= layoutBeforeAnchorBoundary) { - return layoutBeforeAnchorBoundary - viewSize; // happy case, lay it out before the anchor - } - if (viewSize <= viewportSize - layoutAfterAnchorBoundary) { - return layoutAfterAnchorBoundary; // ok case, lay it out after the anchor - } - return 0; // sad case, lay it over the anchor - } - } - exports.layout = layout; - class ContextView extends lifecycle_1.Disposable { - constructor(container, domPosition) { - super(); - this.container = null; - this.delegate = null; - this.toDisposeOnClean = lifecycle_1.Disposable.None; - this.toDisposeOnSetContainer = lifecycle_1.Disposable.None; - this.shadowRoot = null; - this.shadowRootHostElement = null; - this.view = DOM.$('.context-view'); - this.useFixedPosition = false; - this.useShadowDOM = false; - DOM.hide(this.view); - this.setContainer(container, domPosition); - this._register((0, lifecycle_1.toDisposable)(() => this.setContainer(null, 1 /* ABSOLUTE */))); - } - setContainer(container, domPosition) { - var _a; - if (this.container) { - this.toDisposeOnSetContainer.dispose(); - if (this.shadowRoot) { - this.shadowRoot.removeChild(this.view); - this.shadowRoot = null; - (_a = this.shadowRootHostElement) === null || _a === void 0 ? void 0 : _a.remove(); - this.shadowRootHostElement = null; - } - else { - this.container.removeChild(this.view); - } - this.container = null; - } - if (container) { - this.container = container; - this.useFixedPosition = domPosition !== 1 /* ABSOLUTE */; - this.useShadowDOM = domPosition === 3 /* FIXED_SHADOW */; - if (this.useShadowDOM) { - this.shadowRootHostElement = DOM.$('.shadow-root-host'); - this.container.appendChild(this.shadowRootHostElement); - this.shadowRoot = this.shadowRootHostElement.attachShadow({ mode: 'open' }); - const style = document.createElement('style'); - style.textContent = SHADOW_ROOT_CSS; - this.shadowRoot.appendChild(style); - this.shadowRoot.appendChild(this.view); - this.shadowRoot.appendChild(DOM.$('slot')); - } - else { - this.container.appendChild(this.view); - } - const toDisposeOnSetContainer = new lifecycle_1.DisposableStore(); - ContextView.BUBBLE_UP_EVENTS.forEach(event => { - toDisposeOnSetContainer.add(DOM.addStandardDisposableListener(this.container, event, (e) => { - this.onDOMEvent(e, false); - })); - }); - ContextView.BUBBLE_DOWN_EVENTS.forEach(event => { - toDisposeOnSetContainer.add(DOM.addStandardDisposableListener(this.container, event, (e) => { - this.onDOMEvent(e, true); - }, true)); - }); - this.toDisposeOnSetContainer = toDisposeOnSetContainer; - } - } - show(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'; - this.view.style.zIndex = '2500'; - this.view.style.position = this.useFixedPosition ? 'fixed' : 'absolute'; - 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(); - } - } - getViewElement() { - return this.view; - } - layout() { - 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(); - } - doLayout() { - // Check that we still have a delegate - this.delegate.layout may have hidden - if (!this.isVisible()) { - return; - } - // Get anchor - let anchor = this.delegate.getAnchor(); - // Compute around - let around; - // Get the element's position and size (to anchor the view) - if (DOM.isHTMLElement(anchor)) { - let 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 - }; - } - const viewSizeWidth = DOM.getTotalWidth(this.view); - const viewSizeHeight = DOM.getTotalHeight(this.view); - const anchorPosition = this.delegate.anchorPosition || 0 /* BELOW */; - const anchorAlignment = this.delegate.anchorAlignment || 0 /* LEFT */; - const anchorAxisAlignment = this.delegate.anchorAxisAlignment || 0 /* VERTICAL */; - let top; - let left; - if (anchorAxisAlignment === 0 /* VERTICAL */) { - const verticalAnchor = { offset: around.top - window.pageYOffset, size: around.height, position: anchorPosition === 0 /* BELOW */ ? 0 /* Before */ : 1 /* After */ }; - const horizontalAnchor = { offset: around.left, size: around.width, position: anchorAlignment === 0 /* LEFT */ ? 0 /* Before */ : 1 /* After */, mode: LayoutAnchorMode.ALIGN }; - top = layout(window.innerHeight, viewSizeHeight, verticalAnchor) + window.pageYOffset; - // if view intersects vertically with anchor, we must avoid the anchor - if (range_1.Range.intersects({ start: top, end: top + viewSizeHeight }, { start: verticalAnchor.offset, end: verticalAnchor.offset + verticalAnchor.size })) { - horizontalAnchor.mode = LayoutAnchorMode.AVOID; - } - left = layout(window.innerWidth, viewSizeWidth, horizontalAnchor); - } - else { - const horizontalAnchor = { offset: around.left, size: around.width, position: anchorAlignment === 0 /* LEFT */ ? 0 /* Before */ : 1 /* After */ }; - const verticalAnchor = { offset: around.top, size: around.height, position: anchorPosition === 0 /* BELOW */ ? 0 /* Before */ : 1 /* After */, mode: LayoutAnchorMode.ALIGN }; - left = layout(window.innerWidth, viewSizeWidth, horizontalAnchor); - // if view intersects horizontally with anchor, we must avoid the anchor - if (range_1.Range.intersects({ start: left, end: left + viewSizeWidth }, { start: horizontalAnchor.offset, end: horizontalAnchor.offset + horizontalAnchor.size })) { - verticalAnchor.mode = LayoutAnchorMode.AVOID; - } - top = layout(window.innerHeight, viewSizeHeight, verticalAnchor) + window.pageYOffset; - } - this.view.classList.remove('top', 'bottom', 'left', 'right'); - this.view.classList.add(anchorPosition === 0 /* BELOW */ ? 'bottom' : 'top'); - this.view.classList.add(anchorAlignment === 0 /* LEFT */ ? 'left' : 'right'); - this.view.classList.toggle('fixed', this.useFixedPosition); - const containerPosition = DOM.getDomNodePagePosition(this.container); - this.view.style.top = `${top - (this.useFixedPosition ? DOM.getDomNodePagePosition(this.view).top : containerPosition.top)}px`; - this.view.style.left = `${left - (this.useFixedPosition ? DOM.getDomNodePagePosition(this.view).left : containerPosition.left)}px`; - this.view.style.width = 'initial'; - } - hide(data) { - const 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); - } - isVisible() { - return !!this.delegate; - } - onDOMEvent(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(); - } - } - } - dispose() { - this.hide(); - super.dispose(); - } - } - exports.ContextView = ContextView; - ContextView.BUBBLE_UP_EVENTS = ['click', 'keydown', 'focus', 'blur']; - ContextView.BUBBLE_DOWN_EVENTS = ['click']; - let SHADOW_ROOT_CSS = /* css */ ` - :host { - all: initial; /* 1st rule so subsequent properties are reset. */ - } - - @font-face { - font-family: "codicon"; - src: url("./codicon.ttf?5d4d76ab2ce5108968ad644d591a16a6") format("truetype"); - } - - .codicon[class*='codicon-'] { - font: normal normal normal 16px/1 codicon; - display: inline-block; - text-decoration: none; - text-rendering: auto; - text-align: center; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; - user-select: none; - -webkit-user-select: none; - -ms-user-select: none; - } - - :host { - font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", system-ui, "Ubuntu", "Droid Sans", sans-serif; - } - - :host-context(.mac) { font-family: -apple-system, BlinkMacSystemFont, sans-serif; } - :host-context(.mac:lang(zh-Hans)) { font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB", sans-serif; } - :host-context(.mac:lang(zh-Hant)) { font-family: -apple-system, BlinkMacSystemFont, "PingFang TC", sans-serif; } - :host-context(.mac:lang(ja)) { font-family: -apple-system, BlinkMacSystemFont, "Hiragino Kaku Gothic Pro", sans-serif; } - :host-context(.mac:lang(ko)) { font-family: -apple-system, BlinkMacSystemFont, "Nanum Gothic", "Apple SD Gothic Neo", "AppleGothic", sans-serif; } - - :host-context(.windows) { font-family: "Segoe WPC", "Segoe UI", sans-serif; } - :host-context(.windows:lang(zh-Hans)) { font-family: "Segoe WPC", "Segoe UI", "Microsoft YaHei", sans-serif; } - :host-context(.windows:lang(zh-Hant)) { font-family: "Segoe WPC", "Segoe UI", "Microsoft Jhenghei", sans-serif; } - :host-context(.windows:lang(ja)) { font-family: "Segoe WPC", "Segoe UI", "Yu Gothic UI", "Meiryo UI", sans-serif; } - :host-context(.windows:lang(ko)) { font-family: "Segoe WPC", "Segoe UI", "Malgun Gothic", "Dotom", sans-serif; } - - :host-context(.linux) { font-family: system-ui, "Ubuntu", "Droid Sans", sans-serif; } - :host-context(.linux:lang(zh-Hans)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans SC", "Source Han Sans CN", "Source Han Sans", sans-serif; } - :host-context(.linux:lang(zh-Hant)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans TC", "Source Han Sans TW", "Source Han Sans", sans-serif; } - :host-context(.linux:lang(ja)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans J", "Source Han Sans JP", "Source Han Sans", sans-serif; } - :host-context(.linux:lang(ko)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans K", "Source Han Sans JR", "Source Han Sans", "UnDotum", "FBaekmuk Gulim", sans-serif; } -`; -}); - -define(__m[309/*vs/css!vs/base/browser/ui/countBadge/countBadge*/], __M([10/*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[208/*vs/base/browser/ui/countBadge/countBadge*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,8/*vs/base/common/strings*/,29/*vs/base/common/color*/,42/*vs/base/common/objects*/,309/*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 }); - exports.CountBadge = void 0; - const defaultOpts = { - badgeBackground: color_1.Color.fromHex('#4D4D4D'), - badgeForeground: color_1.Color.fromHex('#FFFFFF') - }; - class CountBadge { - constructor(container, options) { - this.count = 0; - this.options = options || Object.create(null); - (0, objects_1.mixin)(this.options, defaultOpts, false); - this.badgeBackground = this.options.badgeBackground; - this.badgeForeground = this.options.badgeForeground; - this.badgeBorder = this.options.badgeBorder; - this.element = (0, dom_1.append)(container, (0, dom_1.$)('.monaco-count-badge')); - this.countFormat = this.options.countFormat || '{0}'; - this.titleFormat = this.options.titleFormat || ''; - this.setCount(this.options.count || 0); - } - setCount(count) { - this.count = count; - this.render(); - } - setTitleFormat(titleFormat) { - this.titleFormat = titleFormat; - this.render(); - } - render() { - this.element.textContent = (0, strings_1.format)(this.countFormat, this.count); - this.element.title = (0, strings_1.format)(this.titleFormat, this.count); - this.applyStyles(); - } - style(styles) { - this.badgeBackground = styles.badgeBackground; - this.badgeForeground = styles.badgeForeground; - this.badgeBorder = styles.badgeBorder; - this.applyStyles(); - } - applyStyles() { - if (this.element) { - const background = this.badgeBackground ? this.badgeBackground.toString() : ''; - const foreground = this.badgeForeground ? this.badgeForeground.toString() : ''; - const 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; - } - } - } - exports.CountBadge = CountBadge; -}); - -define(__m[209/*vs/css!vs/base/browser/ui/dropdown/dropdown*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[210/*vs/css!vs/base/browser/ui/findinput/findInput*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[310/*vs/css!vs/base/browser/ui/hover/hover*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[311/*vs/css!vs/base/browser/ui/iconLabel/iconlabel*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[312/*vs/css!vs/base/browser/ui/inputbox/inputBox*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[313/*vs/css!vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[211/*vs/css!vs/base/browser/ui/list/list*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[314/*vs/css!vs/base/browser/ui/mouseCursor/mouseCursor*/], __M([10/*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[131/*vs/base/browser/ui/mouseCursor/mouseCursor*/], __M([0/*require*/,1/*exports*/,314/*vs/css!vs/base/browser/ui/mouseCursor/mouseCursor*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MOUSE_CURSOR_TEXT_CSS_CLASS_NAME = void 0; - exports.MOUSE_CURSOR_TEXT_CSS_CLASS_NAME = `monaco-mouse-cursor-text`; -}); - -define(__m[315/*vs/css!vs/base/browser/ui/progressbar/progressbar*/], __M([10/*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[316/*vs/base/browser/ui/progressbar/progressbar*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,29/*vs/base/common/color*/,42/*vs/base/common/objects*/,7/*vs/base/browser/dom*/,15/*vs/base/common/async*/,315/*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 }); - exports.ProgressBar = void 0; - const CSS_DONE = 'done'; - const CSS_ACTIVE = 'active'; - const CSS_INFINITE = 'infinite'; - const CSS_DISCRETE = 'discrete'; - const defaultOpts = { - progressBarBackground: color_1.Color.fromHex('#0E70C0') - }; - /** - * A progress bar with support for infinite or discrete progress. - */ - class ProgressBar extends lifecycle_1.Disposable { - constructor(container, options) { - super(); - this.options = options || Object.create(null); - (0, objects_1.mixin)(this.options, defaultOpts, false); - this.workedVal = 0; - this.progressBarBackground = this.options.progressBarBackground; - this._register(this.showDelayedScheduler = new async_1.RunOnceScheduler(() => (0, dom_1.show)(this.element), 0)); - this.create(container); - } - create(container) { - this.element = document.createElement('div'); - this.element.classList.add('monaco-progress-container'); - this.element.setAttribute('role', 'progressbar'); - this.element.setAttribute('aria-valuemin', '0'); - container.appendChild(this.element); - this.bit = document.createElement('div'); - this.bit.classList.add('progress-bit'); - this.element.appendChild(this.bit); - this.applyStyles(); - } - off() { - this.bit.style.width = 'inherit'; - this.bit.style.opacity = '1'; - this.element.classList.remove(CSS_ACTIVE, CSS_INFINITE, CSS_DISCRETE); - this.workedVal = 0; - this.totalWork = undefined; - } - /** - * Stops the progressbar from showing any progress instantly without fading out. - */ - stop() { - return this.doDone(false); - } - doDone(delayed) { - this.element.classList.add(CSS_DONE); - // let it grow to 100% width and hide afterwards - if (!this.element.classList.contains(CSS_INFINITE)) { - this.bit.style.width = 'inherit'; - if (delayed) { - setTimeout(() => this.off(), 200); - } - else { - this.off(); - } - } - // let it fade out and hide afterwards - else { - this.bit.style.opacity = '0'; - if (delayed) { - setTimeout(() => this.off(), 200); - } - else { - this.off(); - } - } - return this; - } - /** - * Use this mode to indicate progress that has no total number of work units. - */ - infinite() { - this.bit.style.width = '2%'; - this.bit.style.opacity = '1'; - this.element.classList.remove(CSS_DISCRETE, CSS_DONE); - this.element.classList.add(CSS_ACTIVE, CSS_INFINITE); - return this; - } - getContainer() { - return this.element; - } - style(styles) { - this.progressBarBackground = styles.progressBarBackground; - this.applyStyles(); - } - applyStyles() { - if (this.bit) { - const background = this.progressBarBackground ? this.progressBarBackground.toString() : ''; - this.bit.style.backgroundColor = background; - } - } - } - exports.ProgressBar = ProgressBar; -}); - -define(__m[317/*vs/css!vs/base/browser/ui/sash/sash*/], __M([10/*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[107/*vs/base/browser/ui/sash/sash*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,60/*vs/base/browser/touch*/,6/*vs/base/common/event*/,7/*vs/base/browser/dom*/,91/*vs/base/browser/event*/,15/*vs/base/common/async*/,90/*vs/base/common/decorators*/,317/*vs/css!vs/base/browser/ui/sash/sash*/]), function (require, exports, lifecycle_1, platform_1, touch_1, event_1, dom_1, event_2, async_1, decorators_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Sash = exports.OrthogonalEdge = void 0; - let DEBUG = false; - var OrthogonalEdge; - (function (OrthogonalEdge) { - OrthogonalEdge["North"] = "north"; - OrthogonalEdge["South"] = "south"; - OrthogonalEdge["East"] = "east"; - OrthogonalEdge["West"] = "west"; - })(OrthogonalEdge = exports.OrthogonalEdge || (exports.OrthogonalEdge = {})); - let globalSize = 4; - const onDidChangeGlobalSize = new event_1.Emitter(); - let globalHoverDelay = 300; - const onDidChangeHoverDelay = new event_1.Emitter(); - class MouseEventFactory { - constructor() { - this.disposables = new lifecycle_1.DisposableStore(); - } - get onPointerMove() { - return this.disposables.add(new event_2.DomEmitter(window, 'mousemove')).event; - } - get onPointerUp() { - return this.disposables.add(new event_2.DomEmitter(window, 'mouseup')).event; - } - dispose() { - this.disposables.dispose(); - } - } - __decorate([ - decorators_1.memoize - ], MouseEventFactory.prototype, "onPointerMove", null); - __decorate([ - decorators_1.memoize - ], MouseEventFactory.prototype, "onPointerUp", null); - class GestureEventFactory { - constructor(el) { - this.el = el; - this.disposables = new lifecycle_1.DisposableStore(); - } - get onPointerMove() { - return this.disposables.add(new event_2.DomEmitter(this.el, touch_1.EventType.Change)).event; - } - get onPointerUp() { - return this.disposables.add(new event_2.DomEmitter(this.el, touch_1.EventType.End)).event; - } - dispose() { - this.disposables.dispose(); - } - } - __decorate([ - decorators_1.memoize - ], GestureEventFactory.prototype, "onPointerMove", null); - __decorate([ - decorators_1.memoize - ], GestureEventFactory.prototype, "onPointerUp", null); - class OrthogonalPointerEventFactory { - constructor(factory) { - this.factory = factory; - } - get onPointerMove() { - return this.factory.onPointerMove; - } - get onPointerUp() { - return this.factory.onPointerUp; - } - dispose() { - // noop - } - } - __decorate([ - decorators_1.memoize - ], OrthogonalPointerEventFactory.prototype, "onPointerMove", null); - __decorate([ - decorators_1.memoize - ], OrthogonalPointerEventFactory.prototype, "onPointerUp", null); - class Sash extends lifecycle_1.Disposable { - constructor(container, layoutProvider, options) { - super(); - this.hoverDelay = globalHoverDelay; - this.hoverDelayer = this._register(new async_1.Delayer(this.hoverDelay)); - 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.orthogonalStartDragHandleDisposables = this._register(new lifecycle_1.DisposableStore()); - this.orthogonalEndSashDisposables = this._register(new lifecycle_1.DisposableStore()); - this.orthogonalEndDragHandleDisposables = this._register(new lifecycle_1.DisposableStore()); - this.el = (0, dom_1.append)(container, (0, dom_1.$)('.monaco-sash')); - if (options.orthogonalEdge) { - this.el.classList.add(`orthogonal-edge-${options.orthogonalEdge}`); - } - if (platform_1.isMacintosh) { - this.el.classList.add('mac'); - } - const onMouseDown = this._register(new event_2.DomEmitter(this.el, 'mousedown')).event; - this._register(onMouseDown(e => this.onPointerStart(e, new MouseEventFactory()), this)); - const onMouseDoubleClick = this._register(new event_2.DomEmitter(this.el, 'dblclick')).event; - this._register(onMouseDoubleClick(this.onPointerDoublePress, this)); - const onMouseEnter = this._register(new event_2.DomEmitter(this.el, 'mouseenter')).event; - this._register(onMouseEnter(() => Sash.onMouseEnter(this))); - const onMouseLeave = this._register(new event_2.DomEmitter(this.el, 'mouseleave')).event; - this._register(onMouseLeave(() => Sash.onMouseLeave(this))); - this._register(touch_1.Gesture.addTarget(this.el)); - const onTouchStart = event_1.Event.map(this._register(new event_2.DomEmitter(this.el, touch_1.EventType.Start)).event, e => { var _a; return (Object.assign(Object.assign({}, e), { target: (_a = e.initialTarget) !== null && _a !== void 0 ? _a : null })); }); - this._register(onTouchStart(e => this.onPointerStart(e, new GestureEventFactory(this.el)), this)); - const onTap = this._register(new event_2.DomEmitter(this.el, touch_1.EventType.Tap)).event; - const onDoubleTap = event_1.Event.map(event_1.Event.filter(event_1.Event.debounce(onTap, (res, event) => { var _a; return ({ event, count: ((_a = res === null || res === void 0 ? void 0 : res.count) !== null && _a !== void 0 ? _a : 0) + 1 }); }, 250), ({ count }) => count === 2), ({ event }) => { var _a; return (Object.assign(Object.assign({}, event), { target: (_a = event.initialTarget) !== null && _a !== void 0 ? _a : null })); }); - this._register(onDoubleTap(this.onPointerDoublePress, this)); - if (typeof options.size === 'number') { - this.size = options.size; - if (options.orientation === 0 /* VERTICAL */) { - this.el.style.width = `${this.size}px`; - } - else { - this.el.style.height = `${this.size}px`; - } - } - else { - this.size = globalSize; - this._register(onDidChangeGlobalSize.event(size => { - this.size = size; - this.layout(); - })); - } - this._register(onDidChangeHoverDelay.event(delay => this.hoverDelay = delay)); - this.hidden = false; - this.layoutProvider = layoutProvider; - this.orthogonalStartSash = options.orthogonalStartSash; - this.orthogonalEndSash = options.orthogonalEndSash; - this.orientation = options.orientation || 0 /* VERTICAL */; - if (this.orientation === 1 /* HORIZONTAL */) { - this.el.classList.add('horizontal'); - this.el.classList.remove('vertical'); - } - else { - this.el.classList.remove('horizontal'); - this.el.classList.add('vertical'); - } - this.el.classList.toggle('debug', DEBUG); - this.layout(); - } - get state() { return this._state; } - set state(state) { - if (this._state === state) { - return; - } - this.el.classList.toggle('disabled', state === 0 /* Disabled */); - this.el.classList.toggle('minimum', state === 1 /* Minimum */); - this.el.classList.toggle('maximum', state === 2 /* Maximum */); - this._state = state; - this._onDidEnablementChange.fire(state); - } - get orthogonalStartSash() { return this._orthogonalStartSash; } - set orthogonalStartSash(sash) { - this.orthogonalStartDragHandleDisposables.clear(); - this.orthogonalStartSashDisposables.clear(); - if (sash) { - const onChange = (state) => { - this.orthogonalStartDragHandleDisposables.clear(); - if (state !== 0 /* Disabled */) { - this._orthogonalStartDragHandle = (0, dom_1.append)(this.el, (0, dom_1.$)('.orthogonal-drag-handle.start')); - this.orthogonalStartDragHandleDisposables.add((0, lifecycle_1.toDisposable)(() => this._orthogonalStartDragHandle.remove())); - this.orthogonalStartDragHandleDisposables.add(new event_2.DomEmitter(this._orthogonalStartDragHandle, 'mouseenter')).event(() => Sash.onMouseEnter(sash), undefined, this.orthogonalStartDragHandleDisposables); - this.orthogonalStartDragHandleDisposables.add(new event_2.DomEmitter(this._orthogonalStartDragHandle, 'mouseleave')).event(() => Sash.onMouseLeave(sash), undefined, this.orthogonalStartDragHandleDisposables); - } - }; - this.orthogonalStartSashDisposables.add(sash.onDidEnablementChange(onChange, this)); - onChange(sash.state); - } - this._orthogonalStartSash = sash; - } - get orthogonalEndSash() { return this._orthogonalEndSash; } - set orthogonalEndSash(sash) { - this.orthogonalEndDragHandleDisposables.clear(); - this.orthogonalEndSashDisposables.clear(); - if (sash) { - const onChange = (state) => { - this.orthogonalEndDragHandleDisposables.clear(); - if (state !== 0 /* Disabled */) { - this._orthogonalEndDragHandle = (0, dom_1.append)(this.el, (0, dom_1.$)('.orthogonal-drag-handle.end')); - this.orthogonalEndDragHandleDisposables.add((0, lifecycle_1.toDisposable)(() => this._orthogonalEndDragHandle.remove())); - this.orthogonalEndDragHandleDisposables.add(new event_2.DomEmitter(this._orthogonalEndDragHandle, 'mouseenter')).event(() => Sash.onMouseEnter(sash), undefined, this.orthogonalEndDragHandleDisposables); - this.orthogonalEndDragHandleDisposables.add(new event_2.DomEmitter(this._orthogonalEndDragHandle, 'mouseleave')).event(() => Sash.onMouseLeave(sash), undefined, this.orthogonalEndDragHandleDisposables); - } - }; - this.orthogonalEndSashDisposables.add(sash.onDidEnablementChange(onChange, this)); - onChange(sash.state); - } - this._orthogonalEndSash = sash; - } - onPointerStart(event, pointerEventFactory) { - dom_1.EventHelper.stop(event); - let isMultisashResize = false; - if (!event.__orthogonalSashEvent) { - const orthogonalSash = this.getOrthogonalSash(event); - if (orthogonalSash) { - isMultisashResize = true; - event.__orthogonalSashEvent = true; - orthogonalSash.onPointerStart(event, new OrthogonalPointerEventFactory(pointerEventFactory)); - } - } - if (this.linkedSash && !event.__linkedSashEvent) { - event.__linkedSashEvent = true; - this.linkedSash.onPointerStart(event, new OrthogonalPointerEventFactory(pointerEventFactory)); - } - if (!this.state) { - return; - } - const iframes = (0, dom_1.getElementsByTagName)('iframe'); - for (const iframe of iframes) { - iframe.style.pointerEvents = 'none'; // disable mouse events on iframes as long as we drag the sash - } - const startX = event.pageX; - const startY = event.pageY; - const altKey = event.altKey; - const startEvent = { startX, currentX: startX, startY, currentY: startY, altKey }; - this.el.classList.add('active'); - this._onDidStart.fire(startEvent); - // fix https://github.com/microsoft/vscode/issues/21675 - const style = (0, dom_1.createStyleSheet)(this.el); - const updateStyle = () => { - let 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.textContent = `* { cursor: ${cursor} !important; }`; - }; - const disposables = new lifecycle_1.DisposableStore(); - updateStyle(); - if (!isMultisashResize) { - this.onDidEnablementChange(updateStyle, null, disposables); - } - const onPointerMove = (e) => { - dom_1.EventHelper.stop(e, false); - const event = { startX, currentX: e.pageX, startY, currentY: e.pageY, altKey }; - this._onDidChange.fire(event); - }; - const onPointerUp = (e) => { - dom_1.EventHelper.stop(e, false); - this.el.removeChild(style); - this.el.classList.remove('active'); - this._onDidEnd.fire(); - disposables.dispose(); - for (const iframe of iframes) { - iframe.style.pointerEvents = 'auto'; - } - }; - pointerEventFactory.onPointerMove(onPointerMove, null, disposables); - pointerEventFactory.onPointerUp(onPointerUp, null, disposables); - disposables.add(pointerEventFactory); - } - onPointerDoublePress(e) { - const orthogonalSash = this.getOrthogonalSash(e); - if (orthogonalSash) { - orthogonalSash._onDidReset.fire(); - } - if (this.linkedSash) { - this.linkedSash._onDidReset.fire(); - } - this._onDidReset.fire(); - } - static onMouseEnter(sash, fromLinkedSash = false) { - if (sash.el.classList.contains('active')) { - sash.hoverDelayer.cancel(); - sash.el.classList.add('hover'); - } - else { - sash.hoverDelayer.trigger(() => sash.el.classList.add('hover'), sash.hoverDelay).then(undefined, () => { }); - } - if (!fromLinkedSash && sash.linkedSash) { - Sash.onMouseEnter(sash.linkedSash, true); - } - } - static onMouseLeave(sash, fromLinkedSash = false) { - sash.hoverDelayer.cancel(); - sash.el.classList.remove('hover'); - if (!fromLinkedSash && sash.linkedSash) { - Sash.onMouseLeave(sash.linkedSash, true); - } - } - clearSashHoverState() { - Sash.onMouseLeave(this); - } - layout() { - if (this.orientation === 0 /* VERTICAL */) { - const verticalProvider = this.layoutProvider; - this.el.style.left = verticalProvider.getVerticalSashLeft(this) - (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 { - const horizontalProvider = this.layoutProvider; - this.el.style.top = horizontalProvider.getHorizontalSashTop(this) - (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'; - } - } - } - hide() { - this.hidden = true; - this.el.style.display = 'none'; - this.el.setAttribute('aria-hidden', 'true'); - } - getOrthogonalSash(e) { - if (!e.target || !(e.target instanceof HTMLElement)) { - return undefined; - } - if (e.target.classList.contains('orthogonal-drag-handle')) { - return e.target.classList.contains('start') ? this.orthogonalStartSash : this.orthogonalEndSash; - } - return undefined; - } - dispose() { - super.dispose(); - this.el.remove(); - } - } - exports.Sash = Sash; -}); - -define(__m[318/*vs/css!vs/base/browser/ui/scrollbar/media/scrollbars*/], __M([10/*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[61/*vs/base/browser/ui/scrollbar/scrollableElement*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,30/*vs/base/browser/fastDomNode*/,55/*vs/base/browser/mouseEvent*/,296/*vs/base/browser/ui/scrollbar/horizontalScrollbar*/,297/*vs/base/browser/ui/scrollbar/verticalScrollbar*/,52/*vs/base/browser/ui/widget*/,15/*vs/base/common/async*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,127/*vs/base/common/scrollable*/,39/*vs/base/browser/browser*/,318/*vs/css!vs/base/browser/ui/scrollbar/media/scrollbars*/]), function (require, exports, dom, fastDomNode_1, mouseEvent_1, horizontalScrollbar_1, verticalScrollbar_1, widget_1, async_1, event_1, lifecycle_1, platform, scrollable_1, browser_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DomScrollableElement = exports.SmoothScrollableElement = exports.ScrollableElement = exports.AbstractScrollableElement = exports.MouseWheelClassifier = void 0; - const HIDE_TIMEOUT = 500; - const SCROLL_WHEEL_SENSITIVITY = 50; - const SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED = true; - class MouseWheelClassifierItem { - constructor(timestamp, deltaX, deltaY) { - this.timestamp = timestamp; - this.deltaX = deltaX; - this.deltaY = deltaY; - this.score = 0; - } - } - class MouseWheelClassifier { - constructor() { - this._capacity = 5; - this._memory = []; - this._front = -1; - this._rear = -1; - } - isPhysicalMouseWheel() { - if (this._front === -1 && this._rear === -1) { - // no elements - return false; - } - // 0.5 * last + 0.25 * 2nd last + 0.125 * 3rd last + ... - let remainingInfluence = 1; - let score = 0; - let iteration = 1; - let index = this._rear; - do { - const 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); - } - accept(timestamp, deltaX, deltaY) { - const 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. - */ - _computeScore(item) { - if (Math.abs(item.deltaX) > 0 && Math.abs(item.deltaY) > 0) { - // both axes exercised => definitely not a physical mouse wheel - return 1; - } - let score = 0.5; - const 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 (!this._isAlmostInt(item.deltaX) || !this._isAlmostInt(item.deltaY)) { - // non-integer deltas => indicator that this is not a physical mouse wheel - score += 0.25; - } - return Math.min(Math.max(score, 0), 1); - } - _isAlmostInt(value) { - const delta = Math.abs(Math.round(value) - value); - return (delta < 0.01); - } - } - exports.MouseWheelClassifier = MouseWheelClassifier; - MouseWheelClassifier.INSTANCE = new MouseWheelClassifier(); - class AbstractScrollableElement extends widget_1.Widget { - constructor(element, options, scrollable) { - super(); - this._onScroll = this._register(new event_1.Emitter()); - this.onScroll = this._onScroll.event; - this._onWillScroll = this._register(new event_1.Emitter()); - element.style.overflow = 'hidden'; - this._options = resolveOptions(options); - this._scrollable = scrollable; - this._register(this._scrollable.onScroll((e) => { - this._onWillScroll.fire(e); - this._onDidScroll(e); - this._onScroll.fire(e); - })); - const scrollbarHost = { - onMouseWheel: (mouseWheelEvent) => this._onMouseWheel(mouseWheelEvent), - onDragStart: () => this._onDragStart(), - onDragEnd: () => 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 = (0, fastDomNode_1.createFastDomNode)(document.createElement('div')); - this._leftShadowDomNode.setClassName('shadow'); - this._domNode.appendChild(this._leftShadowDomNode.domNode); - this._topShadowDomNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div')); - this._topShadowDomNode.setClassName('shadow'); - this._domNode.appendChild(this._topShadowDomNode.domNode); - this._topLeftShadowDomNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div')); - this._topLeftShadowDomNode.setClassName('shadow'); - 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, (e) => this._onMouseOver(e)); - this.onnonbubblingmouseout(this._listenOnDomNode, (e) => this._onMouseOut(e)); - this._hideTimeout = this._register(new async_1.TimeoutTimer()); - this._isDragging = false; - this._mouseIsOver = false; - this._shouldRender = true; - this._revealOnScroll = true; - } - dispose() { - this._mouseWheelToDispose = (0, lifecycle_1.dispose)(this._mouseWheelToDispose); - super.dispose(); - } - /** - * Get the generated 'scrollable' dom node - */ - getDomNode() { - return this._domNode; - } - getOverviewRulerLayoutInfo() { - 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. - */ - delegateVerticalScrollbarMouseDown(browserEvent) { - this._verticalScrollbar.delegateMouseDown(browserEvent); - } - getScrollDimensions() { - return this._scrollable.getScrollDimensions(); - } - setScrollDimensions(dimensions) { - this._scrollable.setScrollDimensions(dimensions, false); - } - /** - * Update the class name of the scrollable element. - */ - updateClassName(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. - */ - updateOptions(newOptions) { - if (typeof newOptions.handleMouseWheel !== 'undefined') { - this._options.handleMouseWheel = newOptions.handleMouseWheel; - this._setListeningToMouseWheel(this._options.handleMouseWheel); - } - if (typeof newOptions.mouseWheelScrollSensitivity !== 'undefined') { - this._options.mouseWheelScrollSensitivity = newOptions.mouseWheelScrollSensitivity; - } - if (typeof newOptions.fastScrollSensitivity !== 'undefined') { - this._options.fastScrollSensitivity = newOptions.fastScrollSensitivity; - } - if (typeof newOptions.scrollPredominantAxis !== 'undefined') { - this._options.scrollPredominantAxis = newOptions.scrollPredominantAxis; - } - if (typeof newOptions.horizontal !== 'undefined') { - this._options.horizontal = newOptions.horizontal; - } - if (typeof newOptions.vertical !== 'undefined') { - this._options.vertical = newOptions.vertical; - } - if (typeof newOptions.horizontalScrollbarSize !== 'undefined') { - this._options.horizontalScrollbarSize = newOptions.horizontalScrollbarSize; - } - if (typeof newOptions.verticalScrollbarSize !== 'undefined') { - this._options.verticalScrollbarSize = newOptions.verticalScrollbarSize; - } - if (typeof newOptions.scrollByPage !== 'undefined') { - this._options.scrollByPage = newOptions.scrollByPage; - } - this._horizontalScrollbar.updateOptions(this._options); - this._verticalScrollbar.updateOptions(this._options); - if (!this._options.lazyRender) { - this._render(); - } - } - // -------------------- mouse wheel scrolling -------------------- - _setListeningToMouseWheel(shouldListen) { - const isListening = (this._mouseWheelToDispose.length > 0); - if (isListening === shouldListen) { - // No change - return; - } - // Stop listening (if necessary) - this._mouseWheelToDispose = (0, lifecycle_1.dispose)(this._mouseWheelToDispose); - // Start listening (if necessary) - if (shouldListen) { - const onMouseWheel = (browserEvent) => { - this._onMouseWheel(new mouseEvent_1.StandardWheelEvent(browserEvent)); - }; - this._mouseWheelToDispose.push(dom.addDisposableListener(this._listenOnDomNode, dom.EventType.MOUSE_WHEEL, onMouseWheel, { passive: false })); - } - } - _onMouseWheel(e) { - const classifier = MouseWheelClassifier.INSTANCE; - if (SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED) { - const osZoomFactor = window.devicePixelRatio / (0, browser_1.getZoomFactor)(); - if (platform.isWindows || platform.isLinux) { - // On Windows and Linux, the incoming delta events are multiplied with the OS zoom factor. - // The OS zoom factor can be reverse engineered by using the device pixel ratio and the configured zoom factor into account. - classifier.accept(Date.now(), e.deltaX / osZoomFactor, e.deltaY / osZoomFactor); - } - else { - classifier.accept(Date.now(), e.deltaX, e.deltaY); - } - } - // console.log(`${Date.now()}, ${e.deltaY}, ${e.deltaX}`); - let didScroll = false; - if (e.deltaY || e.deltaX) { - let deltaY = e.deltaY * this._options.mouseWheelScrollSensitivity; - let deltaX = e.deltaX * this._options.mouseWheelScrollSensitivity; - if (this._options.scrollPredominantAxis) { - if (Math.abs(deltaY) >= Math.abs(deltaX)) { - deltaX = 0; - } - else { - deltaY = 0; - } - } - if (this._options.flipAxes) { - [deltaY, deltaX] = [deltaX, deltaY]; - } - // Convert vertical scrolling to horizontal if shift is held, this - // is handled at a higher level on Mac - const 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; - } - const futureScrollPosition = this._scrollable.getFutureScrollPosition(); - let desiredScrollPosition = {}; - if (deltaY) { - const desiredScrollTop = futureScrollPosition.scrollTop - SCROLL_WHEEL_SENSITIVITY * deltaY; - this._verticalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollTop); - } - if (deltaX) { - const 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) { - const canPerformSmoothScroll = (SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED - && this._options.mouseWheelSmoothScroll - && classifier.isPhysicalMouseWheel()); - if (canPerformSmoothScroll) { - this._scrollable.setScrollPositionSmooth(desiredScrollPosition); - } - else { - this._scrollable.setScrollPositionNow(desiredScrollPosition); - } - didScroll = true; - } - } - let consumeMouseWheel = didScroll; - if (!consumeMouseWheel && this._options.alwaysConsumeMouseWheel) { - consumeMouseWheel = true; - } - if (!consumeMouseWheel && this._options.consumeMouseWheelIfScrollbarIsNeeded && (this._verticalScrollbar.isNeeded() || this._horizontalScrollbar.isNeeded())) { - consumeMouseWheel = true; - } - if (consumeMouseWheel) { - e.preventDefault(); - e.stopPropagation(); - } - } - _onDidScroll(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`. - */ - renderNow() { - if (!this._options.lazyRender) { - throw new Error('Please use `lazyRender` together with `renderNow`!'); - } - this._render(); - } - _render() { - if (!this._shouldRender) { - return; - } - this._shouldRender = false; - this._horizontalScrollbar.render(); - this._verticalScrollbar.render(); - if (this._options.useShadows) { - const scrollState = this._scrollable.getCurrentScrollPosition(); - const enableTop = scrollState.scrollTop > 0; - const enableLeft = scrollState.scrollLeft > 0; - const leftClassName = (enableLeft ? ' left' : ''); - const topClassName = (enableTop ? ' top' : ''); - const topLeftClassName = (enableLeft || enableTop ? ' top-left-corner' : ''); - this._leftShadowDomNode.setClassName(`shadow${leftClassName}`); - this._topShadowDomNode.setClassName(`shadow${topClassName}`); - this._topLeftShadowDomNode.setClassName(`shadow${topLeftClassName}${topClassName}${leftClassName}`); - } - } - // -------------------- fade in / fade out -------------------- - _onDragStart() { - this._isDragging = true; - this._reveal(); - } - _onDragEnd() { - this._isDragging = false; - this._hide(); - } - _onMouseOut(e) { - this._mouseIsOver = false; - this._hide(); - } - _onMouseOver(e) { - this._mouseIsOver = true; - this._reveal(); - } - _reveal() { - this._verticalScrollbar.beginReveal(); - this._horizontalScrollbar.beginReveal(); - this._scheduleHide(); - } - _hide() { - if (!this._mouseIsOver && !this._isDragging) { - this._verticalScrollbar.beginHide(); - this._horizontalScrollbar.beginHide(); - } - } - _scheduleHide() { - if (!this._mouseIsOver && !this._isDragging) { - this._hideTimeout.cancelAndSet(() => this._hide(), HIDE_TIMEOUT); - } - } - } - exports.AbstractScrollableElement = AbstractScrollableElement; - class ScrollableElement extends AbstractScrollableElement { - constructor(element, options) { - options = options || {}; - options.mouseWheelSmoothScroll = false; - const scrollable = new scrollable_1.Scrollable(0, (callback) => dom.scheduleAtNextAnimationFrame(callback)); - super(element, options, scrollable); - this._register(scrollable); - } - setScrollPosition(update) { - this._scrollable.setScrollPositionNow(update); - } - } - exports.ScrollableElement = ScrollableElement; - class SmoothScrollableElement extends AbstractScrollableElement { - constructor(element, options, scrollable) { - super(element, options, scrollable); - } - setScrollPosition(update) { - if (update.reuseAnimation) { - this._scrollable.setScrollPositionSmooth(update, update.reuseAnimation); - } - else { - this._scrollable.setScrollPositionNow(update); - } - } - getScrollPosition() { - return this._scrollable.getCurrentScrollPosition(); - } - } - exports.SmoothScrollableElement = SmoothScrollableElement; - class DomScrollableElement extends ScrollableElement { - constructor(element, options) { - super(element, options); - this._element = element; - this.onScroll((e) => { - if (e.scrollTopChanged) { - this._element.scrollTop = e.scrollTop; - } - if (e.scrollLeftChanged) { - this._element.scrollLeft = e.scrollLeft; - } - }); - this.scanDomNode(); - } - scanDomNode() { - // 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, - }); - } - } - exports.DomScrollableElement = DomScrollableElement; - function resolveOptions(opts) { - const 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), - consumeMouseWheelIfScrollbarIsNeeded: (typeof opts.consumeMouseWheelIfScrollbarIsNeeded !== 'undefined' ? opts.consumeMouseWheelIfScrollbarIsNeeded : 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), - scrollPredominantAxis: (typeof opts.scrollPredominantAxis !== 'undefined' ? opts.scrollPredominantAxis : true), - 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), - scrollByPage: (typeof opts.scrollByPage !== 'undefined' ? opts.scrollByPage : false) - }; - 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. - *--------------------------------------------------------------------------------------------*/ -define(__m[319/*vs/base/browser/ui/hover/hoverWidget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,61/*vs/base/browser/ui/scrollbar/scrollableElement*/,310/*vs/css!vs/base/browser/ui/hover/hover*/]), function (require, exports, dom, lifecycle_1, scrollableElement_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.HoverAction = exports.HoverWidget = void 0; - const $ = dom.$; - class HoverWidget extends lifecycle_1.Disposable { - constructor() { - super(); - this.containerDomNode = document.createElement('div'); - this.containerDomNode.className = 'monaco-hover'; - this.containerDomNode.tabIndex = 0; - this.containerDomNode.setAttribute('role', 'tooltip'); - this.contentsDomNode = document.createElement('div'); - this.contentsDomNode.className = 'monaco-hover-content'; - this._scrollbar = this._register(new scrollableElement_1.DomScrollableElement(this.contentsDomNode, { - consumeMouseWheelIfScrollbarIsNeeded: true - })); - this.containerDomNode.appendChild(this._scrollbar.getDomNode()); - } - onContentsChanged() { - this._scrollbar.scanDomNode(); - } - } - exports.HoverWidget = HoverWidget; - class HoverAction extends lifecycle_1.Disposable { - constructor(parent, actionOptions, keybindingLabel) { - super(); - this.actionContainer = dom.append(parent, $('div.action-container')); - this.action = dom.append(this.actionContainer, $('a.action')); - this.action.setAttribute('href', '#'); - this.action.setAttribute('role', 'button'); - if (actionOptions.iconClass) { - dom.append(this.action, $(`span.icon.${actionOptions.iconClass}`)); - } - const label = dom.append(this.action, $('span')); - label.textContent = keybindingLabel ? `${actionOptions.label} (${keybindingLabel})` : actionOptions.label; - this._register(dom.addDisposableListener(this.actionContainer, dom.EventType.CLICK, e => { - e.stopPropagation(); - e.preventDefault(); - actionOptions.run(this.actionContainer); - })); - this.setEnabled(true); - } - static render(parent, actionOptions, keybindingLabel) { - return new HoverAction(parent, actionOptions, keybindingLabel); - } - setEnabled(enabled) { - if (enabled) { - this.actionContainer.classList.remove('disabled'); - this.actionContainer.removeAttribute('aria-disabled'); - } - else { - this.actionContainer.classList.add('disabled'); - this.actionContainer.setAttribute('aria-disabled', 'true'); - } - } - } - exports.HoverAction = HoverAction; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - - - - - - -define(__m[166/*vs/base/browser/ui/list/listView*/], __M([0/*require*/,1/*exports*/,42/*vs/base/common/objects*/,2/*vs/base/common/lifecycle*/,60/*vs/base/browser/touch*/,6/*vs/base/common/event*/,61/*vs/base/browser/ui/scrollbar/scrollableElement*/,127/*vs/base/common/scrollable*/,289/*vs/base/browser/ui/list/rangeMap*/,295/*vs/base/browser/ui/list/rowCache*/,90/*vs/base/common/decorators*/,126/*vs/base/common/range*/,19/*vs/base/common/arrays*/,164/*vs/base/browser/dnd*/,15/*vs/base/common/async*/,39/*vs/base/browser/browser*/,7/*vs/base/browser/dom*/,91/*vs/base/browser/event*/]), function (require, exports, objects_1, lifecycle_1, touch_1, event_1, scrollableElement_1, scrollable_1, rangeMap_1, rowCache_1, decorators_1, range_1, arrays_1, dnd_1, async_1, browser_1, dom_1, event_2) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ListView = exports.NativeDragAndDropData = exports.ExternalElementsDragAndDropData = exports.ElementsDragAndDropData = void 0; - const DefaultOptions = { - useShadows: true, - verticalScrollMode: 1 /* Auto */, - setRowLineHeight: true, - setRowHeight: true, - supportDynamicHeights: false, - dnd: { - getDragElements(e) { return [e]; }, - getDragURI() { return null; }, - onDragStart() { }, - onDragOver() { return false; }, - drop() { } - }, - horizontalScrolling: false, - transformOptimization: true, - alwaysConsumeMouseWheel: true, - }; - class ElementsDragAndDropData { - constructor(elements) { - this.elements = elements; - } - update() { } - getData() { - return this.elements; - } - } - exports.ElementsDragAndDropData = ElementsDragAndDropData; - class ExternalElementsDragAndDropData { - constructor(elements) { - this.elements = elements; - } - update() { } - getData() { - return this.elements; - } - } - exports.ExternalElementsDragAndDropData = ExternalElementsDragAndDropData; - class NativeDragAndDropData { - constructor() { - this.types = []; - this.files = []; - } - update(dataTransfer) { - if (dataTransfer.types) { - this.types.splice(0, this.types.length, ...dataTransfer.types); - } - if (dataTransfer.files) { - this.files.splice(0, this.files.length); - for (let i = 0; i < dataTransfer.files.length; i++) { - const file = dataTransfer.files.item(i); - if (file && (file.size || file.type)) { - this.files.push(file); - } - } - } - } - getData() { - return { - types: this.types, - files: this.files - }; - } - } - exports.NativeDragAndDropData = NativeDragAndDropData; - function equalsDragFeedback(f1, f2) { - if (Array.isArray(f1) && Array.isArray(f2)) { - return (0, arrays_1.equals)(f1, f2); - } - return f1 === f2; - } - class ListViewAccessibilityProvider { - constructor(accessibilityProvider) { - if (accessibilityProvider === null || accessibilityProvider === void 0 ? void 0 : accessibilityProvider.getSetSize) { - this.getSetSize = accessibilityProvider.getSetSize.bind(accessibilityProvider); - } - else { - this.getSetSize = (e, i, l) => l; - } - if (accessibilityProvider === null || accessibilityProvider === void 0 ? void 0 : accessibilityProvider.getPosInSet) { - this.getPosInSet = accessibilityProvider.getPosInSet.bind(accessibilityProvider); - } - else { - this.getPosInSet = (e, i) => i + 1; - } - if (accessibilityProvider === null || accessibilityProvider === void 0 ? void 0 : accessibilityProvider.getRole) { - this.getRole = accessibilityProvider.getRole.bind(accessibilityProvider); - } - else { - this.getRole = _ => 'listitem'; - } - if (accessibilityProvider === null || accessibilityProvider === void 0 ? void 0 : accessibilityProvider.isChecked) { - this.isChecked = accessibilityProvider.isChecked.bind(accessibilityProvider); - } - else { - this.isChecked = _ => undefined; - } - } - } - class ListView { - constructor(container, virtualDelegate, renderers, 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(); - this._horizontalScrolling = false; - 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 (const renderer of renderers) { - 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'; - this.domNode.classList.add(this.domId); - this.domNode.tabIndex = 0; - this.domNode.classList.toggle('mouse-support', typeof options.mouseSupport === 'boolean' ? options.mouseSupport : true); - this._horizontalScrolling = (0, objects_1.getOrDefault)(options, o => o.horizontalScrolling, DefaultOptions.horizontalScrolling); - this.domNode.classList.toggle('horizontal-scrolling', this._horizontalScrolling); - this.additionalScrollHeight = typeof options.additionalScrollHeight === 'undefined' ? 0 : options.additionalScrollHeight; - this.accessibilityProvider = new ListViewAccessibilityProvider(options.accessibilityProvider); - this.rowsContainer = document.createElement('div'); - this.rowsContainer.className = 'monaco-list-rows'; - const transformOptimization = (0, objects_1.getOrDefault)(options, o => o.transformOptimization, DefaultOptions.transformOptimization); - if (transformOptimization) { - this.rowsContainer.style.transform = 'translate3d(0px, 0px, 0px)'; - } - this.disposables.add(touch_1.Gesture.addTarget(this.rowsContainer)); - this.scrollable = new scrollable_1.Scrollable((0, objects_1.getOrDefault)(options, o => o.smoothScrolling, false) ? 125 : 0, cb => (0, dom_1.scheduleAtNextAnimationFrame)(cb)); - this.scrollableElement = this.disposables.add(new scrollableElement_1.SmoothScrollableElement(this.rowsContainer, { - alwaysConsumeMouseWheel: (0, objects_1.getOrDefault)(options, o => o.alwaysConsumeMouseWheel, DefaultOptions.alwaysConsumeMouseWheel), - horizontal: 1 /* Auto */, - vertical: (0, objects_1.getOrDefault)(options, o => o.verticalScrollMode, DefaultOptions.verticalScrollMode), - useShadows: (0, objects_1.getOrDefault)(options, o => o.useShadows, DefaultOptions.useShadows), - mouseWheelScrollSensitivity: options.mouseWheelScrollSensitivity, - fastScrollSensitivity: options.fastScrollSensitivity - }, this.scrollable)); - this.domNode.appendChild(this.scrollableElement.getDomNode()); - container.appendChild(this.domNode); - this.scrollableElement.onScroll(this.onScroll, this, this.disposables); - this.disposables.add((0, dom_1.addDisposableListener)(this.rowsContainer, touch_1.EventType.Change, e => this.onTouchChange(e))); - // Prevent the monaco-scrollable-element from scrolling - // https://github.com/microsoft/vscode/issues/44181 - this.disposables.add((0, dom_1.addDisposableListener)(this.scrollableElement.getDomNode(), 'scroll', e => e.target.scrollTop = 0)); - this.disposables.add((0, dom_1.addDisposableListener)(this.domNode, 'dragover', e => this.onDragOver(this.toDragEvent(e)))); - this.disposables.add((0, dom_1.addDisposableListener)(this.domNode, 'drop', e => this.onDrop(this.toDragEvent(e)))); - this.disposables.add((0, dom_1.addDisposableListener)(this.domNode, 'dragleave', e => this.onDragLeave(this.toDragEvent(e)))); - this.disposables.add((0, dom_1.addDisposableListener)(this.domNode, 'dragend', e => this.onDragEnd(e))); - this.setRowLineHeight = (0, objects_1.getOrDefault)(options, o => o.setRowLineHeight, DefaultOptions.setRowLineHeight); - this.setRowHeight = (0, objects_1.getOrDefault)(options, o => o.setRowHeight, DefaultOptions.setRowHeight); - this.supportDynamicHeights = (0, objects_1.getOrDefault)(options, o => o.supportDynamicHeights, DefaultOptions.supportDynamicHeights); - this.dnd = (0, objects_1.getOrDefault)(options, o => o.dnd, DefaultOptions.dnd); - this.layout(); - } - get contentHeight() { return this.rangeMap.size; } - get horizontalScrolling() { return this._horizontalScrolling; } - set horizontalScrolling(value) { - if (value === this._horizontalScrolling) { - return; - } - if (value && this.supportDynamicHeights) { - throw new Error('Horizontal scrolling and dynamic heights not supported simultaneously'); - } - this._horizontalScrolling = value; - this.domNode.classList.toggle('horizontal-scrolling', this._horizontalScrolling); - if (this._horizontalScrolling) { - for (const item of this.items) { - this.measureItemWidth(item); - } - this.updateScrollWidth(); - this.scrollableElement.setScrollDimensions({ width: (0, dom_1.getContentWidth)(this.domNode) }); - this.rowsContainer.style.width = `${Math.max(this.scrollWidth || 0, this.renderWidth)}px`; - } - else { - this.scrollableElementWidthDelayer.cancel(); - this.scrollableElement.setScrollDimensions({ width: this.renderWidth, scrollWidth: this.renderWidth }); - this.rowsContainer.style.width = ''; - } - } - updateOptions(options) { - if (options.additionalScrollHeight !== undefined) { - this.additionalScrollHeight = options.additionalScrollHeight; - this.scrollableElement.setScrollDimensions({ scrollHeight: this.scrollHeight }); - } - if (options.smoothScrolling !== undefined) { - this.scrollable.setSmoothScrollDuration(options.smoothScrolling ? 125 : 0); - } - if (options.horizontalScrolling !== undefined) { - this.horizontalScrolling = options.horizontalScrolling; - } - if (options.mouseWheelScrollSensitivity !== undefined) { - this.scrollableElement.updateOptions({ mouseWheelScrollSensitivity: options.mouseWheelScrollSensitivity }); - } - if (options.fastScrollSensitivity !== undefined) { - this.scrollableElement.updateOptions({ fastScrollSensitivity: options.fastScrollSensitivity }); - } - } - splice(start, deleteCount, 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); - } - } - _splice(start, deleteCount, elements = []) { - const previousRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight); - const deleteRange = { start, end: start + deleteCount }; - const removeRange = range_1.Range.intersect(previousRenderRange, deleteRange); - // try to reuse rows, avoid removing them from DOM - const rowsToDispose = new Map(); - for (let i = removeRange.start; i < removeRange.end; i++) { - const item = this.items[i]; - item.dragStartDisposable.dispose(); - if (item.row) { - let rows = rowsToDispose.get(item.templateId); - if (!rows) { - rows = []; - rowsToDispose.set(item.templateId, rows); - } - const renderer = this.renderers.get(item.templateId); - if (renderer && renderer.disposeElement) { - renderer.disposeElement(item.element, i, item.row.templateData, item.size); - } - rows.push(item.row); - } - item.row = null; - } - const previousRestRange = { start: start + deleteCount, end: this.items.length }; - const previousRenderedRestRange = range_1.Range.intersect(previousRestRange, previousRenderRange); - const previousUnrenderedRestRanges = range_1.Range.relativeComplement(previousRestRange, previousRenderRange); - const inserted = elements.map(element => ({ - id: String(this.itemId++), - 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 - })); - let 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); - deleted = this.items; - this.items = inserted; - } - else { - this.rangeMap.splice(start, deleteCount, inserted); - deleted = this.items.splice(start, deleteCount, ...inserted); - } - const delta = elements.length - deleteCount; - const renderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight); - const renderedRestRange = (0, rangeMap_1.shift)(previousRenderedRestRange, delta); - const updateRange = range_1.Range.intersect(renderRange, renderedRestRange); - for (let i = updateRange.start; i < updateRange.end; i++) { - this.updateItemInDOM(this.items[i], i); - } - const removeRanges = range_1.Range.relativeComplement(renderedRestRange, renderRange); - for (const range of removeRanges) { - for (let i = range.start; i < range.end; i++) { - this.removeItemFromDOM(i); - } - } - const unrenderedRestRanges = previousUnrenderedRestRanges.map(r => (0, rangeMap_1.shift)(r, delta)); - const elementsRange = { start, end: start + elements.length }; - const insertRanges = [elementsRange, ...unrenderedRestRanges].map(r => range_1.Range.intersect(renderRange, r)); - const beforeElement = this.getNextToLastElement(insertRanges); - for (const range of insertRanges) { - for (let i = range.start; i < range.end; i++) { - const item = this.items[i]; - const rows = rowsToDispose.get(item.templateId); - const row = rows === null || rows === void 0 ? void 0 : rows.pop(); - this.insertItemInDOM(i, beforeElement, row); - } - } - for (const rows of rowsToDispose.values()) { - for (const row of rows) { - this.cache.release(row); - } - } - this.eventuallyUpdateScrollDimensions(); - if (this.supportDynamicHeights) { - this._rerender(this.scrollTop, this.renderHeight); - } - return deleted.map(i => i.element); - } - eventuallyUpdateScrollDimensions() { - this._scrollHeight = this.contentHeight; - this.rowsContainer.style.height = `${this._scrollHeight}px`; - if (!this.scrollableElementUpdateDisposable) { - this.scrollableElementUpdateDisposable = (0, dom_1.scheduleAtNextAnimationFrame)(() => { - this.scrollableElement.setScrollDimensions({ scrollHeight: this.scrollHeight }); - this.updateScrollWidth(); - this.scrollableElementUpdateDisposable = null; - }); - } - } - eventuallyUpdateScrollWidth() { - if (!this.horizontalScrolling) { - this.scrollableElementWidthDelayer.cancel(); - return; - } - this.scrollableElementWidthDelayer.trigger(() => this.updateScrollWidth()); - } - updateScrollWidth() { - if (!this.horizontalScrolling) { - return; - } - let scrollWidth = 0; - for (const item of this.items) { - if (typeof item.width !== 'undefined') { - scrollWidth = Math.max(scrollWidth, item.width); - } - } - this.scrollWidth = scrollWidth; - this.scrollableElement.setScrollDimensions({ scrollWidth: scrollWidth === 0 ? 0 : (scrollWidth + 10) }); - } - rerender() { - if (!this.supportDynamicHeights) { - return; - } - for (const item of this.items) { - item.lastDynamicHeightWidth = undefined; - } - this._rerender(this.lastRenderTop, this.lastRenderHeight); - } - get length() { - return this.items.length; - } - get renderHeight() { - const scrollDimensions = this.scrollableElement.getScrollDimensions(); - return scrollDimensions.height; - } - element(index) { - return this.items[index].element; - } - domElement(index) { - const row = this.items[index].row; - return row && row.domNode; - } - elementHeight(index) { - return this.items[index].size; - } - elementTop(index) { - return this.rangeMap.positionAt(index); - } - indexAt(position) { - return this.rangeMap.indexAt(position); - } - indexAfter(position) { - return this.rangeMap.indexAfter(position); - } - layout(height, width) { - let scrollDimensions = { - height: typeof height === 'number' ? height : (0, dom_1.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 : (0, dom_1.getContentWidth)(this.domNode) - }); - } - } - // Render - render(previousRenderRange, renderTop, renderHeight, renderLeft, scrollWidth, updateItemsInDOM = false) { - const renderRange = this.getRenderRange(renderTop, renderHeight); - const rangesToInsert = range_1.Range.relativeComplement(renderRange, previousRenderRange); - const rangesToRemove = range_1.Range.relativeComplement(previousRenderRange, renderRange); - const beforeElement = this.getNextToLastElement(rangesToInsert); - if (updateItemsInDOM) { - const rangesToUpdate = range_1.Range.intersect(previousRenderRange, renderRange); - for (let i = rangesToUpdate.start; i < rangesToUpdate.end; i++) { - this.updateItemInDOM(this.items[i], i); - } - } - for (const range of rangesToInsert) { - for (let i = range.start; i < range.end; i++) { - this.insertItemInDOM(i, beforeElement); - } - } - for (const range of rangesToRemove) { - for (let i = range.start; i < range.end; i++) { - this.removeItemFromDOM(i); - } - } - if (renderLeft !== undefined) { - this.rowsContainer.style.left = `-${renderLeft}px`; - } - this.rowsContainer.style.top = `-${renderTop}px`; - if (this.horizontalScrolling && scrollWidth !== undefined) { - this.rowsContainer.style.width = `${Math.max(scrollWidth, this.renderWidth)}px`; - } - this.lastRenderTop = renderTop; - this.lastRenderHeight = renderHeight; - } - // DOM operations - insertItemInDOM(index, beforeElement, row) { - const item = this.items[index]; - if (!item.row) { - item.row = row !== null && row !== void 0 ? row : this.cache.alloc(item.templateId); - } - const role = this.accessibilityProvider.getRole(item.element) || 'listitem'; - item.row.domNode.setAttribute('role', role); - const checked = this.accessibilityProvider.isChecked(item.element); - 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); - const 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); - } - const uri = this.dnd.getDragURI(item.element); - item.dragStartDisposable.dispose(); - item.row.domNode.draggable = !!uri; - if (uri) { - item.dragStartDisposable = (0, dom_1.addDisposableListener)(item.row.domNode, 'dragstart', event => this.onDragStart(item.element, uri, event)); - } - if (this.horizontalScrolling) { - this.measureItemWidth(item); - this.eventuallyUpdateScrollWidth(); - } - } - measureItemWidth(item) { - if (!item.row || !item.row.domNode) { - return; - } - item.row.domNode.style.width = browser_1.isFirefox ? '-moz-fit-content' : 'fit-content'; - item.width = (0, dom_1.getContentWidth)(item.row.domNode); - const 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 = ''; - } - updateItemInDOM(item, index) { - item.row.domNode.style.top = `${this.elementTop(index)}px`; - if (this.setRowHeight) { - 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.accessibilityProvider.getSetSize(item.element, index, this.length))); - item.row.domNode.setAttribute('aria-posinset', String(this.accessibilityProvider.getPosInSet(item.element, index))); - item.row.domNode.setAttribute('id', this.getElementDomId(index)); - item.row.domNode.classList.toggle('drop-target', item.dropTarget); - } - removeItemFromDOM(index) { - const item = this.items[index]; - item.dragStartDisposable.dispose(); - if (item.row) { - const 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(); - } - } - getScrollTop() { - const scrollPosition = this.scrollableElement.getScrollPosition(); - return scrollPosition.scrollTop; - } - setScrollTop(scrollTop, reuseAnimation) { - if (this.scrollableElementUpdateDisposable) { - this.scrollableElementUpdateDisposable.dispose(); - this.scrollableElementUpdateDisposable = null; - this.scrollableElement.setScrollDimensions({ scrollHeight: this.scrollHeight }); - } - this.scrollableElement.setScrollPosition({ scrollTop, reuseAnimation }); - } - get scrollTop() { - return this.getScrollTop(); - } - set scrollTop(scrollTop) { - this.setScrollTop(scrollTop); - } - get scrollHeight() { - return this._scrollHeight + (this.horizontalScrolling ? 10 : 0) + this.additionalScrollHeight; - } - // Events - get onMouseClick() { return event_1.Event.map(this.disposables.add(new event_2.DomEmitter(this.domNode, 'click')).event, e => this.toMouseEvent(e)); } - get onMouseDblClick() { return event_1.Event.map(this.disposables.add(new event_2.DomEmitter(this.domNode, 'dblclick')).event, e => this.toMouseEvent(e)); } - get onMouseMiddleClick() { return event_1.Event.filter(event_1.Event.map(this.disposables.add(new event_2.DomEmitter(this.domNode, 'auxclick')).event, e => this.toMouseEvent(e)), e => e.browserEvent.button === 1); } - get onMouseDown() { return event_1.Event.map(this.disposables.add(new event_2.DomEmitter(this.domNode, 'mousedown')).event, e => this.toMouseEvent(e)); } - get onContextMenu() { return event_1.Event.any(event_1.Event.map(this.disposables.add(new event_2.DomEmitter(this.domNode, 'contextmenu')).event, e => this.toMouseEvent(e)), event_1.Event.map(this.disposables.add(new event_2.DomEmitter(this.domNode, touch_1.EventType.Contextmenu)).event, e => this.toGestureEvent(e))); } - get onTouchStart() { return event_1.Event.map(this.disposables.add(new event_2.DomEmitter(this.domNode, 'touchstart')).event, e => this.toTouchEvent(e)); } - get onTap() { return event_1.Event.map(this.disposables.add(new event_2.DomEmitter(this.rowsContainer, touch_1.EventType.Tap)).event, e => this.toGestureEvent(e)); } - toMouseEvent(browserEvent) { - const index = this.getItemIndexFromEventTarget(browserEvent.target || null); - const item = typeof index === 'undefined' ? undefined : this.items[index]; - const element = item && item.element; - return { browserEvent, index, element }; - } - toTouchEvent(browserEvent) { - const index = this.getItemIndexFromEventTarget(browserEvent.target || null); - const item = typeof index === 'undefined' ? undefined : this.items[index]; - const element = item && item.element; - return { browserEvent, index, element }; - } - toGestureEvent(browserEvent) { - const index = this.getItemIndexFromEventTarget(browserEvent.initialTarget || null); - const item = typeof index === 'undefined' ? undefined : this.items[index]; - const element = item && item.element; - return { browserEvent, index, element }; - } - toDragEvent(browserEvent) { - const index = this.getItemIndexFromEventTarget(browserEvent.target || null); - const item = typeof index === 'undefined' ? undefined : this.items[index]; - const element = item && item.element; - return { browserEvent, index, element }; - } - onScroll(e) { - try { - const previousRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight); - this.render(previousRenderRange, e.scrollTop, e.height, e.scrollLeft, e.scrollWidth); - if (this.supportDynamicHeights) { - this._rerender(e.scrollTop, e.height, e.inSmoothScrolling); - } - } - catch (err) { - console.error('Got bad scroll event:', e); - throw err; - } - } - onTouchChange(event) { - event.preventDefault(); - event.stopPropagation(); - this.scrollTop -= event.translationY; - } - // DND - onDragStart(element, uri, event) { - if (!event.dataTransfer) { - return; - } - const elements = this.dnd.getDragElements(element); - event.dataTransfer.effectAllowed = 'copyMove'; - event.dataTransfer.setData(dnd_1.DataTransfers.TEXT, uri); - if (event.dataTransfer.setDragImage) { - let label; - if (this.dnd.getDragLabel) { - label = this.dnd.getDragLabel(elements, event); - } - if (typeof label === 'undefined') { - label = String(elements.length); - } - const dragImage = (0, dom_1.$)('.monaco-drag-image'); - dragImage.textContent = label; - document.body.appendChild(dragImage); - event.dataTransfer.setDragImage(dragImage, -10, -10); - setTimeout(() => document.body.removeChild(dragImage), 0); - } - this.currentDragData = new ElementsDragAndDropData(elements); - dnd_1.StaticDND.CurrentDragAndDropData = new ExternalElementsDragAndDropData(elements); - if (this.dnd.onDragStart) { - this.dnd.onDragStart(this.currentDragData, event); - } - } - onDragOver(event) { - 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 NativeDragAndDropData(); - } - } - const 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'; - let 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 = (0, arrays_1.distinct)(feedback).filter(i => i >= -1 && i < this.length).sort((a, b) => 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 - this.domNode.classList.add('drop-target'); - this.rowsContainer.classList.add('drop-target'); - this.currentDragFeedbackDisposable = (0, lifecycle_1.toDisposable)(() => { - this.domNode.classList.remove('drop-target'); - this.rowsContainer.classList.remove('drop-target'); - }); - } - else { - for (const index of feedback) { - const item = this.items[index]; - item.dropTarget = true; - if (item.row) { - item.row.domNode.classList.add('drop-target'); - } - } - this.currentDragFeedbackDisposable = (0, lifecycle_1.toDisposable)(() => { - for (const index of feedback) { - const item = this.items[index]; - item.dropTarget = false; - if (item.row) { - item.row.domNode.classList.remove('drop-target'); - } - } - }); - } - return true; - } - onDragLeave(event) { - var _a, _b; - this.onDragLeaveTimeout.dispose(); - this.onDragLeaveTimeout = (0, async_1.disposableTimeout)(() => this.clearDragOverFeedback(), 100); - if (this.currentDragData) { - (_b = (_a = this.dnd).onDragLeave) === null || _b === void 0 ? void 0 : _b.call(_a, this.currentDragData, event.element, event.index, event.browserEvent); - } - } - onDrop(event) { - if (!this.canDrop) { - return; - } - const 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); - } - onDragEnd(event) { - this.canDrop = false; - this.teardownDragAndDropScrollTopAnimation(); - this.clearDragOverFeedback(); - this.currentDragData = undefined; - dnd_1.StaticDND.CurrentDragAndDropData = undefined; - if (this.dnd.onDragEnd) { - this.dnd.onDragEnd(event); - } - } - clearDragOverFeedback() { - this.currentDragFeedback = undefined; - this.currentDragFeedbackDisposable.dispose(); - this.currentDragFeedbackDisposable = lifecycle_1.Disposable.None; - } - // DND scroll top animation - setupDragAndDropScrollTopAnimation(event) { - if (!this.dragOverAnimationDisposable) { - const viewTop = (0, dom_1.getTopLeftOffset)(this.domNode).top; - this.dragOverAnimationDisposable = (0, dom_1.animate)(this.animateDragAndDropScrollTop.bind(this, viewTop)); - } - this.dragOverAnimationStopDisposable.dispose(); - this.dragOverAnimationStopDisposable = (0, async_1.disposableTimeout)(() => { - if (this.dragOverAnimationDisposable) { - this.dragOverAnimationDisposable.dispose(); - this.dragOverAnimationDisposable = undefined; - } - }, 1000); - this.dragOverMouseY = event.pageY; - } - animateDragAndDropScrollTop(viewTop) { - if (this.dragOverMouseY === undefined) { - return; - } - const diff = this.dragOverMouseY - viewTop; - const 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))); - } - } - teardownDragAndDropScrollTopAnimation() { - this.dragOverAnimationStopDisposable.dispose(); - if (this.dragOverAnimationDisposable) { - this.dragOverAnimationDisposable.dispose(); - this.dragOverAnimationDisposable = undefined; - } - } - // Util - getItemIndexFromEventTarget(target) { - const scrollableElement = this.scrollableElement.getDomNode(); - let element = target; - while (element instanceof HTMLElement && element !== this.rowsContainer && scrollableElement.contains(element)) { - const rawIndex = element.getAttribute('data-index'); - if (rawIndex) { - const index = Number(rawIndex); - if (!isNaN(index)) { - return index; - } - } - element = element.parentElement; - } - return undefined; - } - getRenderRange(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. - */ - _rerender(renderTop, renderHeight, inSmoothScrolling) { - const 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 - let anchorElementIndex; - let 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; - } - let heightDiff = 0; - while (true) { - const renderRange = this.getRenderRange(renderTop, renderHeight); - let didChange = false; - for (let i = renderRange.start; i < renderRange.end; i++) { - const 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(); - } - const unrenderRanges = range_1.Range.relativeComplement(previousRenderRange, renderRange); - for (const range of unrenderRanges) { - for (let i = range.start; i < range.end; i++) { - if (this.items[i].row) { - this.removeItemFromDOM(i); - } - } - } - const renderRanges = range_1.Range.relativeComplement(renderRange, previousRenderRange); - for (const range of renderRanges) { - for (let i = range.start; i < range.end; i++) { - const afterIndex = i + 1; - const beforeRow = afterIndex < this.items.length ? this.items[afterIndex].row : null; - const beforeElement = beforeRow ? beforeRow.domNode : null; - this.insertItemInDOM(i, beforeElement); - } - } - for (let i = renderRange.start; i < renderRange.end; i++) { - if (this.items[i].row) { - this.updateItemInDOM(this.items[i], i); - } - } - if (typeof anchorElementIndex === 'number') { - // To compute a destination scroll top, we need to take into account the current smooth scrolling - // animation, and then reuse it with a new target (to avoid prolonging the scroll) - // See https://github.com/microsoft/vscode/issues/104144 - // See https://github.com/microsoft/vscode/pull/104284 - // See https://github.com/microsoft/vscode/issues/107704 - const deltaScrollTop = this.scrollable.getFutureScrollPosition().scrollTop - renderTop; - const newScrollTop = this.elementTop(anchorElementIndex) - anchorElementTopDelta + deltaScrollTop; - this.setScrollTop(newScrollTop, inSmoothScrolling); - } - this._onDidChangeContentHeight.fire(this.contentHeight); - return; - } - } - } - probeDynamicHeight(index) { - const item = this.items[index]; - if (!item.hasDynamicHeight || item.lastDynamicHeightWidth === this.renderWidth) { - return 0; - } - if (!!this.virtualDelegate.hasDynamicHeight && !this.virtualDelegate.hasDynamicHeight(item.element)) { - return 0; - } - const size = item.size; - if (!this.setRowHeight && item.row) { - let newSize = item.row.domNode.offsetHeight; - item.size = newSize; - item.lastDynamicHeightWidth = this.renderWidth; - return newSize - size; - } - const row = this.cache.alloc(item.templateId); - row.domNode.style.height = ''; - this.rowsContainer.appendChild(row.domNode); - const 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; - } - getNextToLastElement(ranges) { - const lastRange = ranges[ranges.length - 1]; - if (!lastRange) { - return null; - } - const nextToLastItem = this.items[lastRange.end]; - if (!nextToLastItem) { - return null; - } - if (!nextToLastItem.row) { - return null; - } - return nextToLastItem.row.domNode; - } - getElementDomId(index) { - return `${this.domId}_${index}`; - } - // Dispose - dispose() { - if (this.items) { - for (const item of this.items) { - if (item.row) { - const renderer = this.renderers.get(item.row.templateId); - if (renderer) { - if (renderer.disposeElement) { - renderer.disposeElement(item.element, -1, item.row.templateData, undefined); - } - renderer.disposeTemplate(item.row.templateData); - } - } - } - this.items = []; - } - if (this.domNode && this.domNode.parentNode) { - this.domNode.parentNode.removeChild(this.domNode); - } - (0, 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); - 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[108/*vs/base/browser/ui/list/listWidget*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,20/*vs/base/common/types*/,19/*vs/base/common/arrays*/,90/*vs/base/common/decorators*/,17/*vs/base/common/platform*/,60/*vs/base/browser/touch*/,51/*vs/base/browser/keyboardEvent*/,6/*vs/base/common/event*/,91/*vs/base/browser/event*/,283/*vs/base/browser/ui/list/list*/,166/*vs/base/browser/ui/list/listView*/,29/*vs/base/common/color*/,42/*vs/base/common/objects*/,284/*vs/base/browser/ui/list/splice*/,102/*vs/base/common/numbers*/,67/*vs/base/common/filters*/,44/*vs/base/browser/ui/aria/aria*/,7/*vs/base/browser/dom*/,15/*vs/base/common/async*/,211/*vs/css!vs/base/browser/ui/list/list*/]), function (require, exports, lifecycle_1, types_1, arrays_1, decorators_1, platform, touch_1, keyboardEvent_1, event_1, event_2, list_1, listView_1, color_1, objects_1, splice_1, numbers_1, filters_1, aria_1, dom_1, async_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.List = exports.DefaultStyleController = exports.MouseController = exports.isSelectionRangeChangeEvent = exports.isSelectionSingleChangeEvent = exports.DefaultKeyboardNavigationDelegate = exports.isMonacoEditor = exports.isInputElement = void 0; - class TraitRenderer { - constructor(trait) { - this.trait = trait; - this.renderedElements = []; - } - get templateId() { - return `template:${this.trait.trait}`; - } - renderTemplate(container) { - return container; - } - renderElement(element, index, templateData) { - const renderedElementIndex = this.renderedElements.findIndex(el => el.templateData === templateData); - if (renderedElementIndex >= 0) { - const rendered = this.renderedElements[renderedElementIndex]; - this.trait.unrender(templateData); - rendered.index = index; - } - else { - const rendered = { index, templateData }; - this.renderedElements.push(rendered); - } - this.trait.renderIndex(index, templateData); - } - splice(start, deleteCount, insertCount) { - const rendered = []; - for (const renderedElement of this.renderedElements) { - 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; - } - renderIndexes(indexes) { - for (const { index, templateData } of this.renderedElements) { - if (indexes.indexOf(index) > -1) { - this.trait.renderIndex(index, templateData); - } - } - } - disposeTemplate(templateData) { - const index = this.renderedElements.findIndex(el => el.templateData === templateData); - if (index < 0) { - return; - } - this.renderedElements.splice(index, 1); - } - } - class Trait { - constructor(_trait) { - this._trait = _trait; - this.length = 0; - this.indexes = []; - this.sortedIndexes = []; - this._onChange = new event_1.Emitter(); - this.onChange = this._onChange.event; - } - get trait() { return this._trait; } - get renderer() { - return new TraitRenderer(this); - } - splice(start, deleteCount, elements) { - var _a; - deleteCount = Math.max(0, Math.min(deleteCount, this.length - start)); - const diff = elements.length - deleteCount; - const end = start + deleteCount; - const sortedIndexes = [ - ...this.sortedIndexes.filter(i => i < start), - ...elements.map((hasTrait, i) => hasTrait ? i + start : -1).filter(i => i !== -1), - ...this.sortedIndexes.filter(i => i >= end).map(i => i + diff) - ]; - const length = this.length + diff; - if (this.sortedIndexes.length > 0 && sortedIndexes.length === 0 && length > 0) { - const first = (_a = this.sortedIndexes.find(index => index >= start)) !== null && _a !== void 0 ? _a : length - 1; - sortedIndexes.push(Math.min(first, length - 1)); - } - this.renderer.splice(start, deleteCount, elements.length); - this._set(sortedIndexes, sortedIndexes); - this.length = length; - } - renderIndex(index, container) { - container.classList.toggle(this._trait, this.contains(index)); - } - unrender(container) { - container.classList.remove(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. - */ - set(indexes, browserEvent) { - return this._set(indexes, [...indexes].sort(numericSort), browserEvent); - } - _set(indexes, sortedIndexes, browserEvent) { - const result = this.indexes; - const sortedResult = this.sortedIndexes; - this.indexes = indexes; - this.sortedIndexes = sortedIndexes; - const toRender = disjunction(sortedResult, indexes); - this.renderer.renderIndexes(toRender); - this._onChange.fire({ indexes, browserEvent }); - return result; - } - get() { - return this.indexes; - } - contains(index) { - return (0, arrays_1.binarySearch)(this.sortedIndexes, index, numericSort) >= 0; - } - dispose() { - (0, lifecycle_1.dispose)(this._onChange); - } - } - __decorate([ - decorators_1.memoize - ], Trait.prototype, "renderer", null); - class SelectionTrait extends Trait { - constructor(setAriaSelected) { - super('selected'); - this.setAriaSelected = setAriaSelected; - } - renderIndex(index, container) { - super.renderIndex(index, container); - if (this.setAriaSelected) { - if (this.contains(index)) { - container.setAttribute('aria-selected', 'true'); - } - else { - container.setAttribute('aria-selected', 'false'); - } - } - } - } - /** - * The TraitSpliceable is used as a util class to be able - * to preserve traits across splice calls, given an identity - * provider. - */ - class TraitSpliceable { - constructor(trait, view, identityProvider) { - this.trait = trait; - this.view = view; - this.identityProvider = identityProvider; - } - splice(start, deleteCount, elements) { - if (!this.identityProvider) { - return this.trait.splice(start, deleteCount, elements.map(() => false)); - } - const pastElementsWithTrait = this.trait.get().map(i => this.identityProvider.getId(this.view.element(i)).toString()); - const elementsWithTrait = elements.map(e => pastElementsWithTrait.indexOf(this.identityProvider.getId(e).toString()) > -1); - this.trait.splice(start, deleteCount, elementsWithTrait); - } - } - function isInputElement(e) { - return e.tagName === 'INPUT' || e.tagName === 'TEXTAREA'; - } - exports.isInputElement = isInputElement; - function isMonacoEditor(e) { - if (e.classList.contains('monaco-editor')) { - return true; - } - if (e.classList.contains('monaco-list')) { - return false; - } - if (!e.parentElement) { - return false; - } - return isMonacoEditor(e.parentElement); - } - exports.isMonacoEditor = isMonacoEditor; - class KeyboardController { - constructor(list, view, options) { - this.list = list; - this.view = view; - this.disposables = new lifecycle_1.DisposableStore(); - this.multipleSelectionDisposables = new lifecycle_1.DisposableStore(); - this.onKeyDown.filter(e => e.keyCode === 3 /* Enter */).on(this.onEnter, this, this.disposables); - this.onKeyDown.filter(e => e.keyCode === 16 /* UpArrow */).on(this.onUpArrow, this, this.disposables); - this.onKeyDown.filter(e => e.keyCode === 18 /* DownArrow */).on(this.onDownArrow, this, this.disposables); - this.onKeyDown.filter(e => e.keyCode === 11 /* PageUp */).on(this.onPageUpArrow, this, this.disposables); - this.onKeyDown.filter(e => e.keyCode === 12 /* PageDown */).on(this.onPageDownArrow, this, this.disposables); - this.onKeyDown.filter(e => e.keyCode === 9 /* Escape */).on(this.onEscape, this, this.disposables); - if (options.multipleSelectionSupport !== false) { - this.onKeyDown.filter(e => (platform.isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === 31 /* KEY_A */).on(this.onCtrlA, this, this.multipleSelectionDisposables); - } - } - get onKeyDown() { - return event_1.Event.chain(this.disposables.add(new event_2.DomEmitter(this.view.domNode, 'keydown')).event) - .filter(e => !isInputElement(e.target)) - .map(e => new keyboardEvent_1.StandardKeyboardEvent(e)); - } - updateOptions(optionsUpdate) { - if (optionsUpdate.multipleSelectionSupport !== undefined) { - this.multipleSelectionDisposables.clear(); - if (optionsUpdate.multipleSelectionSupport) { - this.onKeyDown.filter(e => (platform.isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === 31 /* KEY_A */).on(this.onCtrlA, this, this.multipleSelectionDisposables); - } - } - } - onEnter(e) { - e.preventDefault(); - e.stopPropagation(); - this.list.setSelection(this.list.getFocus(), e.browserEvent); - } - onUpArrow(e) { - e.preventDefault(); - e.stopPropagation(); - this.list.focusPrevious(1, false, e.browserEvent); - this.list.reveal(this.list.getFocus()[0]); - this.view.domNode.focus(); - } - onDownArrow(e) { - e.preventDefault(); - e.stopPropagation(); - this.list.focusNext(1, false, e.browserEvent); - this.list.reveal(this.list.getFocus()[0]); - this.view.domNode.focus(); - } - onPageUpArrow(e) { - e.preventDefault(); - e.stopPropagation(); - this.list.focusPreviousPage(e.browserEvent); - this.list.reveal(this.list.getFocus()[0]); - this.view.domNode.focus(); - } - onPageDownArrow(e) { - e.preventDefault(); - e.stopPropagation(); - this.list.focusNextPage(e.browserEvent); - this.list.reveal(this.list.getFocus()[0]); - this.view.domNode.focus(); - } - onCtrlA(e) { - e.preventDefault(); - e.stopPropagation(); - this.list.setSelection((0, arrays_1.range)(this.list.length), e.browserEvent); - this.view.domNode.focus(); - } - onEscape(e) { - if (this.list.getSelection().length) { - e.preventDefault(); - e.stopPropagation(); - this.list.setSelection([], e.browserEvent); - this.view.domNode.focus(); - } - } - dispose() { - this.disposables.dispose(); - this.multipleSelectionDisposables.dispose(); - } - } - __decorate([ - decorators_1.memoize - ], KeyboardController.prototype, "onKeyDown", null); - var TypeLabelControllerState; - (function (TypeLabelControllerState) { - TypeLabelControllerState[TypeLabelControllerState["Idle"] = 0] = "Idle"; - TypeLabelControllerState[TypeLabelControllerState["Typing"] = 1] = "Typing"; - })(TypeLabelControllerState || (TypeLabelControllerState = {})); - exports.DefaultKeyboardNavigationDelegate = new class { - mightProducePrintableCharacter(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 */); - } - }; - class TypeLabelController { - constructor(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.previouslyFocused = -1; - this.enabledDisposables = new lifecycle_1.DisposableStore(); - this.disposables = new lifecycle_1.DisposableStore(); - this.updateOptions(list.options); - } - updateOptions(options) { - const enableKeyboardNavigation = typeof options.enableKeyboardNavigation === 'undefined' ? true : !!options.enableKeyboardNavigation; - if (enableKeyboardNavigation) { - this.enable(); - } - else { - this.disable(); - } - if (typeof options.automaticKeyboardNavigation !== 'undefined') { - this.automaticKeyboardNavigation = options.automaticKeyboardNavigation; - } - } - enable() { - if (this.enabled) { - return; - } - const onChar = event_1.Event.chain(this.enabledDisposables.add(new event_2.DomEmitter(this.view.domNode, 'keydown')).event) - .filter(e => !isInputElement(e.target)) - .filter(() => this.automaticKeyboardNavigation || this.triggered) - .map(event => new keyboardEvent_1.StandardKeyboardEvent(event)) - .filter(e => this.delegate.mightProducePrintableCharacter(e)) - .forEach(e => { e.stopPropagation(); e.preventDefault(); }) - .map(event => event.browserEvent.key) - .event; - const onClear = event_1.Event.debounce(onChar, () => null, 800); - const onInput = event_1.Event.reduce(event_1.Event.any(onChar, onClear), (r, i) => i === null ? null : ((r || '') + i)); - onInput(this.onInput, this, this.enabledDisposables); - onClear(this.onClear, this, this.enabledDisposables); - this.enabled = true; - this.triggered = false; - } - disable() { - if (!this.enabled) { - return; - } - this.enabledDisposables.clear(); - this.enabled = false; - this.triggered = false; - } - onClear() { - var _a; - const focus = this.list.getFocus(); - if (focus.length > 0 && focus[0] === this.previouslyFocused) { - // List: re-anounce element on typing end since typed keys will interupt aria label of focused element - // Do not announce if there was a focus change at the end to prevent duplication https://github.com/microsoft/vscode/issues/95961 - const ariaLabel = (_a = this.list.options.accessibilityProvider) === null || _a === void 0 ? void 0 : _a.getAriaLabel(this.list.element(focus[0])); - if (ariaLabel) { - (0, aria_1.alert)(ariaLabel); - } - } - this.previouslyFocused = -1; - } - onInput(word) { - if (!word) { - this.state = TypeLabelControllerState.Idle; - this.triggered = false; - return; - } - const focus = this.list.getFocus(); - const start = focus.length > 0 ? focus[0] : 0; - const delta = this.state === TypeLabelControllerState.Idle ? 1 : 0; - this.state = TypeLabelControllerState.Typing; - for (let i = 0; i < this.list.length; i++) { - const index = (start + i + delta) % this.list.length; - const label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(this.view.element(index)); - const labelStr = label && label.toString(); - if (typeof labelStr === 'undefined' || (0, filters_1.matchesPrefix)(word, labelStr)) { - this.previouslyFocused = start; - this.list.setFocus([index]); - this.list.reveal(index); - return; - } - } - } - dispose() { - this.disable(); - this.enabledDisposables.dispose(); - this.disposables.dispose(); - } - } - class DOMFocusController { - constructor(list, view) { - this.list = list; - this.view = view; - this.disposables = new lifecycle_1.DisposableStore(); - const onKeyDown = event_1.Event.chain(this.disposables.add(new event_2.DomEmitter(view.domNode, 'keydown')).event) - .filter(e => !isInputElement(e.target)) - .map(e => new keyboardEvent_1.StandardKeyboardEvent(e)); - onKeyDown.filter(e => e.keyCode === 2 /* Tab */ && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey) - .on(this.onTab, this, this.disposables); - } - onTab(e) { - if (e.target !== this.view.domNode) { - return; - } - const focus = this.list.getFocus(); - if (focus.length === 0) { - return; - } - const focusedDomElement = this.view.domElement(focus[0]); - if (!focusedDomElement) { - return; - } - const tabIndexElement = focusedDomElement.querySelector('[tabIndex]'); - if (!tabIndexElement || !(tabIndexElement instanceof HTMLElement) || tabIndexElement.tabIndex === -1) { - return; - } - const style = window.getComputedStyle(tabIndexElement); - if (style.visibility === 'hidden' || style.display === 'none') { - return; - } - e.preventDefault(); - e.stopPropagation(); - tabIndexElement.focus(); - } - dispose() { - this.disposables.dispose(); - } - } - 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; - } - const DefaultMultipleSelectionController = { - isSelectionSingleChangeEvent, - isSelectionRangeChangeEvent - }; - class MouseController { - constructor(list) { - this.list = list; - this.disposables = new lifecycle_1.DisposableStore(); - this._onPointer = new event_1.Emitter(); - this.onPointer = this._onPointer.event; - if (list.options.multipleSelectionSupport !== false) { - this.multipleSelectionController = this.list.options.multipleSelectionController || DefaultMultipleSelectionController; - } - 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())); - } - event_1.Event.any(list.onMouseClick, list.onMouseMiddleClick, list.onTap)(this.onViewPointer, this, this.disposables); - } - updateOptions(optionsUpdate) { - if (optionsUpdate.multipleSelectionSupport !== undefined) { - this.multipleSelectionController = undefined; - if (optionsUpdate.multipleSelectionSupport) { - this.multipleSelectionController = this.list.options.multipleSelectionController || DefaultMultipleSelectionController; - } - } - } - isSelectionSingleChangeEvent(event) { - if (!this.multipleSelectionController) { - return false; - } - return this.multipleSelectionController.isSelectionSingleChangeEvent(event); - } - isSelectionRangeChangeEvent(event) { - if (!this.multipleSelectionController) { - return false; - } - return this.multipleSelectionController.isSelectionRangeChangeEvent(event); - } - isSelectionChangeEvent(event) { - return this.isSelectionSingleChangeEvent(event) || this.isSelectionRangeChangeEvent(event); - } - onMouseDown(e) { - if (isMonacoEditor(e.browserEvent.target)) { - return; - } - if (document.activeElement !== e.browserEvent.target) { - this.list.domFocus(); - } - } - onContextMenu(e) { - if (isMonacoEditor(e.browserEvent.target)) { - return; - } - const focus = typeof e.index === 'undefined' ? [] : [e.index]; - this.list.setFocus(focus, e.browserEvent); - } - onViewPointer(e) { - if (!this.mouseSupport) { - return; - } - if (isInputElement(e.browserEvent.target) || isMonacoEditor(e.browserEvent.target)) { - return; - } - const focus = e.index; - if (typeof focus === 'undefined') { - this.list.setFocus([], e.browserEvent); - this.list.setSelection([], e.browserEvent); - this.list.setAnchor(undefined); - return; - } - if (this.isSelectionRangeChangeEvent(e)) { - return this.changeSelection(e); - } - if (this.isSelectionChangeEvent(e)) { - return this.changeSelection(e); - } - this.list.setFocus([focus], e.browserEvent); - this.list.setAnchor(focus); - if (!isMouseRightClick(e.browserEvent)) { - this.list.setSelection([focus], e.browserEvent); - } - this._onPointer.fire(e); - } - onDoubleClick(e) { - if (isInputElement(e.browserEvent.target) || isMonacoEditor(e.browserEvent.target)) { - return; - } - if (this.isSelectionChangeEvent(e)) { - return; - } - const focus = this.list.getFocus(); - this.list.setSelection(focus, e.browserEvent); - } - changeSelection(e) { - const focus = e.index; - let anchor = this.list.getAnchor(); - if (this.isSelectionRangeChangeEvent(e)) { - if (typeof anchor === 'undefined') { - const currentFocus = this.list.getFocus()[0]; - anchor = currentFocus !== null && currentFocus !== void 0 ? currentFocus : focus; - this.list.setAnchor(anchor); - } - const min = Math.min(anchor, focus); - const max = Math.max(anchor, focus); - const rangeSelection = (0, arrays_1.range)(min, max + 1); - const selection = this.list.getSelection(); - const contiguousRange = getContiguousRangeContaining(disjunction(selection, [anchor]), anchor); - if (contiguousRange.length === 0) { - return; - } - const newSelection = disjunction(rangeSelection, relativeComplement(selection, contiguousRange)); - this.list.setSelection(newSelection, e.browserEvent); - this.list.setFocus([focus], e.browserEvent); - } - else if (this.isSelectionSingleChangeEvent(e)) { - const selection = this.list.getSelection(); - const newSelection = selection.filter(i => i !== focus); - this.list.setFocus([focus]); - this.list.setAnchor(focus); - if (selection.length === newSelection.length) { - this.list.setSelection([...newSelection, focus], e.browserEvent); - } - else { - this.list.setSelection(newSelection, e.browserEvent); - } - } - } - dispose() { - this.disposables.dispose(); - } - } - exports.MouseController = MouseController; - class DefaultStyleController { - constructor(styleElement, selectorSuffix) { - this.styleElement = styleElement; - this.selectorSuffix = selectorSuffix; - } - style(styles) { - const suffix = this.selectorSuffix && `.${this.selectorSuffix}`; - const 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.listActiveSelectionIconForeground) { - content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected .codicon { color: ${styles.listActiveSelectionIconForeground}; }`); - } - if (styles.listFocusAndSelectionBackground) { - content.push(` - .monaco-drag-image, - .monaco-list${suffix}:focus .monaco-list-row.selected.focused { background-color: ${styles.listFocusAndSelectionBackground}; } - `); - } - if (styles.listFocusAndSelectionForeground) { - content.push(` - .monaco-drag-image, - .monaco-list${suffix}:focus .monaco-list-row.selected.focused { color: ${styles.listFocusAndSelectionForeground}; } - `); - } - if (styles.listInactiveFocusForeground) { - content.push(`.monaco-list${suffix} .monaco-list-row.focused { color: ${styles.listInactiveFocusForeground}; }`); - content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { color: ${styles.listInactiveFocusForeground}; }`); // overwrite :hover style in this case! - } - if (styles.listInactiveSelectionIconForeground) { - content.push(`.monaco-list${suffix} .monaco-list-row.focused .codicon { color: ${styles.listInactiveSelectionIconForeground}; }`); - } - 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(` - .monaco-drag-image, - .monaco-list${suffix}:focus .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; } - `); - } - 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(` - .monaco-list${suffix}.drop-target, - .monaco-list${suffix} .monaco-list-rows.drop-target, - .monaco-list${suffix} .monaco-list-row.drop-target { background-color: ${styles.listDropBackground} !important; color: inherit !important; } - `); - } - 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}; }`); - } - if (styles.tableColumnsBorder) { - content.push(` - .monaco-table:hover > .monaco-split-view2, - .monaco-table:hover > .monaco-split-view2 .monaco-sash.vertical::before { - border-color: ${styles.tableColumnsBorder}; - }`); - } - this.styleElement.textContent = content.join('\n'); - } - } - exports.DefaultStyleController = DefaultStyleController; - const defaultStyles = { - listFocusBackground: color_1.Color.fromHex('#7FB0D0'), - listActiveSelectionBackground: color_1.Color.fromHex('#0E639C'), - listActiveSelectionForeground: color_1.Color.fromHex('#FFFFFF'), - listActiveSelectionIconForeground: color_1.Color.fromHex('#FFFFFF'), - listFocusAndSelectionBackground: color_1.Color.fromHex('#094771'), - listFocusAndSelectionForeground: color_1.Color.fromHex('#FFFFFF'), - listInactiveSelectionBackground: color_1.Color.fromHex('#3F3F46'), - listInactiveSelectionIconForeground: color_1.Color.fromHex('#FFFFFF'), - listHoverBackground: color_1.Color.fromHex('#2A2D2E'), - listDropBackground: color_1.Color.fromHex('#383B3D'), - treeIndentGuidesStroke: color_1.Color.fromHex('#a9a9a9'), - tableColumnsBorder: color_1.Color.fromHex('#cccccc').transparent(0.2) - }; - const DefaultOptions = { - keyboardSupport: true, - mouseSupport: true, - multipleSelectionSupport: true, - dnd: { - getDragURI() { return null; }, - onDragStart() { }, - onDragOver() { return false; }, - drop() { } - } - }; - // TODO@Joao: move these utils into a SortedArray class - function getContiguousRangeContaining(range, value) { - const index = range.indexOf(value); - if (index === -1) { - return []; - } - const result = []; - let 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) { - const result = []; - let 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) { - const result = []; - let 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; - } - const numericSort = (a, b) => a - b; - class PipelineRenderer { - constructor(_templateId, renderers) { - this._templateId = _templateId; - this.renderers = renderers; - } - get templateId() { - return this._templateId; - } - renderTemplate(container) { - return this.renderers.map(r => r.renderTemplate(container)); - } - renderElement(element, index, templateData, height) { - let i = 0; - for (const renderer of this.renderers) { - renderer.renderElement(element, index, templateData[i++], height); - } - } - disposeElement(element, index, templateData, height) { - let i = 0; - for (const renderer of this.renderers) { - if (renderer.disposeElement) { - renderer.disposeElement(element, index, templateData[i], height); - } - i += 1; - } - } - disposeTemplate(templateData) { - let i = 0; - for (const renderer of this.renderers) { - renderer.disposeTemplate(templateData[i++]); - } - } - } - class AccessibiltyRenderer { - constructor(accessibilityProvider) { - this.accessibilityProvider = accessibilityProvider; - this.templateId = 'a18n'; - } - renderTemplate(container) { - return container; - } - renderElement(element, index, container) { - const ariaLabel = this.accessibilityProvider.getAriaLabel(element); - if (ariaLabel) { - container.setAttribute('aria-label', ariaLabel); - } - else { - container.removeAttribute('aria-label'); - } - const ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element); - if (typeof ariaLevel === 'number') { - container.setAttribute('aria-level', `${ariaLevel}`); - } - else { - container.removeAttribute('aria-level'); - } - } - disposeTemplate(templateData) { - // noop - } - } - class ListViewDragAndDrop { - constructor(list, dnd) { - this.list = list; - this.dnd = dnd; - } - getDragElements(element) { - const selection = this.list.getSelectedElements(); - const elements = selection.indexOf(element) > -1 ? selection : [element]; - return elements; - } - getDragURI(element) { - return this.dnd.getDragURI(element); - } - getDragLabel(elements, originalEvent) { - if (this.dnd.getDragLabel) { - return this.dnd.getDragLabel(elements, originalEvent); - } - return undefined; - } - onDragStart(data, originalEvent) { - if (this.dnd.onDragStart) { - this.dnd.onDragStart(data, originalEvent); - } - } - onDragOver(data, targetElement, targetIndex, originalEvent) { - return this.dnd.onDragOver(data, targetElement, targetIndex, originalEvent); - } - onDragLeave(data, targetElement, targetIndex, originalEvent) { - var _a, _b; - (_b = (_a = this.dnd).onDragLeave) === null || _b === void 0 ? void 0 : _b.call(_a, data, targetElement, targetIndex, originalEvent); - } - onDragEnd(originalEvent) { - if (this.dnd.onDragEnd) { - this.dnd.onDragEnd(originalEvent); - } - } - drop(data, targetElement, targetIndex, originalEvent) { - this.dnd.drop(data, targetElement, targetIndex, originalEvent); - } - } - class List { - constructor(user, container, virtualDelegate, renderers, _options = DefaultOptions) { - var _a; - this.user = user; - this._options = _options; - this.focus = new Trait('focused'); - this.anchor = new Trait('anchor'); - this.eventBufferer = new event_1.EventBufferer(); - this._ariaLabel = ''; - this.disposables = new lifecycle_1.DisposableStore(); - this._onDidDispose = new event_1.Emitter(); - this.onDidDispose = this._onDidDispose.event; - const role = this._options.accessibilityProvider && this._options.accessibilityProvider.getWidgetRole ? (_a = this._options.accessibilityProvider) === null || _a === void 0 ? void 0 : _a.getWidgetRole() : 'list'; - this.selection = new SelectionTrait(role !== 'listbox'); - (0, objects_1.mixin)(_options, defaultStyles, false); - const 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(r => new PipelineRenderer(r.templateId, [...baseRenderers, r])); - const viewOptions = Object.assign(Object.assign({}, _options), { dnd: _options.dnd && new ListViewDragAndDrop(this, _options.dnd) }); - this.view = new listView_1.ListView(container, virtualDelegate, renderers, viewOptions); - this.view.domNode.setAttribute('role', role); - if (_options.styleController) { - this.styleController = _options.styleController(this.view.domId); - } - else { - const styleElement = (0, dom_1.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), - new TraitSpliceable(this.anchor, this.view, _options.identityProvider), - this.view - ]); - this.disposables.add(this.focus); - this.disposables.add(this.selection); - this.disposables.add(this.anchor); - this.disposables.add(this.view); - this.disposables.add(this._onDidDispose); - this.disposables.add(new DOMFocusController(this, this.view)); - if (typeof _options.keyboardSupport !== 'boolean' || _options.keyboardSupport) { - this.keyboardController = new KeyboardController(this, this.view, _options); - this.disposables.add(this.keyboardController); - } - if (_options.keyboardNavigationLabelProvider) { - const delegate = _options.keyboardNavigationDelegate || exports.DefaultKeyboardNavigationDelegate; - this.typeLabelController = new TypeLabelController(this, this.view, _options.keyboardNavigationLabelProvider, delegate); - this.disposables.add(this.typeLabelController); - } - this.mouseController = this.createMouseController(_options); - this.disposables.add(this.mouseController); - this.onDidChangeFocus(this._onFocusChange, this, this.disposables); - this.onDidChangeSelection(this._onSelectionChange, this, this.disposables); - if (this.accessibilityProvider) { - this.ariaLabel = this.accessibilityProvider.getWidgetAriaLabel(); - } - if (this._options.multipleSelectionSupport !== false) { - this.view.domNode.setAttribute('aria-multiselectable', 'true'); - } - } - get onDidChangeFocus() { - return event_1.Event.map(this.eventBufferer.wrapEvent(this.focus.onChange), e => this.toListEvent(e)); - } - get onDidChangeSelection() { - return event_1.Event.map(this.eventBufferer.wrapEvent(this.selection.onChange), e => this.toListEvent(e)); - } - get domId() { return this.view.domId; } - get onMouseClick() { return this.view.onMouseClick; } - get onMouseDblClick() { return this.view.onMouseDblClick; } - get onMouseMiddleClick() { return this.view.onMouseMiddleClick; } - get onPointer() { return this.mouseController.onPointer; } - get onMouseDown() { return this.view.onMouseDown; } - get onTouchStart() { return this.view.onTouchStart; } - get onTap() { return this.view.onTap; } - /** - * Possible context menu trigger events: - * - ContextMenu key - * - Shift F10 - * - Ctrl Option Shift M (macOS with VoiceOver) - * - Mouse right click - */ - get onContextMenu() { - let didJustPressContextMenuKey = false; - const fromKeyDown = event_1.Event.chain(this.disposables.add(new event_2.DomEmitter(this.view.domNode, 'keydown')).event) - .map(e => new keyboardEvent_1.StandardKeyboardEvent(e)) - .filter(e => didJustPressContextMenuKey = e.keyCode === 58 /* ContextMenu */ || (e.shiftKey && e.keyCode === 68 /* F10 */)) - .map(event_2.stopEvent) - .filter(() => false) - .event; - const fromKeyUp = event_1.Event.chain(this.disposables.add(new event_2.DomEmitter(this.view.domNode, 'keyup')).event) - .forEach(() => didJustPressContextMenuKey = false) - .map(e => new keyboardEvent_1.StandardKeyboardEvent(e)) - .filter(e => e.keyCode === 58 /* ContextMenu */ || (e.shiftKey && e.keyCode === 68 /* F10 */)) - .map(event_2.stopEvent) - .map(({ browserEvent }) => { - const focus = this.getFocus(); - const index = focus.length ? focus[0] : undefined; - const element = typeof index !== 'undefined' ? this.view.element(index) : undefined; - const anchor = typeof index !== 'undefined' ? this.view.domElement(index) : this.view.domNode; - return { index, element, anchor, browserEvent }; - }) - .event; - const fromMouse = event_1.Event.chain(this.view.onContextMenu) - .filter(_ => !didJustPressContextMenuKey) - .map(({ element, index, browserEvent }) => ({ element, index, anchor: { x: browserEvent.pageX + 1, y: browserEvent.pageY }, browserEvent })) - .event; - return event_1.Event.any(fromKeyDown, fromKeyUp, fromMouse); - } - get onKeyDown() { return this.disposables.add(new event_2.DomEmitter(this.view.domNode, 'keydown')).event; } - get onDidFocus() { return event_1.Event.signal(this.disposables.add(new event_2.DomEmitter(this.view.domNode, 'focus', true)).event); } - createMouseController(options) { - return new MouseController(this); - } - updateOptions(optionsUpdate = {}) { - var _a; - this._options = Object.assign(Object.assign({}, this._options), optionsUpdate); - if (this.typeLabelController) { - this.typeLabelController.updateOptions(this._options); - } - if (this._options.multipleSelectionController !== undefined) { - if (this._options.multipleSelectionSupport) { - this.view.domNode.setAttribute('aria-multiselectable', 'true'); - } - else { - this.view.domNode.removeAttribute('aria-multiselectable'); - } - } - this.mouseController.updateOptions(optionsUpdate); - (_a = this.keyboardController) === null || _a === void 0 ? void 0 : _a.updateOptions(optionsUpdate); - this.view.updateOptions(optionsUpdate); - } - get options() { - return this._options; - } - splice(start, deleteCount, 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(() => this.spliceable.splice(start, deleteCount, elements)); - } - rerender() { - this.view.rerender(); - } - element(index) { - return this.view.element(index); - } - get length() { - return this.view.length; - } - get contentHeight() { - return this.view.contentHeight; - } - get scrollTop() { - return this.view.getScrollTop(); - } - set scrollTop(scrollTop) { - this.view.setScrollTop(scrollTop); - } - get ariaLabel() { - return this._ariaLabel; - } - set ariaLabel(value) { - this._ariaLabel = value; - this.view.domNode.setAttribute('aria-label', value); - } - domFocus() { - this.view.domNode.focus({ preventScroll: true }); - } - layout(height, width) { - this.view.layout(height, width); - } - setSelection(indexes, browserEvent) { - for (const index of indexes) { - if (index < 0 || index >= this.length) { - throw new list_1.ListError(this.user, `Invalid index ${index}`); - } - } - this.selection.set(indexes, browserEvent); - } - getSelection() { - return this.selection.get(); - } - getSelectedElements() { - return this.getSelection().map(i => this.view.element(i)); - } - setAnchor(index) { - if (typeof index === 'undefined') { - this.anchor.set([]); - return; - } - if (index < 0 || index >= this.length) { - throw new list_1.ListError(this.user, `Invalid index ${index}`); - } - this.anchor.set([index]); - } - getAnchor() { - return (0, arrays_1.firstOrDefault)(this.anchor.get(), undefined); - } - getAnchorElement() { - const anchor = this.getAnchor(); - return typeof anchor === 'undefined' ? undefined : this.element(anchor); - } - setFocus(indexes, browserEvent) { - for (const index of indexes) { - if (index < 0 || index >= this.length) { - throw new list_1.ListError(this.user, `Invalid index ${index}`); - } - } - this.focus.set(indexes, browserEvent); - } - focusNext(n = 1, loop = false, browserEvent, filter) { - if (this.length === 0) { - return; - } - const focus = this.focus.get(); - const index = this.findNextIndex(focus.length > 0 ? focus[0] + n : 0, loop, filter); - if (index > -1) { - this.setFocus([index], browserEvent); - } - } - focusPrevious(n = 1, loop = false, browserEvent, filter) { - if (this.length === 0) { - return; - } - const focus = this.focus.get(); - const index = this.findPreviousIndex(focus.length > 0 ? focus[0] - n : 0, loop, filter); - if (index > -1) { - this.setFocus([index], browserEvent); - } - } - focusNextPage(browserEvent, filter) { - return __awaiter(this, void 0, void 0, function* () { - let lastPageIndex = this.view.indexAt(this.view.getScrollTop() + this.view.renderHeight); - lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1; - const lastPageElement = this.view.element(lastPageIndex); - const currentlyFocusedElement = this.getFocusedElements()[0]; - if (currentlyFocusedElement !== lastPageElement) { - const lastGoodPageIndex = this.findPreviousIndex(lastPageIndex, false, filter); - if (lastGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(lastGoodPageIndex)) { - this.setFocus([lastGoodPageIndex], browserEvent); - } - else { - this.setFocus([lastPageIndex], browserEvent); - } - } - else { - const previousScrollTop = this.view.getScrollTop(); - this.view.setScrollTop(previousScrollTop + this.view.renderHeight - this.view.elementHeight(lastPageIndex)); - if (this.view.getScrollTop() !== previousScrollTop) { - this.setFocus([]); - // Let the scroll event listener run - yield (0, async_1.timeout)(0); - yield this.focusNextPage(browserEvent, filter); - } - } - }); - } - focusPreviousPage(browserEvent, filter) { - return __awaiter(this, void 0, void 0, function* () { - let firstPageIndex; - const scrollTop = this.view.getScrollTop(); - if (scrollTop === 0) { - firstPageIndex = this.view.indexAt(scrollTop); - } - else { - firstPageIndex = this.view.indexAfter(scrollTop - 1); - } - const firstPageElement = this.view.element(firstPageIndex); - const currentlyFocusedElement = this.getFocusedElements()[0]; - if (currentlyFocusedElement !== firstPageElement) { - const firstGoodPageIndex = this.findNextIndex(firstPageIndex, false, filter); - if (firstGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(firstGoodPageIndex)) { - this.setFocus([firstGoodPageIndex], browserEvent); - } - else { - this.setFocus([firstPageIndex], browserEvent); - } - } - else { - const previousScrollTop = scrollTop; - this.view.setScrollTop(scrollTop - this.view.renderHeight); - if (this.view.getScrollTop() !== previousScrollTop) { - this.setFocus([]); - // Let the scroll event listener run - yield (0, async_1.timeout)(0); - yield this.focusPreviousPage(browserEvent, filter); - } - } - }); - } - focusLast(browserEvent, filter) { - if (this.length === 0) { - return; - } - const index = this.findPreviousIndex(this.length - 1, false, filter); - if (index > -1) { - this.setFocus([index], browserEvent); - } - } - focusFirst(browserEvent, filter) { - this.focusNth(0, browserEvent, filter); - } - focusNth(n, browserEvent, filter) { - if (this.length === 0) { - return; - } - const index = this.findNextIndex(n, false, filter); - if (index > -1) { - this.setFocus([index], browserEvent); - } - } - findNextIndex(index, loop = false, filter) { - for (let 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; - } - findPreviousIndex(index, loop = false, filter) { - for (let 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; - } - getFocus() { - return this.focus.get(); - } - getFocusedElements() { - return this.getFocus().map(i => this.view.element(i)); - } - reveal(index, relativeTop) { - if (index < 0 || index >= this.length) { - throw new list_1.ListError(this.user, `Invalid index ${index}`); - } - const scrollTop = this.view.getScrollTop(); - const elementTop = this.view.elementTop(index); - const elementHeight = this.view.elementHeight(index); - if ((0, types_1.isNumber)(relativeTop)) { - // y = mx + b - const m = elementHeight - this.view.renderHeight; - this.view.setScrollTop(m * (0, numbers_1.clamp)(relativeTop, 0, 1) + elementTop); - } - else { - const viewItemBottom = elementTop + elementHeight; - const scrollBottom = scrollTop + this.view.renderHeight; - if (elementTop < scrollTop && viewItemBottom >= scrollBottom) { - // The element is already overflowing the viewport, no-op - } - else if (elementTop < scrollTop || (viewItemBottom >= scrollBottom && elementHeight >= this.view.renderHeight)) { - this.view.setScrollTop(elementTop); - } - else if (viewItemBottom >= scrollBottom) { - 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. - */ - getRelativeTop(index) { - if (index < 0 || index >= this.length) { - throw new list_1.ListError(this.user, `Invalid index ${index}`); - } - const scrollTop = this.view.getScrollTop(); - const elementTop = this.view.elementTop(index); - const elementHeight = this.view.elementHeight(index); - if (elementTop < scrollTop || elementTop + elementHeight > scrollTop + this.view.renderHeight) { - return null; - } - // y = mx + b - const m = elementHeight - this.view.renderHeight; - return Math.abs((scrollTop - elementTop) / m); - } - getHTMLElement() { - return this.view.domNode; - } - style(styles) { - this.styleController.style(styles); - } - toListEvent({ indexes, browserEvent }) { - return { indexes, elements: indexes.map(i => this.view.element(i)), browserEvent }; - } - _onFocusChange() { - const focus = this.focus.get(); - this.view.domNode.classList.toggle('element-focused', focus.length > 0); - this.onDidChangeActiveDescendant(); - } - onDidChangeActiveDescendant() { - var _a; - const focus = this.focus.get(); - if (focus.length > 0) { - let id; - 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'); - } - } - _onSelectionChange() { - const selection = this.selection.get(); - this.view.domNode.classList.toggle('selection-none', selection.length === 0); - this.view.domNode.classList.toggle('selection-single', selection.length === 1); - this.view.domNode.classList.toggle('selection-multiple', selection.length > 1); - } - dispose() { - this._onDidDispose.fire(); - this.disposables.dispose(); - this._onDidDispose.dispose(); - } - } - __decorate([ - decorators_1.memoize - ], List.prototype, "onDidChangeFocus", null); - __decorate([ - decorators_1.memoize - ], List.prototype, "onDidChangeSelection", null); - __decorate([ - decorators_1.memoize - ], List.prototype, "onContextMenu", null); - __decorate([ - decorators_1.memoize - ], List.prototype, "onKeyDown", null); - __decorate([ - decorators_1.memoize - ], List.prototype, "onDidFocus", null); - exports.List = List; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[320/*vs/base/browser/ui/list/listPaging*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,19/*vs/base/common/arrays*/,108/*vs/base/browser/ui/list/listWidget*/,6/*vs/base/common/event*/,23/*vs/base/common/cancellation*/,211/*vs/css!vs/base/browser/ui/list/list*/]), function (require, exports, lifecycle_1, arrays_1, listWidget_1, event_1, cancellation_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.PagedList = void 0; - class PagedRenderer { - constructor(renderer, modelProvider) { - this.renderer = renderer; - this.modelProvider = modelProvider; - } - get templateId() { return this.renderer.templateId; } - renderTemplate(container) { - const data = this.renderer.renderTemplate(container); - return { data, disposable: lifecycle_1.Disposable.None }; - } - renderElement(index, _, data, height) { - if (data.disposable) { - data.disposable.dispose(); - } - if (!data.data) { - return; - } - const model = this.modelProvider(); - if (model.isResolved(index)) { - return this.renderer.renderElement(model.get(index), index, data.data, height); - } - const cts = new cancellation_1.CancellationTokenSource(); - const promise = model.resolve(index, cts.token); - data.disposable = { dispose: () => cts.cancel() }; - this.renderer.renderPlaceholder(index, data.data); - promise.then(entry => this.renderer.renderElement(entry, index, data.data, height)); - } - disposeTemplate(data) { - if (data.disposable) { - data.disposable.dispose(); - data.disposable = undefined; - } - if (data.data) { - this.renderer.disposeTemplate(data.data); - data.data = undefined; - } - } - } - class PagedAccessibilityProvider { - constructor(modelProvider, accessibilityProvider) { - this.modelProvider = modelProvider; - this.accessibilityProvider = accessibilityProvider; - } - getWidgetAriaLabel() { - return this.accessibilityProvider.getWidgetAriaLabel(); - } - getAriaLabel(index) { - const model = this.modelProvider(); - if (!model.isResolved(index)) { - return null; - } - return this.accessibilityProvider.getAriaLabel(model.get(index)); - } - } - function fromPagedListOptions(modelProvider, options) { - return Object.assign(Object.assign({}, options), { accessibilityProvider: options.accessibilityProvider && new PagedAccessibilityProvider(modelProvider, options.accessibilityProvider) }); - } - class PagedList { - constructor(user, container, virtualDelegate, renderers, options = {}) { - const modelProvider = () => this.model; - const pagedRenderers = renderers.map(r => new PagedRenderer(r, modelProvider)); - this.list = new listWidget_1.List(user, container, virtualDelegate, pagedRenderers, fromPagedListOptions(modelProvider, options)); - } - updateOptions(options) { - this.list.updateOptions(options); - } - getHTMLElement() { - return this.list.getHTMLElement(); - } - get onDidFocus() { - return this.list.onDidFocus; - } - get onDidDispose() { - return this.list.onDidDispose; - } - get onMouseDblClick() { - return event_1.Event.map(this.list.onMouseDblClick, ({ element, index, browserEvent }) => ({ element: element === undefined ? undefined : this._model.get(element), index, browserEvent })); - } - get onPointer() { - return event_1.Event.map(this.list.onPointer, ({ element, index, browserEvent }) => ({ element: element === undefined ? undefined : this._model.get(element), index, browserEvent })); - } - get onDidChangeSelection() { - return event_1.Event.map(this.list.onDidChangeSelection, ({ elements, indexes, browserEvent }) => ({ elements: elements.map(e => this._model.get(e)), indexes, browserEvent })); - } - get model() { - return this._model; - } - set model(model) { - this._model = model; - this.list.splice(0, this.list.length, (0, arrays_1.range)(model.length)); - } - getFocus() { - return this.list.getFocus(); - } - getSelection() { - return this.list.getSelection(); - } - getSelectedElements() { - return this.getSelection().map(i => this.model.get(i)); - } - style(styles) { - this.list.style(styles); - } - dispose() { - this.list.dispose(); - } - } - exports.PagedList = PagedList; -}); - -define(__m[321/*vs/css!vs/base/browser/ui/splitview/splitview*/], __M([10/*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[212/*vs/base/browser/ui/splitview/splitview*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,6/*vs/base/common/event*/,20/*vs/base/common/types*/,102/*vs/base/common/numbers*/,19/*vs/base/common/arrays*/,107/*vs/base/browser/ui/sash/sash*/,29/*vs/base/common/color*/,7/*vs/base/browser/dom*/,61/*vs/base/browser/ui/scrollbar/scrollableElement*/,127/*vs/base/common/scrollable*/,321/*vs/css!vs/base/browser/ui/splitview/splitview*/]), function (require, exports, lifecycle_1, event_1, types, numbers_1, arrays_1, sash_1, color_1, dom_1, scrollableElement_1, scrollable_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.SplitView = exports.Sizing = void 0; - const defaultStyles = { - separatorBorder: color_1.Color.transparent - }; - class ViewItem { - constructor(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; - container.classList.add('visible'); - } - else { - this._size = 0; - this._cachedVisibleSize = size.cachedVisibleSize; - } - } - set size(size) { - this._size = size; - } - get size() { - return this._size; - } - get visible() { - return typeof this._cachedVisibleSize === 'undefined'; - } - setVisible(visible, size) { - if (visible === this.visible) { - return; - } - if (visible) { - this.size = (0, numbers_1.clamp)(this._cachedVisibleSize, this.viewMinimumSize, this.viewMaximumSize); - this._cachedVisibleSize = undefined; - } - else { - this._cachedVisibleSize = typeof size === 'number' ? size : this.size; - this.size = 0; - } - this.container.classList.toggle('visible', visible); - if (this.view.setVisible) { - this.view.setVisible(visible); - } - } - get minimumSize() { return this.visible ? this.view.minimumSize : 0; } - get viewMinimumSize() { return this.view.minimumSize; } - get maximumSize() { return this.visible ? this.view.maximumSize : 0; } - get viewMaximumSize() { return this.view.maximumSize; } - get priority() { return this.view.priority; } - get snap() { return !!this.view.snap; } - set enabled(enabled) { - this.container.style.pointerEvents = enabled ? '' : 'none'; - } - layout(offset, layoutContext) { - this.layoutContainer(offset); - this.view.layout(this.size, offset, layoutContext); - } - dispose() { - this.disposable.dispose(); - return this.view; - } - } - class VerticalViewItem extends ViewItem { - layoutContainer(offset) { - this.container.style.top = `${offset}px`; - this.container.style.height = `${this.size}px`; - } - } - class HorizontalViewItem extends ViewItem { - layoutContainer(offset) { - this.container.style.left = `${offset}px`; - this.container.style.width = `${this.size}px`; - } - } - 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 }; } - Sizing.Split = Split; - function Invisible(cachedVisibleSize) { return { type: 'invisible', cachedVisibleSize }; } - Sizing.Invisible = Invisible; - })(Sizing = exports.Sizing || (exports.Sizing = {})); - class SplitView extends lifecycle_1.Disposable { - constructor(container, options = {}) { - var _a, _b; - super(); - 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.getSashOrthogonalSize = options.getSashOrthogonalSize; - this.el = document.createElement('div'); - this.el.classList.add('monaco-split-view2'); - this.el.classList.add(this.orientation === 0 /* VERTICAL */ ? 'vertical' : 'horizontal'); - container.appendChild(this.el); - this.sashContainer = (0, dom_1.append)(this.el, (0, dom_1.$)('.sash-container')); - this.viewContainer = (0, dom_1.$)('.split-view-container'); - this.scrollable = new scrollable_1.Scrollable(125, dom_1.scheduleAtNextAnimationFrame); - this.scrollableElement = this._register(new scrollableElement_1.SmoothScrollableElement(this.viewContainer, { - vertical: this.orientation === 0 /* VERTICAL */ ? ((_a = options.scrollbarVisibility) !== null && _a !== void 0 ? _a : 1 /* Auto */) : 2 /* Hidden */, - horizontal: this.orientation === 1 /* HORIZONTAL */ ? ((_b = options.scrollbarVisibility) !== null && _b !== void 0 ? _b : 1 /* Auto */) : 2 /* Hidden */ - }, this.scrollable)); - this.onDidScroll = this.scrollableElement.onScroll; - this._register(this.onDidScroll(e => { - this.viewContainer.scrollTop = e.scrollTop; - this.viewContainer.scrollLeft = e.scrollLeft; - })); - (0, dom_1.append)(this.el, this.scrollableElement.getDomNode()); - 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((viewDescriptor, index) => { - const sizing = types.isUndefined(viewDescriptor.visible) || viewDescriptor.visible ? viewDescriptor.size : { type: 'invisible', cachedVisibleSize: viewDescriptor.size }; - const view = viewDescriptor.view; - this.doAddView(view, sizing, index, true); - }); - // Initialize content size and proportions for first layout - this.contentSize = this.viewItems.reduce((r, i) => r + i.size, 0); - this.saveProportions(); - } - } - get orthogonalStartSash() { return this._orthogonalStartSash; } - set orthogonalStartSash(sash) { - for (const sashItem of this.sashItems) { - sashItem.sash.orthogonalStartSash = sash; - } - this._orthogonalStartSash = sash; - } - get orthogonalEndSash() { return this._orthogonalEndSash; } - set orthogonalEndSash(sash) { - for (const sashItem of this.sashItems) { - sashItem.sash.orthogonalEndSash = sash; - } - this._orthogonalEndSash = sash; - } - get startSnappingEnabled() { return this._startSnappingEnabled; } - set startSnappingEnabled(startSnappingEnabled) { - if (this._startSnappingEnabled === startSnappingEnabled) { - return; - } - this._startSnappingEnabled = startSnappingEnabled; - this.updateSashEnablement(); - } - get endSnappingEnabled() { return this._endSnappingEnabled; } - set endSnappingEnabled(endSnappingEnabled) { - if (this._endSnappingEnabled === endSnappingEnabled) { - return; - } - this._endSnappingEnabled = endSnappingEnabled; - this.updateSashEnablement(); - } - style(styles) { - if (styles.separatorBorder.isTransparent()) { - this.el.classList.remove('separator-border'); - this.el.style.removeProperty('--separator-border'); - } - else { - this.el.classList.add('separator-border'); - this.el.style.setProperty('--separator-border', styles.separatorBorder.toString()); - } - } - addView(view, size, index = this.viewItems.length, skipLayout) { - this.doAddView(view, size, index, skipLayout); - } - layout(size, layoutContext) { - const previousSize = Math.max(this.size, this.contentSize); - this.size = size; - this.layoutContext = layoutContext; - if (!this.proportions) { - const indexes = (0, arrays_1.range)(this.viewItems.length); - const lowPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 1 /* Low */); - const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 2 /* High */); - this.resize(this.viewItems.length - 1, size - previousSize, undefined, lowPriorityIndexes, highPriorityIndexes); - } - else { - for (let i = 0; i < this.viewItems.length; i++) { - const item = this.viewItems[i]; - item.size = (0, numbers_1.clamp)(Math.round(this.proportions[i] * size), item.minimumSize, item.maximumSize); - } - } - this.distributeEmptySpace(); - this.layoutViews(); - } - saveProportions() { - if (this.proportionalLayout && this.contentSize > 0) { - this.proportions = this.viewItems.map(i => i.size / this.contentSize); - } - } - onSashStart({ sash, start, alt }) { - for (const item of this.viewItems) { - item.enabled = false; - } - const index = this.sashItems.findIndex(item => item.sash === sash); - // This way, we can press Alt while we resize a sash, macOS style! - const disposable = (0, lifecycle_1.combinedDisposable)((0, dom_1.addDisposableListener)(document.body, 'keydown', e => resetSashDragState(this.sashDragState.current, e.altKey)), (0, dom_1.addDisposableListener)(document.body, 'keyup', () => resetSashDragState(this.sashDragState.current, false))); - const resetSashDragState = (start, alt) => { - const sizes = this.viewItems.map(i => i.size); - let minDelta = Number.NEGATIVE_INFINITY; - let 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 - const isLastSash = index === this.sashItems.length - 1; - if (isLastSash) { - const viewItem = this.viewItems[index]; - minDelta = (viewItem.minimumSize - viewItem.size) / 2; - maxDelta = (viewItem.maximumSize - viewItem.size) / 2; - } - else { - const viewItem = this.viewItems[index + 1]; - minDelta = (viewItem.size - viewItem.maximumSize) / 2; - maxDelta = (viewItem.size - viewItem.minimumSize) / 2; - } - } - let snapBefore; - let snapAfter; - if (!alt) { - const upIndexes = (0, arrays_1.range)(index, -1); - const downIndexes = (0, arrays_1.range)(index + 1, this.viewItems.length); - const minDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].minimumSize - sizes[i]), 0); - const maxDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].viewMaximumSize - sizes[i]), 0); - const maxDeltaDown = downIndexes.length === 0 ? Number.POSITIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].minimumSize), 0); - const minDeltaDown = downIndexes.length === 0 ? Number.NEGATIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].viewMaximumSize), 0); - const minDelta = Math.max(minDeltaUp, minDeltaDown); - const maxDelta = Math.min(maxDeltaDown, maxDeltaUp); - const snapBeforeIndex = this.findFirstSnapIndex(upIndexes); - const snapAfterIndex = this.findFirstSnapIndex(downIndexes); - if (typeof snapBeforeIndex === 'number') { - const viewItem = this.viewItems[snapBeforeIndex]; - const halfSize = Math.floor(viewItem.viewMinimumSize / 2); - snapBefore = { - index: snapBeforeIndex, - limitDelta: viewItem.visible ? minDelta - halfSize : minDelta + halfSize, - size: viewItem.size - }; - } - if (typeof snapAfterIndex === 'number') { - const viewItem = this.viewItems[snapAfterIndex]; - const halfSize = Math.floor(viewItem.viewMinimumSize / 2); - snapAfter = { - index: snapAfterIndex, - limitDelta: viewItem.visible ? maxDelta + halfSize : maxDelta - halfSize, - size: viewItem.size - }; - } - } - this.sashDragState = { start, current: start, index, sizes, minDelta, maxDelta, alt, snapBefore, snapAfter, disposable }; - }; - resetSashDragState(start, alt); - } - onSashChange({ current }) { - const { index, start, sizes, alt, minDelta, maxDelta, snapBefore, snapAfter } = this.sashDragState; - this.sashDragState.current = current; - const delta = current - start; - const newDelta = this.resize(index, delta, sizes, undefined, undefined, minDelta, maxDelta, snapBefore, snapAfter); - if (alt) { - const isLastSash = index === this.sashItems.length - 1; - const newSizes = this.viewItems.map(i => i.size); - const viewItemIndex = isLastSash ? index : index + 1; - const viewItem = this.viewItems[viewItemIndex]; - const newMinDelta = viewItem.size - viewItem.maximumSize; - const newMaxDelta = viewItem.size - viewItem.minimumSize; - const resizeIndex = isLastSash ? index - 1 : index + 1; - this.resize(resizeIndex, -newDelta, newSizes, undefined, undefined, newMinDelta, newMaxDelta); - } - this.distributeEmptySpace(); - this.layoutViews(); - } - onSashEnd(index) { - this._onDidSashChange.fire(index); - this.sashDragState.disposable.dispose(); - this.saveProportions(); - for (const item of this.viewItems) { - item.enabled = true; - } - } - onViewChange(item, size) { - const index = this.viewItems.indexOf(item); - if (index < 0 || index >= this.viewItems.length) { - return; - } - size = typeof size === 'number' ? size : item.size; - size = (0, 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); - } - } - resizeView(index, size) { - if (this.state !== State.Idle) { - throw new Error('Cant modify splitview'); - } - this.state = State.Busy; - if (index < 0 || index >= this.viewItems.length) { - return; - } - const indexes = (0, arrays_1.range)(this.viewItems.length).filter(i => i !== index); - const lowPriorityIndexes = [...indexes.filter(i => this.viewItems[i].priority === 1 /* Low */), index]; - const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 2 /* High */); - const item = this.viewItems[index]; - size = Math.round(size); - size = (0, numbers_1.clamp)(size, item.minimumSize, Math.min(item.maximumSize, this.size)); - item.size = size; - this.relayout(lowPriorityIndexes, highPriorityIndexes); - this.state = State.Idle; - } - distributeViewSizes() { - const flexibleViewItems = []; - let flexibleSize = 0; - for (const item of this.viewItems) { - if (item.maximumSize - item.minimumSize > 0) { - flexibleViewItems.push(item); - flexibleSize += item.size; - } - } - const size = Math.floor(flexibleSize / flexibleViewItems.length); - for (const item of flexibleViewItems) { - item.size = (0, numbers_1.clamp)(size, item.minimumSize, item.maximumSize); - } - const indexes = (0, arrays_1.range)(this.viewItems.length); - const lowPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 1 /* Low */); - const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 2 /* High */); - this.relayout(lowPriorityIndexes, highPriorityIndexes); - } - getViewSize(index) { - if (index < 0 || index >= this.viewItems.length) { - return -1; - } - return this.viewItems[index].size; - } - doAddView(view, size, index = this.viewItems.length, skipLayout) { - if (this.state !== State.Idle) { - throw new Error('Cant modify splitview'); - } - this.state = State.Busy; - // Add view - const container = (0, dom_1.$)('.split-view-view'); - if (index === this.viewItems.length) { - this.viewContainer.appendChild(container); - } - else { - this.viewContainer.insertBefore(container, this.viewContainer.children.item(index)); - } - const onChangeDisposable = view.onDidChange(size => this.onViewChange(item, size)); - const containerDisposable = (0, lifecycle_1.toDisposable)(() => this.viewContainer.removeChild(container)); - const disposable = (0, lifecycle_1.combinedDisposable)(onChangeDisposable, containerDisposable); - let 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; - } - const 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) { - let opts = { orthogonalStartSash: this.orthogonalStartSash, orthogonalEndSash: this.orthogonalEndSash }; - const sash = this.orientation === 0 /* VERTICAL */ - ? new sash_1.Sash(this.sashContainer, { getHorizontalSashTop: s => this.getSashPosition(s), getHorizontalSashWidth: this.getSashOrthogonalSize }, Object.assign(Object.assign({}, opts), { orientation: 1 /* HORIZONTAL */ })) - : new sash_1.Sash(this.sashContainer, { getVerticalSashLeft: s => this.getSashPosition(s), getVerticalSashHeight: this.getSashOrthogonalSize }, Object.assign(Object.assign({}, opts), { orientation: 0 /* VERTICAL */ })); - const sashEventMapper = this.orientation === 0 /* VERTICAL */ - ? (e) => ({ sash, start: e.startY, current: e.currentY, alt: e.altKey }) - : (e) => ({ sash, start: e.startX, current: e.currentX, alt: e.altKey }); - const onStart = event_1.Event.map(sash.onDidStart, sashEventMapper); - const onStartDisposable = onStart(this.onSashStart, this); - const onChange = event_1.Event.map(sash.onDidChange, sashEventMapper); - const onChangeDisposable = onChange(this.onSashChange, this); - const onEnd = event_1.Event.map(sash.onDidEnd, () => this.sashItems.findIndex(item => item.sash === sash)); - const onEndDisposable = onEnd(this.onSashEnd, this); - const onDidResetDisposable = sash.onDidReset(() => { - const index = this.sashItems.findIndex(item => item.sash === sash); - const upIndexes = (0, arrays_1.range)(index, -1); - const downIndexes = (0, arrays_1.range)(index + 1, this.viewItems.length); - const snapBeforeIndex = this.findFirstSnapIndex(upIndexes); - const 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); - }); - const disposable = (0, lifecycle_1.combinedDisposable)(onStartDisposable, onChangeDisposable, onEndDisposable, onDidResetDisposable, sash); - const sashItem = { sash, disposable }; - this.sashItems.splice(index - 1, 0, sashItem); - } - container.appendChild(view.element); - let 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(); - } - } - relayout(lowPriorityIndexes, highPriorityIndexes) { - const contentSize = this.viewItems.reduce((r, i) => r + i.size, 0); - this.resize(this.viewItems.length - 1, this.size - contentSize, undefined, lowPriorityIndexes, highPriorityIndexes); - this.distributeEmptySpace(); - this.layoutViews(); - this.saveProportions(); - } - resize(index, delta, sizes = this.viewItems.map(i => i.size), lowPriorityIndexes, highPriorityIndexes, overloadMinDelta = Number.NEGATIVE_INFINITY, overloadMaxDelta = Number.POSITIVE_INFINITY, snapBefore, snapAfter) { - if (index < 0 || index >= this.viewItems.length) { - return 0; - } - const upIndexes = (0, arrays_1.range)(index, -1); - const downIndexes = (0, arrays_1.range)(index + 1, this.viewItems.length); - if (highPriorityIndexes) { - for (const index of highPriorityIndexes) { - (0, arrays_1.pushToStart)(upIndexes, index); - (0, arrays_1.pushToStart)(downIndexes, index); - } - } - if (lowPriorityIndexes) { - for (const index of lowPriorityIndexes) { - (0, arrays_1.pushToEnd)(upIndexes, index); - (0, arrays_1.pushToEnd)(downIndexes, index); - } - } - const upItems = upIndexes.map(i => this.viewItems[i]); - const upSizes = upIndexes.map(i => sizes[i]); - const downItems = downIndexes.map(i => this.viewItems[i]); - const downSizes = downIndexes.map(i => sizes[i]); - const minDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].minimumSize - sizes[i]), 0); - const maxDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].maximumSize - sizes[i]), 0); - const maxDeltaDown = downIndexes.length === 0 ? Number.POSITIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].minimumSize), 0); - const minDeltaDown = downIndexes.length === 0 ? Number.NEGATIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].maximumSize), 0); - const minDelta = Math.max(minDeltaUp, minDeltaDown, overloadMinDelta); - const maxDelta = Math.min(maxDeltaDown, maxDeltaUp, overloadMaxDelta); - let snapped = false; - if (snapBefore) { - const snapView = this.viewItems[snapBefore.index]; - const visible = delta >= snapBefore.limitDelta; - snapped = visible !== snapView.visible; - snapView.setVisible(visible, snapBefore.size); - } - if (!snapped && snapAfter) { - const snapView = this.viewItems[snapAfter.index]; - const 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 = (0, numbers_1.clamp)(delta, minDelta, maxDelta); - for (let i = 0, deltaUp = delta; i < upItems.length; i++) { - const item = upItems[i]; - const size = (0, numbers_1.clamp)(upSizes[i] + deltaUp, item.minimumSize, item.maximumSize); - const viewDelta = size - upSizes[i]; - deltaUp -= viewDelta; - item.size = size; - } - for (let i = 0, deltaDown = delta; i < downItems.length; i++) { - const item = downItems[i]; - const size = (0, numbers_1.clamp)(downSizes[i] - deltaDown, item.minimumSize, item.maximumSize); - const viewDelta = size - downSizes[i]; - deltaDown += viewDelta; - item.size = size; - } - return delta; - } - distributeEmptySpace(lowPriorityIndex) { - const contentSize = this.viewItems.reduce((r, i) => r + i.size, 0); - let emptyDelta = this.size - contentSize; - const indexes = (0, arrays_1.range)(this.viewItems.length - 1, -1); - const lowPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 1 /* Low */); - const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 2 /* High */); - for (const index of highPriorityIndexes) { - (0, arrays_1.pushToStart)(indexes, index); - } - for (const index of lowPriorityIndexes) { - (0, arrays_1.pushToEnd)(indexes, index); - } - if (typeof lowPriorityIndex === 'number') { - (0, arrays_1.pushToEnd)(indexes, lowPriorityIndex); - } - for (let i = 0; emptyDelta !== 0 && i < indexes.length; i++) { - const item = this.viewItems[indexes[i]]; - const size = (0, numbers_1.clamp)(item.size + emptyDelta, item.minimumSize, item.maximumSize); - const viewDelta = size - item.size; - emptyDelta -= viewDelta; - item.size = size; - } - } - layoutViews() { - // Save new content size - this.contentSize = this.viewItems.reduce((r, i) => r + i.size, 0); - // Layout views - let offset = 0; - for (const viewItem of this.viewItems) { - viewItem.layout(offset, this.layoutContext); - offset += viewItem.size; - } - // Layout sashes - this.sashItems.forEach(item => item.sash.layout()); - this.updateSashEnablement(); - this.updateScrollableElement(); - } - updateScrollableElement() { - if (this.orientation === 0 /* VERTICAL */) { - this.scrollableElement.setScrollDimensions({ - height: this.size, - scrollHeight: this.contentSize - }); - } - else { - this.scrollableElement.setScrollDimensions({ - width: this.size, - scrollWidth: this.contentSize - }); - } - } - updateSashEnablement() { - let previous = false; - const collapsesDown = this.viewItems.map(i => previous = (i.size - i.minimumSize > 0) || previous); - previous = false; - const expandsDown = this.viewItems.map(i => previous = (i.maximumSize - i.size > 0) || previous); - const reverseViews = [...this.viewItems].reverse(); - previous = false; - const collapsesUp = reverseViews.map(i => previous = (i.size - i.minimumSize > 0) || previous).reverse(); - previous = false; - const expandsUp = reverseViews.map(i => previous = (i.maximumSize - i.size > 0) || previous).reverse(); - let position = 0; - for (let index = 0; index < this.sashItems.length; index++) { - const { sash } = this.sashItems[index]; - const viewItem = this.viewItems[index]; - position += viewItem.size; - const min = !(collapsesDown[index] && expandsUp[index + 1]); - const max = !(expandsDown[index] && collapsesUp[index + 1]); - if (min && max) { - const upIndexes = (0, arrays_1.range)(index, -1); - const downIndexes = (0, arrays_1.range)(index + 1, this.viewItems.length); - const snapBeforeIndex = this.findFirstSnapIndex(upIndexes); - const snapAfterIndex = this.findFirstSnapIndex(downIndexes); - const snappedBefore = typeof snapBeforeIndex === 'number' && !this.viewItems[snapBeforeIndex].visible; - const 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 */; - } - } - } - getSashPosition(sash) { - let position = 0; - for (let i = 0; i < this.sashItems.length; i++) { - position += this.viewItems[i].size; - if (this.sashItems[i].sash === sash) { - return position; - } - } - return 0; - } - findFirstSnapIndex(indexes) { - // visible views first - for (const index of indexes) { - const viewItem = this.viewItems[index]; - if (!viewItem.visible) { - continue; - } - if (viewItem.snap) { - return index; - } - } - // then, hidden views - for (const index of indexes) { - const viewItem = this.viewItems[index]; - if (viewItem.visible && viewItem.maximumSize - viewItem.minimumSize > 0) { - return undefined; - } - if (!viewItem.visible && viewItem.snap) { - return index; - } - } - return undefined; - } - dispose() { - super.dispose(); - this.viewItems.forEach(i => i.dispose()); - this.viewItems = []; - this.sashItems.forEach(i => i.disposable.dispose()); - this.sashItems = []; - } - } - exports.SplitView = SplitView; -}); - -define(__m[322/*vs/css!vs/base/browser/ui/table/table*/], __M([10/*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[323/*vs/base/browser/ui/table/tableWidget*/], __M([0/*require*/,1/*exports*/,108/*vs/base/browser/ui/list/listWidget*/,7/*vs/base/browser/dom*/,212/*vs/base/browser/ui/splitview/splitview*/,6/*vs/base/common/event*/,322/*vs/css!vs/base/browser/ui/table/table*/]), function (require, exports, listWidget_1, dom_1, splitview_1, event_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Table = void 0; - class TableListRenderer { - constructor(columns, renderers, getColumnSize) { - this.columns = columns; - this.getColumnSize = getColumnSize; - this.templateId = TableListRenderer.TemplateId; - this.renderedTemplates = new Set(); - const rendererMap = new Map(renderers.map(r => [r.templateId, r])); - this.renderers = []; - for (const column of columns) { - const renderer = rendererMap.get(column.templateId); - if (!renderer) { - throw new Error(`Table cell renderer for template id ${column.templateId} not found.`); - } - this.renderers.push(renderer); - } - } - renderTemplate(container) { - const rowContainer = (0, dom_1.append)(container, (0, dom_1.$)('.monaco-table-tr')); - const cellContainers = []; - const cellTemplateData = []; - for (let i = 0; i < this.columns.length; i++) { - const renderer = this.renderers[i]; - const cellContainer = (0, dom_1.append)(rowContainer, (0, dom_1.$)('.monaco-table-td', { 'data-col-index': i })); - cellContainer.style.width = `${this.getColumnSize(i)}px`; - cellContainers.push(cellContainer); - cellTemplateData.push(renderer.renderTemplate(cellContainer)); - } - const result = { container, cellContainers, cellTemplateData }; - this.renderedTemplates.add(result); - return result; - } - renderElement(element, index, templateData, height) { - for (let i = 0; i < this.columns.length; i++) { - const column = this.columns[i]; - const cell = column.project(element); - const renderer = this.renderers[i]; - renderer.renderElement(cell, index, templateData.cellTemplateData[i], height); - } - } - disposeElement(element, index, templateData, height) { - for (let i = 0; i < this.columns.length; i++) { - const renderer = this.renderers[i]; - if (renderer.disposeElement) { - const column = this.columns[i]; - const cell = column.project(element); - renderer.disposeElement(cell, index, templateData.cellTemplateData[i], height); - } - } - } - disposeTemplate(templateData) { - for (let i = 0; i < this.columns.length; i++) { - const renderer = this.renderers[i]; - renderer.disposeTemplate(templateData.cellTemplateData[i]); - } - (0, dom_1.clearNode)(templateData.container); - this.renderedTemplates.delete(templateData); - } - layoutColumn(index, size) { - for (const { cellContainers } of this.renderedTemplates) { - cellContainers[index].style.width = `${size}px`; - } - } - } - TableListRenderer.TemplateId = 'row'; - function asListVirtualDelegate(delegate) { - return { - getHeight(row) { return delegate.getHeight(row); }, - getTemplateId() { return TableListRenderer.TemplateId; }, - }; - } - class ColumnHeader { - constructor(column, index) { - this.column = column; - this.index = index; - this._onDidLayout = new event_1.Emitter(); - this.onDidLayout = this._onDidLayout.event; - this.element = (0, dom_1.$)('.monaco-table-th', { 'data-col-index': index, title: column.tooltip }, column.label); - } - get minimumSize() { var _a; return (_a = this.column.minimumWidth) !== null && _a !== void 0 ? _a : 120; } - get maximumSize() { var _a; return (_a = this.column.maximumWidth) !== null && _a !== void 0 ? _a : Number.POSITIVE_INFINITY; } - get onDidChange() { var _a; return (_a = this.column.onDidChangeWidthConstraints) !== null && _a !== void 0 ? _a : event_1.Event.None; } - layout(size) { - this._onDidLayout.fire([this.index, size]); - } - } - class Table { - constructor(user, container, virtualDelegate, columns, renderers, _options) { - this.virtualDelegate = virtualDelegate; - this.domId = `table_id_${++Table.InstanceCount}`; - this.cachedHeight = 0; - this.domNode = (0, dom_1.append)(container, (0, dom_1.$)(`.monaco-table.${this.domId}`)); - const headers = columns.map((c, i) => new ColumnHeader(c, i)); - const descriptor = { - size: headers.reduce((a, b) => a + b.column.weight, 0), - views: headers.map(view => ({ size: view.column.weight, view })) - }; - this.splitview = new splitview_1.SplitView(this.domNode, { - orientation: 1 /* HORIZONTAL */, - scrollbarVisibility: 2 /* Hidden */, - getSashOrthogonalSize: () => this.cachedHeight, - descriptor - }); - this.splitview.el.style.height = `${virtualDelegate.headerRowHeight}px`; - this.splitview.el.style.lineHeight = `${virtualDelegate.headerRowHeight}px`; - const renderer = new TableListRenderer(columns, renderers, i => this.splitview.getViewSize(i)); - this.list = new listWidget_1.List(user, this.domNode, asListVirtualDelegate(virtualDelegate), [renderer], _options); - this.columnLayoutDisposable = event_1.Event.any(...headers.map(h => h.onDidLayout))(([index, size]) => renderer.layoutColumn(index, size)); - this.styleElement = (0, dom_1.createStyleSheet)(this.domNode); - this.style({}); - } - get onDidChangeFocus() { return this.list.onDidChangeFocus; } - get onDidChangeSelection() { return this.list.onDidChangeSelection; } - get onMouseDblClick() { return this.list.onMouseDblClick; } - get onPointer() { return this.list.onPointer; } - get onDidFocus() { return this.list.onDidFocus; } - get onDidDispose() { return this.list.onDidDispose; } - updateOptions(options) { - this.list.updateOptions(options); - } - splice(start, deleteCount, elements = []) { - this.list.splice(start, deleteCount, elements); - } - getHTMLElement() { - return this.domNode; - } - style(styles) { - const content = []; - content.push(`.monaco-table.${this.domId} > .monaco-split-view2 .monaco-sash.vertical::before { - top: ${this.virtualDelegate.headerRowHeight + 1}px; - height: calc(100% - ${this.virtualDelegate.headerRowHeight}px); - }`); - this.styleElement.textContent = content.join('\n'); - this.list.style(styles); - } - getSelectedElements() { - return this.list.getSelectedElements(); - } - getSelection() { - return this.list.getSelection(); - } - getFocus() { - return this.list.getFocus(); - } - dispose() { - this.splitview.dispose(); - this.list.dispose(); - this.columnLayoutDisposable.dispose(); - } - } - exports.Table = Table; - Table.InstanceCount = 0; -}); - -define(__m[324/*vs/css!vs/base/browser/ui/tree/media/tree*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[132/*vs/css!vs/base/parts/quickinput/browser/media/quickInput*/], __M([10/*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[213/*vs/base/parts/quickinput/browser/quickInputUtils*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,125/*vs/base/common/idGenerator*/,132/*vs/css!vs/base/parts/quickinput/browser/media/quickInput*/]), function (require, exports, dom, idGenerator_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getIconClass = void 0; - const iconPathToClass = {}; - const iconClassGenerator = new idGenerator_1.IdGenerator('quick-input-button-icon-'); - function getIconClass(iconPath) { - if (!iconPath) { - return undefined; - } - let iconClass; - const key = iconPath.dark.toString(); - if (iconPathToClass[key]) { - iconClass = iconPathToClass[key]; - } - else { - iconClass = iconClassGenerator.nextId(); - dom.createCSSRule(`.${iconClass}`, `background-image: ${dom.asCSSUrl(iconPath.light || iconPath.dark)}`); - dom.createCSSRule(`.vs-dark .${iconClass}, .hc-black .${iconClass}`, `background-image: ${dom.asCSSUrl(iconPath.dark)}`); - iconPathToClass[key] = iconClass; - } - return iconClass; - } - exports.getIconClass = getIconClass; -}); - -define(__m[325/*vs/css!vs/editor/browser/controller/textAreaHandler*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[326/*vs/css!vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[327/*vs/css!vs/editor/browser/viewParts/decorations/decorations*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[328/*vs/css!vs/editor/browser/viewParts/glyphMargin/glyphMargin*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[329/*vs/css!vs/editor/browser/viewParts/indentGuides/indentGuides*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[330/*vs/css!vs/editor/browser/viewParts/lineNumbers/lineNumbers*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[331/*vs/css!vs/editor/browser/viewParts/lines/viewLines*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[332/*vs/css!vs/editor/browser/viewParts/linesDecorations/linesDecorations*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[333/*vs/css!vs/editor/browser/viewParts/marginDecorations/marginDecorations*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[334/*vs/css!vs/editor/browser/viewParts/minimap/minimap*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[335/*vs/css!vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[336/*vs/css!vs/editor/browser/viewParts/rulers/rulers*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[337/*vs/css!vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[338/*vs/css!vs/editor/browser/viewParts/selections/selections*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[339/*vs/css!vs/editor/browser/viewParts/viewCursors/viewCursors*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[340/*vs/css!vs/editor/browser/widget/media/diffEditor*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[341/*vs/css!vs/editor/browser/widget/media/diffReview*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[342/*vs/css!vs/editor/browser/widget/media/editor*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[343/*vs/css!vs/editor/contrib/anchorSelect/anchorSelect*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[344/*vs/css!vs/editor/contrib/bracketMatching/bracketMatching*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[345/*vs/css!vs/editor/contrib/codeAction/lightBulbWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[346/*vs/css!vs/editor/contrib/codelens/codelensWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[347/*vs/css!vs/editor/contrib/colorPicker/colorPicker*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[348/*vs/css!vs/editor/contrib/dnd/dnd*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[349/*vs/css!vs/editor/contrib/find/findWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[350/*vs/css!vs/editor/contrib/folding/folding*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[351/*vs/css!vs/editor/contrib/gotoError/media/gotoErrorWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[352/*vs/css!vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[353/*vs/css!vs/editor/contrib/gotoSymbol/peek/referencesWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[354/*vs/css!vs/editor/contrib/inlineCompletions/ghostText*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[355/*vs/css!vs/editor/contrib/links/links*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[356/*vs/css!vs/editor/contrib/message/messageController*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[357/*vs/css!vs/editor/contrib/parameterHints/parameterHints*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[358/*vs/css!vs/editor/contrib/peekView/media/peekViewWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[359/*vs/css!vs/editor/contrib/rename/renameInputField*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[360/*vs/css!vs/editor/contrib/snippet/snippetSession*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[361/*vs/css!vs/editor/contrib/suggest/media/suggest*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[362/*vs/css!vs/editor/contrib/zoneWidget/zoneWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[363/*vs/css!vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[364/*vs/css!vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[365/*vs/css!vs/editor/standalone/browser/inspectTokens/inspectTokens*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[366/*vs/css!vs/editor/standalone/browser/quickInput/standaloneQuickInput*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[367/*vs/css!vs/editor/standalone/browser/standalone-tokens*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[368/*vs/css!vs/platform/actions/browser/menuEntryActionViewItem*/], __M([10/*vs/css!vs/editor/editor.main*/]), {}); -define(__m[369/*vs/css!vs/platform/contextview/browser/contextMenuHandler*/], __M([10/*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[370/*vs/editor/browser/config/charWidthReader*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.readCharWidths = exports.CharWidthRequest = void 0; - class CharWidthRequest { - constructor(chr, type) { - this.chr = chr; - this.type = type; - this.width = 0; - } - fulfill(width) { - this.width = width; - } - } - exports.CharWidthRequest = CharWidthRequest; - class DomCharWidthReader { - constructor(bareFontInfo, requests) { - this._bareFontInfo = bareFontInfo; - this._requests = requests; - this._container = null; - this._testElements = null; - } - read() { - // 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; - } - _createDomElements() { - const container = document.createElement('div'); - container.style.position = 'absolute'; - container.style.top = '-50000px'; - container.style.width = '50000px'; - const 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); - const 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); - const 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); - const testElements = []; - for (const request of this._requests) { - let parent; - if (request.type === 0 /* Regular */) { - parent = regularDomNode; - } - if (request.type === 2 /* Bold */) { - parent = boldDomNode; - } - if (request.type === 1 /* Italic */) { - parent = italicDomNode; - } - parent.appendChild(document.createElement('br')); - const testElement = document.createElement('span'); - DomCharWidthReader._render(testElement, request); - parent.appendChild(testElement); - testElements.push(testElement); - } - this._container = container; - this._testElements = testElements; - } - static _render(testElement, request) { - if (request.chr === ' ') { - let htmlString = '\u00a0'; - // Repeat character 256 (2^8) times - for (let i = 0; i < 8; i++) { - htmlString += htmlString; - } - testElement.innerText = htmlString; - } - else { - let testString = request.chr; - // Repeat character 256 (2^8) times - for (let i = 0; i < 8; i++) { - testString += testString; - } - testElement.textContent = testString; - } - } - _readFromDomElements() { - for (let i = 0, len = this._requests.length; i < len; i++) { - const request = this._requests[i]; - const testElement = this._testElements[i]; - request.fulfill(testElement.offsetWidth / 256); - } - } - } - function readCharWidths(bareFontInfo, requests) { - const 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[214/*vs/editor/browser/config/elementSizeObserver*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/]), function (require, exports, lifecycle_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ElementSizeObserver = void 0; - class ElementSizeObserver extends lifecycle_1.Disposable { - constructor(referenceDomElement, dimension, changeCallback) { - super(); - this.referenceDomElement = referenceDomElement; - this.changeCallback = changeCallback; - this.width = -1; - this.height = -1; - this.resizeObserver = null; - this.measureReferenceDomElementToken = -1; - this.measureReferenceDomElement(false, dimension); - } - dispose() { - this.stopObserving(); - super.dispose(); - } - getWidth() { - return this.width; - } - getHeight() { - return this.height; - } - startObserving() { - if (typeof ResizeObserver !== 'undefined') { - if (!this.resizeObserver && this.referenceDomElement) { - this.resizeObserver = new ResizeObserver((entries) => { - if (entries && entries[0] && entries[0].contentRect) { - this.observe({ width: entries[0].contentRect.width, height: entries[0].contentRect.height }); - } - else { - this.observe(); - } - }); - this.resizeObserver.observe(this.referenceDomElement); - } - } - else { - if (this.measureReferenceDomElementToken === -1) { - // setInterval type defaults to NodeJS.Timeout instead of number, so specify it as a number - this.measureReferenceDomElementToken = setInterval(() => this.observe(), 100); - } - } - } - stopObserving() { - if (this.resizeObserver) { - this.resizeObserver.disconnect(); - this.resizeObserver = null; - } - if (this.measureReferenceDomElementToken !== -1) { - clearInterval(this.measureReferenceDomElementToken); - this.measureReferenceDomElementToken = -1; - } - } - observe(dimension) { - this.measureReferenceDomElement(true, dimension); - } - measureReferenceDomElement(callChangeCallback, dimension) { - let observedWidth = 0; - let 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(); - } - } - } - } - 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[167/*vs/editor/browser/editorDom*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,93/*vs/base/browser/globalMouseMoveMonitor*/,55/*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 }); - exports.GlobalEditorMouseMoveMonitor = exports.EditorPointerEventFactory = exports.EditorMouseEventFactory = exports.EditorMouseEvent = exports.createEditorPagePosition = exports.EditorPagePosition = exports.ClientCoordinates = exports.PageCoordinates = void 0; - /** - * Coordinates relative to the whole document (e.g. mouse event's pageX and pageY) - */ - class PageCoordinates { - constructor(x, y) { - this.x = x; - this.y = y; - this._pageCoordinatesBrand = undefined; - } - toClientCoordinates() { - return new ClientCoordinates(this.x - dom.StandardWindow.scrollX, this.y - dom.StandardWindow.scrollY); - } - } - 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. - */ - class ClientCoordinates { - constructor(clientX, clientY) { - this.clientX = clientX; - this.clientY = clientY; - this._clientCoordinatesBrand = undefined; - } - toPageCoordinates() { - return new PageCoordinates(this.clientX + dom.StandardWindow.scrollX, this.clientY + dom.StandardWindow.scrollY); - } - } - exports.ClientCoordinates = ClientCoordinates; - /** - * The position of the editor in the page. - */ - class EditorPagePosition { - constructor(x, y, width, height) { - this.x = x; - this.y = y; - this.width = width; - this.height = height; - this._editorPagePositionBrand = undefined; - } - } - exports.EditorPagePosition = EditorPagePosition; - function createEditorPagePosition(editorViewDomNode) { - const editorPos = dom.getDomNodePagePosition(editorViewDomNode); - return new EditorPagePosition(editorPos.left, editorPos.top, editorPos.width, editorPos.height); - } - exports.createEditorPagePosition = createEditorPagePosition; - class EditorMouseEvent extends mouseEvent_1.StandardMouseEvent { - constructor(e, editorViewDomNode) { - super(e); - this._editorMouseEventBrand = undefined; - this.pos = new PageCoordinates(this.posx, this.posy); - this.editorPos = createEditorPagePosition(editorViewDomNode); - } - } - exports.EditorMouseEvent = EditorMouseEvent; - class EditorMouseEventFactory { - constructor(editorViewDomNode) { - this._editorViewDomNode = editorViewDomNode; - } - _create(e) { - return new EditorMouseEvent(e, this._editorViewDomNode); - } - onContextMenu(target, callback) { - return dom.addDisposableListener(target, 'contextmenu', (e) => { - callback(this._create(e)); - }); - } - onMouseUp(target, callback) { - return dom.addDisposableListener(target, 'mouseup', (e) => { - callback(this._create(e)); - }); - } - onMouseDown(target, callback) { - return dom.addDisposableListener(target, 'mousedown', (e) => { - callback(this._create(e)); - }); - } - onMouseLeave(target, callback) { - return dom.addDisposableNonBubblingMouseOutListener(target, (e) => { - callback(this._create(e)); - }); - } - onMouseMoveThrottled(target, callback, merger, minimumTimeMs) { - const myMerger = (lastEvent, currentEvent) => { - return merger(lastEvent, this._create(currentEvent)); - }; - return dom.addDisposableThrottledListener(target, 'mousemove', callback, myMerger, minimumTimeMs); - } - } - exports.EditorMouseEventFactory = EditorMouseEventFactory; - class EditorPointerEventFactory { - constructor(editorViewDomNode) { - this._editorViewDomNode = editorViewDomNode; - } - _create(e) { - return new EditorMouseEvent(e, this._editorViewDomNode); - } - onPointerUp(target, callback) { - return dom.addDisposableListener(target, 'pointerup', (e) => { - callback(this._create(e)); - }); - } - onPointerDown(target, callback) { - return dom.addDisposableListener(target, 'pointerdown', (e) => { - callback(this._create(e)); - }); - } - onPointerLeave(target, callback) { - return dom.addDisposableNonBubblingPointerOutListener(target, (e) => { - callback(this._create(e)); - }); - } - onPointerMoveThrottled(target, callback, merger, minimumTimeMs) { - const myMerger = (lastEvent, currentEvent) => { - return merger(lastEvent, this._create(currentEvent)); - }; - return dom.addDisposableThrottledListener(target, 'pointermove', callback, myMerger, minimumTimeMs); - } - } - exports.EditorPointerEventFactory = EditorPointerEventFactory; - class GlobalEditorMouseMoveMonitor extends lifecycle_1.Disposable { - constructor(editorViewDomNode) { - super(); - this._editorViewDomNode = editorViewDomNode; - this._globalMouseMoveMonitor = this._register(new globalMouseMoveMonitor_1.GlobalMouseMoveMonitor()); - this._keydownListener = null; - } - startMonitoring(initialElement, initialButtons, merger, mouseMoveCallback, onStopCallback) { - // 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', (e) => { - const kb = e.toKeybinding(); - if (kb.isModifierKey()) { - // Allow modifier keys - return; - } - this._globalMouseMoveMonitor.stopMonitoring(true, e.browserEvent); - }, true); - const myMerger = (lastEvent, currentEvent) => { - return merger(lastEvent, new EditorMouseEvent(currentEvent, this._editorViewDomNode)); - }; - this._globalMouseMoveMonitor.startMonitoring(initialElement, initialButtons, myMerger, mouseMoveCallback, (e) => { - this._keydownListener.dispose(); - onStopCallback(e); - }); - } - stopMonitoring() { - this._globalMouseMoveMonitor.stopMonitoring(true); - } - } - 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[371/*vs/editor/browser/services/abstractCodeEditorService*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/]), function (require, exports, event_1, lifecycle_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.AbstractCodeEditorService = void 0; - class AbstractCodeEditorService extends lifecycle_1.Disposable { - constructor() { - super(); - 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._onDecorationTypeRegistered = this._register(new event_1.Emitter()); - this._modelProperties = new Map(); - this._codeEditors = Object.create(null); - this._diffEditors = Object.create(null); - } - addCodeEditor(editor) { - this._codeEditors[editor.getId()] = editor; - this._onCodeEditorAdd.fire(editor); - } - removeCodeEditor(editor) { - if (delete this._codeEditors[editor.getId()]) { - this._onCodeEditorRemove.fire(editor); - } - } - listCodeEditors() { - return Object.keys(this._codeEditors).map(id => this._codeEditors[id]); - } - addDiffEditor(editor) { - this._diffEditors[editor.getId()] = editor; - this._onDiffEditorAdd.fire(editor); - } - removeDiffEditor(editor) { - if (delete this._diffEditors[editor.getId()]) { - this._onDiffEditorRemove.fire(editor); - } - } - listDiffEditors() { - return Object.keys(this._diffEditors).map(id => this._diffEditors[id]); - } - getFocusedCodeEditor() { - let editorWithWidgetFocus = null; - const editors = this.listCodeEditors(); - for (const editor of editors) { - if (editor.hasTextFocus()) { - // bingo! - return editor; - } - if (editor.hasWidgetFocus()) { - editorWithWidgetFocus = editor; - } - } - return editorWithWidgetFocus; - } - setModelProperty(resource, key, value) { - const key1 = resource.toString(); - let dest; - if (this._modelProperties.has(key1)) { - dest = this._modelProperties.get(key1); - } - else { - dest = new Map(); - this._modelProperties.set(key1, dest); - } - dest.set(key, value); - } - getModelProperty(resource, key) { - const key1 = resource.toString(); - if (this._modelProperties.has(key1)) { - const innerMap = this._modelProperties.get(key1); - return innerMap.get(key); - } - return undefined; - } - } - 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[215/*vs/editor/browser/viewParts/minimap/minimapCharSheet*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getCharIndex = exports.allCharCodes = void 0; - exports.allCharCodes = (() => { - const v = []; - for (let i = 32 /* START_CH_CODE */; i <= 126 /* END_CH_CODE */; i++) { - v.push(i); - } - v.push(65533 /* UNKNOWN_CODE */); - return v; - })(); - const getCharIndex = (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; - }; - exports.getCharIndex = getCharIndex; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/minimap/minimapCharRenderer*/], __M([0/*require*/,1/*exports*/,215/*vs/editor/browser/viewParts/minimap/minimapCharSheet*/,129/*vs/base/common/uint*/]), function (require, exports, minimapCharSheet_1, uint_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MinimapCharRenderer = void 0; - class MinimapCharRenderer { - constructor(charData, scale) { - this.scale = scale; - this._minimapCharRendererBrand = undefined; - this.charDataNormal = MinimapCharRenderer.soften(charData, 12 / 15); - this.charDataLight = MinimapCharRenderer.soften(charData, 50 / 60); - } - static soften(input, ratio) { - let result = new Uint8ClampedArray(input.length); - for (let i = 0, len = input.length; i < len; i++) { - result[i] = (0, uint_1.toUint8)(input[i] * ratio); - } - return result; - } - renderChar(target, dx, dy, chCode, color, backgroundColor, fontScale, useLighterFont, force1pxHeight) { - const charWidth = 1 /* BASE_CHAR_WIDTH */ * this.scale; - const charHeight = 2 /* BASE_CHAR_HEIGHT */ * this.scale; - const renderHeight = (force1pxHeight ? 1 : charHeight); - if (dx + charWidth > target.width || dy + renderHeight > target.height) { - console.warn('bad render request outside image data'); - return; - } - const charData = useLighterFont ? this.charDataLight : this.charDataNormal; - const charIndex = (0, minimapCharSheet_1.getCharIndex)(chCode, fontScale); - const destWidth = target.width * 4 /* RGBA_CHANNELS_CNT */; - const backgroundR = backgroundColor.r; - const backgroundG = backgroundColor.g; - const backgroundB = backgroundColor.b; - const deltaR = color.r - backgroundR; - const deltaG = color.g - backgroundG; - const deltaB = color.b - backgroundB; - const dest = target.data; - let sourceOffset = charIndex * charWidth * charHeight; - let row = dy * destWidth + dx * 4 /* RGBA_CHANNELS_CNT */; - for (let y = 0; y < renderHeight; y++) { - let column = row; - for (let x = 0; x < charWidth; x++) { - const c = charData[sourceOffset++] / 255; - dest[column++] = backgroundR + deltaR * c; - dest[column++] = backgroundG + deltaG * c; - dest[column++] = backgroundB + deltaB * c; - column++; - } - row += destWidth; - } - } - blockRenderChar(target, dx, dy, color, backgroundColor, useLighterFont, force1pxHeight) { - const charWidth = 1 /* BASE_CHAR_WIDTH */ * this.scale; - const charHeight = 2 /* BASE_CHAR_HEIGHT */ * this.scale; - const renderHeight = (force1pxHeight ? 1 : charHeight); - if (dx + charWidth > target.width || dy + renderHeight > target.height) { - console.warn('bad render request outside image data'); - return; - } - const destWidth = target.width * 4 /* RGBA_CHANNELS_CNT */; - const c = 0.5; - const backgroundR = backgroundColor.r; - const backgroundG = backgroundColor.g; - const backgroundB = backgroundColor.b; - const deltaR = color.r - backgroundR; - const deltaG = color.g - backgroundG; - const deltaB = color.b - backgroundB; - const colorR = backgroundR + deltaR * c; - const colorG = backgroundG + deltaG * c; - const colorB = backgroundB + deltaB * c; - const dest = target.data; - let row = dy * destWidth + dx * 4 /* RGBA_CHANNELS_CNT */; - for (let y = 0; y < renderHeight; y++) { - let column = row; - for (let x = 0; x < charWidth; x++) { - dest[column++] = colorR; - dest[column++] = colorG; - dest[column++] = colorB; - column++; - } - row += destWidth; - } - } - } - 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[373/*vs/editor/browser/viewParts/minimap/minimapPreBaked*/], __M([0/*require*/,1/*exports*/,80/*vs/base/common/functional*/]), function (require, exports, functional_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.prebakedMiniMaps = void 0; - const 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 - }; - const decodeData = (str) => { - const output = new Uint8ClampedArray(str.length / 2); - for (let 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: (0, functional_1.once)(() => decodeData('0000511D6300CF609C709645A78432005642574171487021003C451900274D35D762755E8B629C5BA856AF57BA649530C167D1512A272A3F6038604460398526BCA2A968DB6F8957C768BE5FBE2FB467CF5D8D5B795DC7625B5DFF50DE64C466DB2FC47CD860A65E9A2EB96CB54CE06DA763AB2EA26860524D3763536601005116008177A8705E53AB738E6A982F88BAA35B5F5B626D9C636B449B737E5B7B678598869A662F6B5B8542706C704C80736A607578685B70594A49715A4522E792')), - 2: (0, functional_1.once)(() => 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[374/*vs/editor/browser/viewParts/minimap/minimapCharRendererFactory*/], __M([0/*require*/,1/*exports*/,372/*vs/editor/browser/viewParts/minimap/minimapCharRenderer*/,215/*vs/editor/browser/viewParts/minimap/minimapCharSheet*/,373/*vs/editor/browser/viewParts/minimap/minimapPreBaked*/,129/*vs/base/common/uint*/]), function (require, exports, minimapCharRenderer_1, minimapCharSheet_1, minimapPreBaked_1, uint_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MinimapCharRendererFactory = void 0; - /** - * 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. - */ - class MinimapCharRendererFactory { - /** - * Creates a new character renderer factory with the given scale. - */ - static create(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; - } - let 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. - */ - static createSampleData(fontFamily) { - const canvas = document.createElement('canvas'); - const 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'; - let x = 0; - for (const code of minimapCharSheet_1.allCharCodes) { - 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. - */ - static createFromSampleData(source, scale) { - const 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'); - } - let charData = MinimapCharRendererFactory._downsample(source, scale); - return new minimapCharRenderer_1.MinimapCharRenderer(charData, scale); - } - static _downsampleChar(source, sourceOffset, dest, destOffset, scale) { - const width = 1 /* BASE_CHAR_WIDTH */ * scale; - const height = 2 /* BASE_CHAR_HEIGHT */ * scale; - let targetIndex = destOffset; - let 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 (let 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) - const sourceY1 = (y / height) * 16 /* SAMPLED_CHAR_HEIGHT */; - const sourceY2 = ((y + 1) / height) * 16 /* SAMPLED_CHAR_HEIGHT */; - for (let x = 0; x < width; x++) { - const sourceX1 = (x / width) * 10 /* SAMPLED_CHAR_WIDTH */; - const sourceX2 = ((x + 1) / width) * 10 /* SAMPLED_CHAR_WIDTH */; - // 2. Sample all of them, summing them up and weighting them. Similar - // to bilinear interpolation. - let value = 0; - let samples = 0; - for (let sy = sourceY1; sy < sourceY2; sy++) { - const sourceRow = sourceOffset + Math.floor(sy) * 3840 /* RGBA_SAMPLED_ROW_WIDTH */; - const yBalance = 1 - (sy - Math.floor(sy)); - for (let sx = sourceX1; sx < sourceX2; sx++) { - const xBalance = 1 - (sx - Math.floor(sx)); - const sourceIndex = sourceRow + Math.floor(sx) * 4 /* RGBA_CHANNELS_CNT */; - const weight = xBalance * yBalance; - samples += weight; - value += ((source[sourceIndex] * source[sourceIndex + 3]) / 255) * weight; - } - } - const final = value / samples; - brightest = Math.max(brightest, final); - dest[targetIndex++] = (0, uint_1.toUint8)(final); - } - } - return brightest; - } - static _downsample(data, scale) { - const pixelsPerCharacter = 2 /* BASE_CHAR_HEIGHT */ * scale * 1 /* BASE_CHAR_WIDTH */ * scale; - const resultLen = pixelsPerCharacter * 96 /* CHAR_COUNT */; - const result = new Uint8ClampedArray(resultLen); - let resultOffset = 0; - let sourceOffset = 0; - let brightest = 0; - for (let 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) { - const adjust = 255 / brightest; - for (let i = 0; i < resultLen; i++) { - result[i] *= adjust; - } - } - return result; - } - } - 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[133/*vs/editor/common/config/editorZoom*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/]), function (require, exports, event_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.EditorZoom = void 0; - exports.EditorZoom = new class { - constructor() { - this._zoomLevel = 0; - this._onDidChangeZoomLevel = new event_1.Emitter(); - this.onDidChangeZoomLevel = this._onDidChangeZoomLevel.event; - } - getZoomLevel() { - return this._zoomLevel; - } - setZoomLevel(zoomLevel) { - zoomLevel = Math.min(Math.max(-5, zoomLevel), 20); - if (this._zoomLevel === zoomLevel) { - return; - } - this._zoomLevel = zoomLevel; - this._onDidChangeZoomLevel.fire(this._zoomLevel); - } - }; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[168/*vs/editor/common/config/fontInfo*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/,133/*vs/editor/common/config/editorZoom*/]), function (require, exports, platform, editorZoom_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.FontInfo = exports.SERIALIZED_FONT_INFO_VERSION = exports.BareFontInfo = void 0; - /** - * Determined from empirical observations. - * @internal - */ - const GOLDEN_LINE_HEIGHT_RATIO = platform.isMacintosh ? 1.5 : 1.35; - /** - * @internal - */ - const MINIMUM_LINE_HEIGHT = 8; - class BareFontInfo { - /** - * @internal - */ - constructor(opts) { - this._bareFontInfoBrand = undefined; - this.zoomLevel = opts.zoomLevel; - this.pixelRatio = opts.pixelRatio; - 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 - */ - static createFromValidatedSettings(options, zoomLevel, pixelRatio, ignoreEditorZoom) { - const fontFamily = options.get(40 /* fontFamily */); - const fontWeight = options.get(44 /* fontWeight */); - const fontSize = options.get(43 /* fontSize */); - const fontFeatureSettings = options.get(42 /* fontLigatures */); - const lineHeight = options.get(57 /* lineHeight */); - const letterSpacing = options.get(54 /* letterSpacing */); - return BareFontInfo._create(fontFamily, fontWeight, fontSize, fontFeatureSettings, lineHeight, letterSpacing, zoomLevel, pixelRatio, ignoreEditorZoom); - } - /** - * @internal - */ - static _create(fontFamily, fontWeight, fontSize, fontFeatureSettings, lineHeight, letterSpacing, zoomLevel, pixelRatio, ignoreEditorZoom) { - if (lineHeight === 0) { - lineHeight = GOLDEN_LINE_HEIGHT_RATIO * fontSize; - } - else if (lineHeight < MINIMUM_LINE_HEIGHT) { - // Values too small to be line heights in pixels are probably in ems. Accept them gracefully. - lineHeight = lineHeight * fontSize; - } - // Enforce integer, minimum constraints - lineHeight = Math.round(lineHeight); - if (lineHeight < MINIMUM_LINE_HEIGHT) { - lineHeight = MINIMUM_LINE_HEIGHT; - } - const editorZoomLevelMultiplier = 1 + (ignoreEditorZoom ? 0 : editorZoom_1.EditorZoom.getZoomLevel() * 0.1); - fontSize *= editorZoomLevelMultiplier; - lineHeight *= editorZoomLevelMultiplier; - return new BareFontInfo({ - zoomLevel: zoomLevel, - pixelRatio: pixelRatio, - fontFamily: fontFamily, - fontWeight: fontWeight, - fontSize: fontSize, - fontFeatureSettings: fontFeatureSettings, - lineHeight: lineHeight, - letterSpacing: letterSpacing - }); - } - /** - * @internal - */ - getId() { - return this.zoomLevel + '-' + this.pixelRatio + '-' + this.fontFamily + '-' + this.fontWeight + '-' + this.fontSize + '-' + this.fontFeatureSettings + '-' + this.lineHeight + '-' + this.letterSpacing; - } - /** - * @internal - */ - getMassagedFontFamily() { - 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; - } - } - exports.BareFontInfo = BareFontInfo; - // change this whenever `FontInfo` members are changed - exports.SERIALIZED_FONT_INFO_VERSION = 1; - class FontInfo extends BareFontInfo { - /** - * @internal - */ - constructor(opts, isTrusted) { - super(opts); - this._editorStylingBrand = undefined; - this.version = exports.SERIALIZED_FONT_INFO_VERSION; - 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.wsmiddotWidth = opts.wsmiddotWidth; - this.maxDigitWidth = opts.maxDigitWidth; - } - /** - * @internal - */ - equals(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.wsmiddotWidth === other.wsmiddotWidth - && this.maxDigitWidth === other.maxDigitWidth); - } - } - 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[94/*vs/editor/common/core/characterClassifier*/], __M([0/*require*/,1/*exports*/,129/*vs/base/common/uint*/]), function (require, exports, uint_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CharacterSet = exports.CharacterClassifier = void 0; - /** - * A fast character classifier that uses a compact array for ASCII values. - */ - class CharacterClassifier { - constructor(_defaultValue) { - let defaultValue = (0, uint_1.toUint8)(_defaultValue); - this._defaultValue = defaultValue; - this._asciiMap = CharacterClassifier._createAsciiMap(defaultValue); - this._map = new Map(); - } - static _createAsciiMap(defaultValue) { - let asciiMap = new Uint8Array(256); - for (let i = 0; i < 256; i++) { - asciiMap[i] = defaultValue; - } - return asciiMap; - } - set(charCode, _value) { - let value = (0, uint_1.toUint8)(_value); - if (charCode >= 0 && charCode < 256) { - this._asciiMap[charCode] = value; - } - else { - this._map.set(charCode, value); - } - } - get(charCode) { - if (charCode >= 0 && charCode < 256) { - return this._asciiMap[charCode]; - } - else { - return (this._map.get(charCode) || this._defaultValue); - } - } - } - exports.CharacterClassifier = CharacterClassifier; - class CharacterSet { - constructor() { - this._actual = new CharacterClassifier(0 /* False */); - } - add(charCode) { - this._actual.set(charCode, 1 /* True */); - } - has(charCode) { - return (this._actual.get(charCode) === 1 /* True */); - } - } - 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[109/*vs/editor/common/controller/wordCharacterClassifier*/], __M([0/*require*/,1/*exports*/,94/*vs/editor/common/core/characterClassifier*/]), function (require, exports, characterClassifier_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getMapForWordSeparators = exports.WordCharacterClassifier = void 0; - class WordCharacterClassifier extends characterClassifier_1.CharacterClassifier { - constructor(wordSeparators) { - super(0 /* Regular */); - for (let 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 */); - } - } - exports.WordCharacterClassifier = WordCharacterClassifier; - function once(computeFn) { - let cache = {}; // TODO@Alex unbounded cache - return (input) => { - if (!cache.hasOwnProperty(input)) { - cache[input] = computeFn(input); - } - return cache[input]; - }; - } - exports.getMapForWordSeparators = once((input) => 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 }); - exports.Position = void 0; - /** - * A position in the editor. - */ - class Position { - constructor(lineNumber, column) { - this.lineNumber = lineNumber; - this.column = column; - } - /** - * Create a new position from this position. - * - * @param newLineNumber new line number - * @param newColumn new column - */ - with(newLineNumber = this.lineNumber, 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 - */ - delta(deltaLineNumber = 0, deltaColumn = 0) { - return this.with(this.lineNumber + deltaLineNumber, this.column + deltaColumn); - } - /** - * Test if this position equals other position - */ - equals(other) { - return Position.equals(this, other); - } - /** - * Test if position `a` equals position `b` - */ - static equals(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. - */ - isBefore(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. - */ - static isBefore(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. - */ - isBeforeOrEqual(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. - */ - static isBeforeOrEqual(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 - */ - static compare(a, b) { - let aLineNumber = a.lineNumber | 0; - let bLineNumber = b.lineNumber | 0; - if (aLineNumber === bLineNumber) { - let aColumn = a.column | 0; - let bColumn = b.column | 0; - return aColumn - bColumn; - } - return aLineNumber - bLineNumber; - } - /** - * Clone this position. - */ - clone() { - return new Position(this.lineNumber, this.column); - } - /** - * Convert to a human-readable representation. - */ - toString() { - return '(' + this.lineNumber + ',' + this.column + ')'; - } - // --- - /** - * Create a `Position` from an `IPosition`. - */ - static lift(pos) { - return new Position(pos.lineNumber, pos.column); - } - /** - * Test if `obj` is an `IPosition`. - */ - static isIPosition(obj) { - return (obj - && (typeof obj.lineNumber === 'number') - && (typeof obj.column === 'number')); - } - } - 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 }); - exports.Range = void 0; - /** - * A range in the editor. (startLineNumber,startColumn) is <= (endLineNumber,endColumn) - */ - class Range { - constructor(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. - */ - isEmpty() { - return Range.isEmpty(this); - } - /** - * Test if `range` is empty. - */ - static isEmpty(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. - */ - containsPosition(position) { - return Range.containsPosition(this, position); - } - /** - * Test if `position` is in `range`. If the position is at the edges, will return true. - */ - static containsPosition(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. - */ - containsRange(range) { - return Range.containsRange(this, range); - } - /** - * Test if `otherRange` is in `range`. If the ranges are equal, will return true. - */ - static containsRange(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. - */ - strictContainsRange(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. - */ - static strictContainsRange(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. - */ - plusRange(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. - */ - static plusRange(a, b) { - let startLineNumber; - let startColumn; - let endLineNumber; - let 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. - */ - intersectRanges(range) { - return Range.intersectRanges(this, range); - } - /** - * A intersection of the two ranges. - */ - static intersectRanges(a, b) { - let resultStartLineNumber = a.startLineNumber; - let resultStartColumn = a.startColumn; - let resultEndLineNumber = a.endLineNumber; - let resultEndColumn = a.endColumn; - let otherStartLineNumber = b.startLineNumber; - let otherStartColumn = b.startColumn; - let otherEndLineNumber = b.endLineNumber; - let 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. - */ - equalsRange(other) { - return Range.equalsRange(this, other); - } - /** - * Test if range `a` equals `b`. - */ - static equalsRange(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) - */ - getEndPosition() { - return Range.getEndPosition(this); - } - /** - * Return the end position (which will be after or equal to the start position) - */ - static getEndPosition(range) { - return new position_1.Position(range.endLineNumber, range.endColumn); - } - /** - * Return the start position (which will be before or equal to the end position) - */ - getStartPosition() { - return Range.getStartPosition(this); - } - /** - * Return the start position (which will be before or equal to the end position) - */ - static getStartPosition(range) { - return new position_1.Position(range.startLineNumber, range.startColumn); - } - /** - * Transform to a user presentable string representation. - */ - toString() { - 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. - */ - setEndPosition(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. - */ - setStartPosition(startLineNumber, startColumn) { - return new Range(startLineNumber, startColumn, this.endLineNumber, this.endColumn); - } - /** - * Create a new empty range using this range's start position. - */ - collapseToStart() { - return Range.collapseToStart(this); - } - /** - * Create a new empty range using this range's start position. - */ - static collapseToStart(range) { - return new Range(range.startLineNumber, range.startColumn, range.startLineNumber, range.startColumn); - } - // --- - static fromPositions(start, end = start) { - return new Range(start.lineNumber, start.column, end.lineNumber, end.column); - } - static lift(range) { - if (!range) { - return null; - } - return new Range(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn); - } - /** - * Test if `obj` is an `IRange`. - */ - static isIRange(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. - */ - static areIntersectingOrTouching(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. - */ - static areIntersecting(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 - */ - static compareRangesUsingStarts(a, b) { - if (a && b) { - const aStartLineNumber = a.startLineNumber | 0; - const bStartLineNumber = b.startLineNumber | 0; - if (aStartLineNumber === bStartLineNumber) { - const aStartColumn = a.startColumn | 0; - const bStartColumn = b.startColumn | 0; - if (aStartColumn === bStartColumn) { - const aEndLineNumber = a.endLineNumber | 0; - const bEndLineNumber = b.endLineNumber | 0; - if (aEndLineNumber === bEndLineNumber) { - const aEndColumn = a.endColumn | 0; - const bEndColumn = b.endColumn | 0; - return aEndColumn - bEndColumn; - } - return aEndLineNumber - bEndLineNumber; - } - return aStartColumn - bStartColumn; - } - return aStartLineNumber - bStartLineNumber; - } - const aExists = (a ? 1 : 0); - const 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 - */ - static compareRangesUsingEnds(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. - */ - static spansMultipleLines(range) { - return range.endLineNumber > range.startLineNumber; - } - } - 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[216/*vs/editor/browser/controller/textAreaState*/], __M([0/*require*/,1/*exports*/,8/*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 }); - exports.PagedScreenReaderStrategy = exports.TextAreaState = exports._debugComposition = void 0; - exports._debugComposition = false; - class TextAreaState { - constructor(value, selectionStart, selectionEnd, selectionStartPosition, selectionEndPosition) { - this.value = value; - this.selectionStart = selectionStart; - this.selectionEnd = selectionEnd; - this.selectionStartPosition = selectionStartPosition; - this.selectionEndPosition = selectionEndPosition; - } - toString() { - return '[ <' + this.value + '>, selectionStart: ' + this.selectionStart + ', selectionEnd: ' + this.selectionEnd + ']'; - } - static readFromTextArea(textArea) { - return new TextAreaState(textArea.getValue(), textArea.getSelectionStart(), textArea.getSelectionEnd(), null, null); - } - collapseSelection() { - return new TextAreaState(this.value, this.value.length, this.value.length, null, null); - } - writeToTextArea(reason, textArea, select) { - if (exports._debugComposition) { - console.log('writeToTextArea ' + reason + ': ' + this.toString()); - } - textArea.setValue(reason, this.value); - if (select) { - textArea.setSelectionRange(reason, this.selectionStart, this.selectionEnd); - } - } - deduceEditorPosition(offset) { - if (offset <= this.selectionStart) { - const str = this.value.substring(offset, this.selectionStart); - return this._finishDeduceEditorPosition(this.selectionStartPosition, str, -1); - } - if (offset >= this.selectionEnd) { - const str = this.value.substring(this.selectionEnd, offset); - return this._finishDeduceEditorPosition(this.selectionEndPosition, str, 1); - } - const str1 = this.value.substring(this.selectionStart, offset); - if (str1.indexOf(String.fromCharCode(8230)) === -1) { - return this._finishDeduceEditorPosition(this.selectionStartPosition, str1, 1); - } - const str2 = this.value.substring(offset, this.selectionEnd); - return this._finishDeduceEditorPosition(this.selectionEndPosition, str2, -1); - } - _finishDeduceEditorPosition(anchor, deltaText, signum) { - let lineFeedCnt = 0; - let lastLineFeedIndex = -1; - while ((lastLineFeedIndex = deltaText.indexOf('\n', lastLineFeedIndex + 1)) !== -1) { - lineFeedCnt++; - } - return [anchor, signum * deltaText.length, lineFeedCnt]; - } - static selectedText(text) { - return new TextAreaState(text, 0, text.length, null, null); - } - static deduceInput(previousState, currentState, couldBeEmojiInput) { - if (!previousState) { - // This is the EMPTY state - return { - text: '', - replacePrevCharCnt: 0, - replaceNextCharCnt: 0, - positionDelta: 0 - }; - } - if (exports._debugComposition) { - console.log('------------------------deduceInput'); - console.log('PREVIOUS STATE: ' + previousState.toString()); - console.log('CURRENT STATE: ' + currentState.toString()); - } - let previousValue = previousState.value; - let previousSelectionStart = previousState.selectionStart; - let previousSelectionEnd = previousState.selectionEnd; - let currentValue = currentState.value; - let currentSelectionStart = currentState.selectionStart; - let currentSelectionEnd = currentState.selectionEnd; - // Strip the previous suffix from the value (without interfering with the current selection) - const previousSuffix = previousValue.substring(previousSelectionEnd); - const currentSuffix = currentValue.substring(currentSelectionEnd); - const suffixLength = strings.commonSuffixLength(previousSuffix, currentSuffix); - currentValue = currentValue.substring(0, currentValue.length - suffixLength); - previousValue = previousValue.substring(0, previousValue.length - suffixLength); - const previousPrefix = previousValue.substring(0, previousSelectionStart); - const currentPrefix = currentValue.substring(0, currentSelectionStart); - const prefixLength = strings.commonPrefixLength(previousPrefix, currentPrefix); - currentValue = currentValue.substring(prefixLength); - previousValue = previousValue.substring(prefixLength); - currentSelectionStart -= prefixLength; - previousSelectionStart -= prefixLength; - currentSelectionEnd -= prefixLength; - previousSelectionEnd -= prefixLength; - if (exports._debugComposition) { - 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 - let potentialEmojiInput = null; - if (currentSelectionStart === currentValue.length) { - // emoji potentially inserted "somewhere" after the previous selection => it should appear at the end of `currentValue` - if (currentValue.startsWith(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 (currentValue.endsWith(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, - replacePrevCharCnt: 0, - replaceNextCharCnt: 0, - positionDelta: 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: '', - replacePrevCharCnt: 0, - replaceNextCharCnt: 0, - positionDelta: 0 - }; - } - } - // no current selection - const replacePreviousCharacters = (previousPrefix.length - prefixLength); - if (exports._debugComposition) { - console.log('REMOVE PREVIOUS: ' + (previousPrefix.length - prefixLength) + ' chars'); - } - return { - text: currentValue, - replacePrevCharCnt: replacePreviousCharacters, - replaceNextCharCnt: 0, - positionDelta: 0 - }; - } - // there is a current selection => composition case - const replacePreviousCharacters = previousSelectionEnd - previousSelectionStart; - return { - text: currentValue, - replacePrevCharCnt: replacePreviousCharacters, - replaceNextCharCnt: 0, - positionDelta: 0 - }; - } - static deduceAndroidCompositionInput(previousState, currentState) { - if (!previousState) { - // This is the EMPTY state - return { - text: '', - replacePrevCharCnt: 0, - replaceNextCharCnt: 0, - positionDelta: 0 - }; - } - if (exports._debugComposition) { - console.log('------------------------deduceAndroidCompositionInput'); - console.log('PREVIOUS STATE: ' + previousState.toString()); - console.log('CURRENT STATE: ' + currentState.toString()); - } - if (previousState.value === currentState.value) { - return { - text: '', - replacePrevCharCnt: 0, - replaceNextCharCnt: 0, - positionDelta: currentState.selectionEnd - previousState.selectionEnd - }; - } - const prefixLength = Math.min(strings.commonPrefixLength(previousState.value, currentState.value), previousState.selectionEnd); - const suffixLength = Math.min(strings.commonSuffixLength(previousState.value, currentState.value), previousState.value.length - previousState.selectionEnd); - const previousValue = previousState.value.substring(prefixLength, previousState.value.length - suffixLength); - const currentValue = currentState.value.substring(prefixLength, currentState.value.length - suffixLength); - const previousSelectionStart = previousState.selectionStart - prefixLength; - const previousSelectionEnd = previousState.selectionEnd - prefixLength; - const currentSelectionStart = currentState.selectionStart - prefixLength; - const currentSelectionEnd = currentState.selectionEnd - prefixLength; - if (exports._debugComposition) { - console.log('AFTER DIFFING PREVIOUS STATE: <' + previousValue + '>, selectionStart: ' + previousSelectionStart + ', selectionEnd: ' + previousSelectionEnd); - console.log('AFTER DIFFING CURRENT STATE: <' + currentValue + '>, selectionStart: ' + currentSelectionStart + ', selectionEnd: ' + currentSelectionEnd); - } - return { - text: currentValue, - replacePrevCharCnt: previousSelectionEnd, - replaceNextCharCnt: previousValue.length - previousSelectionEnd, - positionDelta: currentSelectionEnd - currentValue.length - }; - } - } - exports.TextAreaState = TextAreaState; - TextAreaState.EMPTY = new TextAreaState('', 0, 0, null, null); - class PagedScreenReaderStrategy { - static _getPageOfLine(lineNumber, linesPerPage) { - return Math.floor((lineNumber - 1) / linesPerPage); - } - static _getRangeForPage(page, linesPerPage) { - const offset = page * linesPerPage; - const startLineNumber = offset + 1; - const endLineNumber = offset + linesPerPage; - return new range_1.Range(startLineNumber, 1, endLineNumber + 1, 1); - } - static fromEditorSelection(previousState, model, selection, linesPerPage, trimLongText) { - const selectionStartPage = PagedScreenReaderStrategy._getPageOfLine(selection.startLineNumber, linesPerPage); - const selectionStartPageRange = PagedScreenReaderStrategy._getRangeForPage(selectionStartPage, linesPerPage); - const selectionEndPage = PagedScreenReaderStrategy._getPageOfLine(selection.endLineNumber, linesPerPage); - const selectionEndPageRange = PagedScreenReaderStrategy._getRangeForPage(selectionEndPage, linesPerPage); - const pretextRange = selectionStartPageRange.intersectRanges(new range_1.Range(1, 1, selection.startLineNumber, selection.startColumn)); - let pretext = model.getValueInRange(pretextRange, 1 /* LF */); - const lastLine = model.getLineCount(); - const lastLineMaxColumn = model.getLineMaxColumn(lastLine); - const posttextRange = selectionEndPageRange.intersectRanges(new range_1.Range(selection.endLineNumber, selection.endColumn, lastLine, lastLineMaxColumn)); - let posttext = model.getValueInRange(posttextRange, 1 /* LF */); - let text; - if (selectionStartPage === selectionEndPage || selectionStartPage + 1 === selectionEndPage) { - // take full selection - text = model.getValueInRange(selection, 1 /* LF */); - } - else { - const selectionRange1 = selectionStartPageRange.intersectRanges(selection); - const 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) { - const 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)); - } - } - 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[217/*vs/editor/browser/widget/diffNavigator*/], __M([0/*require*/,1/*exports*/,198/*vs/base/common/assert*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,42/*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 }); - exports.DiffNavigator = void 0; - const defaultOptions = { - followsCaret: true, - ignoreCharChanges: true, - alwaysRevealFirst: true - }; - /** - * Create a new diff navigator for the provided diff editor. - */ - class DiffNavigator extends lifecycle_1.Disposable { - constructor(editor, options = {}) { - super(); - 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(() => this.dispose())); - this._register(this._editor.onDidUpdateDiff(() => this._onDiffUpdated())); - if (this._options.followsCaret) { - this._register(this._editor.getModifiedEditor().onDidChangeCursorPosition((e) => { - if (this.ignoreSelectionChange) { - return; - } - this.nextIdx = -1; - })); - } - if (this._options.alwaysRevealFirst) { - this._register(this._editor.getModifiedEditor().onDidChangeModel((e) => { - this.revealFirst = true; - })); - } - // init things - this._init(); - } - _init() { - let changes = this._editor.getLineChanges(); - if (!changes) { - return; - } - } - _onDiffUpdated() { - 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 */); - } - } - } - _compute(lineChanges) { - // new ranges - this.ranges = []; - if (lineChanges) { - // create ranges from changes - lineChanges.forEach((lineChange) => { - if (!this._options.ignoreCharChanges && lineChange.charChanges) { - lineChange.charChanges.forEach((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((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); - } - _initIdx(fwd) { - let found = false; - let position = this._editor.getPosition(); - if (!position) { - this.nextIdx = 0; - return; - } - for (let i = 0, len = this.ranges.length; i < len && !found; i++) { - let 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; - } - } - _move(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; - } - } - let info = this.ranges[this.nextIdx]; - this.ignoreSelectionChange = true; - try { - let pos = info.range.getStartPosition(); - this._editor.setPosition(pos); - this._editor.revealPositionInCenter(pos, scrollType); - } - finally { - this.ignoreSelectionChange = false; - } - } - canNavigate() { - return this.ranges && this.ranges.length > 0; - } - next(scrollType = 0 /* Smooth */) { - this._move(true, scrollType); - } - previous(scrollType = 0 /* Smooth */) { - this._move(false, scrollType); - } - dispose() { - super.dispose(); - this.ranges = []; - this.disposed = true; - } - } - 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[56/*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 }); - exports.EditOperation = void 0; - class EditOperation { - static insert(position, text) { - return { - range: new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column), - text: text, - forceMoveMarkers: true - }; - } - static delete(range) { - return { - range: range, - text: null - }; - } - static replace(range, text) { - return { - range: range, - text: text - }; - } - static replaceMove(range, text) { - return { - range: range, - text: text, - forceMoveMarkers: true - }; - } - } - 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[375/*vs/editor/common/commands/trimTrailingWhitespaceCommand*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,56/*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 }); - exports.trimTrailingWhitespace = exports.TrimTrailingWhitespaceCommand = void 0; - class TrimTrailingWhitespaceCommand { - constructor(selection, cursors) { - this._selection = selection; - this._cursors = cursors; - this._selectionId = null; - } - getEditOperations(model, builder) { - let ops = trimTrailingWhitespace(model, this._cursors); - for (let i = 0, len = ops.length; i < len; i++) { - let op = ops[i]; - builder.addEditOperation(op.range, op.text); - } - this._selectionId = builder.trackSelection(this._selection); - } - computeCursorState(model, helper) { - return helper.getTrackedSelection(this._selectionId); - } - } - 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((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 (let i = cursors.length - 2; i >= 0; i--) { - if (cursors[i].lineNumber === cursors[i + 1].lineNumber) { - // Remove cursor at `i` - cursors.splice(i, 1); - } - } - let r = []; - let rLen = 0; - let cursorIndex = 0; - let cursorLen = cursors.length; - for (let lineNumber = 1, lineCount = model.getLineCount(); lineNumber <= lineCount; lineNumber++) { - let lineContent = model.getLineContent(lineNumber); - let maxLineColumn = lineContent.length + 1; - let 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; - } - let lastNonWhitespaceIndex = strings.lastNonWhitespaceIndex(lineContent); - let 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[218/*vs/editor/common/core/rgba*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.RGBA8 = void 0; - /** - * A very VM friendly rgba datastructure. - * Please don't touch unless you take a look at the IR. - */ - class RGBA8 { - constructor(r, g, b, a) { - this._rgba8Brand = undefined; - this.r = RGBA8._clamp(r); - this.g = RGBA8._clamp(g); - this.b = RGBA8._clamp(b); - this.a = RGBA8._clamp(a); - } - equals(other) { - return (this.r === other.r - && this.g === other.g - && this.b === other.b - && this.a === other.a); - } - static _clamp(c) { - if (c < 0) { - return 0; - } - if (c > 255) { - return 255; - } - return c | 0; - } - } - exports.RGBA8 = RGBA8; - RGBA8.Empty = new RGBA8(0, 0, 0, 0); -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[21/*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 }); - exports.Selection = void 0; - /** - * A selection in the editor. - * The selection is a range that has an orientation. - */ - class Selection extends range_1.Range { - constructor(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn) { - super(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn); - this.selectionStartLineNumber = selectionStartLineNumber; - this.selectionStartColumn = selectionStartColumn; - this.positionLineNumber = positionLineNumber; - this.positionColumn = positionColumn; - } - /** - * Transform to a human-readable representation. - */ - toString() { - return '[' + this.selectionStartLineNumber + ',' + this.selectionStartColumn + ' -> ' + this.positionLineNumber + ',' + this.positionColumn + ']'; - } - /** - * Test if equals other selection. - */ - equalsSelection(other) { - return (Selection.selectionsEqual(this, other)); - } - /** - * Test if the two selections are equal. - */ - static selectionsEqual(a, b) { - return (a.selectionStartLineNumber === b.selectionStartLineNumber && - a.selectionStartColumn === b.selectionStartColumn && - a.positionLineNumber === b.positionLineNumber && - a.positionColumn === b.positionColumn); - } - /** - * Get directions (LTR or RTL). - */ - getDirection() { - 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`. - */ - setEndPosition(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`. - */ - getPosition() { - return new position_1.Position(this.positionLineNumber, this.positionColumn); - } - /** - * Create a new selection with a different `selectionStartLineNumber` and `selectionStartColumn`. - */ - setStartPosition(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 - */ - static fromPositions(start, end = start) { - return new Selection(start.lineNumber, start.column, end.lineNumber, end.column); - } - /** - * Create a `Selection` from an `ISelection`. - */ - static liftSelection(sel) { - return new Selection(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn); - } - /** - * `a` equals `b`. - */ - static selectionsArrEqual(a, b) { - if (a && !b || !a && b) { - return false; - } - if (!a && !b) { - return true; - } - if (a.length !== b.length) { - return false; - } - for (let 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`. - */ - static isISelection(obj) { - return (obj - && (typeof obj.selectionStartLineNumber === 'number') - && (typeof obj.selectionStartColumn === 'number') - && (typeof obj.positionLineNumber === 'number') - && (typeof obj.positionColumn === 'number')); - } - /** - * Create with a direction. - */ - static createWithDirection(startLineNumber, startColumn, endLineNumber, endColumn, direction) { - if (direction === 0 /* LTR */) { - return new Selection(startLineNumber, startColumn, endLineNumber, endColumn); - } - return new Selection(endLineNumber, endColumn, startLineNumber, startColumn); - } - } - 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[169/*vs/editor/browser/controller/textAreaInput*/], __M([0/*require*/,1/*exports*/,39/*vs/base/browser/browser*/,7/*vs/base/browser/dom*/,15/*vs/base/common/async*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,106/*vs/base/common/mime*/,17/*vs/base/common/platform*/,8/*vs/base/common/strings*/,216/*vs/editor/browser/controller/textAreaState*/,13/*vs/editor/common/core/position*/,21/*vs/editor/common/core/selection*/]), function (require, exports, browser, dom, async_1, event_1, lifecycle_1, mime_1, platform, strings, textAreaState_1, position_1, selection_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.TextAreaInput = exports.InMemoryClipboardMetadataManager = exports.CopyOptions = exports.TextAreaSyntethicEvents = void 0; - var TextAreaSyntethicEvents; - (function (TextAreaSyntethicEvents) { - TextAreaSyntethicEvents.Tap = '-monaco-textarea-synthetic-tap'; - })(TextAreaSyntethicEvents = exports.TextAreaSyntethicEvents || (exports.TextAreaSyntethicEvents = {})); - 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. - */ - class InMemoryClipboardMetadataManager { - constructor() { - this._lastState = null; - } - set(lastCopiedValue, data) { - this._lastState = { lastCopiedValue, data }; - } - get(pastedText) { - if (this._lastState && this._lastState.lastCopiedValue === pastedText) { - // match! - return this._lastState.data; - } - this._lastState = null; - return null; - } - } - exports.InMemoryClipboardMetadataManager = InMemoryClipboardMetadataManager; - InMemoryClipboardMetadataManager.INSTANCE = new 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). - */ - class TextAreaInput extends lifecycle_1.Disposable { - constructor(host, textArea) { - super(); - 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(() => this._onCut.fire(), 0)); - this._asyncFocusGainWriteScreenReaderContent = this._register(new async_1.RunOnceScheduler(() => this.writeScreenReaderContent('asyncFocusGain'), 0)); - this._textAreaState = textAreaState_1.TextAreaState.EMPTY; - this._selectionChangeListener = null; - this.writeScreenReaderContent('ctor'); - this._hasFocus = false; - this._isDoingComposition = false; - this._nextCommand = 0 /* Type */; - let lastKeyDown = null; - this._register(dom.addStandardDisposableListener(textArea.domNode, 'keydown', (e) => { - if (e.keyCode === 109 /* KEY_IN_COMPOSITION */ - || (this._isDoingComposition && 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(); - } - lastKeyDown = e; - this._onKeyDown.fire(e); - })); - this._register(dom.addStandardDisposableListener(textArea.domNode, 'keyup', (e) => { - this._onKeyUp.fire(e); - })); - this._register(dom.addDisposableListener(textArea.domNode, 'compositionstart', (e) => { - if (textAreaState_1._debugComposition) { - console.log(`[compositionstart]`, e); - } - if (this._isDoingComposition) { - return; - } - this._isDoingComposition = true; - if (platform.isMacintosh - && this._textAreaState.selectionStart === this._textAreaState.selectionEnd - && this._textAreaState.selectionStart > 0 - && this._textAreaState.value.substr(this._textAreaState.selectionStart - 1, 1) === e.data) { - const isArrowKey = (lastKeyDown && lastKeyDown.equals(109 /* KEY_IN_COMPOSITION */) - && (lastKeyDown.code === 'ArrowRight' || lastKeyDown.code === 'ArrowLeft')); - if (isArrowKey || browser.isFirefox) { - // Handling long press case on Chromium/Safari macOS + arrow key => pretend the character was selected - // or long press case on Firefox on macOS - if (textAreaState_1._debugComposition) { - console.log(`[compositionstart] Handling long press case on macOS + arrow key or Firefox`, e); - } - this._textAreaState = new textAreaState_1.TextAreaState(this._textAreaState.value, this._textAreaState.selectionStart - 1, this._textAreaState.selectionEnd, this._textAreaState.selectionStartPosition ? new position_1.Position(this._textAreaState.selectionStartPosition.lineNumber, this._textAreaState.selectionStartPosition.column - 1) : null, this._textAreaState.selectionEndPosition); - this._onCompositionStart.fire({ revealDeltaColumns: -1 }); - return; - } - } - if (browser.isAndroid) { - // when tapping on the editor, Android enters composition mode to edit the current word - // so we cannot clear the textarea on Android and we must pretend the current word was selected - this._onCompositionStart.fire({ revealDeltaColumns: -this._textAreaState.selectionStart }); - return; - } - this._setAndWriteTextAreaState('compositionstart', textAreaState_1.TextAreaState.EMPTY); - this._onCompositionStart.fire({ revealDeltaColumns: 0 }); - })); - /** - * Deduce the typed input from a text area's value and the last observed state. - */ - const deduceInputFromTextAreaValue = (couldBeEmojiInput) => { - const oldState = this._textAreaState; - const newState = textAreaState_1.TextAreaState.readFromTextArea(this._textArea); - return [newState, textAreaState_1.TextAreaState.deduceInput(oldState, newState, couldBeEmojiInput)]; - }; - const deduceAndroidCompositionInput = () => { - const oldState = this._textAreaState; - const newState = textAreaState_1.TextAreaState.readFromTextArea(this._textArea); - return [newState, textAreaState_1.TextAreaState.deduceAndroidCompositionInput(oldState, newState)]; - }; - /** - * Deduce the composition input from a string. - */ - const deduceComposition = (text) => { - const oldState = this._textAreaState; - const newState = textAreaState_1.TextAreaState.selectedText(text); - const typeInput = { - text: newState.value, - replacePrevCharCnt: oldState.selectionEnd - oldState.selectionStart, - replaceNextCharCnt: 0, - positionDelta: 0 - }; - return [newState, typeInput]; - }; - this._register(dom.addDisposableListener(textArea.domNode, 'compositionupdate', (e) => { - if (textAreaState_1._debugComposition) { - console.log(`[compositionupdate]`, e); - } - if (browser.isAndroid) { - // On Android, the data sent with the composition update event is unusable. - // For example, if the cursor is in the middle of a word like Mic|osoft - // and Microsoft is chosen from the keyboard's suggestions, the e.data will contain "Microsoft". - // This is not really usable because it doesn't tell us where the edit began and where it ended. - const [newState, typeInput] = deduceAndroidCompositionInput(); - this._textAreaState = newState; - this._onType.fire(typeInput); - this._onCompositionUpdate.fire(e); - return; - } - const [newState, typeInput] = deduceComposition(e.data || ''); - this._textAreaState = newState; - this._onType.fire(typeInput); - this._onCompositionUpdate.fire(e); - })); - this._register(dom.addDisposableListener(textArea.domNode, 'compositionend', (e) => { - if (textAreaState_1._debugComposition) { - console.log(`[compositionend]`, 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; - } - this._isDoingComposition = false; - if (browser.isAndroid) { - // On Android, the data sent with the composition update event is unusable. - // For example, if the cursor is in the middle of a word like Mic|osoft - // and Microsoft is chosen from the keyboard's suggestions, the e.data will contain "Microsoft". - // This is not really usable because it doesn't tell us where the edit began and where it ended. - const [newState, typeInput] = deduceAndroidCompositionInput(); - this._textAreaState = newState; - this._onType.fire(typeInput); - this._onCompositionEnd.fire(); - return; - } - const [newState, typeInput] = deduceComposition(e.data || ''); - this._textAreaState = newState; - this._onType.fire(typeInput); - // isChrome: the textarea is not updated correctly when composition ends - // isFirefox: the textarea is not updated correctly after inserting emojis - // => we cannot assume the text at the end consists only of the composited text - if (browser.isChrome || browser.isFirefox) { - this._textAreaState = textAreaState_1.TextAreaState.readFromTextArea(this._textArea); - } - this._onCompositionEnd.fire(); - })); - this._register(dom.addDisposableListener(textArea.domNode, 'input', () => { - // 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; - } - const [newState, typeInput] = deduceInputFromTextAreaValue(/*couldBeEmojiInput*/ platform.isMacintosh); - if (typeInput.replacePrevCharCnt === 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 !== '' || typeInput.replacePrevCharCnt !== 0) { - this._onType.fire(typeInput); - } - } - else { - if (typeInput.text !== '' || typeInput.replacePrevCharCnt !== 0) { - this._firePaste(typeInput.text, null); - } - this._nextCommand = 0 /* Type */; - } - })); - // --- Clipboard operations - this._register(dom.addDisposableListener(textArea.domNode, 'cut', (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', (e) => { - this._ensureClipboardGetsEditorSelection(e); - })); - this._register(dom.addDisposableListener(textArea.domNode, 'paste', (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)) { - const [pastePlainText, metadata] = ClipboardEventUtils.getTextData(e); - 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', () => { - const hadFocus = this._hasFocus; - this._setHasFocus(true); - if (browser.isSafari && !hadFocus && this._hasFocus) { - // When "tabbing into" the textarea, immediately after dispatching the 'focus' event, - // Safari will always move the selection at offset 0 in the textarea - this._asyncFocusGainWriteScreenReaderContent.schedule(); - } - })); - this._register(dom.addDisposableListener(textArea.domNode, 'blur', () => { - if (this._isDoingComposition) { - // See https://github.com/microsoft/vscode/issues/112621 - // where compositionend is not triggered when the editor - // is taken off-dom during a composition - // Clear the flag to be able to write to the textarea - this._isDoingComposition = false; - // Clear the textarea to avoid an unwanted cursor type - this.writeScreenReaderContent('blurWithoutCompositionEnd'); - // Fire artificial composition end - this._onCompositionEnd.fire(); - } - this._setHasFocus(false); - })); - this._register(dom.addDisposableListener(textArea.domNode, TextAreaSyntethicEvents.Tap, () => { - if (browser.isAndroid && this._isDoingComposition) { - // on Android, tapping does not cancel the current composition, so the - // textarea is stuck showing the old composition - // Clear the flag to be able to write to the textarea - this._isDoingComposition = false; - // Clear the textarea to avoid an unwanted cursor type - this.writeScreenReaderContent('tapWithoutCompositionEnd'); - // Fire artificial composition end - this._onCompositionEnd.fire(); - } - })); - } - _installSelectionChangeListener() { - // See https://github.com/microsoft/vscode/issues/27216 and https://github.com/microsoft/vscode/issues/98256 - // 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 - // `selectionchange` events often come multiple times for a single logical change - // so throttle multiple `selectionchange` events that burst in a short period of time. - let previousSelectionChangeEventTime = 0; - return dom.addDisposableListener(document, 'selectionchange', (e) => { - if (!this._hasFocus) { - return; - } - if (this._isDoingComposition) { - return; - } - if (!browser.isChrome) { - // Support only for Chrome until testing happens on other browsers - return; - } - const now = Date.now(); - const delta1 = now - previousSelectionChangeEventTime; - previousSelectionChangeEventTime = now; - if (delta1 < 5) { - // received another `selectionchange` event within 5ms of the previous `selectionchange` event - // => ignore it - return; - } - const 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; - } - const newValue = this._textArea.getValue(); - if (this._textAreaState.value !== newValue) { - // Cannot correlate a position in the textarea with a position in the editor... - return; - } - const newSelectionStart = this._textArea.getSelectionStart(); - const newSelectionEnd = this._textArea.getSelectionEnd(); - if (this._textAreaState.selectionStart === newSelectionStart && this._textAreaState.selectionEnd === newSelectionEnd) { - // Nothing to do... - return; - } - const _newSelectionStartPosition = this._textAreaState.deduceEditorPosition(newSelectionStart); - const newSelectionStartPosition = this._host.deduceModelPosition(_newSelectionStartPosition[0], _newSelectionStartPosition[1], _newSelectionStartPosition[2]); - const _newSelectionEndPosition = this._textAreaState.deduceEditorPosition(newSelectionEnd); - const newSelectionEndPosition = this._host.deduceModelPosition(_newSelectionEndPosition[0], _newSelectionEndPosition[1], _newSelectionEndPosition[2]); - const newSelection = new selection_1.Selection(newSelectionStartPosition.lineNumber, newSelectionStartPosition.column, newSelectionEndPosition.lineNumber, newSelectionEndPosition.column); - this._onSelectionChangeRequest.fire(newSelection); - }); - } - dispose() { - super.dispose(); - if (this._selectionChangeListener) { - this._selectionChangeListener.dispose(); - this._selectionChangeListener = null; - } - } - focusTextArea() { - // 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(); - } - isFocused() { - return this._hasFocus; - } - refreshFocusState() { - const 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); - } - } - _setHasFocus(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) { - this.writeScreenReaderContent('focusgain'); - } - if (this._hasFocus) { - this._onFocus.fire(); - } - else { - this._onBlur.fire(); - } - } - _setAndWriteTextAreaState(reason, textAreaState) { - if (!this._hasFocus) { - textAreaState = textAreaState.collapseSelection(); - } - textAreaState.writeToTextArea(reason, this._textArea, this._hasFocus); - this._textAreaState = textAreaState; - } - writeScreenReaderContent(reason) { - if (this._isDoingComposition) { - // Do not write to the text area when doing composition - return; - } - this._setAndWriteTextAreaState(reason, this._host.getScreenReaderContent(this._textAreaState)); - } - _ensureClipboardGetsEditorSelection(e) { - const dataToCopy = this._host.getDataToCopy(ClipboardEventUtils.canUseTextData(e)); - const 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); - } - _firePaste(text, metadata) { - if (!metadata) { - // try the in-memory store - metadata = InMemoryClipboardMetadataManager.INSTANCE.get(text); - } - this._onPaste.fire({ - text: text, - metadata: metadata - }); - } - } - exports.TextAreaInput = TextAreaInput; - class ClipboardEventUtils { - static canUseTextData(e) { - if (e.clipboardData) { - return true; - } - if (window.clipboardData) { - return true; - } - return false; - } - static getTextData(e) { - if (e.clipboardData) { - e.preventDefault(); - const text = e.clipboardData.getData(mime_1.Mimes.text); - let metadata = null; - const 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(); - const text = window.clipboardData.getData('Text'); - return [text, null]; - } - throw new Error('ClipboardEventUtils.getTextData: Cannot use text data!'); - } - static setTextData(e, text, html, metadata) { - if (e.clipboardData) { - e.clipboardData.setData(mime_1.Mimes.text, 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!'); - } - } - class TextAreaWrapper extends lifecycle_1.Disposable { - constructor(_textArea) { - super(); - this._actual = _textArea; - this._ignoreSelectionChangeTime = 0; - } - setIgnoreSelectionChangeTime(reason) { - this._ignoreSelectionChangeTime = Date.now(); - } - getIgnoreSelectionChangeTime() { - return this._ignoreSelectionChangeTime; - } - resetSelectionChangeTime() { - this._ignoreSelectionChangeTime = 0; - } - getValue() { - // console.log('current value: ' + this._textArea.value); - return this._actual.domNode.value; - } - setValue(reason, value) { - const 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; - } - getSelectionStart() { - return this._actual.domNode.selectionDirection === 'backward' ? this._actual.domNode.selectionEnd : this._actual.domNode.selectionStart; - } - getSelectionEnd() { - return this._actual.domNode.selectionDirection === 'backward' ? this._actual.domNode.selectionStart : this._actual.domNode.selectionEnd; - } - setSelectionRange(reason, selectionStart, selectionEnd) { - const textArea = this._actual.domNode; - let activeElement = null; - const shadowRoot = dom.getShadowRoot(textArea); - if (shadowRoot) { - activeElement = shadowRoot.activeElement; - } - else { - activeElement = document.activeElement; - } - const currentIsFocused = (activeElement === textArea); - const currentSelectionStart = textArea.selectionStart; - const 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 { - const 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) - } - } - } -}); - -/*--------------------------------------------------------------------------------------------- - * 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/editor/common/commands/replaceCommand*/], __M([0/*require*/,1/*exports*/,21/*vs/editor/common/core/selection*/]), function (require, exports, selection_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ReplaceCommandThatPreservesSelection = exports.ReplaceCommandWithOffsetCursorState = exports.ReplaceCommandWithoutChangingPosition = exports.ReplaceCommandThatSelectsText = exports.ReplaceCommand = void 0; - class ReplaceCommand { - constructor(range, text, insertsAutoWhitespace = false) { - this._range = range; - this._text = text; - this.insertsAutoWhitespace = insertsAutoWhitespace; - } - getEditOperations(model, builder) { - builder.addTrackedEditOperation(this._range, this._text); - } - computeCursorState(model, helper) { - let inverseEditOperations = helper.getInverseEditOperations(); - let srcRange = inverseEditOperations[0].range; - return new selection_1.Selection(srcRange.endLineNumber, srcRange.endColumn, srcRange.endLineNumber, srcRange.endColumn); - } - } - exports.ReplaceCommand = ReplaceCommand; - class ReplaceCommandThatSelectsText { - constructor(range, text) { - this._range = range; - this._text = text; - } - getEditOperations(model, builder) { - builder.addTrackedEditOperation(this._range, this._text); - } - computeCursorState(model, helper) { - const inverseEditOperations = helper.getInverseEditOperations(); - const srcRange = inverseEditOperations[0].range; - return new selection_1.Selection(srcRange.startLineNumber, srcRange.startColumn, srcRange.endLineNumber, srcRange.endColumn); - } - } - exports.ReplaceCommandThatSelectsText = ReplaceCommandThatSelectsText; - class ReplaceCommandWithoutChangingPosition { - constructor(range, text, insertsAutoWhitespace = false) { - this._range = range; - this._text = text; - this.insertsAutoWhitespace = insertsAutoWhitespace; - } - getEditOperations(model, builder) { - builder.addTrackedEditOperation(this._range, this._text); - } - computeCursorState(model, helper) { - let inverseEditOperations = helper.getInverseEditOperations(); - let srcRange = inverseEditOperations[0].range; - return new selection_1.Selection(srcRange.startLineNumber, srcRange.startColumn, srcRange.startLineNumber, srcRange.startColumn); - } - } - exports.ReplaceCommandWithoutChangingPosition = ReplaceCommandWithoutChangingPosition; - class ReplaceCommandWithOffsetCursorState { - constructor(range, text, lineNumberDeltaOffset, columnDeltaOffset, insertsAutoWhitespace = false) { - this._range = range; - this._text = text; - this._columnDeltaOffset = columnDeltaOffset; - this._lineNumberDeltaOffset = lineNumberDeltaOffset; - this.insertsAutoWhitespace = insertsAutoWhitespace; - } - getEditOperations(model, builder) { - builder.addTrackedEditOperation(this._range, this._text); - } - computeCursorState(model, helper) { - let inverseEditOperations = helper.getInverseEditOperations(); - let 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); - } - } - exports.ReplaceCommandWithOffsetCursorState = ReplaceCommandWithOffsetCursorState; - class ReplaceCommandThatPreservesSelection { - constructor(editRange, text, initialSelection, forceMoveMarkers = false) { - this._range = editRange; - this._text = text; - this._initialSelection = initialSelection; - this._forceMoveMarkers = forceMoveMarkers; - this._selectionId = null; - } - getEditOperations(model, builder) { - builder.addTrackedEditOperation(this._range, this._text, this._forceMoveMarkers); - this._selectionId = builder.trackSelection(this._initialSelection); - } - computeCursorState(model, helper) { - return helper.getTrackedSelection(this._selectionId); - } - } - 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[376/*vs/editor/common/commands/surroundSelectionCommand*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/]), function (require, exports, range_1, selection_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.SurroundSelectionCommand = void 0; - class SurroundSelectionCommand { - constructor(range, charBeforeSelection, charAfterSelection) { - this._range = range; - this._charBeforeSelection = charBeforeSelection; - this._charAfterSelection = charAfterSelection; - } - getEditOperations(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); - } - computeCursorState(model, helper) { - let inverseEditOperations = helper.getInverseEditOperations(); - let firstOperationRange = inverseEditOperations[0].range; - let secondOperationRange = inverseEditOperations[1].range; - return new selection_1.Selection(firstOperationRange.endLineNumber, firstOperationRange.endColumn, secondOperationRange.endLineNumber, secondOperationRange.endColumn - this._charAfterSelection.length); - } - } - 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[83/*vs/editor/common/core/stringBuilder*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,17/*vs/base/common/platform*/,103/*vs/base/common/buffer*/]), function (require, exports, strings, platform, buffer) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.decodeUTF16LE = exports.createStringBuilder = exports.hasTextDecoder = exports.getPlatformTextDecoder = void 0; - let _utf16LE_TextDecoder; - function getUTF16LE_TextDecoder() { - if (!_utf16LE_TextDecoder) { - _utf16LE_TextDecoder = new TextDecoder('UTF-16LE'); - } - return _utf16LE_TextDecoder; - } - let _utf16BE_TextDecoder; - function getUTF16BE_TextDecoder() { - if (!_utf16BE_TextDecoder) { - _utf16BE_TextDecoder = new TextDecoder('UTF-16BE'); - } - return _utf16BE_TextDecoder; - } - let _platformTextDecoder; - function getPlatformTextDecoder() { - if (!_platformTextDecoder) { - _platformTextDecoder = platform.isLittleEndian() ? getUTF16LE_TextDecoder() : getUTF16BE_TextDecoder(); - } - return _platformTextDecoder; - } - exports.getPlatformTextDecoder = getPlatformTextDecoder; - exports.hasTextDecoder = (typeof TextDecoder !== 'undefined'); - if (exports.hasTextDecoder) { - exports.createStringBuilder = (capacity) => new StringBuilder(capacity); - exports.decodeUTF16LE = standardDecodeUTF16LE; - } - else { - exports.createStringBuilder = (capacity) => new CompatStringBuilder(); - exports.decodeUTF16LE = compatDecodeUTF16LE; - } - function standardDecodeUTF16LE(source, offset, len) { - const view = new Uint16Array(source.buffer, offset, len); - if (len > 0 && (view[0] === 0xFEFF || view[0] === 0xFFFE)) { - // UTF16 sometimes starts with a BOM https://de.wikipedia.org/wiki/Byte_Order_Mark - // It looks like TextDecoder.decode will eat up a leading BOM (0xFEFF or 0xFFFE) - // We don't want that behavior because we know the string is UTF16LE and the BOM should be maintained - // So we use the manual decoder - return compatDecodeUTF16LE(source, offset, len); - } - return getUTF16LE_TextDecoder().decode(view); - } - function compatDecodeUTF16LE(source, offset, len) { - let result = []; - let resultLen = 0; - for (let i = 0; i < len; i++) { - const charCode = buffer.readUInt16LE(source, offset); - offset += 2; - result[resultLen++] = String.fromCharCode(charCode); - } - return result.join(''); - } - class StringBuilder { - constructor(capacity) { - this._capacity = capacity | 0; - this._buffer = new Uint16Array(this._capacity); - this._completedStrings = null; - this._bufferLength = 0; - } - reset() { - this._completedStrings = null; - this._bufferLength = 0; - } - build() { - if (this._completedStrings !== null) { - this._flushBuffer(); - return this._completedStrings.join(''); - } - return this._buildBuffer(); - } - _buildBuffer() { - if (this._bufferLength === 0) { - return ''; - } - const view = new Uint16Array(this._buffer.buffer, 0, this._bufferLength); - return getPlatformTextDecoder().decode(view); - } - _flushBuffer() { - const bufferString = this._buildBuffer(); - this._bufferLength = 0; - if (this._completedStrings === null) { - this._completedStrings = [bufferString]; - } - else { - this._completedStrings[this._completedStrings.length] = bufferString; - } - } - write1(charCode) { - const remainingSpace = this._capacity - this._bufferLength; - if (remainingSpace <= 1) { - if (remainingSpace === 0 || strings.isHighSurrogate(charCode)) { - this._flushBuffer(); - } - } - this._buffer[this._bufferLength++] = charCode; - } - appendASCII(charCode) { - if (this._bufferLength === this._capacity) { - // buffer is full - this._flushBuffer(); - } - this._buffer[this._bufferLength++] = charCode; - } - appendASCIIString(str) { - const 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 (let i = 0; i < strLen; i++) { - this._buffer[this._bufferLength++] = str.charCodeAt(i); - } - } - } - class CompatStringBuilder { - constructor() { - this._pieces = []; - this._piecesLen = 0; - } - reset() { - this._pieces = []; - this._piecesLen = 0; - } - build() { - return this._pieces.join(''); - } - write1(charCode) { - this._pieces[this._piecesLen++] = String.fromCharCode(charCode); - } - appendASCII(charCode) { - this._pieces[this._piecesLen++] = String.fromCharCode(charCode); - } - appendASCIIString(str) { - this._pieces[this._piecesLen++] = str; - } - } -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[170/*vs/editor/browser/view/viewLayer*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/fastDomNode*/,83/*vs/editor/common/core/stringBuilder*/]), function (require, exports, fastDomNode_1, stringBuilder_1) { - "use strict"; - var _a; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.VisibleLinesCollection = exports.RenderedLinesCollection = void 0; - class RenderedLinesCollection { - constructor(createLine) { - this._createLine = createLine; - this._set(1, []); - } - flush() { - this._set(1, []); - } - _set(rendLineNumberStart, lines) { - this._lines = lines; - this._rendLineNumberStart = rendLineNumberStart; - } - _get() { - return { - rendLineNumberStart: this._rendLineNumberStart, - lines: this._lines - }; - } - /** - * @returns Inclusive line number that is inside this collection - */ - getStartLineNumber() { - return this._rendLineNumberStart; - } - /** - * @returns Inclusive line number that is inside this collection - */ - getEndLineNumber() { - return this._rendLineNumberStart + this._lines.length - 1; - } - getCount() { - return this._lines.length; - } - getLine(lineNumber) { - const 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 - */ - onLinesDeleted(deleteFromLineNumber, deleteToLineNumber) { - if (this.getCount() === 0) { - // no lines - return null; - } - const startLineNumber = this.getStartLineNumber(); - const endLineNumber = this.getEndLineNumber(); - if (deleteToLineNumber < startLineNumber) { - // deleting above the viewport - const deleteCnt = deleteToLineNumber - deleteFromLineNumber + 1; - this._rendLineNumberStart -= deleteCnt; - return null; - } - if (deleteFromLineNumber > endLineNumber) { - // deleted below the viewport - return null; - } - // Record what needs to be deleted - let deleteStartIndex = 0; - let deleteCount = 0; - for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { - const 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 - let deleteAboveCount = 0; - if (deleteToLineNumber < startLineNumber) { - // the entire deleted lines are above - deleteAboveCount = deleteToLineNumber - deleteFromLineNumber + 1; - } - else { - deleteAboveCount = startLineNumber - deleteFromLineNumber; - } - this._rendLineNumberStart -= deleteAboveCount; - } - const deleted = this._lines.splice(deleteStartIndex, deleteCount); - return deleted; - } - onLinesChanged(changeFromLineNumber, changeToLineNumber) { - if (this.getCount() === 0) { - // no lines - return false; - } - const startLineNumber = this.getStartLineNumber(); - const endLineNumber = this.getEndLineNumber(); - let someoneNotified = false; - for (let changedLineNumber = changeFromLineNumber; changedLineNumber <= changeToLineNumber; changedLineNumber++) { - if (changedLineNumber >= startLineNumber && changedLineNumber <= endLineNumber) { - // Notify the line - this._lines[changedLineNumber - this._rendLineNumberStart].onContentChanged(); - someoneNotified = true; - } - } - return someoneNotified; - } - onLinesInserted(insertFromLineNumber, insertToLineNumber) { - if (this.getCount() === 0) { - // no lines - return null; - } - const insertCnt = insertToLineNumber - insertFromLineNumber + 1; - const startLineNumber = this.getStartLineNumber(); - const 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 - const 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 - const newLines = []; - for (let i = 0; i < insertCnt; i++) { - newLines[i] = this._createLine(); - } - const insertIndex = insertFromLineNumber - this._rendLineNumberStart; - const beforeLines = this._lines.slice(0, insertIndex); - const afterLines = this._lines.slice(insertIndex, this._lines.length - insertCnt); - const deletedLines = this._lines.slice(this._lines.length - insertCnt, this._lines.length); - this._lines = beforeLines.concat(newLines).concat(afterLines); - return deletedLines; - } - onTokensChanged(ranges) { - if (this.getCount() === 0) { - // no lines - return false; - } - const startLineNumber = this.getStartLineNumber(); - const endLineNumber = this.getEndLineNumber(); - let notifiedSomeone = false; - for (let i = 0, len = ranges.length; i < len; i++) { - const rng = ranges[i]; - if (rng.toLineNumber < startLineNumber || rng.fromLineNumber > endLineNumber) { - // range outside viewport - continue; - } - const from = Math.max(startLineNumber, rng.fromLineNumber); - const to = Math.min(endLineNumber, rng.toLineNumber); - for (let lineNumber = from; lineNumber <= to; lineNumber++) { - const lineIndex = lineNumber - this._rendLineNumberStart; - this._lines[lineIndex].onTokensChanged(); - notifiedSomeone = true; - } - } - return notifiedSomeone; - } - } - exports.RenderedLinesCollection = RenderedLinesCollection; - class VisibleLinesCollection { - constructor(host) { - this._host = host; - this.domNode = this._createDomNode(); - this._linesCollection = new RenderedLinesCollection(() => this._host.createVisibleLine()); - } - _createDomNode() { - const domNode = (0, 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 - onConfigurationChanged(e) { - if (e.hasChanged(129 /* layoutInfo */)) { - return true; - } - return false; - } - onFlushed(e) { - this._linesCollection.flush(); - // No need to clear the dom node because a full .innerHTML will occur in ViewLayerRenderer._render - return true; - } - onLinesChanged(e) { - return this._linesCollection.onLinesChanged(e.fromLineNumber, e.toLineNumber); - } - onLinesDeleted(e) { - const deleted = this._linesCollection.onLinesDeleted(e.fromLineNumber, e.toLineNumber); - if (deleted) { - // Remove from DOM - for (let i = 0, len = deleted.length; i < len; i++) { - const lineDomNode = deleted[i].getDomNode(); - if (lineDomNode) { - this.domNode.domNode.removeChild(lineDomNode); - } - } - } - return true; - } - onLinesInserted(e) { - const deleted = this._linesCollection.onLinesInserted(e.fromLineNumber, e.toLineNumber); - if (deleted) { - // Remove from DOM - for (let i = 0, len = deleted.length; i < len; i++) { - const lineDomNode = deleted[i].getDomNode(); - if (lineDomNode) { - this.domNode.domNode.removeChild(lineDomNode); - } - } - } - return true; - } - onScrollChanged(e) { - return e.scrollTopChanged; - } - onTokensChanged(e) { - return this._linesCollection.onTokensChanged(e.ranges); - } - onZonesChanged(e) { - return true; - } - // ---- end view event handlers - getStartLineNumber() { - return this._linesCollection.getStartLineNumber(); - } - getEndLineNumber() { - return this._linesCollection.getEndLineNumber(); - } - getVisibleLine(lineNumber) { - return this._linesCollection.getLine(lineNumber); - } - renderLines(viewportData) { - const inp = this._linesCollection._get(); - const renderer = new ViewLayerRenderer(this.domNode.domNode, this._host, viewportData); - const 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) - const resCtx = renderer.render(ctx, viewportData.startLineNumber, viewportData.endLineNumber, viewportData.relativeVerticalOffset); - this._linesCollection._set(resCtx.rendLineNumberStart, resCtx.lines); - } - } - exports.VisibleLinesCollection = VisibleLinesCollection; - class ViewLayerRenderer { - constructor(domNode, host, viewportData) { - this.domNode = domNode; - this.host = host; - this.viewportData = viewportData; - } - render(inContext, startLineNumber, stopLineNumber, deltaTop) { - const 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 (let 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 - const fromLineNumber = startLineNumber; - const 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 - const 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 - const fromLineNumber = ctx.rendLineNumberStart + ctx.linesLength; - const 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 - const fromLineNumber = Math.max(0, stopLineNumber - ctx.rendLineNumberStart + 1); - const toLineNumber = ctx.linesLength - 1; - const removeCnt = toLineNumber - fromLineNumber + 1; - if (removeCnt > 0) { - this._removeLinesAfter(ctx, removeCnt); - ctx.linesLength -= removeCnt; - } - } - this._finishRendering(ctx, false, deltaTop); - return ctx; - } - _renderUntouchedLines(ctx, startIndex, endIndex, deltaTop, deltaLN) { - const rendLineNumberStart = ctx.rendLineNumberStart; - const lines = ctx.lines; - for (let i = startIndex; i <= endIndex; i++) { - const lineNumber = rendLineNumberStart + i; - lines[i].layoutLine(lineNumber, deltaTop[lineNumber - deltaLN]); - } - } - _insertLinesBefore(ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) { - const newLines = []; - let newLinesLen = 0; - for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) { - newLines[newLinesLen++] = this.host.createVisibleLine(); - } - ctx.lines = newLines.concat(ctx.lines); - } - _removeLinesBefore(ctx, removeCount) { - for (let i = 0; i < removeCount; i++) { - const lineDomNode = ctx.lines[i].getDomNode(); - if (lineDomNode) { - this.domNode.removeChild(lineDomNode); - } - } - ctx.lines.splice(0, removeCount); - } - _insertLinesAfter(ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) { - const newLines = []; - let newLinesLen = 0; - for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) { - newLines[newLinesLen++] = this.host.createVisibleLine(); - } - ctx.lines = ctx.lines.concat(newLines); - } - _removeLinesAfter(ctx, removeCount) { - const removeIndex = ctx.linesLength - removeCount; - for (let i = 0; i < removeCount; i++) { - const lineDomNode = ctx.lines[removeIndex + i].getDomNode(); - if (lineDomNode) { - this.domNode.removeChild(lineDomNode); - } - } - ctx.lines.splice(removeIndex, removeCount); - } - _finishRenderingNewLines(ctx, domNodeIsEmpty, newLinesHTML, wasNew) { - if (ViewLayerRenderer._ttPolicy) { - newLinesHTML = ViewLayerRenderer._ttPolicy.createHTML(newLinesHTML); - } - const lastChild = this.domNode.lastChild; - if (domNodeIsEmpty || !lastChild) { - this.domNode.innerHTML = newLinesHTML; // explains the ugly casts -> https://github.com/microsoft/vscode/issues/106396#issuecomment-692625393; - } - else { - lastChild.insertAdjacentHTML('afterend', newLinesHTML); - } - let currChild = this.domNode.lastChild; - for (let i = ctx.linesLength - 1; i >= 0; i--) { - const line = ctx.lines[i]; - if (wasNew[i]) { - line.setDomNode(currChild); - currChild = currChild.previousSibling; - } - } - } - _finishRenderingInvalidLines(ctx, invalidLinesHTML, wasInvalid) { - const hugeDomNode = document.createElement('div'); - if (ViewLayerRenderer._ttPolicy) { - invalidLinesHTML = ViewLayerRenderer._ttPolicy.createHTML(invalidLinesHTML); - } - hugeDomNode.innerHTML = invalidLinesHTML; - for (let i = 0; i < ctx.linesLength; i++) { - const line = ctx.lines[i]; - if (wasInvalid[i]) { - const source = hugeDomNode.firstChild; - const lineDomNode = line.getDomNode(); - lineDomNode.parentNode.replaceChild(source, lineDomNode); - line.setDomNode(source); - } - } - } - _finishRendering(ctx, domNodeIsEmpty, deltaTop) { - const sb = ViewLayerRenderer._sb; - const linesLength = ctx.linesLength; - const lines = ctx.lines; - const rendLineNumberStart = ctx.rendLineNumberStart; - const wasNew = []; - { - sb.reset(); - let hadNewLine = false; - for (let i = 0; i < linesLength; i++) { - const line = lines[i]; - wasNew[i] = false; - const lineDomNode = line.getDomNode(); - if (lineDomNode) { - // line is not new - continue; - } - const 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(); - let hadInvalidLine = false; - const wasInvalid = []; - for (let i = 0; i < linesLength; i++) { - const line = lines[i]; - wasInvalid[i] = false; - if (wasNew[i]) { - // line was new - continue; - } - const 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._ttPolicy = (_a = window.trustedTypes) === null || _a === void 0 ? void 0 : _a.createPolicy('editorViewLayer', { createHTML: value => value }); - ViewLayerRenderer._sb = (0, stringBuilder_1.createStringBuilder)(100000); -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[134/*vs/editor/common/core/token*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.TokenizationResult2 = exports.TokenizationResult = exports.Token = void 0; - class Token { - constructor(offset, type, language) { - this._tokenBrand = undefined; - this.offset = offset | 0; // @perf - this.type = type; - this.language = language; - } - toString() { - return '(' + this.offset + ', ' + this.type + ')'; - } - } - exports.Token = Token; - class TokenizationResult { - constructor(tokens, endState) { - this._tokenizationResultBrand = undefined; - this.tokens = tokens; - this.endState = endState; - } - } - exports.TokenizationResult = TokenizationResult; - class TokenizationResult2 { - constructor(tokens, endState) { - this._tokenizationResult2Brand = undefined; - this.tokens = tokens; - this.endState = endState; - } - } - 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[377/*vs/editor/common/diff/diffComputer*/], __M([0/*require*/,1/*exports*/,128/*vs/base/common/diff/diff*/,8/*vs/base/common/strings*/]), function (require, exports, diff_1, strings) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DiffComputer = void 0; - const MINIMUM_MATCHING_CHARACTER_LENGTH = 3; - function computeDiff(originalSequence, modifiedSequence, continueProcessingPredicate, pretty) { - const diffAlgo = new diff_1.LcsDiff(originalSequence, modifiedSequence, continueProcessingPredicate); - return diffAlgo.ComputeDiff(pretty); - } - class LineSequence { - constructor(lines) { - const startColumns = []; - const endColumns = []; - for (let i = 0, length = lines.length; i < length; i++) { - startColumns[i] = getFirstNonBlankColumn(lines[i], 1); - endColumns[i] = getLastNonBlankColumn(lines[i], 1); - } - this.lines = lines; - this._startColumns = startColumns; - this._endColumns = endColumns; - } - getElements() { - const elements = []; - for (let 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; - } - getStrictElement(index) { - return this.lines[index]; - } - getStartLineNumber(i) { - return i + 1; - } - getEndLineNumber(i) { - return i + 1; - } - createCharSequence(shouldIgnoreTrimWhitespace, startIndex, endIndex) { - const charCodes = []; - const lineNumbers = []; - const columns = []; - let len = 0; - for (let index = startIndex; index <= endIndex; index++) { - const lineContent = this.lines[index]; - const startColumn = (shouldIgnoreTrimWhitespace ? this._startColumns[index] : 1); - const endColumn = (shouldIgnoreTrimWhitespace ? this._endColumns[index] : lineContent.length + 1); - for (let 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); - } - } - class CharSequence { - constructor(charCodes, lineNumbers, columns) { - this._charCodes = charCodes; - this._lineNumbers = lineNumbers; - this._columns = columns; - } - getElements() { - return this._charCodes; - } - getStartLineNumber(i) { - return this._lineNumbers[i]; - } - getStartColumn(i) { - return this._columns[i]; - } - getEndLineNumber(i) { - return this._lineNumbers[i]; - } - getEndColumn(i) { - return this._columns[i] + 1; - } - } - class CharChange { - constructor(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; - } - static createFromDiffChange(diffChange, originalCharSequence, modifiedCharSequence) { - let originalStartLineNumber; - let originalStartColumn; - let originalEndLineNumber; - let originalEndColumn; - let modifiedStartLineNumber; - let modifiedStartColumn; - let modifiedEndLineNumber; - let 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); - } - } - function postProcessCharChanges(rawChanges) { - if (rawChanges.length <= 1) { - return rawChanges; - } - const result = [rawChanges[0]]; - let prevChange = result[0]; - for (let i = 1, len = rawChanges.length; i < len; i++) { - const currChange = rawChanges[i]; - const originalMatchingLength = currChange.originalStart - (prevChange.originalStart + prevChange.originalLength); - const modifiedMatchingLength = currChange.modifiedStart - (prevChange.modifiedStart + prevChange.modifiedLength); - // Both of the above should be equal, but the continueProcessingPredicate may prevent this from being true - const 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; - } - class LineChange { - constructor(originalStartLineNumber, originalEndLineNumber, modifiedStartLineNumber, modifiedEndLineNumber, charChanges) { - this.originalStartLineNumber = originalStartLineNumber; - this.originalEndLineNumber = originalEndLineNumber; - this.modifiedStartLineNumber = modifiedStartLineNumber; - this.modifiedEndLineNumber = modifiedEndLineNumber; - this.charChanges = charChanges; - } - static createFromDiffResult(shouldIgnoreTrimWhitespace, diffChange, originalLineSequence, modifiedLineSequence, continueCharDiff, shouldComputeCharChanges, shouldPostProcessCharChanges) { - let originalStartLineNumber; - let originalEndLineNumber; - let modifiedStartLineNumber; - let modifiedEndLineNumber; - let 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... - const originalCharSequence = originalLineSequence.createCharSequence(shouldIgnoreTrimWhitespace, diffChange.originalStart, diffChange.originalStart + diffChange.originalLength - 1); - const modifiedCharSequence = modifiedLineSequence.createCharSequence(shouldIgnoreTrimWhitespace, diffChange.modifiedStart, diffChange.modifiedStart + diffChange.modifiedLength - 1); - let rawChanges = computeDiff(originalCharSequence, modifiedCharSequence, continueCharDiff, true).changes; - if (shouldPostProcessCharChanges) { - rawChanges = postProcessCharChanges(rawChanges); - } - charChanges = []; - for (let i = 0, length = rawChanges.length; i < length; i++) { - charChanges.push(CharChange.createFromDiffChange(rawChanges[i], originalCharSequence, modifiedCharSequence)); - } - } - return new LineChange(originalStartLineNumber, originalEndLineNumber, modifiedStartLineNumber, modifiedEndLineNumber, charChanges); - } - } - class DiffComputer { - constructor(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... - } - computeDiff() { - if (this.original.lines.length === 1 && this.original.lines[0].length === 0) { - // empty original => fast path - if (this.modified.lines.length === 1 && this.modified.lines[0].length === 0) { - return { - quitEarly: false, - changes: [] - }; - } - 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 - }] - }] - }; - } - const diffResult = computeDiff(this.original, this.modified, this.continueLineDiff, this.shouldMakePrettyDiff); - const rawChanges = diffResult.changes; - const quitEarly = diffResult.quitEarly; - // The diff is always computed with ignoring trim whitespace - // This ensures we get the prettiest diff - if (this.shouldIgnoreTrimWhitespace) { - const lineChanges = []; - for (let i = 0, length = rawChanges.length; i < length; 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 - const result = []; - let originalLineIndex = 0; - let modifiedLineIndex = 0; - for (let i = -1 /* !!!! */, len = rawChanges.length; i < len; i++) { - const nextChange = (i + 1 < len ? rawChanges[i + 1] : null); - const originalStop = (nextChange ? nextChange.originalStart : this.originalLines.length); - const modifiedStop = (nextChange ? nextChange.modifiedStart : this.modifiedLines.length); - while (originalLineIndex < originalStop && modifiedLineIndex < modifiedStop) { - const originalLine = this.originalLines[originalLineIndex]; - const modifiedLine = this.modifiedLines[modifiedLineIndex]; - if (originalLine !== modifiedLine) { - // These lines differ only in trim whitespace - // Check the leading whitespace - { - let originalStartColumn = getFirstNonBlankColumn(originalLine, 1); - let modifiedStartColumn = getFirstNonBlankColumn(modifiedLine, 1); - while (originalStartColumn > 1 && modifiedStartColumn > 1) { - const originalChar = originalLine.charCodeAt(originalStartColumn - 2); - const 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 - { - let originalEndColumn = getLastNonBlankColumn(originalLine, 1); - let modifiedEndColumn = getLastNonBlankColumn(modifiedLine, 1); - const originalMaxColumn = originalLine.length + 1; - const modifiedMaxColumn = modifiedLine.length + 1; - while (originalEndColumn < originalMaxColumn && modifiedEndColumn < modifiedMaxColumn) { - const originalChar = originalLine.charCodeAt(originalEndColumn - 1); - const 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 - }; - } - _pushTrimWhitespaceCharChange(result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn) { - if (this._mergeTrimWhitespaceCharChange(result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn)) { - // Merged into previous - return; - } - let 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)); - } - _mergeTrimWhitespaceCharChange(result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn) { - const len = result.length; - if (len === 0) { - return false; - } - const 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; - } - } - exports.DiffComputer = DiffComputer; - function getFirstNonBlankColumn(txt, defaultValue) { - const r = strings.firstNonWhitespaceIndex(txt); - if (r === -1) { - return defaultValue; - } - return r + 1; - } - function getLastNonBlankColumn(txt, defaultValue) { - const r = strings.lastNonWhitespaceIndex(txt); - if (r === -1) { - return defaultValue; - } - return r + 2; - } - function createContinueProcessingPredicate(maximumRuntime) { - if (maximumRuntime === 0) { - return () => true; - } - const startTime = Date.now(); - return () => { - 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[219/*vs/editor/common/editorAction*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.InternalEditorAction = void 0; - class InternalEditorAction { - constructor(id, label, alias, precondition, run, contextKeyService) { - this.id = id; - this.label = label; - this.alias = alias; - this._precondition = precondition; - this._run = run; - this._contextKeyService = contextKeyService; - } - isSupported() { - return this._contextKeyService.contextMatchesRules(this._precondition); - } - run() { - if (!this.isSupported()) { - return Promise.resolve(undefined); - } - return this._run(); - } - } - exports.InternalEditorAction = InternalEditorAction; -}); - -define(__m[110/*vs/editor/common/editorCommon*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.EditorType = exports.isThemeColor = void 0; - /** - * @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' - }; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/browser/editorBrowser*/], __M([0/*require*/,1/*exports*/,110/*vs/editor/common/editorCommon*/]), function (require, exports, editorCommon) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getCodeEditor = exports.isDiffEditor = exports.isCodeEditor = void 0; - /** - *@internal - */ - function isCodeEditor(thing) { - if (thing && typeof thing.getEditorType === 'function') { - return thing.getEditorType() === editorCommon.EditorType.ICodeEditor; - } - else { - return false; - } - } - exports.isCodeEditor = isCodeEditor; - /** - *@internal - */ - function isDiffEditor(thing) { - if (thing && typeof thing.getEditorType === 'function') { - return thing.getEditorType() === editorCommon.EditorType.IDiffEditor; - } - else { - return false; - } - } - exports.isDiffEditor = isDiffEditor; - /** - *@internal - */ - function getCodeEditor(thing) { - if (isCodeEditor(thing)) { - return thing; - } - if (isDiffEditor(thing)) { - return thing.getModifiedEditor(); - } - return null; - } - exports.getCodeEditor = getCodeEditor; -}); - -define(__m[53/*vs/editor/common/model*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ApplyEditsResult = exports.ValidAnnotatedEditOperation = exports.FindMatch = exports.TextModelResolvedOptions = exports.MinimapPosition = exports.OverviewRulerLane = void 0; - /** - * 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 = {})); - class TextModelResolvedOptions { - /** - * @internal - */ - constructor(src) { - this._textModelResolvedOptionsBrand = undefined; - 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 - */ - equals(other) { - return (this.tabSize === other.tabSize - && this.indentSize === other.indentSize - && this.insertSpaces === other.insertSpaces - && this.defaultEOL === other.defaultEOL - && this.trimAutoWhitespace === other.trimAutoWhitespace); - } - /** - * @internal - */ - createChangeEvent(newOpts) { - return { - tabSize: this.tabSize !== newOpts.tabSize, - indentSize: this.indentSize !== newOpts.indentSize, - insertSpaces: this.insertSpaces !== newOpts.insertSpaces, - trimAutoWhitespace: this.trimAutoWhitespace !== newOpts.trimAutoWhitespace, - }; - } - } - exports.TextModelResolvedOptions = TextModelResolvedOptions; - class FindMatch { - /** - * @internal - */ - constructor(range, matches) { - this._findMatchBrand = undefined; - this.range = range; - this.matches = matches; - } - } - exports.FindMatch = FindMatch; - /** - * @internal - */ - class ValidAnnotatedEditOperation { - constructor(identifier, range, text, forceMoveMarkers, isAutoWhitespaceEdit, _isTracked) { - this.identifier = identifier; - this.range = range; - this.text = text; - this.forceMoveMarkers = forceMoveMarkers; - this.isAutoWhitespaceEdit = isAutoWhitespaceEdit; - this._isTracked = _isTracked; - } - } - exports.ValidAnnotatedEditOperation = ValidAnnotatedEditOperation; - /** - * @internal - */ - class ApplyEditsResult { - constructor(reverseEdits, changes, trimAutoWhitespaceLineNumbers) { - this.reverseEdits = reverseEdits; - this.changes = changes; - this.trimAutoWhitespaceLineNumbers = trimAutoWhitespaceLineNumbers; - } - } - 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[378/*vs/editor/common/model/indentationGuesser*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.guessIndentation = void 0; - class SpacesDiffResult { - constructor() { - this.spacesDiff = 0; - this.looksLikeAlignment = false; - } - } - /** - * 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 - let i; - for (i = 0; i < aLength && i < bLength; i++) { - let aCharCode = a.charCodeAt(i); - let bCharCode = b.charCodeAt(i); - if (aCharCode !== bCharCode) { - break; - } - } - let aSpacesCnt = 0, aTabsCount = 0; - for (let j = i; j < aLength; j++) { - let aCharCode = a.charCodeAt(j); - if (aCharCode === 32 /* Space */) { - aSpacesCnt++; - } - else { - aTabsCount++; - } - } - let bSpacesCnt = 0, bTabsCount = 0; - for (let j = i; j < bLength; j++) { - let bCharCode = b.charCodeAt(j); - if (bCharCode === 32 /* Space */) { - bSpacesCnt++; - } - else { - bTabsCount++; - } - } - if (aSpacesCnt > 0 && aTabsCount > 0) { - return; - } - if (bSpacesCnt > 0 && bTabsCount > 0) { - return; - } - let tabsDiff = Math.abs(aTabsCount - bTabsCount); - let 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 - const linesCount = Math.min(source.getLineCount(), 10000); - let linesIndentedWithTabsCount = 0; // number of lines that contain at least one tab in indentation - let linesIndentedWithSpacesCount = 0; // number of lines that contain only spaces in indentation - let previousLineText = ''; // content of latest line that contained non-whitespace chars - let previousLineIndentation = 0; // index at which latest line contained the first non-whitespace char - const ALLOWED_TAB_SIZE_GUESSES = [2, 4, 6, 8, 3, 5, 7]; // prefer even guesses for `tabSize`, limit to [2, 8]. - const MAX_ALLOWED_TAB_SIZE_GUESS = 8; // max(ALLOWED_TAB_SIZE_GUESSES) = 8 - let spacesDiffCount = [0, 0, 0, 0, 0, 0, 0, 0, 0]; // `tabSize` scores - let tmp = new SpacesDiffResult(); - for (let lineNumber = 1; lineNumber <= linesCount; lineNumber++) { - let currentLineLength = source.getLineLength(lineNumber); - let 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. - const useCurrentLineText = (currentLineLength <= 65536); - let currentLineHasContent = false; // does `currentLineText` contain non-whitespace chars - let currentLineIndentation = 0; // index at which `currentLineText` contains the first non-whitespace char - let currentLineSpacesCount = 0; // count of spaces found in `currentLineText` indentation - let currentLineTabsCount = 0; // count of tabs found in `currentLineText` indentation - for (let j = 0, lenJ = currentLineLength; j < lenJ; j++) { - let 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; - } - } - let currentSpacesDiff = tmp.spacesDiff; - if (currentSpacesDiff <= MAX_ALLOWED_TAB_SIZE_GUESS) { - spacesDiffCount[currentSpacesDiff]++; - } - previousLineText = currentLineText; - previousLineIndentation = currentLineIndentation; - } - let insertSpaces = defaultInsertSpaces; - if (linesIndentedWithTabsCount !== linesIndentedWithSpacesCount) { - insertSpaces = (linesIndentedWithTabsCount < linesIndentedWithSpacesCount); - } - let tabSize = defaultTabSize; - // Guess tabSize only if inserting spaces... - if (insertSpaces) { - let tabSizeScore = (insertSpaces ? 0 : 0.1 * linesCount); - // console.log("score threshold: " + tabSizeScore); - ALLOWED_TAB_SIZE_GUESSES.forEach((possibleTabSize) => { - let possibleTabSizeScore = spacesDiffCount[possibleTabSize]; - if (possibleTabSizeScore > tabSizeScore) { - tabSizeScore = 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[379/*vs/editor/common/model/intervalTree*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.intervalCompare = exports.recomputeMaxEnd = exports.nodeAcceptEdit = exports.IntervalTree = exports.SENTINEL = exports.IntervalNode = exports.getNodeColor = void 0; - 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 getNodeStickiness(node) { - return ((node.metadata & 24 /* StickinessMask */) >>> 3 /* StickinessOffset */); - } - function _setNodeStickiness(node, stickiness) { - node.metadata = ((node.metadata & 231 /* StickinessMaskInverse */) | (stickiness << 3 /* StickinessOffset */)); - } - function getCollapseOnReplaceEdit(node) { - return ((node.metadata & 32 /* CollapseOnReplaceEditMask */) >>> 5 /* CollapseOnReplaceEditOffset */) === 1; - } - function setCollapseOnReplaceEdit(node, value) { - node.metadata = ((node.metadata & 223 /* CollapseOnReplaceEditMaskInverse */) | ((value ? 1 : 0) << 5 /* CollapseOnReplaceEditOffset */)); - } - class IntervalNode { - constructor(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 */); - setCollapseOnReplaceEdit(this, false); - this.cachedVersionId = 0; - this.cachedAbsoluteStart = start; - this.cachedAbsoluteEnd = end; - this.range = null; - setNodeIsVisited(this, false); - } - reset(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; - } - setOptions(options) { - this.options = options; - let className = this.options.className; - setNodeIsForValidation(this, (className === "squiggly-error" /* EditorErrorDecoration */ - || className === "squiggly-warning" /* EditorWarningDecoration */ - || className === "squiggly-info" /* EditorInfoDecoration */)); - _setNodeStickiness(this, this.options.stickiness); - setCollapseOnReplaceEdit(this, this.options.collapseOnReplaceEdit); - } - setCachedOffsets(absoluteStart, absoluteEnd, cachedVersionId) { - if (this.cachedVersionId !== cachedVersionId) { - this.range = null; - } - this.cachedVersionId = cachedVersionId; - this.cachedAbsoluteStart = absoluteStart; - this.cachedAbsoluteEnd = absoluteEnd; - } - detach() { - this.parent = null; - this.left = null; - this.right = null; - } - } - 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 */); - class IntervalTree { - constructor() { - this.root = exports.SENTINEL; - this.requestNormalizeDelta = false; - } - intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId) { - if (this.root === exports.SENTINEL) { - return []; - } - return intervalSearch(this, start, end, filterOwnerId, filterOutValidation, cachedVersionId); - } - search(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! - */ - collectNodesFromOwner(ownerId) { - return collectNodesFromOwner(this, ownerId); - } - /** - * Will not set `cachedAbsoluteStart` nor `cachedAbsoluteEnd` on the returned nodes! - */ - collectNodesPostOrder() { - return collectNodesPostOrder(this); - } - insert(node) { - rbTreeInsert(this, node); - this._normalizeDeltaIfNecessary(); - } - delete(node) { - rbTreeDelete(this, node); - this._normalizeDeltaIfNecessary(); - } - resolveNode(node, cachedVersionId) { - const initialNode = node; - let delta = 0; - while (node !== this.root) { - if (node === node.parent.right) { - delta += node.parent.delta; - } - node = node.parent; - } - const nodeStart = initialNode.start + delta; - const nodeEnd = initialNode.end + delta; - initialNode.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId); - } - acceptReplace(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 - const nodesOfInterest = searchForEditing(this, offset, offset + length); - // (2) remove all nodes that are intersecting this edit - for (let i = 0, len = nodesOfInterest.length; i < len; i++) { - const 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 (let i = 0, len = nodesOfInterest.length; i < len; i++) { - const 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(); - } - _normalizeDeltaIfNecessary() { - if (!this.requestNormalizeDelta) { - return; - } - this.requestNormalizeDelta = false; - normalizeDelta(this); - } - } - exports.IntervalTree = IntervalTree; - //#region Delta Normalization - function normalizeDelta(T) { - let node = T.root; - let 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) { - const nodeStickiness = getNodeStickiness(node); - const startStickToPreviousCharacter = (nodeStickiness === 0 /* AlwaysGrowsWhenTypingAtEdges */ - || nodeStickiness === 2 /* GrowsOnlyWhenTypingBefore */); - const endStickToPreviousCharacter = (nodeStickiness === 1 /* NeverGrowsWhenTypingAtEdges */ - || nodeStickiness === 2 /* GrowsOnlyWhenTypingBefore */); - const deletingCnt = (end - start); - const insertingCnt = textLength; - const commonLength = Math.min(deletingCnt, insertingCnt); - const nodeStart = node.start; - let startDone = false; - const nodeEnd = node.end; - let 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; - } - { - const 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) { - const 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; - } - } - { - const 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 - const 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. - let node = T.root; - let delta = 0; - let nodeMaxEnd = 0; - let nodeStart = 0; - let nodeEnd = 0; - let result = []; - let 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. - let node = T.root; - let delta = 0; - let nodeMaxEnd = 0; - let nodeStart = 0; - const 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) { - let node = T.root; - let result = []; - let 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) { - let node = T.root; - let result = []; - let 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) { - let node = T.root; - let delta = 0; - let nodeStart = 0; - let nodeEnd = 0; - let result = []; - let 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); - let 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. - let node = T.root; - let delta = 0; - let nodeMaxEnd = 0; - let nodeStart = 0; - let nodeEnd = 0; - let result = []; - let 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); - let 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 - let x = newNode; - while (x !== T.root && getNodeColor(x.parent) === 1 /* Red */) { - if (x.parent === x.parent.parent.left) { - const 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 { - const 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) { - let delta = 0; - let x = T.root; - const zAbsoluteStart = z.start; - const zAbsoluteEnd = z.end; - while (true) { - const 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) { - let x; - let 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; - } - let 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 - let 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) { - const 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) { - const 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) { - let maxEnd = node.end; - if (node.left !== exports.SENTINEL) { - const leftMaxEnd = node.left.maxEnd; - if (leftMaxEnd > maxEnd) { - maxEnd = leftMaxEnd; - } - } - if (node.right !== exports.SENTINEL) { - const 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) { - const 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[380/*vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.recomputeTreeMetadata = exports.updateTreeMetadata = exports.fixInsert = exports.rbDelete = exports.rightRotate = exports.leftRotate = exports.resetSentinel = exports.calculateLF = exports.calculateSize = exports.righttest = exports.leftest = exports.SENTINEL = exports.TreeNode = void 0; - class TreeNode { - constructor(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; - } - next() { - if (this.right !== exports.SENTINEL) { - return leftest(this.right); - } - let 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; - } - } - prev() { - if (this.left !== exports.SENTINEL) { - return righttest(this.left); - } - let 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; - } - } - detach() { - this.parent = null; - this.left = null; - this.right = null; - } - } - 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) { - let 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) { - let 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) { - let x; - let 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; - } - let 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) { - let newSizeLeft = calculateSize(x); - let newLFLeft = calculateLF(x); - if (newSizeLeft !== x.parent.size_left || newLFLeft !== x.parent.lf_left) { - let delta = newSizeLeft - x.parent.size_left; - let 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 - let 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) { - const 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 { - const 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) { - let delta = 0; - let 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[220/*vs/editor/common/model/textChange*/], __M([0/*require*/,1/*exports*/,103/*vs/base/common/buffer*/,83/*vs/editor/common/core/stringBuilder*/]), function (require, exports, buffer, stringBuilder_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.compressConsecutiveTextChanges = exports.TextChange = void 0; - function escapeNewLine(str) { - return (str - .replace(/\n/g, '\\n') - .replace(/\r/g, '\\r')); - } - class TextChange { - constructor(oldPosition, oldText, newPosition, newText) { - this.oldPosition = oldPosition; - this.oldText = oldText; - this.newPosition = newPosition; - this.newText = newText; - } - get oldLength() { - return this.oldText.length; - } - get oldEnd() { - return this.oldPosition + this.oldText.length; - } - get newLength() { - return this.newText.length; - } - get newEnd() { - return this.newPosition + this.newText.length; - } - toString() { - if (this.oldText.length === 0) { - return `(insert@${this.oldPosition} "${escapeNewLine(this.newText)}")`; - } - if (this.newText.length === 0) { - return `(delete@${this.oldPosition} "${escapeNewLine(this.oldText)}")`; - } - return `(replace@${this.oldPosition} "${escapeNewLine(this.oldText)}" with "${escapeNewLine(this.newText)}")`; - } - static _writeStringSize(str) { - return (4 + 2 * str.length); - } - static _writeString(b, str, offset) { - const len = str.length; - buffer.writeUInt32BE(b, len, offset); - offset += 4; - for (let i = 0; i < len; i++) { - buffer.writeUInt16LE(b, str.charCodeAt(i), offset); - offset += 2; - } - return offset; - } - static _readString(b, offset) { - const len = buffer.readUInt32BE(b, offset); - offset += 4; - return (0, stringBuilder_1.decodeUTF16LE)(b, offset, len); - } - writeSize() { - return (+4 // oldPosition - + 4 // newPosition - + TextChange._writeStringSize(this.oldText) - + TextChange._writeStringSize(this.newText)); - } - write(b, offset) { - buffer.writeUInt32BE(b, this.oldPosition, offset); - offset += 4; - buffer.writeUInt32BE(b, this.newPosition, offset); - offset += 4; - offset = TextChange._writeString(b, this.oldText, offset); - offset = TextChange._writeString(b, this.newText, offset); - return offset; - } - static read(b, offset, dest) { - const oldPosition = buffer.readUInt32BE(b, offset); - offset += 4; - const newPosition = buffer.readUInt32BE(b, offset); - offset += 4; - const oldText = TextChange._readString(b, offset); - offset += TextChange._writeStringSize(oldText); - const newText = TextChange._readString(b, offset); - offset += TextChange._writeStringSize(newText); - dest.push(new TextChange(oldPosition, oldText, newPosition, newText)); - return offset; - } - } - exports.TextChange = TextChange; - function compressConsecutiveTextChanges(prevEdits, currEdits) { - if (prevEdits === null || prevEdits.length === 0) { - return currEdits; - } - const compressor = new TextChangeCompressor(prevEdits, currEdits); - return compressor.compress(); - } - exports.compressConsecutiveTextChanges = compressConsecutiveTextChanges; - class TextChangeCompressor { - constructor(prevEdits, currEdits) { - this._prevEdits = prevEdits; - this._currEdits = currEdits; - this._result = []; - this._resultLen = 0; - this._prevLen = this._prevEdits.length; - this._prevDeltaOffset = 0; - this._currLen = this._currEdits.length; - this._currDeltaOffset = 0; - } - compress() { - let prevIndex = 0; - let currIndex = 0; - let prevEdit = this._getPrev(prevIndex); - let currEdit = this._getCurr(currIndex); - while (prevIndex < this._prevLen || currIndex < this._currLen) { - if (prevEdit === null) { - this._acceptCurr(currEdit); - currEdit = this._getCurr(++currIndex); - continue; - } - if (currEdit === null) { - this._acceptPrev(prevEdit); - prevEdit = this._getPrev(++prevIndex); - continue; - } - if (currEdit.oldEnd <= prevEdit.newPosition) { - this._acceptCurr(currEdit); - currEdit = this._getCurr(++currIndex); - continue; - } - if (prevEdit.newEnd <= currEdit.oldPosition) { - this._acceptPrev(prevEdit); - prevEdit = this._getPrev(++prevIndex); - continue; - } - if (currEdit.oldPosition < prevEdit.newPosition) { - const [e1, e2] = TextChangeCompressor._splitCurr(currEdit, prevEdit.newPosition - currEdit.oldPosition); - this._acceptCurr(e1); - currEdit = e2; - continue; - } - if (prevEdit.newPosition < currEdit.oldPosition) { - const [e1, e2] = TextChangeCompressor._splitPrev(prevEdit, currEdit.oldPosition - prevEdit.newPosition); - this._acceptPrev(e1); - prevEdit = e2; - continue; - } - // At this point, currEdit.oldPosition === prevEdit.newPosition - let mergePrev; - let mergeCurr; - if (currEdit.oldEnd === prevEdit.newEnd) { - mergePrev = prevEdit; - mergeCurr = currEdit; - prevEdit = this._getPrev(++prevIndex); - currEdit = this._getCurr(++currIndex); - } - else if (currEdit.oldEnd < prevEdit.newEnd) { - const [e1, e2] = TextChangeCompressor._splitPrev(prevEdit, currEdit.oldLength); - mergePrev = e1; - mergeCurr = currEdit; - prevEdit = e2; - currEdit = this._getCurr(++currIndex); - } - else { - const [e1, e2] = TextChangeCompressor._splitCurr(currEdit, prevEdit.newLength); - mergePrev = prevEdit; - mergeCurr = e1; - prevEdit = this._getPrev(++prevIndex); - currEdit = e2; - } - this._result[this._resultLen++] = new TextChange(mergePrev.oldPosition, mergePrev.oldText, mergeCurr.newPosition, mergeCurr.newText); - this._prevDeltaOffset += mergePrev.newLength - mergePrev.oldLength; - this._currDeltaOffset += mergeCurr.newLength - mergeCurr.oldLength; - } - const merged = TextChangeCompressor._merge(this._result); - const cleaned = TextChangeCompressor._removeNoOps(merged); - return cleaned; - } - _acceptCurr(currEdit) { - this._result[this._resultLen++] = TextChangeCompressor._rebaseCurr(this._prevDeltaOffset, currEdit); - this._currDeltaOffset += currEdit.newLength - currEdit.oldLength; - } - _getCurr(currIndex) { - return (currIndex < this._currLen ? this._currEdits[currIndex] : null); - } - _acceptPrev(prevEdit) { - this._result[this._resultLen++] = TextChangeCompressor._rebasePrev(this._currDeltaOffset, prevEdit); - this._prevDeltaOffset += prevEdit.newLength - prevEdit.oldLength; - } - _getPrev(prevIndex) { - return (prevIndex < this._prevLen ? this._prevEdits[prevIndex] : null); - } - static _rebaseCurr(prevDeltaOffset, currEdit) { - return new TextChange(currEdit.oldPosition - prevDeltaOffset, currEdit.oldText, currEdit.newPosition, currEdit.newText); - } - static _rebasePrev(currDeltaOffset, prevEdit) { - return new TextChange(prevEdit.oldPosition, prevEdit.oldText, prevEdit.newPosition + currDeltaOffset, prevEdit.newText); - } - static _splitPrev(edit, offset) { - const preText = edit.newText.substr(0, offset); - const postText = edit.newText.substr(offset); - return [ - new TextChange(edit.oldPosition, edit.oldText, edit.newPosition, preText), - new TextChange(edit.oldEnd, '', edit.newPosition + offset, postText) - ]; - } - static _splitCurr(edit, offset) { - const preText = edit.oldText.substr(0, offset); - const postText = edit.oldText.substr(offset); - return [ - new TextChange(edit.oldPosition, preText, edit.newPosition, edit.newText), - new TextChange(edit.oldPosition + offset, postText, edit.newEnd, '') - ]; - } - static _merge(edits) { - if (edits.length === 0) { - return edits; - } - let result = [], resultLen = 0; - let prev = edits[0]; - for (let i = 1; i < edits.length; i++) { - const curr = edits[i]; - if (prev.oldEnd === curr.oldPosition) { - // Merge into `prev` - prev = new TextChange(prev.oldPosition, prev.oldText + curr.oldText, prev.newPosition, prev.newText + curr.newText); - } - else { - result[resultLen++] = prev; - prev = curr; - } - } - result[resultLen++] = prev; - return result; - } - static _removeNoOps(edits) { - if (edits.length === 0) { - return edits; - } - let result = [], resultLen = 0; - for (let i = 0; i < edits.length; i++) { - const edit = edits[i]; - if (edit.oldText === edit.newText) { - continue; - } - result[resultLen++] = edit; - } - 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[96/*vs/editor/common/model/textModelEvents*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.InternalModelContentChangeEvent = exports.ModelInjectedTextChangedEvent = exports.ModelRawContentChangedEvent = exports.ModelRawEOLChanged = exports.ModelRawLinesInserted = exports.ModelRawLinesDeleted = exports.ModelRawLineChanged = exports.LineInjectedText = exports.ModelRawFlush = void 0; - /** - * An event describing that a model has been reset to a new value. - * @internal - */ - class ModelRawFlush { - constructor() { - this.changeType = 1 /* Flush */; - } - } - exports.ModelRawFlush = ModelRawFlush; - /** - * Represents text injected on a line - * @internal - */ - class LineInjectedText { - constructor(ownerId, lineNumber, column, options, order) { - this.ownerId = ownerId; - this.lineNumber = lineNumber; - this.column = column; - this.options = options; - this.order = order; - } - static applyInjectedText(lineText, injectedTexts) { - if (!injectedTexts || injectedTexts.length === 0) { - return lineText; - } - let result = ''; - let lastOriginalOffset = 0; - for (const injectedText of injectedTexts) { - result += lineText.substring(lastOriginalOffset, injectedText.column - 1); - lastOriginalOffset = injectedText.column - 1; - result += injectedText.options.content; - } - result += lineText.substring(lastOriginalOffset); - return result; - } - static fromDecorations(decorations) { - const result = []; - for (const decoration of decorations) { - if (decoration.options.before && decoration.options.before.content.length > 0) { - result.push(new LineInjectedText(decoration.ownerId, decoration.range.startLineNumber, decoration.range.startColumn, decoration.options.before, 0)); - } - if (decoration.options.after && decoration.options.after.content.length > 0) { - result.push(new LineInjectedText(decoration.ownerId, decoration.range.endLineNumber, decoration.range.endColumn, decoration.options.after, 1)); - } - } - result.sort((a, b) => { - if (a.lineNumber === b.lineNumber) { - if (a.column === b.column) { - return a.order - b.order; - } - return a.column - b.column; - } - return a.lineNumber - b.lineNumber; - }); - return result; - } - } - exports.LineInjectedText = LineInjectedText; - /** - * An event describing that a line has changed in a model. - * @internal - */ - class ModelRawLineChanged { - constructor(lineNumber, detail, injectedText) { - this.changeType = 2 /* LineChanged */; - this.lineNumber = lineNumber; - this.detail = detail; - this.injectedText = injectedText; - } - } - exports.ModelRawLineChanged = ModelRawLineChanged; - /** - * An event describing that line(s) have been deleted in a model. - * @internal - */ - class ModelRawLinesDeleted { - constructor(fromLineNumber, toLineNumber) { - this.changeType = 3 /* LinesDeleted */; - this.fromLineNumber = fromLineNumber; - this.toLineNumber = toLineNumber; - } - } - exports.ModelRawLinesDeleted = ModelRawLinesDeleted; - /** - * An event describing that line(s) have been inserted in a model. - * @internal - */ - class ModelRawLinesInserted { - constructor(fromLineNumber, toLineNumber, detail, injectedTexts) { - this.changeType = 4 /* LinesInserted */; - this.injectedTexts = injectedTexts; - this.fromLineNumber = fromLineNumber; - this.toLineNumber = toLineNumber; - this.detail = detail; - } - } - exports.ModelRawLinesInserted = ModelRawLinesInserted; - /** - * An event describing that a model has had its EOL changed. - * @internal - */ - class ModelRawEOLChanged { - constructor() { - this.changeType = 5 /* EOLChanged */; - } - } - exports.ModelRawEOLChanged = ModelRawEOLChanged; - /** - * An event describing a change in the text of a model. - * @internal - */ - class ModelRawContentChangedEvent { - constructor(changes, versionId, isUndoing, isRedoing) { - this.changes = changes; - this.versionId = versionId; - this.isUndoing = isUndoing; - this.isRedoing = isRedoing; - this.resultingSelection = null; - } - containsEvent(type) { - for (let i = 0, len = this.changes.length; i < len; i++) { - const change = this.changes[i]; - if (change.changeType === type) { - return true; - } - } - return false; - } - static merge(a, b) { - const changes = [].concat(a.changes).concat(b.changes); - const versionId = b.versionId; - const isUndoing = (a.isUndoing || b.isUndoing); - const isRedoing = (a.isRedoing || b.isRedoing); - return new ModelRawContentChangedEvent(changes, versionId, isUndoing, isRedoing); - } - } - exports.ModelRawContentChangedEvent = ModelRawContentChangedEvent; - /** - * An event describing a change in injected text. - * @internal - */ - class ModelInjectedTextChangedEvent { - constructor(changes) { - this.changes = changes; - } - } - exports.ModelInjectedTextChangedEvent = ModelInjectedTextChangedEvent; - /** - * @internal - */ - class InternalModelContentChangeEvent { - constructor(rawContentChangedEvent, contentChangedEvent) { - this.rawContentChangedEvent = rawContentChangedEvent; - this.contentChangedEvent = contentChangedEvent; - } - merge(other) { - const rawContentChangedEvent = ModelRawContentChangedEvent.merge(this.rawContentChangedEvent, other.rawContentChangedEvent); - const contentChangedEvent = InternalModelContentChangeEvent._mergeChangeEvents(this.contentChangedEvent, other.contentChangedEvent); - return new InternalModelContentChangeEvent(rawContentChangedEvent, contentChangedEvent); - } - static _mergeChangeEvents(a, b) { - const changes = [].concat(a.changes).concat(b.changes); - const eol = b.eol; - const versionId = b.versionId; - const isUndoing = (a.isUndoing || b.isUndoing); - const isRedoing = (a.isRedoing || b.isRedoing); - const isFlush = (a.isFlush || b.isFlush); - return { - changes: changes, - eol: eol, - versionId: versionId, - isUndoing: isUndoing, - isRedoing: isRedoing, - isFlush: isFlush - }; - } - } - 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[171/*vs/editor/common/model/textModelSearch*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,109/*vs/editor/common/controller/wordCharacterClassifier*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,53/*vs/editor/common/model*/]), function (require, exports, strings, wordCharacterClassifier_1, position_1, range_1, model_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Searcher = exports.isValidMatch = exports.TextModelSearch = exports.createFindMatch = exports.SearchData = exports.isMultilineRegexSource = exports.SearchParams = void 0; - const LIMIT_FIND_COUNT = 999; - class SearchParams { - constructor(searchString, isRegex, matchCase, wordSeparators) { - this.searchString = searchString; - this.isRegex = isRegex; - this.matchCase = matchCase; - this.wordSeparators = wordSeparators; - } - parseSearchRequest() { - if (this.searchString === '') { - return null; - } - // Try to create a RegExp out of the params - let multiline; - if (this.isRegex) { - multiline = isMultilineRegexSource(this.searchString); - } - else { - multiline = (this.searchString.indexOf('\n') >= 0); - } - let 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; - } - let 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 ? (0, wordCharacterClassifier_1.getMapForWordSeparators)(this.wordSeparators) : null, canUseSimpleSearch ? this.searchString : null); - } - } - exports.SearchParams = SearchParams; - function isMultilineRegexSource(searchString) { - if (!searchString || searchString.length === 0) { - return false; - } - for (let i = 0, len = searchString.length; i < len; i++) { - const chCode = searchString.charCodeAt(i); - if (chCode === 92 /* Backslash */) { - // move to next char - i++; - if (i >= len) { - // string ends with a \ - break; - } - const nextChCode = searchString.charCodeAt(i); - if (nextChCode === 110 /* n */ || nextChCode === 114 /* r */ || nextChCode === 87 /* W */ || nextChCode === 119 /* w */) { - return true; - } - } - } - return false; - } - exports.isMultilineRegexSource = isMultilineRegexSource; - class SearchData { - constructor(regex, wordSeparators, simpleSearch) { - this.regex = regex; - this.wordSeparators = wordSeparators; - this.simpleSearch = simpleSearch; - } - } - exports.SearchData = SearchData; - function createFindMatch(range, rawMatches, captureMatches) { - if (!captureMatches) { - return new model_1.FindMatch(range, null); - } - let matches = []; - for (let i = 0, len = rawMatches.length; i < len; i++) { - matches[i] = rawMatches[i]; - } - return new model_1.FindMatch(range, matches); - } - exports.createFindMatch = createFindMatch; - class LineFeedCounter { - constructor(text) { - let lineFeedsOffsets = []; - let lineFeedsOffsetsLen = 0; - for (let i = 0, textLen = text.length; i < textLen; i++) { - if (text.charCodeAt(i) === 10 /* LineFeed */) { - lineFeedsOffsets[lineFeedsOffsetsLen++] = i; - } - } - this._lineFeedsOffsets = lineFeedsOffsets; - } - findLineFeedCountBeforeOffset(offset) { - const lineFeedsOffsets = this._lineFeedsOffsets; - let min = 0; - let 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) { - const 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; - } - } - class TextModelSearch { - static findMatches(model, searchParams, searchRange, captureMatches, limitResultCount) { - const 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 - */ - static _getMultilineMatchRange(model, deltaOffset, text, lfCounter, matchIndex, match0) { - let startOffset; - let lineFeedCountBeforeMatch = 0; - if (lfCounter) { - lineFeedCountBeforeMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex); - startOffset = deltaOffset + matchIndex + lineFeedCountBeforeMatch /* add as many \r as there were \n */; - } - else { - startOffset = deltaOffset + matchIndex; - } - let endOffset; - if (lfCounter) { - let lineFeedCountBeforeEndOfMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex + match0.length); - let lineFeedCountInMatch = lineFeedCountBeforeEndOfMatch - lineFeedCountBeforeMatch; - endOffset = startOffset + match0.length + lineFeedCountInMatch /* add as many \r as there were \n */; - } - else { - endOffset = startOffset + match0.length; - } - const startPosition = model.getPositionAt(startOffset); - const endPosition = model.getPositionAt(endOffset); - return new range_1.Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column); - } - static _doFindMatchesMultiline(model, searchRange, searcher, captureMatches, limitResultCount) { - const 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` - const text = model.getValueInRange(searchRange, 1 /* LF */); - const lfCounter = (model.getEOL() === '\r\n' ? new LineFeedCounter(text) : null); - const result = []; - let counter = 0; - let 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; - } - static _doFindMatchesLineByLine(model, searchRange, searchData, captureMatches, limitResultCount) { - const result = []; - let resultLen = 0; - // Early case for a search range that starts & stops on the same line number - if (searchRange.startLineNumber === searchRange.endLineNumber) { - const text = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1, searchRange.endColumn - 1); - resultLen = this._findMatchesInLine(searchData, text, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result, captureMatches, limitResultCount); - return result; - } - // Collect results from first line - const 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 (let 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) { - const text = model.getLineContent(searchRange.endLineNumber).substring(0, searchRange.endColumn - 1); - resultLen = this._findMatchesInLine(searchData, text, searchRange.endLineNumber, 0, resultLen, result, captureMatches, limitResultCount); - } - return result; - } - static _findMatchesInLine(searchData, text, lineNumber, deltaOffset, resultLen, result, captureMatches, limitResultCount) { - const wordSeparators = searchData.wordSeparators; - if (!captureMatches && searchData.simpleSearch) { - const searchString = searchData.simpleSearch; - const searchStringLen = searchString.length; - const textLength = text.length; - let 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; - } - const searcher = new Searcher(searchData.wordSeparators, searchData.regex); - let 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; - } - static findNextMatch(model, searchParams, searchStart, captureMatches) { - const searchData = searchParams.parseSearchRequest(); - if (!searchData) { - return null; - } - const 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); - } - static _doFindNextMatchMultiline(model, searchStart, searcher, captureMatches) { - const searchTextStart = new position_1.Position(searchStart.lineNumber, 1); - const deltaOffset = model.getOffsetAt(searchTextStart); - const 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` - const text = model.getValueInRange(new range_1.Range(searchTextStart.lineNumber, searchTextStart.column, lineCount, model.getLineMaxColumn(lineCount)), 1 /* LF */); - const lfCounter = (model.getEOL() === '\r\n' ? new LineFeedCounter(text) : null); - searcher.reset(searchStart.column - 1); - let 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; - } - static _doFindNextMatchLineByLine(model, searchStart, searcher, captureMatches) { - const lineCount = model.getLineCount(); - const startLineNumber = searchStart.lineNumber; - // Look in first line - const text = model.getLineContent(startLineNumber); - const r = this._findFirstMatchInLine(searcher, text, startLineNumber, searchStart.column, captureMatches); - if (r) { - return r; - } - for (let i = 1; i <= lineCount; i++) { - const lineIndex = (startLineNumber + i - 1) % lineCount; - const text = model.getLineContent(lineIndex + 1); - const r = this._findFirstMatchInLine(searcher, text, lineIndex + 1, 1, captureMatches); - if (r) { - return r; - } - } - return null; - } - static _findFirstMatchInLine(searcher, text, lineNumber, fromColumn, captureMatches) { - // Set regex to search from column - searcher.reset(fromColumn - 1); - const 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; - } - static findPreviousMatch(model, searchParams, searchStart, captureMatches) { - const searchData = searchParams.parseSearchRequest(); - if (!searchData) { - return null; - } - const 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); - } - static _doFindPreviousMatchMultiline(model, searchStart, searcher, captureMatches) { - const 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]; - } - const 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; - } - static _doFindPreviousMatchLineByLine(model, searchStart, searcher, captureMatches) { - const lineCount = model.getLineCount(); - const startLineNumber = searchStart.lineNumber; - // Look in first line - const text = model.getLineContent(startLineNumber).substring(0, searchStart.column - 1); - const r = this._findLastMatchInLine(searcher, text, startLineNumber, captureMatches); - if (r) { - return r; - } - for (let i = 1; i <= lineCount; i++) { - const lineIndex = (lineCount + startLineNumber - i - 1) % lineCount; - const text = model.getLineContent(lineIndex + 1); - const r = this._findLastMatchInLine(searcher, text, lineIndex + 1, captureMatches); - if (r) { - return r; - } - } - return null; - } - static _findLastMatchInLine(searcher, text, lineNumber, captureMatches) { - let bestResult = null; - let 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; - } - } - exports.TextModelSearch = TextModelSearch; - function leftIsWordBounday(wordSeparators, text, textLength, matchStartIndex, matchLength) { - if (matchStartIndex === 0) { - // Match starts at start of string - return true; - } - const 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) { - const 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; - } - const 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) { - const 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; - class Searcher { - constructor(wordSeparators, searchRegex) { - this._wordSeparators = wordSeparators; - this._searchRegex = searchRegex; - this._prevMatchStartIndex = -1; - this._prevMatchLength = 0; - } - reset(lastIndex) { - this._searchRegex.lastIndex = lastIndex; - this._prevMatchStartIndex = -1; - this._prevMatchLength = 0; - } - next(text) { - const textLength = text.length; - let 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; - } - const matchStartIndex = m.index; - const 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 two if surrogate pair found and by one otherwise - if (strings.getNextCodePoint(text, textLength, this._searchRegex.lastIndex) > 0xFFFF) { - this._searchRegex.lastIndex += 2; - } - else { - 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; - } - } - 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[221/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase*/], __M([0/*require*/,1/*exports*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,53/*vs/editor/common/model*/,380/*vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase*/,171/*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 }); - exports.PieceTreeBase = exports.StringBuffer = exports.Piece = exports.createLineStarts = exports.createLineStartsFast = exports.LineStarts = exports.createUintArray = exports.AverageBufferSize = void 0; - // const lfRegex = new RegExp(/\r\n|\r|\n/g); - exports.AverageBufferSize = 65535; - function createUintArray(arr) { - let 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; - class LineStarts { - constructor(lineStarts, cr, lf, crlf, isBasicASCII) { - this.lineStarts = lineStarts; - this.cr = cr; - this.lf = lf; - this.crlf = crlf; - this.isBasicASCII = isBasicASCII; - } - } - exports.LineStarts = LineStarts; - function createLineStartsFast(str, readonly = true) { - let r = [0], rLength = 1; - for (let i = 0, len = str.length; i < len; i++) { - const 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; - let rLength = 1; - let cr = 0, lf = 0, crlf = 0; - let isBasicASCII = true; - for (let i = 0, len = str.length; i < len; i++) { - const 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; - } - } - } - } - const result = new LineStarts(createUintArray(r), cr, lf, crlf, isBasicASCII); - r.length = 0; - return result; - } - exports.createLineStarts = createLineStarts; - class Piece { - constructor(bufferIndex, start, end, lineFeedCnt, length) { - this.bufferIndex = bufferIndex; - this.start = start; - this.end = end; - this.lineFeedCnt = lineFeedCnt; - this.length = length; - } - } - exports.Piece = Piece; - class StringBuffer { - constructor(buffer, lineStarts) { - this.buffer = buffer; - this.lineStarts = lineStarts; - } - } - exports.StringBuffer = StringBuffer; - /** - * Readonly snapshot for piece tree. - * In a real multiple thread environment, to make snapshot reading always work correctly, we need to - * 1. Make TreeNode.piece immutable, then reading and writing can run in parallel. - * 2. TreeNode/Buffers normalization should not happen during snapshot reading. - */ - class PieceTreeSnapshot { - constructor(tree, BOM) { - this._pieces = []; - this._tree = tree; - this._BOM = BOM; - this._index = 0; - if (tree.root !== rbTreeBase_1.SENTINEL) { - tree.iterate(tree.root, node => { - if (node !== rbTreeBase_1.SENTINEL) { - this._pieces.push(node.piece); - } - return true; - }); - } - } - read() { - if (this._pieces.length === 0) { - if (this._index === 0) { - this._index++; - return this._BOM; - } - else { - return null; - } - } - if (this._index > this._pieces.length - 1) { - return null; - } - if (this._index === 0) { - return this._BOM + this._tree.getPieceContent(this._pieces[this._index++]); - } - return this._tree.getPieceContent(this._pieces[this._index++]); - } - } - class PieceTreeSearchCache { - constructor(limit) { - this._limit = limit; - this._cache = []; - } - get(offset) { - for (let i = this._cache.length - 1; i >= 0; i--) { - let nodePos = this._cache[i]; - if (nodePos.nodeStartOffset <= offset && nodePos.nodeStartOffset + nodePos.node.piece.length >= offset) { - return nodePos; - } - } - return null; - } - get2(lineNumber) { - for (let i = this._cache.length - 1; i >= 0; i--) { - let nodePos = this._cache[i]; - if (nodePos.nodeStartLineNumber && nodePos.nodeStartLineNumber < lineNumber && nodePos.nodeStartLineNumber + nodePos.node.piece.lineFeedCnt >= lineNumber) { - return nodePos; - } - } - return null; - } - set(nodePosition) { - if (this._cache.length >= this._limit) { - this._cache.shift(); - } - this._cache.push(nodePosition); - } - validate(offset) { - let hasInvalidVal = false; - let tmp = this._cache; - for (let i = 0; i < tmp.length; i++) { - let nodePos = tmp[i]; - if (nodePos.node.parent === null || nodePos.nodeStartOffset >= offset) { - tmp[i] = null; - hasInvalidVal = true; - continue; - } - } - if (hasInvalidVal) { - let newArr = []; - for (const entry of tmp) { - if (entry !== null) { - newArr.push(entry); - } - } - this._cache = newArr; - } - } - } - class PieceTreeBase { - constructor(chunks, eol, eolNormalized) { - this.create(chunks, eol, eolNormalized); - } - create(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; - let lastNode = null; - for (let 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); - } - let 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(); - } - normalizeEOL(eol) { - let averageBufferSize = exports.AverageBufferSize; - let min = averageBufferSize - Math.floor(averageBufferSize / 3); - let max = min * 2; - let tempChunk = ''; - let tempChunkLen = 0; - let chunks = []; - this.iterate(this.root, node => { - let str = this.getNodeContent(node); - let len = str.length; - if (tempChunkLen <= min || tempChunkLen + len < max) { - tempChunk += str; - tempChunkLen += len; - return true; - } - // flush anyways - let 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) { - let text = tempChunk.replace(/\r\n|\r|\n/g, eol); - chunks.push(new StringBuffer(text, createLineStartsFast(text))); - } - this.create(chunks, eol, true); - } - // #region Buffer API - getEOL() { - return this._EOL; - } - setEOL(newEOL) { - this._EOL = newEOL; - this._EOLLength = this._EOL.length; - this.normalizeEOL(newEOL); - } - createSnapshot(BOM) { - return new PieceTreeSnapshot(this, BOM); - } - getOffsetAt(lineNumber, column) { - let leftLen = 0; // inorder - let 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 - let 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; - } - getPositionAt(offset) { - offset = Math.floor(offset); - offset = Math.max(0, offset); - let x = this.root; - let lfCnt = 0; - let 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) { - let out = this.getIndexOf(x, offset - x.size_left); - lfCnt += x.lf_left + out.index; - if (out.index === 0) { - let lineStartOffset = this.getOffsetAt(lfCnt + 1, 1); - let 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 - let lineStartOffset = this.getOffsetAt(lfCnt + 1, 1); - let column = originalOffset - offset - lineStartOffset; - return new position_1.Position(lfCnt + 1, column + 1); - } - else { - x = x.right; - } - } - } - return new position_1.Position(1, 1); - } - getValueInRange(range, eol) { - if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) { - return ''; - } - let startPosition = this.nodeAt2(range.startLineNumber, range.startColumn); - let endPosition = this.nodeAt2(range.endLineNumber, range.endColumn); - let 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; - } - getValueInRange2(startPosition, endPosition) { - if (startPosition.node === endPosition.node) { - let node = startPosition.node; - let buffer = this._buffers[node.piece.bufferIndex].buffer; - let startOffset = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start); - return buffer.substring(startOffset + startPosition.remainder, startOffset + endPosition.remainder); - } - let x = startPosition.node; - let buffer = this._buffers[x.piece.bufferIndex].buffer; - let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); - let ret = buffer.substring(startOffset + startPosition.remainder, startOffset + x.piece.length); - x = x.next(); - while (x !== rbTreeBase_1.SENTINEL) { - let buffer = this._buffers[x.piece.bufferIndex].buffer; - let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); - if (x === endPosition.node) { - ret += buffer.substring(startOffset, startOffset + endPosition.remainder); - break; - } - else { - ret += buffer.substr(startOffset, x.piece.length); - } - x = x.next(); - } - return ret; - } - getLinesContent() { - let lines = []; - let linesLength = 0; - let currentLine = ''; - let danglingCR = false; - this.iterate(this.root, node => { - if (node === rbTreeBase_1.SENTINEL) { - return true; - } - const piece = node.piece; - let pieceLength = piece.length; - if (pieceLength === 0) { - return true; - } - const buffer = this._buffers[piece.bufferIndex].buffer; - const lineStarts = this._buffers[piece.bufferIndex].lineStarts; - const pieceStartLine = piece.start.line; - const pieceEndLine = piece.end.line; - let 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 (let 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; - } - getLength() { - return this._length; - } - getLineCount() { - return this._lineCnt; - } - getLineContent(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; - } - _getCharCode(nodePos) { - if (nodePos.remainder === nodePos.node.piece.length) { - // the char we want to fetch is at the head of next node. - let matchingNode = nodePos.node.next(); - if (!matchingNode) { - return 0; - } - let buffer = this._buffers[matchingNode.piece.bufferIndex]; - let startOffset = this.offsetInBuffer(matchingNode.piece.bufferIndex, matchingNode.piece.start); - return buffer.buffer.charCodeAt(startOffset); - } - else { - let buffer = this._buffers[nodePos.node.piece.bufferIndex]; - let startOffset = this.offsetInBuffer(nodePos.node.piece.bufferIndex, nodePos.node.piece.start); - let targetOffset = startOffset + nodePos.remainder; - return buffer.buffer.charCodeAt(targetOffset); - } - } - getLineCharCode(lineNumber, index) { - let nodePos = this.nodeAt2(lineNumber, index + 1); - return this._getCharCode(nodePos); - } - getLineLength(lineNumber) { - if (lineNumber === this.getLineCount()) { - let startOffset = this.getOffsetAt(lineNumber, 1); - return this.getLength() - startOffset; - } - return this.getOffsetAt(lineNumber + 1, 1) - this.getOffsetAt(lineNumber, 1) - this._EOLLength; - } - findMatchesInNode(node, searcher, startLineNumber, startColumn, startCursor, endCursor, searchData, captureMatches, limitResultCount, resultLen, result) { - let buffer = this._buffers[node.piece.bufferIndex]; - let startOffsetInBuffer = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start); - let start = this.offsetInBuffer(node.piece.bufferIndex, startCursor); - let end = this.offsetInBuffer(node.piece.bufferIndex, endCursor); - let m; - // Reset regex to search from the beginning - let ret = { line: 0, column: 0 }; - let searchText; - let offsetInBuffer; - if (searcher._wordSeparators) { - searchText = buffer.buffer.substring(start, end); - offsetInBuffer = (offset) => offset + start; - searcher.reset(0); - } - else { - searchText = buffer.buffer; - offsetInBuffer = (offset) => 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); - let lineFeedCnt = this.getLineFeedCnt(node.piece.bufferIndex, startCursor, ret); - let retStartColumn = ret.line === startCursor.line ? ret.column - startCursor.column + startColumn : ret.column + 1; - let retEndColumn = retStartColumn + m[0].length; - result[resultLen++] = (0, 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; - } - findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount) { - const result = []; - let resultLen = 0; - const searcher = new textModelSearch_1.Searcher(searchData.wordSeparators, searchData.regex); - let startPosition = this.nodeAt2(searchRange.startLineNumber, searchRange.startColumn); - if (startPosition === null) { - return []; - } - let endPosition = this.nodeAt2(searchRange.endLineNumber, searchRange.endColumn); - if (endPosition === null) { - return []; - } - let start = this.positionInBuffer(startPosition.node, startPosition.remainder); - let 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; - } - let startLineNumber = searchRange.startLineNumber; - let currentNode = startPosition.node; - while (currentNode !== endPosition.node) { - let lineBreakCnt = this.getLineFeedCnt(currentNode.piece.bufferIndex, start, currentNode.piece.end); - if (lineBreakCnt >= 1) { - // last line break position - let lineStarts = this._buffers[currentNode.piece.bufferIndex].lineStarts; - let startOffsetInBuffer = this.offsetInBuffer(currentNode.piece.bufferIndex, currentNode.piece.start); - let nextLineStartOffset = lineStarts[start.line + lineBreakCnt]; - let startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1; - resultLen = this.findMatchesInNode(currentNode, searcher, startLineNumber, startColumn, start, this.positionInBuffer(currentNode, nextLineStartOffset - startOffsetInBuffer), searchData, captureMatches, limitResultCount, resultLen, result); - if (resultLen >= limitResultCount) { - return result; - } - startLineNumber += lineBreakCnt; - } - let startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0; - // search for the remaining content - if (startLineNumber === searchRange.endLineNumber) { - const text = this.getLineContent(startLineNumber).substring(startColumn, searchRange.endColumn - 1); - resultLen = this._findMatchesInLine(searchData, searcher, text, searchRange.endLineNumber, startColumn, resultLen, result, captureMatches, limitResultCount); - return result; - } - resultLen = this._findMatchesInLine(searchData, searcher, this.getLineContent(startLineNumber).substr(startColumn), startLineNumber, startColumn, 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) { - let startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0; - const text = this.getLineContent(startLineNumber).substring(startColumn, searchRange.endColumn - 1); - resultLen = this._findMatchesInLine(searchData, searcher, text, searchRange.endLineNumber, startColumn, resultLen, result, captureMatches, limitResultCount); - return result; - } - let startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1; - resultLen = this.findMatchesInNode(endPosition.node, searcher, startLineNumber, startColumn, start, end, searchData, captureMatches, limitResultCount, resultLen, result); - return result; - } - _findMatchesInLine(searchData, searcher, text, lineNumber, deltaOffset, resultLen, result, captureMatches, limitResultCount) { - const wordSeparators = searchData.wordSeparators; - if (!captureMatches && searchData.simpleSearch) { - const searchString = searchData.simpleSearch; - const searchStringLen = searchString.length; - const textLength = text.length; - let lastMatchIndex = -searchStringLen; - while ((lastMatchIndex = text.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) { - if (!wordSeparators || (0, 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; - } - let m; - // Reset regex to search from the beginning - searcher.reset(0); - do { - m = searcher.next(text); - if (m) { - result[resultLen++] = (0, 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 - insert(offset, value, eolNormalized = false) { - this._EOLNormalized = this._EOLNormalized && eolNormalized; - this._lastVisitedLine.lineNumber = 0; - this._lastVisitedLine.value = ''; - if (this.root !== rbTreeBase_1.SENTINEL) { - let { node, remainder, nodeStartOffset } = this.nodeAt(offset); - let piece = node.piece; - let bufferIndex = piece.bufferIndex; - let 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.validate(offset); - } - else if (nodeStartOffset + node.piece.length > offset) { - // we are inserting into the middle of a node. - let nodesToDel = []; - let 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)) { - let headOfRight = this.nodeCharCodeAt(node, remainder); - if (headOfRight === 10 /** \n */) { - let 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)) { - let tailOfLeft = this.nodeCharCodeAt(node, remainder - 1); - if (tailOfLeft === 13 /** \r */) { - let 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); - } - let newPieces = this.createNewPieces(value); - if (newRightPiece.length > 0) { - this.rbInsertRight(node, newRightPiece); - } - let tmpNode = node; - for (let k = 0; k < newPieces.length; k++) { - tmpNode = this.rbInsertRight(tmpNode, newPieces[k]); - } - this.deleteNodes(nodesToDel); - } - else { - this.insertContentToNodeRight(value, node); - } - } - else { - // insert new node - let pieces = this.createNewPieces(value); - let node = this.rbInsertLeft(null, pieces[0]); - for (let 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(); - } - delete(offset, cnt) { - this._lastVisitedLine.lineNumber = 0; - this._lastVisitedLine.value = ''; - if (cnt <= 0 || this.root === rbTreeBase_1.SENTINEL) { - return; - } - let startPosition = this.nodeAt(offset); - let endPosition = this.nodeAt(offset + cnt); - let startNode = startPosition.node; - let endNode = endPosition.node; - if (startNode === endNode) { - let startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder); - let endSplitPosInBuffer = this.positionInBuffer(startNode, endPosition.remainder); - if (startPosition.nodeStartOffset === offset) { - if (cnt === startNode.piece.length) { // delete node - let next = startNode.next(); - (0, rbTreeBase_1.rbDelete)(this, startNode); - this.validateCRLFWithPrevNode(next); - this.computeBufferMetadata(); - return; - } - this.deleteNodeHead(startNode, endSplitPosInBuffer); - this._searchCache.validate(offset); - this.validateCRLFWithPrevNode(startNode); - this.computeBufferMetadata(); - return; - } - if (startPosition.nodeStartOffset + startNode.piece.length === offset + cnt) { - this.deleteNodeTail(startNode, startSplitPosInBuffer); - this.validateCRLFWithNextNode(startNode); - this.computeBufferMetadata(); - return; - } - // delete content in the middle, this node will be splitted to nodes - this.shrinkNode(startNode, startSplitPosInBuffer, endSplitPosInBuffer); - this.computeBufferMetadata(); - return; - } - let nodesToDel = []; - let startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder); - this.deleteNodeTail(startNode, startSplitPosInBuffer); - this._searchCache.validate(offset); - if (startNode.piece.length === 0) { - nodesToDel.push(startNode); - } - // update last touched node - let endSplitPosInBuffer = this.positionInBuffer(endNode, endPosition.remainder); - this.deleteNodeHead(endNode, endSplitPosInBuffer); - if (endNode.piece.length === 0) { - nodesToDel.push(endNode); - } - // delete nodes in between - let secondNode = startNode.next(); - for (let node = secondNode; node !== rbTreeBase_1.SENTINEL && node !== endNode; node = node.next()) { - nodesToDel.push(node); - } - let prev = startNode.piece.length === 0 ? startNode.prev() : startNode; - this.deleteNodes(nodesToDel); - this.validateCRLFWithNextNode(prev); - this.computeBufferMetadata(); - } - insertContentToNodeLeft(value, node) { - // we are inserting content to the beginning of node - let nodesToDel = []; - if (this.shouldCheckCRLF() && this.endWithCR(value) && this.startWithLF(node)) { - // move `\n` to new node. - let piece = node.piece; - let newStart = { line: piece.start.line + 1, column: 0 }; - let nPiece = new Piece(piece.bufferIndex, newStart, piece.end, this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end), piece.length - 1); - node.piece = nPiece; - value += '\n'; - (0, rbTreeBase_1.updateTreeMetadata)(this, node, -1, -1); - if (node.piece.length === 0) { - nodesToDel.push(node); - } - } - let newPieces = this.createNewPieces(value); - let newNode = this.rbInsertLeft(node, newPieces[newPieces.length - 1]); - for (let k = newPieces.length - 2; k >= 0; k--) { - newNode = this.rbInsertLeft(newNode, newPieces[k]); - } - this.validateCRLFWithPrevNode(newNode); - this.deleteNodes(nodesToDel); - } - insertContentToNodeRight(value, node) { - // we are inserting to the right of this node. - if (this.adjustCarriageReturnFromNext(value, node)) { - // move \n to the new node. - value += '\n'; - } - let newPieces = this.createNewPieces(value); - let newNode = this.rbInsertRight(node, newPieces[0]); - let tmpNode = newNode; - for (let k = 1; k < newPieces.length; k++) { - tmpNode = this.rbInsertRight(tmpNode, newPieces[k]); - } - this.validateCRLFWithPrevNode(newNode); - } - positionInBuffer(node, remainder, ret) { - let piece = node.piece; - let bufferIndex = node.piece.bufferIndex; - let lineStarts = this._buffers[bufferIndex].lineStarts; - let startOffset = lineStarts[piece.start.line] + piece.start.column; - let offset = startOffset + remainder; - // binary search offset between startOffset and endOffset - let low = piece.start.line; - let high = piece.end.line; - let mid = 0; - let midStop = 0; - let 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 - }; - } - getLineFeedCnt(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; - } - let 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; - } - let nextLineStartOffset = lineStarts[end.line + 1]; - let 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. - let previousCharOffset = endOffset - 1; // end.column > 0 so it's okay. - let buffer = this._buffers[bufferIndex].buffer; - if (buffer.charCodeAt(previousCharOffset) === 13) { - return end.line - start.line + 1; - } - else { - return end.line - start.line; - } - } - offsetInBuffer(bufferIndex, cursor) { - let lineStarts = this._buffers[bufferIndex].lineStarts; - return lineStarts[cursor.line] + cursor.column; - } - deleteNodes(nodes) { - for (let i = 0; i < nodes.length; i++) { - (0, rbTreeBase_1.rbDelete)(this, nodes[i]); - } - } - createNewPieces(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 - let newPieces = []; - while (text.length > exports.AverageBufferSize) { - const lastChar = text.charCodeAt(exports.AverageBufferSize - 1); - let splitText; - 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); - } - let lineStarts = createLineStartsFast(splitText); - newPieces.push(new Piece(this._buffers.length, /* buffer index */ { line: 0, column: 0 }, { line: lineStarts.length - 1, column: splitText.length - lineStarts[lineStarts.length - 1] }, lineStarts.length - 1, splitText.length)); - this._buffers.push(new StringBuffer(splitText, lineStarts)); - } - let lineStarts = createLineStartsFast(text); - newPieces.push(new Piece(this._buffers.length, /* buffer index */ { line: 0, column: 0 }, { line: lineStarts.length - 1, column: text.length - lineStarts[lineStarts.length - 1] }, lineStarts.length - 1, text.length)); - this._buffers.push(new StringBuffer(text, lineStarts)); - return newPieces; - } - let startOffset = this._buffers[0].buffer.length; - const lineStarts = createLineStartsFast(text, false); - let 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 (let 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 (let 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; - } - const endOffset = this._buffers[0].buffer.length; - let endIndex = this._buffers[0].lineStarts.length - 1; - let endColumn = endOffset - this._buffers[0].lineStarts[endIndex]; - let endPos = { line: endIndex, column: endColumn }; - let newPiece = new Piece(0, /** todo@peng */ start, endPos, this.getLineFeedCnt(0, start, endPos), endOffset - startOffset); - this._lastChangeBufferPos = endPos; - return [newPiece]; - } - getLineRawContent(lineNumber, endOffset = 0) { - let x = this.root; - let ret = ''; - let cache = this._searchCache.get2(lineNumber); - if (cache) { - x = cache.node; - let prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber - 1); - let buffer = this._buffers[x.piece.bufferIndex].buffer; - let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); - if (cache.nodeStartLineNumber + x.piece.lineFeedCnt === lineNumber) { - ret = buffer.substring(startOffset + prevAccumulatedValue, startOffset + x.piece.length); - } - else { - let accumulatedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber); - return buffer.substring(startOffset + prevAccumulatedValue, startOffset + accumulatedValue - endOffset); - } - } - else { - let nodeStartOffset = 0; - const 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) { - let prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2); - let accumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1); - let buffer = this._buffers[x.piece.bufferIndex].buffer; - let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); - nodeStartOffset += x.size_left; - this._searchCache.set({ - node: x, - nodeStartOffset, - nodeStartLineNumber: originalLineNumber - (lineNumber - 1 - x.lf_left) - }); - return buffer.substring(startOffset + prevAccumulatedValue, startOffset + accumulatedValue - endOffset); - } - else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) { - let prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2); - let buffer = this._buffers[x.piece.bufferIndex].buffer; - let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); - ret = buffer.substring(startOffset + prevAccumulatedValue, 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) { - let buffer = this._buffers[x.piece.bufferIndex].buffer; - if (x.piece.lineFeedCnt > 0) { - let accumulatedValue = this.getAccumulatedValue(x, 0); - let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); - ret += buffer.substring(startOffset, startOffset + accumulatedValue - endOffset); - return ret; - } - else { - let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start); - ret += buffer.substr(startOffset, x.piece.length); - } - x = x.next(); - } - return ret; - } - computeBufferMetadata() { - let x = this.root; - let lfCnt = 1; - let 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.validate(this._length); - } - // #region node operations - getIndexOf(node, accumulatedValue) { - let piece = node.piece; - let pos = this.positionInBuffer(node, accumulatedValue); - let 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. - let 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 }; - } - getAccumulatedValue(node, index) { - if (index < 0) { - return 0; - } - let piece = node.piece; - let lineStarts = this._buffers[piece.bufferIndex].lineStarts; - let 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; - } - } - deleteNodeTail(node, pos) { - const piece = node.piece; - const originalLFCnt = piece.lineFeedCnt; - const originalEndOffset = this.offsetInBuffer(piece.bufferIndex, piece.end); - const newEnd = pos; - const newEndOffset = this.offsetInBuffer(piece.bufferIndex, newEnd); - const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd); - const lf_delta = newLineFeedCnt - originalLFCnt; - const size_delta = newEndOffset - originalEndOffset; - const newLength = piece.length + size_delta; - node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength); - (0, rbTreeBase_1.updateTreeMetadata)(this, node, size_delta, lf_delta); - } - deleteNodeHead(node, pos) { - const piece = node.piece; - const originalLFCnt = piece.lineFeedCnt; - const originalStartOffset = this.offsetInBuffer(piece.bufferIndex, piece.start); - const newStart = pos; - const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end); - const newStartOffset = this.offsetInBuffer(piece.bufferIndex, newStart); - const lf_delta = newLineFeedCnt - originalLFCnt; - const size_delta = originalStartOffset - newStartOffset; - const newLength = piece.length + size_delta; - node.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength); - (0, rbTreeBase_1.updateTreeMetadata)(this, node, size_delta, lf_delta); - } - shrinkNode(node, start, end) { - const piece = node.piece; - const originalStartPos = piece.start; - const originalEndPos = piece.end; - // old piece, originalStartPos, start - const oldLength = piece.length; - const oldLFCnt = piece.lineFeedCnt; - const newEnd = start; - const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd); - const newLength = this.offsetInBuffer(piece.bufferIndex, start) - this.offsetInBuffer(piece.bufferIndex, originalStartPos); - node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength); - (0, rbTreeBase_1.updateTreeMetadata)(this, node, newLength - oldLength, newLineFeedCnt - oldLFCnt); - // new right piece, end, originalEndPos - let newPiece = new Piece(piece.bufferIndex, end, originalEndPos, this.getLineFeedCnt(piece.bufferIndex, end, originalEndPos), this.offsetInBuffer(piece.bufferIndex, originalEndPos) - this.offsetInBuffer(piece.bufferIndex, end)); - let newNode = this.rbInsertRight(node, newPiece); - this.validateCRLFWithPrevNode(newNode); - } - appendToNode(node, value) { - if (this.adjustCarriageReturnFromNext(value, node)) { - value += '\n'; - } - const hitCRLF = this.shouldCheckCRLF() && this.startWithLF(value) && this.endWithCR(node); - const startOffset = this._buffers[0].buffer.length; - this._buffers[0].buffer += value; - const lineStarts = createLineStartsFast(value, false); - for (let i = 0; i < lineStarts.length; i++) { - lineStarts[i] += startOffset; - } - if (hitCRLF) { - let 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)); - const endIndex = this._buffers[0].lineStarts.length - 1; - const endColumn = this._buffers[0].buffer.length - this._buffers[0].lineStarts[endIndex]; - const newEnd = { line: endIndex, column: endColumn }; - const newLength = node.piece.length + value.length; - const oldLineFeedCnt = node.piece.lineFeedCnt; - const newLineFeedCnt = this.getLineFeedCnt(0, node.piece.start, newEnd); - const lf_delta = newLineFeedCnt - oldLineFeedCnt; - node.piece = new Piece(node.piece.bufferIndex, node.piece.start, newEnd, newLineFeedCnt, newLength); - this._lastChangeBufferPos = newEnd; - (0, rbTreeBase_1.updateTreeMetadata)(this, node, value.length, lf_delta); - } - nodeAt(offset) { - let x = this.root; - let cache = this._searchCache.get(offset); - if (cache) { - return { - node: cache.node, - nodeStartOffset: cache.nodeStartOffset, - remainder: offset - cache.nodeStartOffset - }; - } - let 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; - let ret = { - node: x, - remainder: offset - x.size_left, - 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; - } - nodeAt2(lineNumber, column) { - let x = this.root; - let 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) { - let prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2); - let accumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1); - nodeStartOffset += x.size_left; - return { - node: x, - remainder: Math.min(prevAccumualtedValue + column - 1, accumulatedValue), - nodeStartOffset - }; - } - else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) { - let prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2); - if (prevAccumualtedValue + column - 1 <= x.piece.length) { - return { - node: x, - remainder: prevAccumualtedValue + column - 1, - 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) { - let accumulatedValue = this.getAccumulatedValue(x, 0); - let nodeStartOffset = this.offsetOfNode(x); - return { - node: x, - remainder: Math.min(column - 1, accumulatedValue), - nodeStartOffset - }; - } - else { - if (x.piece.length >= column - 1) { - let nodeStartOffset = this.offsetOfNode(x); - return { - node: x, - remainder: column - 1, - nodeStartOffset - }; - } - else { - column -= x.piece.length; - } - } - x = x.next(); - } - return null; - } - nodeCharCodeAt(node, offset) { - if (node.piece.lineFeedCnt < 1) { - return -1; - } - let buffer = this._buffers[node.piece.bufferIndex]; - let newOffset = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start) + offset; - return buffer.buffer.charCodeAt(newOffset); - } - offsetOfNode(node) { - if (!node) { - return 0; - } - let 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 - shouldCheckCRLF() { - return !(this._EOLNormalized && this._EOL === '\n'); - } - startWithLF(val) { - if (typeof val === 'string') { - return val.charCodeAt(0) === 10; - } - if (val === rbTreeBase_1.SENTINEL || val.piece.lineFeedCnt === 0) { - return false; - } - let piece = val.piece; - let lineStarts = this._buffers[piece.bufferIndex].lineStarts; - let line = piece.start.line; - let 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; - } - let nextLineOffset = lineStarts[line + 1]; - if (nextLineOffset > startOffset + 1) { - return false; - } - return this._buffers[piece.bufferIndex].buffer.charCodeAt(startOffset) === 10; - } - endWithCR(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; - } - validateCRLFWithPrevNode(nextNode) { - if (this.shouldCheckCRLF() && this.startWithLF(nextNode)) { - let node = nextNode.prev(); - if (this.endWithCR(node)) { - this.fixCRLF(node, nextNode); - } - } - } - validateCRLFWithNextNode(node) { - if (this.shouldCheckCRLF() && this.endWithCR(node)) { - let nextNode = node.next(); - if (this.startWithLF(nextNode)) { - this.fixCRLF(node, nextNode); - } - } - } - fixCRLF(prev, next) { - let nodesToDel = []; - // update node - let lineStarts = this._buffers[prev.piece.bufferIndex].lineStarts; - let 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 }; - } - const prevNewLength = prev.piece.length - 1; - const prevNewLFCnt = prev.piece.lineFeedCnt - 1; - prev.piece = new Piece(prev.piece.bufferIndex, prev.piece.start, newEnd, prevNewLFCnt, prevNewLength); - (0, rbTreeBase_1.updateTreeMetadata)(this, prev, -1, -1); - if (prev.piece.length === 0) { - nodesToDel.push(prev); - } - // update nextNode - let newStart = { line: next.piece.start.line + 1, column: 0 }; - const newLength = next.piece.length - 1; - const newLineFeedCnt = this.getLineFeedCnt(next.piece.bufferIndex, newStart, next.piece.end); - next.piece = new Piece(next.piece.bufferIndex, newStart, next.piece.end, newLineFeedCnt, newLength); - (0, rbTreeBase_1.updateTreeMetadata)(this, next, -1, -1); - if (next.piece.length === 0) { - nodesToDel.push(next); - } - // create new piece which contains \r\n - let pieces = this.createNewPieces('\r\n'); - this.rbInsertRight(prev, pieces[0]); - // delete empty nodes - for (let i = 0; i < nodesToDel.length; i++) { - (0, rbTreeBase_1.rbDelete)(this, nodesToDel[i]); - } - } - adjustCarriageReturnFromNext(value, node) { - if (this.shouldCheckCRLF() && this.endWithCR(value)) { - let nextNode = node.next(); - if (this.startWithLF(nextNode)) { - // move `\n` forward - value += '\n'; - if (nextNode.piece.length === 1) { - (0, rbTreeBase_1.rbDelete)(this, nextNode); - } - else { - const piece = nextNode.piece; - const newStart = { line: piece.start.line + 1, column: 0 }; - const newLength = piece.length - 1; - const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end); - nextNode.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength); - (0, rbTreeBase_1.updateTreeMetadata)(this, nextNode, -1, -1); - } - return true; - } - } - return false; - } - // #endregion - // #endregion - // #region Tree operations - iterate(node, callback) { - if (node === rbTreeBase_1.SENTINEL) { - return callback(rbTreeBase_1.SENTINEL); - } - let leftRet = this.iterate(node.left, callback); - if (!leftRet) { - return leftRet; - } - return callback(node) && this.iterate(node.right, callback); - } - getNodeContent(node) { - if (node === rbTreeBase_1.SENTINEL) { - return ''; - } - let buffer = this._buffers[node.piece.bufferIndex]; - let currentContent; - let piece = node.piece; - let startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start); - let endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end); - currentContent = buffer.buffer.substring(startOffset, endOffset); - return currentContent; - } - getPieceContent(piece) { - let buffer = this._buffers[piece.bufferIndex]; - let startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start); - let endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end); - let currentContent = buffer.buffer.substring(startOffset, endOffset); - return currentContent; - } - /** - * node node - * / \ / \ - * a b <---- a b - * / - * z - */ - rbInsertRight(node, p) { - let 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; - let 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 { - let nextNode = (0, rbTreeBase_1.leftest)(node.right); - nextNode.left = z; - z.parent = nextNode; - } - (0, rbTreeBase_1.fixInsert)(this, z); - return z; - } - /** - * node node - * / \ / \ - * a b ----> a b - * \ - * z - */ - rbInsertLeft(node, p) { - let 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 { - let prevNode = (0, rbTreeBase_1.righttest)(node.left); // a - prevNode.right = z; - z.parent = prevNode; - } - (0, rbTreeBase_1.fixInsert)(this, z); - return z; - } - } - 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[135/*vs/editor/common/model/wordHelper*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getWordAtText = exports.ensureValidWordDefinition = exports.DEFAULT_WORD_REGEXP = exports.USUAL_WORD_SEPARATORS = void 0; - 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 = '') { - let source = '(-?\\d*\\.\\d\\w*)|([^'; - for (const sep of exports.USUAL_WORD_SEPARATORS) { - 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) { - let result = exports.DEFAULT_WORD_REGEXP; - if (wordDefinition && (wordDefinition instanceof RegExp)) { - if (!wordDefinition.global) { - let 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; - const _defaultConfig = { - maxLen: 1000, - windowSize: 15, - timeBudget: 150 - }; - function getWordAtText(column, wordDefinition, text, textOffset, config = _defaultConfig) { - if (text.length > config.maxLen) { - // don't throw strings that long at the regexp - // but use a sub-string in which a word must occur - let start = column - config.maxLen / 2; - if (start < 0) { - start = 0; - } - else { - textOffset += start; - } - text = text.substring(start, column + config.maxLen / 2); - return getWordAtText(column, wordDefinition, text, textOffset, config); - } - const t1 = Date.now(); - const pos = column - 1 - textOffset; - let prevRegexIndex = -1; - let match = null; - for (let i = 1;; i++) { - // check time budget - if (Date.now() - t1 >= config.timeBudget) { - break; - } - // reset the index at which the regexp should start matching, also know where it - // should stop so that subsequent search don't repeat previous searches - const regexIndex = pos - config.windowSize * i; - wordDefinition.lastIndex = Math.max(0, regexIndex); - const thisMatch = _findRegexMatchEnclosingPosition(wordDefinition, text, pos, prevRegexIndex); - if (!thisMatch && match) { - // stop: we have something - break; - } - match = thisMatch; - // stop: searched at start - if (regexIndex <= 0) { - break; - } - prevRegexIndex = regexIndex; - } - if (match) { - let result = { - word: match[0], - startColumn: textOffset + 1 + match.index, - endColumn: textOffset + 1 + match.index + match[0].length - }; - wordDefinition.lastIndex = 0; - return result; - } - return null; - } - exports.getWordAtText = getWordAtText; - function _findRegexMatchEnclosingPosition(wordDefinition, text, pos, stopPos) { - let match; - while (match = wordDefinition.exec(text)) { - const matchIndex = match.index || 0; - if (matchIndex <= pos && wordDefinition.lastIndex >= pos) { - return match; - } - else if (stopPos > 0 && matchIndex > stopPos) { - return null; - } - } - 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[381/*vs/editor/common/modes/abstractMode*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.FrankensteinMode = void 0; - class FrankensteinMode { - constructor(languageIdentifier) { - this._languageIdentifier = languageIdentifier; - } - getId() { - return this._languageIdentifier.language; - } - } - 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[112/*vs/editor/common/modes/languageConfiguration*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.AutoClosingPairs = exports.StandardAutoClosingPairConditional = exports.IndentAction = void 0; - /** - * 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 - */ - class StandardAutoClosingPairConditional { - constructor(source) { - this._standardAutoClosingPairConditionalBrand = undefined; - this.open = source.open; - this.close = source.close; - // initially allowed in all tokens - this._standardTokenMask = 0; - if (Array.isArray(source.notIn)) { - for (let i = 0, len = source.notIn.length; i < len; i++) { - const 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; - } - } - } - } - isOK(standardToken) { - return (this._standardTokenMask & standardToken) === 0; - } - } - exports.StandardAutoClosingPairConditional = StandardAutoClosingPairConditional; - /** - * @internal - */ - class AutoClosingPairs { - constructor(autoClosingPairs) { - this.autoClosingPairsOpenByStart = new Map(); - this.autoClosingPairsOpenByEnd = new Map(); - this.autoClosingPairsCloseByStart = new Map(); - this.autoClosingPairsCloseByEnd = new Map(); - this.autoClosingPairsCloseSingleChar = new Map(); - for (const pair of autoClosingPairs) { - appendEntry(this.autoClosingPairsOpenByStart, pair.open.charAt(0), pair); - appendEntry(this.autoClosingPairsOpenByEnd, pair.open.charAt(pair.open.length - 1), pair); - appendEntry(this.autoClosingPairsCloseByStart, pair.close.charAt(0), pair); - appendEntry(this.autoClosingPairsCloseByEnd, pair.close.charAt(pair.close.length - 1), pair); - if (pair.close.length === 1 && pair.open.length === 1) { - appendEntry(this.autoClosingPairsCloseSingleChar, pair.close, pair); - } - } - } - } - exports.AutoClosingPairs = AutoClosingPairs; - function appendEntry(target, key, value) { - if (target.has(key)) { - target.get(key).push(value); - } - else { - target.set(key, [value]); - } - } -}); - -/*--------------------------------------------------------------------------------------------- - * 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/common/modes/languageSelector*/], __M([0/*require*/,1/*exports*/,201/*vs/base/common/glob*/,73/*vs/base/common/path*/]), function (require, exports, glob_1, path_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.score = void 0; - function score(selector, candidateUri, candidateLanguage, candidateIsSynchronized) { - if (Array.isArray(selector)) { - // array -> take max individual value - let ret = 0; - for (const filter of selector) { - const 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 - const { language, pattern, scheme, hasAccessToAllModels } = selector; // TODO: microsoft/TypeScript#42768 - if (!candidateIsSynchronized && !hasAccessToAllModels) { - return 0; - } - let 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) { - let normalizedPattern; - if (typeof pattern === 'string') { - normalizedPattern = pattern; - } - else { - // Since this pattern has a `base` property, we need - // to normalize this path first before passing it on - // because we will compare it against `Uri.fsPath` - // which uses platform specific separators. - // Refs: https://github.com/microsoft/vscode/issues/99938 - normalizedPattern = Object.assign(Object.assign({}, pattern), { base: (0, path_1.normalize)(pattern.base) }); - } - if (normalizedPattern === candidateUri.fsPath || (0, glob_1.match)(normalizedPattern, 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[383/*vs/editor/common/modes/linkComputer*/], __M([0/*require*/,1/*exports*/,94/*vs/editor/common/core/characterClassifier*/]), function (require, exports, characterClassifier_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.computeLinks = exports.LinkComputer = exports.StateMachine = exports.Uint8Matrix = void 0; - class Uint8Matrix { - constructor(rows, cols, defaultValue) { - const data = new Uint8Array(rows * cols); - for (let i = 0, len = rows * cols; i < len; i++) { - data[i] = defaultValue; - } - this._data = data; - this.rows = rows; - this.cols = cols; - } - get(row, col) { - return this._data[row * this.cols + col]; - } - set(row, col, value) { - this._data[row * this.cols + col] = value; - } - } - exports.Uint8Matrix = Uint8Matrix; - class StateMachine { - constructor(edges) { - let maxCharCode = 0; - let maxState = 0 /* Invalid */; - for (let i = 0, len = edges.length; i < len; i++) { - let [from, chCode, to] = edges[i]; - if (chCode > maxCharCode) { - maxCharCode = chCode; - } - if (from > maxState) { - maxState = from; - } - if (to > maxState) { - maxState = to; - } - } - maxCharCode++; - maxState++; - let states = new Uint8Matrix(maxState, maxCharCode, 0 /* Invalid */); - for (let i = 0, len = edges.length; i < len; i++) { - let [from, chCode, to] = edges[i]; - states.set(from, chCode, to); - } - this._states = states; - this._maxCharCode = maxCharCode; - } - nextState(currentState, chCode) { - if (chCode < 0 || chCode >= this._maxCharCode) { - return 0 /* Invalid */; - } - return this._states.get(currentState, chCode); - } - } - exports.StateMachine = StateMachine; - // State machine for http:// or https:// or file:// - let _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; - } - let _classifier = null; - function getClassifier() { - if (_classifier === null) { - _classifier = new characterClassifier_1.CharacterClassifier(0 /* None */); - const FORCE_TERMINATION_CHARACTERS = ' \t<>\'\"、。。、,.:;‘〈「『〔([{「」}])〕』」〉’`~…'; - for (let i = 0; i < FORCE_TERMINATION_CHARACTERS.length; i++) { - _classifier.set(FORCE_TERMINATION_CHARACTERS.charCodeAt(i), 1 /* ForceTermination */); - } - const CANNOT_END_WITH_CHARACTERS = '.,;'; - for (let i = 0; i < CANNOT_END_WITH_CHARACTERS.length; i++) { - _classifier.set(CANNOT_END_WITH_CHARACTERS.charCodeAt(i), 2 /* CannotEndIn */); - } - } - return _classifier; - } - class LinkComputer { - static _createLink(classifier, line, lineNumber, linkBeginIndex, linkEndIndex) { - // Do not allow to end link in certain characters... - let lastIncludedCharIndex = linkEndIndex - 1; - do { - const chCode = line.charCodeAt(lastIncludedCharIndex); - const 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) { - const charCodeBeforeLink = line.charCodeAt(linkBeginIndex - 1); - const 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) - }; - } - static computeLinks(model, stateMachine = getStateMachine()) { - const classifier = getClassifier(); - let result = []; - for (let i = 1, lineCount = model.getLineCount(); i <= lineCount; i++) { - const line = model.getLineContent(i); - const len = line.length; - let j = 0; - let linkBeginIndex = 0; - let linkBeginChCode = 0; - let state = 1 /* Start */; - let hasOpenParens = false; - let hasOpenSquareBracket = false; - let inSquareBrackets = false; - let hasOpenCurlyBracket = false; - while (j < len) { - let resetStateMachine = false; - const chCode = line.charCodeAt(j); - if (state === 13 /* Accept */) { - let chClass; - switch (chCode) { - case 40 /* OpenParen */: - hasOpenParens = true; - chClass = 0 /* None */; - break; - case 41 /* CloseParen */: - chClass = (hasOpenParens ? 0 /* None */ : 1 /* ForceTermination */); - break; - case 91 /* OpenSquareBracket */: - inSquareBrackets = true; - hasOpenSquareBracket = true; - chClass = 0 /* None */; - break; - case 93 /* CloseSquareBracket */: - inSquareBrackets = false; - 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; - case 32 /* Space */: - // ` ` allow space in between [ and ] - chClass = (inSquareBrackets ? 0 /* None */ : 1 /* ForceTermination */); - 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 */) { - let chClass; - 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; - } - } - 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[172/*vs/editor/common/modes/supports*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ignoreBracketsInToken = exports.ScopedLineTokens = exports.createScopedLineTokens = void 0; - function createScopedLineTokens(context, offset) { - let tokenCount = context.getCount(); - let tokenIndex = context.findTokenIndexAtOffset(offset); - let desiredLanguageId = context.getLanguageId(tokenIndex); - let lastTokenIndex = tokenIndex; - while (lastTokenIndex + 1 < tokenCount && context.getLanguageId(lastTokenIndex + 1) === desiredLanguageId) { - lastTokenIndex++; - } - let 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; - class ScopedLineTokens { - constructor(actual, languageId, firstTokenIndex, lastTokenIndex, firstCharOffset, lastCharOffset) { - this._scopedLineTokensBrand = undefined; - this._actual = actual; - this.languageId = languageId; - this._firstTokenIndex = firstTokenIndex; - this._lastTokenIndex = lastTokenIndex; - this.firstCharOffset = firstCharOffset; - this._lastCharOffset = lastCharOffset; - } - getLineContent() { - const actualLineContent = this._actual.getLineContent(); - return actualLineContent.substring(this.firstCharOffset, this._lastCharOffset); - } - getActualLineContentBefore(offset) { - const actualLineContent = this._actual.getLineContent(); - return actualLineContent.substring(0, this.firstCharOffset + offset); - } - getTokenCount() { - return this._lastTokenIndex - this._firstTokenIndex; - } - findTokenIndexAtOffset(offset) { - return this._actual.findTokenIndexAtOffset(offset + this.firstCharOffset) - this._firstTokenIndex; - } - getStandardTokenType(tokenIndex) { - return this._actual.getStandardTokenType(tokenIndex + this._firstTokenIndex); - } - } - 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[384/*vs/editor/common/modes/supports/characterPair*/], __M([0/*require*/,1/*exports*/,112/*vs/editor/common/modes/languageConfiguration*/]), function (require, exports, languageConfiguration_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CharacterPairSupport = void 0; - class CharacterPairSupport { - constructor(config) { - if (config.autoClosingPairs) { - this._autoClosingPairs = config.autoClosingPairs.map(el => new languageConfiguration_1.StandardAutoClosingPairConditional(el)); - } - else if (config.brackets) { - this._autoClosingPairs = config.brackets.map(b => new languageConfiguration_1.StandardAutoClosingPairConditional({ open: b[0], close: b[1] })); - } - else { - this._autoClosingPairs = []; - } - if (config.__electricCharacterSupport && config.__electricCharacterSupport.docComment) { - const 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; - } - getAutoClosingPairs() { - return this._autoClosingPairs; - } - getAutoCloseBeforeSet() { - return this._autoCloseBefore; - } - static shouldAutoClosePair(autoClosingPair, context, column) { - // Always complete on empty line - if (context.getTokenCount() === 0) { - return true; - } - const tokenIndex = context.findTokenIndexAtOffset(column - 2); - const standardTokenType = context.getStandardTokenType(tokenIndex); - return autoClosingPair.isOK(standardTokenType); - } - getSurroundingPairs() { - return this._surroundingPairs; - } - } - exports.CharacterPairSupport = CharacterPairSupport; - CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED = ';:.,=}])> \n\t'; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/common/modes/supports/indentRules*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.IndentRulesSupport = void 0; - function resetGlobalRegex(reg) { - if (reg.global) { - reg.lastIndex = 0; - } - return true; - } - class IndentRulesSupport { - constructor(indentationRules) { - this._indentationRules = indentationRules; - } - shouldIncrease(text) { - if (this._indentationRules) { - if (this._indentationRules.increaseIndentPattern && resetGlobalRegex(this._indentationRules.increaseIndentPattern) && this._indentationRules.increaseIndentPattern.test(text)) { - return true; - } - // if (this._indentationRules.indentNextLinePattern && this._indentationRules.indentNextLinePattern.test(text)) { - // return true; - // } - } - return false; - } - shouldDecrease(text) { - if (this._indentationRules && this._indentationRules.decreaseIndentPattern && resetGlobalRegex(this._indentationRules.decreaseIndentPattern) && this._indentationRules.decreaseIndentPattern.test(text)) { - return true; - } - return false; - } - shouldIndentNextLine(text) { - if (this._indentationRules && this._indentationRules.indentNextLinePattern && resetGlobalRegex(this._indentationRules.indentNextLinePattern) && this._indentationRules.indentNextLinePattern.test(text)) { - return true; - } - return false; - } - shouldIgnore(text) { - // the text matches `unIndentedLinePattern` - if (this._indentationRules && this._indentationRules.unIndentedLinePattern && resetGlobalRegex(this._indentationRules.unIndentedLinePattern) && this._indentationRules.unIndentedLinePattern.test(text)) { - return true; - } - return false; - } - getIndentMetadata(text) { - let 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; - } - } - 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[386/*vs/editor/common/modes/supports/inplaceReplaceSupport*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.BasicInplaceReplace = void 0; - class BasicInplaceReplace { - constructor() { - this._defaultValueSet = [ - ['true', 'false'], - ['True', 'False'], - ['Private', 'Public', 'Friend', 'ReadOnly', 'Partial', 'Protected', 'WriteOnly'], - ['public', 'protected', 'private'], - ]; - } - navigateValueSet(range1, text1, range2, text2, up) { - if (range1 && text1) { - let result = this.doNavigateValueSet(text1, up); - if (result) { - return { - range: range1, - value: result - }; - } - } - if (range2 && text2) { - let result = this.doNavigateValueSet(text2, up); - if (result) { - return { - range: range2, - value: result - }; - } - } - return null; - } - doNavigateValueSet(text, up) { - let numberResult = this.numberReplace(text, up); - if (numberResult !== null) { - return numberResult; - } - return this.textReplace(text, up); - } - numberReplace(value, up) { - let precision = Math.pow(10, value.length - (value.lastIndexOf('.') + 1)); - let n1 = Number(value); - let 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; - } - textReplace(value, up) { - return this.valueSetsReplace(this._defaultValueSet, value, up); - } - valueSetsReplace(valueSets, value, up) { - let result = null; - for (let i = 0, len = valueSets.length; result === null && i < len; i++) { - result = this.valueSetReplace(valueSets[i], value, up); - } - return result; - } - valueSetReplace(valueSet, value, up) { - let 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; - } - } - exports.BasicInplaceReplace = BasicInplaceReplace; - BasicInplaceReplace.INSTANCE = new 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[387/*vs/editor/common/modes/supports/onEnter*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,8/*vs/base/common/strings*/,112/*vs/editor/common/modes/languageConfiguration*/]), function (require, exports, errors_1, strings, languageConfiguration_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.OnEnterSupport = void 0; - class OnEnterSupport { - constructor(opts) { - opts = opts || {}; - opts.brackets = opts.brackets || [ - ['(', ')'], - ['{', '}'], - ['[', ']'] - ]; - this._brackets = []; - opts.brackets.forEach((bracket) => { - const openRegExp = OnEnterSupport._createOpenBracketRegExp(bracket[0]); - const 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 || []; - } - onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText) { - // (1): `regExpRules` - if (autoIndent >= 3 /* Advanced */) { - for (let i = 0, len = this._regExpRules.length; i < len; i++) { - let rule = this._regExpRules[i]; - const regResult = [{ - reg: rule.beforeText, - text: beforeEnterText - }, { - reg: rule.afterText, - text: afterEnterText - }, { - reg: rule.previousLineText, - text: previousLineText - }].every((obj) => { - if (!obj.reg) { - return true; - } - obj.reg.lastIndex = 0; // To disable the effect of the "g" flag. - return obj.reg.test(obj.text); - }); - if (regResult) { - return rule.action; - } - } - } - // (2): Special indent-outdent - if (autoIndent >= 2 /* Brackets */) { - if (beforeEnterText.length > 0 && afterEnterText.length > 0) { - for (let i = 0, len = this._brackets.length; i < len; i++) { - let 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 (let i = 0, len = this._brackets.length; i < len; i++) { - let bracket = this._brackets[i]; - if (bracket.openRegExp.test(beforeEnterText)) { - return { indentAction: languageConfiguration_1.IndentAction.Indent }; - } - } - } - } - return null; - } - static _createOpenBracketRegExp(bracket) { - let str = strings.escapeRegExpCharacters(bracket); - if (!/\B/.test(str.charAt(0))) { - str = '\\b' + str; - } - str += '\\s*$'; - return OnEnterSupport._safeRegExp(str); - } - static _createCloseBracketRegExp(bracket) { - let str = strings.escapeRegExpCharacters(bracket); - if (!/\B/.test(str.charAt(str.length - 1))) { - str = str + '\\b'; - } - str = '^\\s*' + str; - return OnEnterSupport._safeRegExp(str); - } - static _safeRegExp(def) { - try { - return new RegExp(def); - } - catch (err) { - (0, errors_1.onUnexpectedError)(err); - return null; - } - } - } - 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[173/*vs/editor/common/modes/supports/richEditBrackets*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,83/*vs/editor/common/core/stringBuilder*/,3/*vs/editor/common/core/range*/]), function (require, exports, strings, stringBuilder, range_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.BracketsUtils = exports.RichEditBrackets = exports.RichEditBracket = void 0; - class RichEditBracket { - constructor(languageIdentifier, index, open, close, forwardRegex, reversedRegex) { - this._richEditBracketBrand = undefined; - 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); - } - isOpen(text) { - return this._openSet.has(text); - } - isClose(text) { - return this._closeSet.has(text); - } - static _toSet(arr) { - const result = new Set(); - for (const element of arr) { - result.add(element); - } - return result; - } - } - exports.RichEditBracket = RichEditBracket; - function groupFuzzyBrackets(brackets) { - const N = brackets.length; - brackets = brackets.map(b => [b[0].toLowerCase(), b[1].toLowerCase()]); - const group = []; - for (let i = 0; i < N; i++) { - group[i] = i; - } - const areOverlapping = (a, b) => { - const [aOpen, aClose] = a; - const [bOpen, bClose] = b; - return (aOpen === bOpen || aOpen === bClose || aClose === bOpen || aClose === bClose); - }; - const mergeGroups = (g1, g2) => { - const newG = Math.min(g1, g2); - const oldG = Math.max(g1, g2); - for (let 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 (let i = 0; i < N; i++) { - const a = brackets[i]; - for (let j = i + 1; j < N; j++) { - const b = brackets[j]; - if (areOverlapping(a, b)) { - mergeGroups(group[i], group[j]); - } - } - } - const result = []; - for (let g = 0; g < N; g++) { - let currentOpen = []; - let currentClose = []; - for (let i = 0; i < N; i++) { - if (group[i] === g) { - const [open, close] = brackets[i]; - currentOpen.push(open); - currentClose.push(close); - } - } - if (currentOpen.length > 0) { - result.push({ - open: currentOpen, - close: currentClose - }); - } - } - return result; - } - class RichEditBrackets { - constructor(languageIdentifier, _brackets) { - this._richEditBracketsBrand = undefined; - const brackets = groupFuzzyBrackets(_brackets); - this.brackets = brackets.map((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 (const bracket of this.brackets) { - for (const open of bracket.open) { - this.textIsBracket[open] = bracket; - this.textIsOpenBracket[open] = true; - this.maxBracketLength = Math.max(this.maxBracketLength, open.length); - } - for (const close of bracket.close) { - this.textIsBracket[close] = bracket; - this.textIsOpenBracket[close] = false; - this.maxBracketLength = Math.max(this.maxBracketLength, close.length); - } - } - } - } - exports.RichEditBrackets = RichEditBrackets; - function collectSuperstrings(str, brackets, currentIndex, dest) { - for (let i = 0, len = brackets.length; i < len; i++) { - if (i === currentIndex) { - continue; - } - const bracket = brackets[i]; - for (const open of bracket.open) { - if (open.indexOf(str) >= 0) { - dest.push(open); - } - } - for (const close of bracket.close) { - if (close.indexOf(str) >= 0) { - dest.push(close); - } - } - } - } - function lengthcmp(a, b) { - return a.length - b.length; - } - function unique(arr) { - if (arr.length <= 1) { - return arr; - } - const result = []; - const seen = new Set(); - for (const element of arr) { - 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 - let pieces = []; - pieces = pieces.concat(open); - pieces = pieces.concat(close); - for (let 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 - let pieces = []; - pieces = pieces.concat(open); - pieces = pieces.concat(close); - for (let 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) { - let pieces = []; - for (const bracket of brackets) { - for (const open of bracket.open) { - pieces.push(open); - } - for (const close of bracket.close) { - pieces.push(close); - } - } - pieces = unique(pieces); - return createBracketOrRegExp(pieces); - } - function getReversedRegexForBrackets(brackets) { - let pieces = []; - for (const bracket of brackets) { - for (const open of bracket.open) { - pieces.push(open); - } - for (const close of bracket.close) { - pieces.push(close); - } - } - pieces = unique(pieces); - return createBracketOrRegExp(pieces.map(toReversedString)); - } - function prepareBracketForRegExp(str) { - // This bracket pair uses letters like e.g. "begin" - "end" - const insertWordBoundaries = (/^[\w ]+$/.test(str)); - str = strings.escapeRegExpCharacters(str); - return (insertWordBoundaries ? `\\b${str}\\b` : str); - } - function createBracketOrRegExp(pieces) { - let regexStr = `(${pieces.map(prepareBracketForRegExp).join(')|(')})`; - return strings.createRegExp(regexStr, true); - } - const toReversedString = (function () { - function reverse(str) { - if (stringBuilder.hasTextDecoder) { - // create a Uint16Array and then use a TextDecoder to create a string - const arr = new Uint16Array(str.length); - let offset = 0; - for (let i = str.length - 1; i >= 0; i--) { - arr[offset++] = str.charCodeAt(i); - } - return stringBuilder.getPlatformTextDecoder().decode(arr); - } - else { - let result = [], resultLen = 0; - for (let i = str.length - 1; i >= 0; i--) { - result[resultLen++] = str.charAt(i); - } - return result.join(''); - } - } - let lastInput = null; - let lastOutput = null; - return function toReversedString(str) { - if (lastInput !== str) { - lastInput = str; - lastOutput = reverse(lastInput); - } - return lastOutput; - }; - })(); - class BracketsUtils { - static _findPrevBracketInText(reversedBracketRegex, lineNumber, reversedText, offset) { - let m = reversedText.match(reversedBracketRegex); - if (!m) { - return null; - } - let matchOffset = reversedText.length - (m.index || 0); - let matchLength = m[0].length; - let absoluteMatchOffset = offset + matchOffset; - return new range_1.Range(lineNumber, absoluteMatchOffset - matchLength + 1, lineNumber, absoluteMatchOffset + 1); - } - static findPrevBracketInRange(reversedBracketRegex, lineNumber, lineText, startOffset, endOffset) { - // Because JS does not support backwards regex search, we search forwards in a reversed string with a reversed regex ;) - const reversedLineText = toReversedString(lineText); - const reversedSubstr = reversedLineText.substring(lineText.length - endOffset, lineText.length - startOffset); - return this._findPrevBracketInText(reversedBracketRegex, lineNumber, reversedSubstr, startOffset); - } - static findNextBracketInText(bracketRegex, lineNumber, text, offset) { - let m = text.match(bracketRegex); - if (!m) { - return null; - } - let matchOffset = m.index || 0; - let matchLength = m[0].length; - if (matchLength === 0) { - return null; - } - let absoluteMatchOffset = offset + matchOffset; - return new range_1.Range(lineNumber, absoluteMatchOffset + 1, lineNumber, absoluteMatchOffset + 1 + matchLength); - } - static findNextBracketInRange(bracketRegex, lineNumber, lineText, startOffset, endOffset) { - const substr = lineText.substring(startOffset, endOffset); - return this.findNextBracketInText(bracketRegex, lineNumber, substr, startOffset); - } - } - 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[388/*vs/editor/common/modes/supports/electricCharacter*/], __M([0/*require*/,1/*exports*/,172/*vs/editor/common/modes/supports*/,173/*vs/editor/common/modes/supports/richEditBrackets*/]), function (require, exports, supports_1, richEditBrackets_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.BracketElectricCharacterSupport = void 0; - class BracketElectricCharacterSupport { - constructor(richEditBrackets) { - this._richEditBrackets = richEditBrackets; - } - getElectricCharacters() { - let result = []; - if (this._richEditBrackets) { - for (const bracket of this._richEditBrackets.brackets) { - for (const close of bracket.close) { - const lastChar = close.charAt(close.length - 1); - result.push(lastChar); - } - } - } - // Filter duplicate entries - result = result.filter((item, pos, array) => { - return array.indexOf(item) === pos; - }); - return result; - } - onElectricCharacter(character, context, column) { - if (!this._richEditBrackets || this._richEditBrackets.brackets.length === 0) { - return null; - } - const tokenIndex = context.findTokenIndexAtOffset(column - 1); - if ((0, supports_1.ignoreBracketsInToken)(context.getStandardTokenType(tokenIndex))) { - return null; - } - const reversedBracketRegex = this._richEditBrackets.reversedRegex; - const text = context.getLineContent().substring(0, column - 1) + character; - const r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(reversedBracketRegex, 1, text, 0, text.length); - if (!r) { - return null; - } - const bracketText = text.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase(); - const isOpen = this._richEditBrackets.textIsOpenBracket[bracketText]; - if (isOpen) { - return null; - } - const 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 - }; - } - } - 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[45/*vs/editor/common/modes/languageConfigurationRegistry*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,8/*vs/base/common/strings*/,135/*vs/editor/common/model/wordHelper*/,112/*vs/editor/common/modes/languageConfiguration*/,172/*vs/editor/common/modes/supports*/,384/*vs/editor/common/modes/supports/characterPair*/,388/*vs/editor/common/modes/supports/electricCharacter*/,385/*vs/editor/common/modes/supports/indentRules*/,387/*vs/editor/common/modes/supports/onEnter*/,173/*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 }); - exports.LanguageConfigurationRegistry = exports.LanguageConfigurationRegistryImpl = exports.LanguageConfigurationChangeEvent = exports.RichEditSupport = void 0; - class RichEditSupport { - constructor(languageIdentifier, rawConf) { - this._languageIdentifier = languageIdentifier; - this._brackets = null; - this._electricCharacter = null; - this._conf = 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 || {}; - } - get brackets() { - if (!this._brackets && this._conf.brackets) { - this._brackets = new richEditBrackets_1.RichEditBrackets(this._languageIdentifier, this._conf.brackets); - } - return this._brackets; - } - get electricCharacter() { - if (!this._electricCharacter) { - this._electricCharacter = new electricCharacter_1.BracketElectricCharacterSupport(this.brackets); - } - return this._electricCharacter; - } - onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText) { - if (!this._onEnterSupport) { - return null; - } - return this._onEnterSupport.onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText); - } - static _handleComments(conf) { - let commentRule = conf.comments; - if (!commentRule) { - return null; - } - // comment configuration - let comments = {}; - if (commentRule.lineComment) { - comments.lineCommentToken = commentRule.lineComment; - } - if (commentRule.blockComment) { - let [blockStart, blockEnd] = commentRule.blockComment; - comments.blockCommentStartToken = blockStart; - comments.blockCommentEndToken = blockEnd; - } - return comments; - } - } - exports.RichEditSupport = RichEditSupport; - class LanguageConfigurationChangeEvent { - constructor(languageIdentifier) { - this.languageIdentifier = languageIdentifier; - } - } - exports.LanguageConfigurationChangeEvent = LanguageConfigurationChangeEvent; - class LanguageConfigurationEntry { - constructor(configuration, priority, order) { - this.configuration = configuration; - this.priority = priority; - this.order = order; - } - static cmp(a, b) { - if (a.priority === b.priority) { - // higher order last - return a.order - b.order; - } - // higher priority last - return a.priority - b.priority; - } - } - class LanguageConfigurationEntries { - constructor(languageIdentifier) { - this.languageIdentifier = languageIdentifier; - this._resolved = null; - this._entries = []; - this._order = 0; - this._resolved = null; - } - register(configuration, priority) { - const entry = new LanguageConfigurationEntry(configuration, priority, ++this._order); - this._entries.push(entry); - this._resolved = null; - return (0, lifecycle_1.toDisposable)(() => { - for (let i = 0; i < this._entries.length; i++) { - if (this._entries[i] === entry) { - this._entries.splice(i, 1); - this._resolved = null; - break; - } - } - }); - } - getRichEditSupport() { - if (!this._resolved) { - const config = this._resolve(); - if (config) { - this._resolved = new RichEditSupport(this.languageIdentifier, config); - } - } - return this._resolved; - } - _resolve() { - if (this._entries.length === 0) { - return null; - } - this._entries.sort(LanguageConfigurationEntry.cmp); - const result = {}; - for (const entry of this._entries) { - const conf = entry.configuration; - result.comments = conf.comments || result.comments; - result.brackets = conf.brackets || result.brackets; - result.wordPattern = conf.wordPattern || result.wordPattern; - result.indentationRules = conf.indentationRules || result.indentationRules; - result.onEnterRules = conf.onEnterRules || result.onEnterRules; - result.autoClosingPairs = conf.autoClosingPairs || result.autoClosingPairs; - result.surroundingPairs = conf.surroundingPairs || result.surroundingPairs; - result.autoCloseBefore = conf.autoCloseBefore || result.autoCloseBefore; - result.folding = conf.folding || result.folding; - result.__electricCharacterSupport = conf.__electricCharacterSupport || result.__electricCharacterSupport; - } - return result; - } - } - class LanguageConfigurationRegistryImpl { - constructor() { - this._entries2 = new Map(); - this._onDidChange = new event_1.Emitter(); - this.onDidChange = this._onDidChange.event; - } - /** - * @param priority Use a higher number for higher priority - */ - register(languageIdentifier, configuration, priority = 0) { - let entries = this._entries2.get(languageIdentifier.id); - if (!entries) { - entries = new LanguageConfigurationEntries(languageIdentifier); - this._entries2.set(languageIdentifier.id, entries); - } - const disposable = entries.register(configuration, priority); - this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageIdentifier)); - return (0, lifecycle_1.toDisposable)(() => { - disposable.dispose(); - this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageIdentifier)); - }); - } - _getRichEditSupport(languageId) { - const entries = this._entries2.get(languageId); - return entries ? entries.getRichEditSupport() : null; - } - getIndentationRules(languageId) { - const value = this._getRichEditSupport(languageId); - return value ? value.indentationRules || null : null; - } - // begin electricCharacter - _getElectricCharacterSupport(languageId) { - let value = this._getRichEditSupport(languageId); - if (!value) { - return null; - } - return value.electricCharacter || null; - } - getElectricCharacters(languageId) { - let electricCharacterSupport = this._getElectricCharacterSupport(languageId); - if (!electricCharacterSupport) { - return []; - } - return electricCharacterSupport.getElectricCharacters(); - } - /** - * Should return opening bracket type to match indentation with - */ - onElectricCharacter(character, context, column) { - let scopedLineTokens = (0, supports_1.createScopedLineTokens)(context, column - 1); - let electricCharacterSupport = this._getElectricCharacterSupport(scopedLineTokens.languageId); - if (!electricCharacterSupport) { - return null; - } - return electricCharacterSupport.onElectricCharacter(character, scopedLineTokens, column - scopedLineTokens.firstCharOffset); - } - // end electricCharacter - getComments(languageId) { - let value = this._getRichEditSupport(languageId); - if (!value) { - return null; - } - return value.comments || null; - } - // begin characterPair - _getCharacterPairSupport(languageId) { - let value = this._getRichEditSupport(languageId); - if (!value) { - return null; - } - return value.characterPair || null; - } - getAutoClosingPairs(languageId) { - const characterPairSupport = this._getCharacterPairSupport(languageId); - return new languageConfiguration_1.AutoClosingPairs(characterPairSupport ? characterPairSupport.getAutoClosingPairs() : []); - } - getAutoCloseBeforeSet(languageId) { - let characterPairSupport = this._getCharacterPairSupport(languageId); - if (!characterPairSupport) { - return characterPair_1.CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED; - } - return characterPairSupport.getAutoCloseBeforeSet(); - } - getSurroundingPairs(languageId) { - let characterPairSupport = this._getCharacterPairSupport(languageId); - if (!characterPairSupport) { - return []; - } - return characterPairSupport.getSurroundingPairs(); - } - shouldAutoClosePair(autoClosingPair, context, column) { - const scopedLineTokens = (0, supports_1.createScopedLineTokens)(context, column - 1); - return characterPair_1.CharacterPairSupport.shouldAutoClosePair(autoClosingPair, scopedLineTokens, column - scopedLineTokens.firstCharOffset); - } - // end characterPair - getWordDefinition(languageId) { - let value = this._getRichEditSupport(languageId); - if (!value) { - return (0, wordHelper_1.ensureValidWordDefinition)(null); - } - return (0, wordHelper_1.ensureValidWordDefinition)(value.wordDefinition || null); - } - getFoldingRules(languageId) { - let value = this._getRichEditSupport(languageId); - if (!value) { - return {}; - } - return value.foldingRules; - } - // begin Indent Rules - getIndentRulesSupport(languageId) { - let 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 - */ - getPrecedingValidLine(model, lineNumber, indentRulesSupport) { - let languageID = model.getLanguageIdAtPosition(lineNumber, 0); - if (lineNumber > 1) { - let lastLineNumber; - let resultLineNumber = -1; - for (lastLineNumber = lineNumber - 1; lastLineNumber >= 1; lastLineNumber--) { - if (model.getLanguageIdAtPosition(lastLineNumber, 0) !== languageID) { - return resultLineNumber; - } - let 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. - */ - getInheritIndentForLine(autoIndent, model, lineNumber, honorIntentialIndent = true) { - if (autoIndent < 4 /* Full */) { - return null; - } - const indentRulesSupport = this.getIndentRulesSupport(model.getLanguageIdentifier().id); - if (!indentRulesSupport) { - return null; - } - if (lineNumber <= 1) { - return { - indentation: '', - action: null - }; - } - const precedingUnIgnoredLine = this.getPrecedingValidLine(model, lineNumber, indentRulesSupport); - if (precedingUnIgnoredLine < 0) { - return null; - } - else if (precedingUnIgnoredLine < 1) { - return { - indentation: '', - action: null - }; - } - const 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 - }; - } - const previousLine = precedingUnIgnoredLine - 1; - const previousLineIndentMetadata = indentRulesSupport.getIndentMetadata(model.getLineContent(previousLine)); - if (!(previousLineIndentMetadata & (1 /* INCREASE_MASK */ | 2 /* DECREASE_MASK */)) && - (previousLineIndentMetadata & 4 /* INDENT_NEXTLINE_MASK */)) { - let stopLine = 0; - for (let 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 (let i = precedingUnIgnoredLine; i > 0; i--) { - const 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)) { - let stopLine = 0; - for (let 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 - }; - } - } - } - getGoodIndentForLine(autoIndent, virtualModel, languageId, lineNumber, indentConverter) { - if (autoIndent < 4 /* Full */) { - return null; - } - const richEditSupport = this._getRichEditSupport(languageId); - if (!richEditSupport) { - return null; - } - const indentRulesSupport = this.getIndentRulesSupport(languageId); - if (!indentRulesSupport) { - return null; - } - const indent = this.getInheritIndentForLine(autoIndent, virtualModel, lineNumber); - const lineContent = virtualModel.getLineContent(lineNumber); - if (indent) { - const inheritLine = indent.line; - if (inheritLine !== undefined) { - const enterResult = richEditSupport.onEnter(autoIndent, '', virtualModel.getLineContent(inheritLine), ''); - if (enterResult) { - let 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; - } - getIndentForEnter(autoIndent, model, range, indentConverter) { - if (autoIndent < 4 /* Full */) { - return null; - } - model.forceTokenization(range.startLineNumber); - const lineTokens = model.getLineTokens(range.startLineNumber); - const scopedLineTokens = (0, supports_1.createScopedLineTokens)(lineTokens, range.startColumn - 1); - const scopedLineText = scopedLineTokens.getLineContent(); - let embeddedLanguage = false; - let 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); - } - let afterEnterText; - if (range.isEmpty()) { - afterEnterText = scopedLineText.substr(range.startColumn - 1 - scopedLineTokens.firstCharOffset); - } - else { - const endScopedLineTokens = this.getScopedLineTokens(model, range.endLineNumber, range.endColumn); - afterEnterText = endScopedLineTokens.getLineContent().substr(range.endColumn - 1 - scopedLineTokens.firstCharOffset); - } - const indentRulesSupport = this.getIndentRulesSupport(scopedLineTokens.languageId); - if (!indentRulesSupport) { - return null; - } - const beforeEnterResult = beforeEnterText; - const beforeEnterIndent = strings.getLeadingWhitespace(beforeEnterText); - const virtualModel = { - getLineTokens: (lineNumber) => { - return model.getLineTokens(lineNumber); - }, - getLanguageIdentifier: () => { - return model.getLanguageIdentifier(); - }, - getLanguageIdAtPosition: (lineNumber, column) => { - return model.getLanguageIdAtPosition(lineNumber, column); - }, - getLineContent: (lineNumber) => { - if (lineNumber === range.startLineNumber) { - return beforeEnterResult; - } - else { - return model.getLineContent(lineNumber); - } - } - }; - const currentLineIndent = strings.getLeadingWhitespace(lineTokens.getLineContent()); - const afterEnterAction = this.getInheritIndentForLine(autoIndent, virtualModel, range.startLineNumber + 1); - if (!afterEnterAction) { - const beforeEnter = embeddedLanguage ? currentLineIndent : beforeEnterIndent; - return { - beforeEnter: beforeEnter, - afterEnter: beforeEnter - }; - } - let 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. - */ - getIndentActionForType(autoIndent, model, range, ch, indentConverter) { - if (autoIndent < 4 /* Full */) { - return null; - } - const scopedLineTokens = this.getScopedLineTokens(model, range.startLineNumber, range.startColumn); - if (scopedLineTokens.firstCharOffset) { - // this line has mixed languages and indentation rules will not work - return null; - } - const indentRulesSupport = this.getIndentRulesSupport(scopedLineTokens.languageId); - if (!indentRulesSupport) { - return null; - } - const scopedLineText = scopedLineTokens.getLineContent(); - const beforeTypeText = scopedLineText.substr(0, range.startColumn - 1 - scopedLineTokens.firstCharOffset); - // selection support - let afterTypeText; - if (range.isEmpty()) { - afterTypeText = scopedLineText.substr(range.startColumn - 1 - scopedLineTokens.firstCharOffset); - } - else { - const 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 - const r = this.getInheritIndentForLine(autoIndent, model, range.startLineNumber, false); - if (!r) { - return null; - } - let indentation = r.indentation; - if (r.action !== languageConfiguration_1.IndentAction.Indent) { - indentation = indentConverter.unshiftIndent(indentation); - } - return indentation; - } - return null; - } - getIndentMetadata(model, lineNumber) { - const 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 - getEnterAction(autoIndent, model, range) { - const scopedLineTokens = this.getScopedLineTokens(model, range.startLineNumber, range.startColumn); - const richEditSupport = this._getRichEditSupport(scopedLineTokens.languageId); - if (!richEditSupport) { - return null; - } - const scopedLineText = scopedLineTokens.getLineContent(); - const beforeEnterText = scopedLineText.substr(0, range.startColumn - 1 - scopedLineTokens.firstCharOffset); - // selection support - let afterEnterText; - if (range.isEmpty()) { - afterEnterText = scopedLineText.substr(range.startColumn - 1 - scopedLineTokens.firstCharOffset); - } - else { - const endScopedLineTokens = this.getScopedLineTokens(model, range.endLineNumber, range.endColumn); - afterEnterText = endScopedLineTokens.getLineContent().substr(range.endColumn - 1 - scopedLineTokens.firstCharOffset); - } - let previousLineText = ''; - if (range.startLineNumber > 1 && scopedLineTokens.firstCharOffset === 0) { - // This is not the first line and the entire line belongs to this mode - const oneLineAboveScopedLineTokens = this.getScopedLineTokens(model, range.startLineNumber - 1); - if (oneLineAboveScopedLineTokens.languageId === scopedLineTokens.languageId) { - // The line above ends with text belonging to the same mode - previousLineText = oneLineAboveScopedLineTokens.getLineContent(); - } - } - const enterResult = richEditSupport.onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText); - if (!enterResult) { - return null; - } - const indentAction = enterResult.indentAction; - let appendText = enterResult.appendText; - const 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 = ''; - } - } - else if (indentAction === languageConfiguration_1.IndentAction.Indent) { - appendText = '\t' + appendText; - } - let 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 - }; - } - getIndentationAtPosition(model, lineNumber, column) { - const lineText = model.getLineContent(lineNumber); - let indentation = strings.getLeadingWhitespace(lineText); - if (indentation.length > column - 1) { - indentation = indentation.substring(0, column - 1); - } - return indentation; - } - getScopedLineTokens(model, lineNumber, columnNumber) { - model.forceTokenization(lineNumber); - const lineTokens = model.getLineTokens(lineNumber); - const column = (typeof columnNumber === 'undefined' ? model.getLineMaxColumn(lineNumber) - 1 : columnNumber - 1); - return (0, supports_1.createScopedLineTokens)(lineTokens, column); - } - // end onEnter - getBracketsSupport(languageId) { - const value = this._getRichEditSupport(languageId); - if (!value) { - return null; - } - return value.brackets || null; - } - } - 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[389/*vs/editor/common/modes/supports/tokenization*/], __M([0/*require*/,1/*exports*/,29/*vs/base/common/color*/]), function (require, exports, color_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.generateTokensCSSForColorMap = exports.ThemeTrieElement = exports.ThemeTrieElementRule = exports.strcmp = exports.toStandardTokenType = exports.TokenTheme = exports.ColorMap = exports.parseTokenTheme = exports.ParsedTokenThemeRule = void 0; - class ParsedTokenThemeRule { - constructor(token, index, fontStyle, foreground, background) { - this._parsedThemeRuleBrand = undefined; - this.token = token; - this.index = index; - this.fontStyle = fontStyle; - this.foreground = foreground; - this.background = background; - } - } - exports.ParsedTokenThemeRule = ParsedTokenThemeRule; - /** - * Parse a raw theme into rules. - */ - function parseTokenTheme(source) { - if (!source || !Array.isArray(source)) { - return []; - } - let result = [], resultLen = 0; - for (let i = 0, len = source.length; i < len; i++) { - let entry = source[i]; - let fontStyle = -1 /* NotSet */; - if (typeof entry.fontStyle === 'string') { - fontStyle = 0 /* None */; - let segments = entry.fontStyle.split(' '); - for (let j = 0, lenJ = segments.length; j < lenJ; j++) { - let 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; - } - } - } - let foreground = null; - if (typeof entry.foreground === 'string') { - foreground = entry.foreground; - } - let 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((a, b) => { - let r = strcmp(a.token, b.token); - if (r !== 0) { - return r; - } - return a.index - b.index; - }); - // Determine defaults - let defaultFontStyle = 0 /* None */; - let defaultForeground = '000000'; - let defaultBackground = 'ffffff'; - while (parsedThemeRules.length >= 1 && parsedThemeRules[0].token === '') { - let 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; - } - } - let colorMap = new ColorMap(); - // start with token colors from custom token themes - for (let color of customTokenColors) { - colorMap.getId(color); - } - let foregroundColorId = colorMap.getId(defaultForeground); - let backgroundColorId = colorMap.getId(defaultBackground); - let defaults = new ThemeTrieElementRule(defaultFontStyle, foregroundColorId, backgroundColorId); - let root = new ThemeTrieElement(defaults); - for (let i = 0, len = parsedThemeRules.length; i < len; i++) { - let rule = parsedThemeRules[i]; - root.insert(rule.token, rule.fontStyle, colorMap.getId(rule.foreground), colorMap.getId(rule.background)); - } - return new TokenTheme(colorMap, root); - } - const colorRegExp = /^#?([0-9A-Fa-f]{6})([0-9A-Fa-f]{2})?$/; - class ColorMap { - constructor() { - this._lastColorId = 0; - this._id2color = []; - this._color2id = new Map(); - } - getId(color) { - if (color === null) { - return 0; - } - const match = color.match(colorRegExp); - if (!match) { - throw new Error('Illegal value for token color: ' + color); - } - color = match[1].toUpperCase(); - let 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; - } - getColorMap() { - return this._id2color.slice(0); - } - } - exports.ColorMap = ColorMap; - class TokenTheme { - constructor(colorMap, root) { - this._colorMap = colorMap; - this._root = root; - this._cache = new Map(); - } - static createFromRawTokenTheme(source, customTokenColors) { - return this.createFromParsedTokenTheme(parseTokenTheme(source), customTokenColors); - } - static createFromParsedTokenTheme(source, customTokenColors) { - return resolveParsedTokenThemeRules(source, customTokenColors); - } - getColorMap() { - return this._colorMap.getColorMap(); - } - _match(token) { - return this._root.match(token); - } - match(languageId, token) { - // The cache contains the metadata without the language bits set. - let result = this._cache.get(token); - if (typeof result === 'undefined') { - let rule = this._match(token); - let standardToken = toStandardTokenType(token); - result = (rule.metadata - | (standardToken << 8 /* TOKEN_TYPE_OFFSET */)) >>> 0; - this._cache.set(token, result); - } - return (result - | (languageId << 0 /* LANGUAGEID_OFFSET */)) >>> 0; - } - } - exports.TokenTheme = TokenTheme; - const STANDARD_TOKEN_TYPE_REGEXP = /\b(comment|string|regex|regexp)\b/; - function toStandardTokenType(tokenType) { - let 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; - class ThemeTrieElementRule { - constructor(fontStyle, foreground, background) { - this._themeTrieElementRuleBrand = undefined; - 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; - } - clone() { - return new ThemeTrieElementRule(this._fontStyle, this._foreground, this._background); - } - acceptOverwrite(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; - } - } - exports.ThemeTrieElementRule = ThemeTrieElementRule; - class ThemeTrieElement { - constructor(mainRule) { - this._themeTrieElementBrand = undefined; - this._mainRule = mainRule; - this._children = new Map(); - } - match(token) { - if (token === '') { - return this._mainRule; - } - let dotIndex = token.indexOf('.'); - let head; - let tail; - if (dotIndex === -1) { - head = token; - tail = ''; - } - else { - head = token.substring(0, dotIndex); - tail = token.substring(dotIndex + 1); - } - let child = this._children.get(head); - if (typeof child !== 'undefined') { - return child.match(tail); - } - return this._mainRule; - } - insert(token, fontStyle, foreground, background) { - if (token === '') { - // Merge into the main rule - this._mainRule.acceptOverwrite(fontStyle, foreground, background); - return; - } - let dotIndex = token.indexOf('.'); - let head; - let tail; - if (dotIndex === -1) { - head = token; - tail = ''; - } - else { - head = token.substring(0, dotIndex); - tail = token.substring(dotIndex + 1); - } - let 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); - } - } - exports.ThemeTrieElement = ThemeTrieElement; - function generateTokensCSSForColorMap(colorMap) { - let rules = []; - for (let i = 1, len = colorMap.length; i < len; i++) { - let 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[390/*vs/editor/common/modes/tokenizationRegistry*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/]), function (require, exports, event_1, lifecycle_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.TokenizationRegistryImpl = void 0; - class TokenizationRegistryImpl { - constructor() { - this._map = new Map(); - this._promises = new Map(); - this._onDidChange = new event_1.Emitter(); - this.onDidChange = this._onDidChange.event; - this._colorMap = null; - } - fire(languages) { - this._onDidChange.fire({ - changedLanguages: languages, - changedColorMap: false - }); - } - register(language, support) { - this._map.set(language, support); - this.fire([language]); - return (0, lifecycle_1.toDisposable)(() => { - if (this._map.get(language) !== support) { - return; - } - this._map.delete(language); - this.fire([language]); - }); - } - registerPromise(language, supportPromise) { - let registration = null; - let isDisposed = false; - this._promises.set(language, supportPromise.then(support => { - this._promises.delete(language); - if (isDisposed || !support) { - return; - } - registration = this.register(language, support); - })); - return (0, lifecycle_1.toDisposable)(() => { - isDisposed = true; - if (registration) { - registration.dispose(); - } - }); - } - getPromise(language) { - const support = this.get(language); - if (support) { - return Promise.resolve(support); - } - const promise = this._promises.get(language); - if (promise) { - return promise.then(_ => this.get(language)); - } - return null; - } - get(language) { - return (this._map.get(language) || null); - } - setColorMap(colorMap) { - this._colorMap = colorMap; - this._onDidChange.fire({ - changedLanguages: Array.from(this._map.keys()), - changedColorMap: true - }); - } - getColorMap() { - return this._colorMap; - } - getDefaultBackground() { - if (this._colorMap && this._colorMap.length > 2 /* DefaultBackground */) { - return this._colorMap[2 /* DefaultBackground */]; - } - return null; - } - } - exports.TokenizationRegistryImpl = 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[391/*vs/editor/common/services/semanticTokensDto*/], __M([0/*require*/,1/*exports*/,103/*vs/base/common/buffer*/,17/*vs/base/common/platform*/]), function (require, exports, buffer_1, platform) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.encodeSemanticTokensDto = void 0; - function reverseEndianness(arr) { - for (let i = 0, len = arr.length; i < len; i += 4) { - // flip bytes 0<->3 and 1<->2 - const b0 = arr[i + 0]; - const b1 = arr[i + 1]; - const b2 = arr[i + 2]; - const b3 = arr[i + 3]; - arr[i + 0] = b3; - arr[i + 1] = b2; - arr[i + 2] = b1; - arr[i + 3] = b0; - } - } - function toLittleEndianBuffer(arr) { - const uint8Arr = new Uint8Array(arr.buffer, arr.byteOffset, arr.length * 4); - if (!platform.isLittleEndian()) { - // the byte order must be changed - reverseEndianness(uint8Arr); - } - return buffer_1.VSBuffer.wrap(uint8Arr); - } - function encodeSemanticTokensDto(semanticTokens) { - const dest = new Uint32Array(encodeSemanticTokensDtoSize(semanticTokens)); - let offset = 0; - dest[offset++] = semanticTokens.id; - if (semanticTokens.type === 'full') { - dest[offset++] = 1 /* Full */; - dest[offset++] = semanticTokens.data.length; - dest.set(semanticTokens.data, offset); - offset += semanticTokens.data.length; - } - else { - dest[offset++] = 2 /* Delta */; - dest[offset++] = semanticTokens.deltas.length; - for (const delta of semanticTokens.deltas) { - dest[offset++] = delta.start; - dest[offset++] = delta.deleteCount; - if (delta.data) { - dest[offset++] = delta.data.length; - dest.set(delta.data, offset); - offset += delta.data.length; - } - else { - dest[offset++] = 0; - } - } - } - return toLittleEndianBuffer(dest); - } - exports.encodeSemanticTokensDto = encodeSemanticTokensDto; - function encodeSemanticTokensDtoSize(semanticTokens) { - let result = 0; - result += (+1 // id - + 1 // type - ); - if (semanticTokens.type === 'full') { - result += (+1 // data length - + semanticTokens.data.length); - } - else { - result += (+1 // delta count - ); - result += (+1 // start - + 1 // deleteCount - + 1 // data length - ) * semanticTokens.deltas.length; - for (const delta of semanticTokens.deltas) { - if (delta.data) { - result += delta.data.length; - } - } - } - 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[174/*vs/editor/common/standalone/standaloneEnums*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.WrappingIndent = exports.TrackedRangeStickiness = exports.TextEditorCursorStyle = exports.TextEditorCursorBlinkingStyle = exports.SymbolTag = exports.SymbolKind = exports.SignatureHelpTriggerKind = exports.SelectionDirection = exports.ScrollbarVisibility = exports.ScrollType = exports.RenderMinimap = exports.RenderLineNumbersType = exports.OverviewRulerLane = exports.OverlayWidgetPositionPreference = exports.MouseTargetType = exports.MinimapPosition = exports.MarkerTag = exports.MarkerSeverity = exports.KeyCode = exports.InlineCompletionTriggerKind = exports.InlayHintKind = exports.IndentAction = exports.EndOfLineSequence = exports.EndOfLinePreference = exports.EditorOption = exports.EditorAutoIndentStrategy = exports.DocumentHighlightKind = exports.DefaultEndOfLine = exports.CursorChangeReason = exports.ContentWidgetPositionPreference = exports.CompletionTriggerKind = exports.CompletionItemTag = exports.CompletionItemKind = exports.CompletionItemInsertTextRule = exports.AccessibilitySupport = void 0; - // 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["User"] = 25] = "User"; - CompletionItemKind[CompletionItemKind["Issue"] = 26] = "Issue"; - CompletionItemKind[CompletionItemKind["Snippet"] = 27] = "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["autoClosingDelete"] = 6] = "autoClosingDelete"; - EditorOption[EditorOption["autoClosingOvertype"] = 7] = "autoClosingOvertype"; - EditorOption[EditorOption["autoClosingQuotes"] = 8] = "autoClosingQuotes"; - EditorOption[EditorOption["autoIndent"] = 9] = "autoIndent"; - EditorOption[EditorOption["automaticLayout"] = 10] = "automaticLayout"; - EditorOption[EditorOption["autoSurround"] = 11] = "autoSurround"; - EditorOption[EditorOption["codeLens"] = 12] = "codeLens"; - EditorOption[EditorOption["codeLensFontFamily"] = 13] = "codeLensFontFamily"; - EditorOption[EditorOption["codeLensFontSize"] = 14] = "codeLensFontSize"; - EditorOption[EditorOption["colorDecorators"] = 15] = "colorDecorators"; - EditorOption[EditorOption["columnSelection"] = 16] = "columnSelection"; - EditorOption[EditorOption["comments"] = 17] = "comments"; - EditorOption[EditorOption["contextmenu"] = 18] = "contextmenu"; - EditorOption[EditorOption["copyWithSyntaxHighlighting"] = 19] = "copyWithSyntaxHighlighting"; - EditorOption[EditorOption["cursorBlinking"] = 20] = "cursorBlinking"; - EditorOption[EditorOption["cursorSmoothCaretAnimation"] = 21] = "cursorSmoothCaretAnimation"; - EditorOption[EditorOption["cursorStyle"] = 22] = "cursorStyle"; - EditorOption[EditorOption["cursorSurroundingLines"] = 23] = "cursorSurroundingLines"; - EditorOption[EditorOption["cursorSurroundingLinesStyle"] = 24] = "cursorSurroundingLinesStyle"; - EditorOption[EditorOption["cursorWidth"] = 25] = "cursorWidth"; - EditorOption[EditorOption["disableLayerHinting"] = 26] = "disableLayerHinting"; - EditorOption[EditorOption["disableMonospaceOptimizations"] = 27] = "disableMonospaceOptimizations"; - EditorOption[EditorOption["domReadOnly"] = 28] = "domReadOnly"; - EditorOption[EditorOption["dragAndDrop"] = 29] = "dragAndDrop"; - EditorOption[EditorOption["emptySelectionClipboard"] = 30] = "emptySelectionClipboard"; - EditorOption[EditorOption["extraEditorClassName"] = 31] = "extraEditorClassName"; - EditorOption[EditorOption["fastScrollSensitivity"] = 32] = "fastScrollSensitivity"; - EditorOption[EditorOption["find"] = 33] = "find"; - EditorOption[EditorOption["fixedOverflowWidgets"] = 34] = "fixedOverflowWidgets"; - EditorOption[EditorOption["folding"] = 35] = "folding"; - EditorOption[EditorOption["foldingStrategy"] = 36] = "foldingStrategy"; - EditorOption[EditorOption["foldingHighlight"] = 37] = "foldingHighlight"; - EditorOption[EditorOption["foldingImportsByDefault"] = 38] = "foldingImportsByDefault"; - EditorOption[EditorOption["unfoldOnClickAfterEndOfLine"] = 39] = "unfoldOnClickAfterEndOfLine"; - EditorOption[EditorOption["fontFamily"] = 40] = "fontFamily"; - EditorOption[EditorOption["fontInfo"] = 41] = "fontInfo"; - EditorOption[EditorOption["fontLigatures"] = 42] = "fontLigatures"; - EditorOption[EditorOption["fontSize"] = 43] = "fontSize"; - EditorOption[EditorOption["fontWeight"] = 44] = "fontWeight"; - EditorOption[EditorOption["formatOnPaste"] = 45] = "formatOnPaste"; - EditorOption[EditorOption["formatOnType"] = 46] = "formatOnType"; - EditorOption[EditorOption["glyphMargin"] = 47] = "glyphMargin"; - EditorOption[EditorOption["gotoLocation"] = 48] = "gotoLocation"; - EditorOption[EditorOption["hideCursorInOverviewRuler"] = 49] = "hideCursorInOverviewRuler"; - EditorOption[EditorOption["highlightActiveIndentGuide"] = 50] = "highlightActiveIndentGuide"; - EditorOption[EditorOption["hover"] = 51] = "hover"; - EditorOption[EditorOption["inDiffEditor"] = 52] = "inDiffEditor"; - EditorOption[EditorOption["inlineSuggest"] = 53] = "inlineSuggest"; - EditorOption[EditorOption["letterSpacing"] = 54] = "letterSpacing"; - EditorOption[EditorOption["lightbulb"] = 55] = "lightbulb"; - EditorOption[EditorOption["lineDecorationsWidth"] = 56] = "lineDecorationsWidth"; - EditorOption[EditorOption["lineHeight"] = 57] = "lineHeight"; - EditorOption[EditorOption["lineNumbers"] = 58] = "lineNumbers"; - EditorOption[EditorOption["lineNumbersMinChars"] = 59] = "lineNumbersMinChars"; - EditorOption[EditorOption["linkedEditing"] = 60] = "linkedEditing"; - EditorOption[EditorOption["links"] = 61] = "links"; - EditorOption[EditorOption["matchBrackets"] = 62] = "matchBrackets"; - EditorOption[EditorOption["minimap"] = 63] = "minimap"; - EditorOption[EditorOption["mouseStyle"] = 64] = "mouseStyle"; - EditorOption[EditorOption["mouseWheelScrollSensitivity"] = 65] = "mouseWheelScrollSensitivity"; - EditorOption[EditorOption["mouseWheelZoom"] = 66] = "mouseWheelZoom"; - EditorOption[EditorOption["multiCursorMergeOverlapping"] = 67] = "multiCursorMergeOverlapping"; - EditorOption[EditorOption["multiCursorModifier"] = 68] = "multiCursorModifier"; - EditorOption[EditorOption["multiCursorPaste"] = 69] = "multiCursorPaste"; - EditorOption[EditorOption["occurrencesHighlight"] = 70] = "occurrencesHighlight"; - EditorOption[EditorOption["overviewRulerBorder"] = 71] = "overviewRulerBorder"; - EditorOption[EditorOption["overviewRulerLanes"] = 72] = "overviewRulerLanes"; - EditorOption[EditorOption["padding"] = 73] = "padding"; - EditorOption[EditorOption["parameterHints"] = 74] = "parameterHints"; - EditorOption[EditorOption["peekWidgetDefaultFocus"] = 75] = "peekWidgetDefaultFocus"; - EditorOption[EditorOption["definitionLinkOpensInPeek"] = 76] = "definitionLinkOpensInPeek"; - EditorOption[EditorOption["quickSuggestions"] = 77] = "quickSuggestions"; - EditorOption[EditorOption["quickSuggestionsDelay"] = 78] = "quickSuggestionsDelay"; - EditorOption[EditorOption["readOnly"] = 79] = "readOnly"; - EditorOption[EditorOption["renameOnType"] = 80] = "renameOnType"; - EditorOption[EditorOption["renderControlCharacters"] = 81] = "renderControlCharacters"; - EditorOption[EditorOption["renderIndentGuides"] = 82] = "renderIndentGuides"; - EditorOption[EditorOption["renderFinalNewline"] = 83] = "renderFinalNewline"; - EditorOption[EditorOption["renderLineHighlight"] = 84] = "renderLineHighlight"; - EditorOption[EditorOption["renderLineHighlightOnlyWhenFocus"] = 85] = "renderLineHighlightOnlyWhenFocus"; - EditorOption[EditorOption["renderValidationDecorations"] = 86] = "renderValidationDecorations"; - EditorOption[EditorOption["renderWhitespace"] = 87] = "renderWhitespace"; - EditorOption[EditorOption["revealHorizontalRightPadding"] = 88] = "revealHorizontalRightPadding"; - EditorOption[EditorOption["roundedSelection"] = 89] = "roundedSelection"; - EditorOption[EditorOption["rulers"] = 90] = "rulers"; - EditorOption[EditorOption["scrollbar"] = 91] = "scrollbar"; - EditorOption[EditorOption["scrollBeyondLastColumn"] = 92] = "scrollBeyondLastColumn"; - EditorOption[EditorOption["scrollBeyondLastLine"] = 93] = "scrollBeyondLastLine"; - EditorOption[EditorOption["scrollPredominantAxis"] = 94] = "scrollPredominantAxis"; - EditorOption[EditorOption["selectionClipboard"] = 95] = "selectionClipboard"; - EditorOption[EditorOption["selectionHighlight"] = 96] = "selectionHighlight"; - EditorOption[EditorOption["selectOnLineNumbers"] = 97] = "selectOnLineNumbers"; - EditorOption[EditorOption["showFoldingControls"] = 98] = "showFoldingControls"; - EditorOption[EditorOption["showUnused"] = 99] = "showUnused"; - EditorOption[EditorOption["snippetSuggestions"] = 100] = "snippetSuggestions"; - EditorOption[EditorOption["smartSelect"] = 101] = "smartSelect"; - EditorOption[EditorOption["smoothScrolling"] = 102] = "smoothScrolling"; - EditorOption[EditorOption["stickyTabStops"] = 103] = "stickyTabStops"; - EditorOption[EditorOption["stopRenderingLineAfter"] = 104] = "stopRenderingLineAfter"; - EditorOption[EditorOption["suggest"] = 105] = "suggest"; - EditorOption[EditorOption["suggestFontSize"] = 106] = "suggestFontSize"; - EditorOption[EditorOption["suggestLineHeight"] = 107] = "suggestLineHeight"; - EditorOption[EditorOption["suggestOnTriggerCharacters"] = 108] = "suggestOnTriggerCharacters"; - EditorOption[EditorOption["suggestSelection"] = 109] = "suggestSelection"; - EditorOption[EditorOption["tabCompletion"] = 110] = "tabCompletion"; - EditorOption[EditorOption["tabIndex"] = 111] = "tabIndex"; - EditorOption[EditorOption["unusualLineTerminators"] = 112] = "unusualLineTerminators"; - EditorOption[EditorOption["useShadowDOM"] = 113] = "useShadowDOM"; - EditorOption[EditorOption["useTabStops"] = 114] = "useTabStops"; - EditorOption[EditorOption["wordSeparators"] = 115] = "wordSeparators"; - EditorOption[EditorOption["wordWrap"] = 116] = "wordWrap"; - EditorOption[EditorOption["wordWrapBreakAfterCharacters"] = 117] = "wordWrapBreakAfterCharacters"; - EditorOption[EditorOption["wordWrapBreakBeforeCharacters"] = 118] = "wordWrapBreakBeforeCharacters"; - EditorOption[EditorOption["wordWrapColumn"] = 119] = "wordWrapColumn"; - EditorOption[EditorOption["wordWrapOverride1"] = 120] = "wordWrapOverride1"; - EditorOption[EditorOption["wordWrapOverride2"] = 121] = "wordWrapOverride2"; - EditorOption[EditorOption["wrappingIndent"] = 122] = "wrappingIndent"; - EditorOption[EditorOption["wrappingStrategy"] = 123] = "wrappingStrategy"; - EditorOption[EditorOption["showDeprecated"] = 124] = "showDeprecated"; - EditorOption[EditorOption["inlayHints"] = 125] = "inlayHints"; - EditorOption[EditorOption["editorClassName"] = 126] = "editorClassName"; - EditorOption[EditorOption["pixelRatio"] = 127] = "pixelRatio"; - EditorOption[EditorOption["tabFocusMode"] = 128] = "tabFocusMode"; - EditorOption[EditorOption["layoutInfo"] = 129] = "layoutInfo"; - EditorOption[EditorOption["wrappingInfo"] = 130] = "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 = {})); - var InlayHintKind; - (function (InlayHintKind) { - InlayHintKind[InlayHintKind["Other"] = 0] = "Other"; - InlayHintKind[InlayHintKind["Type"] = 1] = "Type"; - InlayHintKind[InlayHintKind["Parameter"] = 2] = "Parameter"; - })(InlayHintKind = exports.InlayHintKind || (exports.InlayHintKind = {})); - /** - * How an {@link InlineCompletionsProvider inline completion provider} was triggered. - */ - var InlineCompletionTriggerKind; - (function (InlineCompletionTriggerKind) { - /** - * Completion was triggered automatically while editing. - * It is sufficient to return a single completion item in this case. - */ - InlineCompletionTriggerKind[InlineCompletionTriggerKind["Automatic"] = 0] = "Automatic"; - /** - * Completion was triggered explicitly by a user gesture. - * Return multiple completion items to enable cycling through them. - */ - InlineCompletionTriggerKind[InlineCompletionTriggerKind["Explicit"] = 1] = "Explicit"; - })(InlineCompletionTriggerKind = exports.InlineCompletionTriggerKind || (exports.InlineCompletionTriggerKind = {})); - /** - * 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) { - KeyCode[KeyCode["DependsOnKbLayout"] = -1] = "DependsOnKbLayout"; - /** - * 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[222/*vs/editor/common/standalone/standaloneBase*/], __M([0/*require*/,1/*exports*/,23/*vs/base/common/cancellation*/,6/*vs/base/common/event*/,41/*vs/base/common/keyCodes*/,24/*vs/base/common/uri*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,134/*vs/editor/common/core/token*/,174/*vs/editor/common/standalone/standaloneEnums*/]), 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 }); - exports.createMonacoBaseAPI = exports.KeyMod = void 0; - class KeyMod { - static chord(firstPart, secondPart) { - return (0, keyCodes_1.KeyChord)(firstPart, secondPart); - } - } - exports.KeyMod = KeyMod; - KeyMod.CtrlCmd = 2048 /* CtrlCmd */; - KeyMod.Shift = 1024 /* Shift */; - KeyMod.Alt = 512 /* Alt */; - KeyMod.WinCtrl = 256 /* WinCtrl */; - 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[223/*vs/editor/common/view/overviewZoneManager*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.OverviewZoneManager = exports.OverviewRulerZone = exports.ColorZone = void 0; - class ColorZone { - constructor(from, to, colorId) { - this._colorZoneBrand = undefined; - this.from = from | 0; - this.to = to | 0; - this.colorId = colorId | 0; - } - static compare(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; - } - } - exports.ColorZone = ColorZone; - /** - * A zone in the overview ruler - */ - class OverviewRulerZone { - constructor(startLineNumber, endLineNumber, color) { - this._overviewRulerZoneBrand = undefined; - this.startLineNumber = startLineNumber; - this.endLineNumber = endLineNumber; - this.color = color; - this._colorZone = null; - } - static compare(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; - } - setColorZone(colorZone) { - this._colorZone = colorZone; - } - getColorZones() { - return this._colorZone; - } - } - exports.OverviewRulerZone = OverviewRulerZone; - class OverviewZoneManager { - constructor(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 = []; - } - getId2Color() { - return this._id2Color; - } - setZones(newZones) { - this._zones = newZones; - this._zones.sort(OverviewRulerZone.compare); - } - setLineHeight(lineHeight) { - if (this._lineHeight === lineHeight) { - return false; - } - this._lineHeight = lineHeight; - this._colorZonesInvalid = true; - return true; - } - setPixelRatio(pixelRatio) { - this._pixelRatio = pixelRatio; - this._colorZonesInvalid = true; - } - getDOMWidth() { - return this._domWidth; - } - getCanvasWidth() { - return this._domWidth * this._pixelRatio; - } - setDOMWidth(width) { - if (this._domWidth === width) { - return false; - } - this._domWidth = width; - this._colorZonesInvalid = true; - return true; - } - getDOMHeight() { - return this._domHeight; - } - getCanvasHeight() { - return this._domHeight * this._pixelRatio; - } - setDOMHeight(height) { - if (this._domHeight === height) { - return false; - } - this._domHeight = height; - this._colorZonesInvalid = true; - return true; - } - getOuterHeight() { - return this._outerHeight; - } - setOuterHeight(outerHeight) { - if (this._outerHeight === outerHeight) { - return false; - } - this._outerHeight = outerHeight; - this._colorZonesInvalid = true; - return true; - } - resolveColorZones() { - const colorZonesInvalid = this._colorZonesInvalid; - const lineHeight = Math.floor(this._lineHeight); // @perf - const totalHeight = Math.floor(this.getCanvasHeight()); // @perf - const outerHeight = Math.floor(this._outerHeight); // @perf - const heightRatio = totalHeight / outerHeight; - const halfMinimumHeight = Math.floor(4 /* MINIMUM_HEIGHT */ * this._pixelRatio / 2); - let allColorZones = []; - for (let i = 0, len = this._zones.length; i < len; i++) { - const zone = this._zones[i]; - if (!colorZonesInvalid) { - const colorZone = zone.getColorZones(); - if (colorZone) { - allColorZones.push(colorZone); - continue; - } - } - const y1 = Math.floor(heightRatio * (this._getVerticalOffsetForLine(zone.startLineNumber))); - const y2 = Math.floor(heightRatio * (this._getVerticalOffsetForLine(zone.endLineNumber) + lineHeight)); - let ycenter = Math.floor((y1 + y2) / 2); - let halfHeight = (y2 - ycenter); - if (halfHeight < halfMinimumHeight) { - halfHeight = halfMinimumHeight; - } - if (ycenter - halfHeight < 0) { - ycenter = halfHeight; - } - if (ycenter + halfHeight > totalHeight) { - ycenter = totalHeight - halfHeight; - } - const color = zone.color; - let colorId = this._color2Id[color]; - if (!colorId) { - colorId = (++this._lastAssignedId); - this._color2Id[color] = colorId; - this._id2Color[colorId] = color; - } - const colorZone = new ColorZone(ycenter - halfHeight, ycenter + halfHeight, colorId); - zone.setColorZone(colorZone); - allColorZones.push(colorZone); - } - this._colorZonesInvalid = false; - allColorZones.sort(ColorZone.compare); - return allColorZones; - } - } - 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[113/*vs/editor/common/view/renderingContext*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.VisibleRanges = exports.HorizontalPosition = exports.HorizontalRange = exports.LineVisibleRanges = exports.RenderingContext = exports.RestrictedRenderingContext = void 0; - class RestrictedRenderingContext { - constructor(viewLayout, viewportData) { - this._restrictedRenderingContextBrand = undefined; - 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; - const vInfo = this._viewLayout.getCurrentViewport(); - this.scrollTop = vInfo.top; - this.scrollLeft = vInfo.left; - this.viewportWidth = vInfo.width; - this.viewportHeight = vInfo.height; - } - getScrolledTopFromAbsoluteTop(absoluteTop) { - return absoluteTop - this.scrollTop; - } - getVerticalOffsetForLineNumber(lineNumber) { - return this._viewLayout.getVerticalOffsetForLineNumber(lineNumber); - } - getDecorationsInViewport() { - return this.viewportData.getDecorationsInViewport(); - } - } - exports.RestrictedRenderingContext = RestrictedRenderingContext; - class RenderingContext extends RestrictedRenderingContext { - constructor(viewLayout, viewportData, viewLines) { - super(viewLayout, viewportData); - this._renderingContextBrand = undefined; - this._viewLines = viewLines; - } - linesVisibleRangesForRange(range, includeNewLines) { - return this._viewLines.linesVisibleRangesForRange(range, includeNewLines); - } - visibleRangeForPosition(position) { - return this._viewLines.visibleRangeForPosition(position); - } - } - exports.RenderingContext = RenderingContext; - class LineVisibleRanges { - constructor(outsideRenderedLine, lineNumber, ranges) { - this.outsideRenderedLine = outsideRenderedLine; - this.lineNumber = lineNumber; - this.ranges = ranges; - } - } - exports.LineVisibleRanges = LineVisibleRanges; - class HorizontalRange { - constructor(left, width) { - this.left = Math.round(left); - this.width = Math.round(width); - } - toString() { - return `[${this.left},${this.width}]`; - } - } - exports.HorizontalRange = HorizontalRange; - class HorizontalPosition { - constructor(outsideRenderedLine, left) { - this.outsideRenderedLine = outsideRenderedLine; - this.left = Math.round(left); - } - } - exports.HorizontalPosition = HorizontalPosition; - class VisibleRanges { - constructor(outsideRenderedLine, ranges) { - this.outsideRenderedLine = outsideRenderedLine; - this.ranges = ranges; - } - } - 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[392/*vs/editor/browser/viewParts/lines/rangeUtil*/], __M([0/*require*/,1/*exports*/,113/*vs/editor/common/view/renderingContext*/]), function (require, exports, renderingContext_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.RangeUtil = void 0; - class FloatHorizontalRange { - constructor(left, width) { - this._floatHorizontalRangeBrand = undefined; - this.left = left; - this.width = width; - } - toString() { - return `[${this.left},${this.width}]`; - } - static compare(a, b) { - return a.left - b.left; - } - } - class RangeUtil { - static _createRange() { - if (!this._handyReadyRange) { - this._handyReadyRange = document.createRange(); - } - return this._handyReadyRange; - } - static _detachRange(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); - } - static _readClientRects(startElement, startOffset, endElement, endOffset, endNode) { - const 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); - } - } - static _mergeAdjacentRanges(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); - let result = [], resultLen = 0; - let prevLeft = ranges[0].left; - let prevWidth = ranges[0].width; - for (let i = 1, len = ranges.length; i < len; i++) { - const range = ranges[i]; - const myLeft = range.left; - const 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; - } - static _createHorizontalRangesFromClientRects(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 - const result = []; - for (let i = 0, len = clientRects.length; i < len; i++) { - const clientRect = clientRects[i]; - result[i] = new FloatHorizontalRange(Math.max(0, clientRect.left - clientRectDeltaLeft), clientRect.width); - } - return this._mergeAdjacentRanges(result); - } - static readHorizontalRanges(domNode, startChildIndex, startOffset, endChildIndex, endOffset, clientRectDeltaLeft, endNode) { - // Panic check - const min = 0; - const 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 (startChildIndex === endChildIndex && startOffset === endOffset && startOffset === 0 && !domNode.children[startChildIndex].firstChild) { - // We must find the position at the beginning of a - // To cover cases of empty s, avoid using a range and use the 's bounding box - const clientRects = domNode.children[startChildIndex].getClientRects(); - return this._createHorizontalRangesFromClientRects(clientRects, clientRectDeltaLeft); - } - // 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 */; - } - } - let startElement = domNode.children[startChildIndex].firstChild; - let 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)); - const clientRects = this._readClientRects(startElement, startOffset, endElement, endOffset, endNode); - return this._createHorizontalRangesFromClientRects(clientRects, clientRectDeltaLeft); - } - } - 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[393/*vs/editor/common/view/viewContext*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ViewContext = exports.EditorTheme = void 0; - class EditorTheme { - constructor(theme) { - this._theme = theme; - } - get type() { - return this._theme.type; - } - update(theme) { - this._theme = theme; - } - getColor(color) { - return this._theme.getColor(color); - } - } - exports.EditorTheme = EditorTheme; - class ViewContext { - constructor(configuration, theme, model) { - this.configuration = configuration; - this.theme = new EditorTheme(theme); - this.model = model; - this.viewLayout = model.viewLayout; - } - addEventHandler(eventHandler) { - this.model.addViewEventHandler(eventHandler); - } - removeEventHandler(eventHandler) { - this.model.removeViewEventHandler(eventHandler); - } - } - 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[175/*vs/editor/common/view/viewEvents*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ViewZonesChangedEvent = exports.ViewTokensColorsChangedEvent = exports.ViewTokensChangedEvent = exports.ViewThemeChangedEvent = exports.ViewScrollChangedEvent = exports.ViewRevealRangeRequestEvent = exports.ViewLinesInsertedEvent = exports.ViewLinesDeletedEvent = exports.ViewLinesChangedEvent = exports.ViewLineMappingChangedEvent = exports.ViewLanguageConfigurationEvent = exports.ViewFocusChangedEvent = exports.ViewFlushedEvent = exports.ViewDecorationsChangedEvent = exports.ViewCursorStateChangedEvent = exports.ViewConfigurationChangedEvent = exports.ViewCompositionEndEvent = exports.ViewCompositionStartEvent = void 0; - class ViewCompositionStartEvent { - constructor() { - this.type = 0 /* ViewCompositionStart */; - } - } - exports.ViewCompositionStartEvent = ViewCompositionStartEvent; - class ViewCompositionEndEvent { - constructor() { - this.type = 1 /* ViewCompositionEnd */; - } - } - exports.ViewCompositionEndEvent = ViewCompositionEndEvent; - class ViewConfigurationChangedEvent { - constructor(source) { - this.type = 2 /* ViewConfigurationChanged */; - this._source = source; - } - hasChanged(id) { - return this._source.hasChanged(id); - } - } - exports.ViewConfigurationChangedEvent = ViewConfigurationChangedEvent; - class ViewCursorStateChangedEvent { - constructor(selections, modelSelections) { - this.type = 3 /* ViewCursorStateChanged */; - this.selections = selections; - this.modelSelections = modelSelections; - } - } - exports.ViewCursorStateChangedEvent = ViewCursorStateChangedEvent; - class ViewDecorationsChangedEvent { - constructor(source) { - this.type = 4 /* ViewDecorationsChanged */; - if (source) { - this.affectsMinimap = source.affectsMinimap; - this.affectsOverviewRuler = source.affectsOverviewRuler; - } - else { - this.affectsMinimap = true; - this.affectsOverviewRuler = true; - } - } - } - exports.ViewDecorationsChangedEvent = ViewDecorationsChangedEvent; - class ViewFlushedEvent { - constructor() { - this.type = 5 /* ViewFlushed */; - // Nothing to do - } - } - exports.ViewFlushedEvent = ViewFlushedEvent; - class ViewFocusChangedEvent { - constructor(isFocused) { - this.type = 6 /* ViewFocusChanged */; - this.isFocused = isFocused; - } - } - exports.ViewFocusChangedEvent = ViewFocusChangedEvent; - class ViewLanguageConfigurationEvent { - constructor() { - this.type = 7 /* ViewLanguageConfigurationChanged */; - } - } - exports.ViewLanguageConfigurationEvent = ViewLanguageConfigurationEvent; - class ViewLineMappingChangedEvent { - constructor() { - this.type = 8 /* ViewLineMappingChanged */; - // Nothing to do - } - } - exports.ViewLineMappingChangedEvent = ViewLineMappingChangedEvent; - class ViewLinesChangedEvent { - constructor(fromLineNumber, toLineNumber) { - this.type = 9 /* ViewLinesChanged */; - this.fromLineNumber = fromLineNumber; - this.toLineNumber = toLineNumber; - } - } - exports.ViewLinesChangedEvent = ViewLinesChangedEvent; - class ViewLinesDeletedEvent { - constructor(fromLineNumber, toLineNumber) { - this.type = 10 /* ViewLinesDeleted */; - this.fromLineNumber = fromLineNumber; - this.toLineNumber = toLineNumber; - } - } - exports.ViewLinesDeletedEvent = ViewLinesDeletedEvent; - class ViewLinesInsertedEvent { - constructor(fromLineNumber, toLineNumber) { - this.type = 11 /* ViewLinesInserted */; - this.fromLineNumber = fromLineNumber; - this.toLineNumber = toLineNumber; - } - } - exports.ViewLinesInsertedEvent = ViewLinesInsertedEvent; - class ViewRevealRangeRequestEvent { - constructor(source, range, selections, verticalType, revealHorizontal, scrollType) { - this.type = 12 /* ViewRevealRangeRequest */; - this.source = source; - this.range = range; - this.selections = selections; - this.verticalType = verticalType; - this.revealHorizontal = revealHorizontal; - this.scrollType = scrollType; - } - } - exports.ViewRevealRangeRequestEvent = ViewRevealRangeRequestEvent; - class ViewScrollChangedEvent { - constructor(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; - } - } - exports.ViewScrollChangedEvent = ViewScrollChangedEvent; - class ViewThemeChangedEvent { - constructor() { - this.type = 14 /* ViewThemeChanged */; - } - } - exports.ViewThemeChangedEvent = ViewThemeChangedEvent; - class ViewTokensChangedEvent { - constructor(ranges) { - this.type = 15 /* ViewTokensChanged */; - this.ranges = ranges; - } - } - exports.ViewTokensChangedEvent = ViewTokensChangedEvent; - class ViewTokensColorsChangedEvent { - constructor() { - this.type = 16 /* ViewTokensColorsChanged */; - // Nothing to do - } - } - exports.ViewTokensColorsChangedEvent = ViewTokensColorsChangedEvent; - class ViewZonesChangedEvent { - constructor() { - this.type = 17 /* ViewZonesChanged */; - // Nothing to do - } - } - exports.ViewZonesChangedEvent = ViewZonesChangedEvent; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/editor/common/viewLayout/lineDecorations*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/]), function (require, exports, strings) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.LineDecorationsNormalizer = exports.DecorationSegment = exports.LineDecoration = void 0; - class LineDecoration { - constructor(startColumn, endColumn, className, type) { - this.startColumn = startColumn; - this.endColumn = endColumn; - this.className = className; - this.type = type; - this._lineDecorationBrand = undefined; - } - static _equals(a, b) { - return (a.startColumn === b.startColumn - && a.endColumn === b.endColumn - && a.className === b.className - && a.type === b.type); - } - static equalsArr(a, b) { - const aLen = a.length; - const bLen = b.length; - if (aLen !== bLen) { - return false; - } - for (let i = 0; i < aLen; i++) { - if (!LineDecoration._equals(a[i], b[i])) { - return false; - } - } - return true; - } - static extractWrapped(arr, startOffset, endOffset) { - if (arr.length === 0) { - return arr; - } - const startColumn = startOffset + 1; - const endColumn = endOffset + 1; - const lineLength = endOffset - startOffset; - const r = []; - let rLength = 0; - for (const dec of arr) { - if (dec.endColumn <= startColumn || dec.startColumn >= endColumn) { - continue; - } - r[rLength++] = new LineDecoration(Math.max(1, dec.startColumn - startColumn + 1), Math.min(lineLength + 1, dec.endColumn - startColumn + 1), dec.className, dec.type); - } - return r; - } - static filter(lineDecorations, lineNumber, minLineColumn, maxLineColumn) { - if (lineDecorations.length === 0) { - return []; - } - let result = [], resultLen = 0; - for (let i = 0, len = lineDecorations.length; i < len; i++) { - const d = lineDecorations[i]; - const 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; - } - const startColumn = (range.startLineNumber === lineNumber ? range.startColumn : minLineColumn); - const endColumn = (range.endLineNumber === lineNumber ? range.endColumn : maxLineColumn); - result[resultLen++] = new LineDecoration(startColumn, endColumn, d.inlineClassName, d.type); - } - return result; - } - static _typeCompare(a, b) { - const ORDER = [2, 0, 1, 3]; - return ORDER[a] - ORDER[b]; - } - static compare(a, b) { - if (a.startColumn !== b.startColumn) { - return a.startColumn - b.startColumn; - } - if (a.endColumn !== b.endColumn) { - return a.endColumn - b.endColumn; - } - const typeCmp = LineDecoration._typeCompare(a.type, b.type); - if (typeCmp !== 0) { - return typeCmp; - } - if (a.className !== b.className) { - return a.className < b.className ? -1 : 1; - } - return 0; - } - } - exports.LineDecoration = LineDecoration; - class DecorationSegment { - constructor(startOffset, endOffset, className, metadata) { - this.startOffset = startOffset; - this.endOffset = endOffset; - this.className = className; - this.metadata = metadata; - } - } - exports.DecorationSegment = DecorationSegment; - class Stack { - constructor() { - this.stopOffsets = []; - this.classNames = []; - this.metadata = []; - this.count = 0; - } - static _metadata(metadata) { - let result = 0; - for (let i = 0, len = metadata.length; i < len; i++) { - result |= metadata[i]; - } - return result; - } - consumeLowerThan(maxStopOffset, nextStartOffset, result) { - while (this.count > 0 && this.stopOffsets[0] < maxStopOffset) { - let 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(' '), Stack._metadata(this.metadata))); - nextStartOffset = this.stopOffsets[i] + 1; - // Consume them - this.stopOffsets.splice(0, i + 1); - this.classNames.splice(0, i + 1); - this.metadata.splice(0, i + 1); - this.count -= (i + 1); - } - if (this.count > 0 && nextStartOffset < maxStopOffset) { - result.push(new DecorationSegment(nextStartOffset, maxStopOffset - 1, this.classNames.join(' '), Stack._metadata(this.metadata))); - nextStartOffset = maxStopOffset; - } - return nextStartOffset; - } - insert(stopOffset, className, metadata) { - if (this.count === 0 || this.stopOffsets[this.count - 1] <= stopOffset) { - // Insert at the end - this.stopOffsets.push(stopOffset); - this.classNames.push(className); - this.metadata.push(metadata); - } - else { - // Find the insertion position for `stopOffset` - for (let i = 0; i < this.count; i++) { - if (this.stopOffsets[i] >= stopOffset) { - this.stopOffsets.splice(i, 0, stopOffset); - this.classNames.splice(i, 0, className); - this.metadata.splice(i, 0, metadata); - break; - } - } - } - this.count++; - return; - } - } - class LineDecorationsNormalizer { - /** - * Normalize line decorations. Overlapping decorations will generate multiple segments - */ - static normalize(lineContent, lineDecorations) { - if (lineDecorations.length === 0) { - return []; - } - let result = []; - const stack = new Stack(); - let nextStartOffset = 0; - for (let i = 0, len = lineDecorations.length; i < len; i++) { - const d = lineDecorations[i]; - let startColumn = d.startColumn; - let endColumn = d.endColumn; - const className = d.className; - const metadata = (d.type === 1 /* Before */ - ? 2 /* PSEUDO_BEFORE */ - : d.type === 2 /* After */ - ? 4 /* PSEUDO_AFTER */ - : 0); - // 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) { - const charCodeBefore = lineContent.charCodeAt(startColumn - 2); - if (strings.isHighSurrogate(charCodeBefore)) { - startColumn--; - } - } - if (endColumn > 1) { - const charCodeBefore = lineContent.charCodeAt(endColumn - 2); - if (strings.isHighSurrogate(charCodeBefore)) { - endColumn--; - } - } - const currentStartOffset = startColumn - 1; - const currentEndOffset = endColumn - 2; - nextStartOffset = stack.consumeLowerThan(currentStartOffset, nextStartOffset, result); - if (stack.count === 0) { - nextStartOffset = currentStartOffset; - } - stack.insert(currentEndOffset, className, metadata); - } - stack.consumeLowerThan(1073741824 /* MAX_SAFE_SMALL_INTEGER */, nextStartOffset, result); - return result; - } - } - 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[394/*vs/editor/common/viewLayout/linesLayout*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/]), function (require, exports, strings) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.LinesLayout = exports.EditorWhitespace = void 0; - class PendingChanges { - constructor() { - this._hasPending = false; - this._inserts = []; - this._changes = []; - this._removes = []; - } - insert(x) { - this._hasPending = true; - this._inserts.push(x); - } - change(x) { - this._hasPending = true; - this._changes.push(x); - } - remove(x) { - this._hasPending = true; - this._removes.push(x); - } - mustCommit() { - return this._hasPending; - } - commit(linesLayout) { - if (!this._hasPending) { - return; - } - const inserts = this._inserts; - const changes = this._changes; - const removes = this._removes; - this._hasPending = false; - this._inserts = []; - this._changes = []; - this._removes = []; - linesLayout._commitPendingChanges(inserts, changes, removes); - } - } - class EditorWhitespace { - constructor(id, afterLineNumber, ordinal, height, minWidth) { - this.id = id; - this.afterLineNumber = afterLineNumber; - this.ordinal = ordinal; - this.height = height; - this.minWidth = minWidth; - this.prefixSum = 0; - } - } - 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). - */ - class LinesLayout { - constructor(lineCount, lineHeight, paddingTop, paddingBottom) { - 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; - this._paddingTop = paddingTop; - this._paddingBottom = paddingBottom; - } - /** - * 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. - */ - static findInsertionIndex(arr, afterLineNumber, ordinal) { - let low = 0; - let high = arr.length; - while (low < high) { - const 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. - */ - setLineHeight(lineHeight) { - this._checkPendingChanges(); - this._lineHeight = lineHeight; - } - /** - * Changes the padding used to calculate vertical offsets. - */ - setPadding(paddingTop, paddingBottom) { - this._paddingTop = paddingTop; - this._paddingBottom = paddingBottom; - } - /** - * Set the number of lines. - * - * @param lineCount New number of lines. - */ - onFlushed(lineCount) { - this._checkPendingChanges(); - this._lineCount = lineCount; - } - changeWhitespace(callback) { - let hadAChange = false; - try { - const accessor = { - insertWhitespace: (afterLineNumber, ordinal, heightInPx, minWidth) => { - hadAChange = true; - afterLineNumber = afterLineNumber | 0; - ordinal = ordinal | 0; - heightInPx = heightInPx | 0; - minWidth = minWidth | 0; - const id = this._instanceId + (++this._lastWhitespaceId); - this._pendingChanges.insert(new EditorWhitespace(id, afterLineNumber, ordinal, heightInPx, minWidth)); - return id; - }, - changeOneWhitespace: (id, newAfterLineNumber, newHeight) => { - hadAChange = true; - newAfterLineNumber = newAfterLineNumber | 0; - newHeight = newHeight | 0; - this._pendingChanges.change({ id, newAfterLineNumber, newHeight }); - }, - removeWhitespace: (id) => { - hadAChange = true; - this._pendingChanges.remove({ id }); - } - }; - callback(accessor); - } - finally { - this._pendingChanges.commit(this); - } - return hadAChange; - } - _commitPendingChanges(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 (const insert of inserts) { - this._insertWhitespace(insert); - } - for (const change of changes) { - this._changeOneWhitespace(change.id, change.newAfterLineNumber, change.newHeight); - } - for (const remove of removes) { - const index = this._findWhitespaceIndex(remove.id); - if (index === -1) { - continue; - } - this._removeWhitespace(index); - } - return; - } - // simply rebuild the entire datastructure - const toRemove = new Set(); - for (const remove of removes) { - toRemove.add(remove.id); - } - const toChange = new Map(); - for (const change of changes) { - toChange.set(change.id, change); - } - const applyRemoveAndChange = (whitespaces) => { - let result = []; - for (const whitespace of whitespaces) { - if (toRemove.has(whitespace.id)) { - continue; - } - if (toChange.has(whitespace.id)) { - const change = toChange.get(whitespace.id); - whitespace.afterLineNumber = change.newAfterLineNumber; - whitespace.height = change.newHeight; - } - result.push(whitespace); - } - return result; - }; - const result = applyRemoveAndChange(this._arr).concat(applyRemoveAndChange(inserts)); - result.sort((a, b) => { - if (a.afterLineNumber === b.afterLineNumber) { - return a.ordinal - b.ordinal; - } - return a.afterLineNumber - b.afterLineNumber; - }); - this._arr = result; - this._prefixSumValidIndex = -1; - } - _checkPendingChanges() { - if (this._pendingChanges.mustCommit()) { - this._pendingChanges.commit(this); - } - } - _insertWhitespace(whitespace) { - const insertIndex = LinesLayout.findInsertionIndex(this._arr, whitespace.afterLineNumber, whitespace.ordinal); - this._arr.splice(insertIndex, 0, whitespace); - this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, insertIndex - 1); - } - _findWhitespaceIndex(id) { - const arr = this._arr; - for (let i = 0, len = arr.length; i < len; i++) { - if (arr[i].id === id) { - return i; - } - } - return -1; - } - _changeOneWhitespace(id, newAfterLineNumber, newHeight) { - const 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 - const 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); - } - } - _removeWhitespace(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 - */ - onLinesDeleted(fromLineNumber, toLineNumber) { - this._checkPendingChanges(); - fromLineNumber = fromLineNumber | 0; - toLineNumber = toLineNumber | 0; - this._lineCount -= (toLineNumber - fromLineNumber + 1); - for (let i = 0, len = this._arr.length; i < len; i++) { - const 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. - */ - onLinesInserted(fromLineNumber, toLineNumber) { - this._checkPendingChanges(); - fromLineNumber = fromLineNumber | 0; - toLineNumber = toLineNumber | 0; - this._lineCount += (toLineNumber - fromLineNumber + 1); - for (let i = 0, len = this._arr.length; i < len; i++) { - const afterLineNumber = this._arr[i].afterLineNumber; - if (fromLineNumber <= afterLineNumber) { - this._arr[i].afterLineNumber += (toLineNumber - fromLineNumber + 1); - } - } - } - /** - * Get the sum of all the whitespaces. - */ - getWhitespacesTotalHeight() { - 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`. - */ - getWhitespacesAccumulatedHeight(index) { - this._checkPendingChanges(); - index = index | 0; - let startIndex = Math.max(0, this._prefixSumValidIndex + 1); - if (startIndex === 0) { - this._arr[0].prefixSum = this._arr[0].height; - startIndex++; - } - for (let 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. - */ - getLinesTotalHeight() { - this._checkPendingChanges(); - const linesHeight = this._lineHeight * this._lineCount; - const whitespacesHeight = this.getWhitespacesTotalHeight(); - return linesHeight + whitespacesHeight + this._paddingTop + this._paddingBottom; - } - /** - * Returns the accumulated height of whitespaces before the given line number. - * - * @param lineNumber The line number - */ - getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber) { - this._checkPendingChanges(); - lineNumber = lineNumber | 0; - const lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber); - if (lastWhitespaceBeforeLineNumber === -1) { - return 0; - } - return this.getWhitespacesAccumulatedHeight(lastWhitespaceBeforeLineNumber); - } - _findLastWhitespaceBeforeLineNumber(lineNumber) { - lineNumber = lineNumber | 0; - // Find the whitespace before line number - const arr = this._arr; - let low = 0; - let high = arr.length - 1; - while (low <= high) { - const delta = (high - low) | 0; - const halfDelta = (delta / 2) | 0; - const 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; - } - _findFirstWhitespaceAfterLineNumber(lineNumber) { - lineNumber = lineNumber | 0; - const lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber); - const 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. - */ - getFirstWhitespaceIndexAfterLineNumber(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`. - */ - getVerticalOffsetForLineNumber(lineNumber) { - this._checkPendingChanges(); - lineNumber = lineNumber | 0; - let previousLinesHeight; - if (lineNumber > 1) { - previousLinesHeight = this._lineHeight * (lineNumber - 1); - } - else { - previousLinesHeight = 0; - } - const previousWhitespacesHeight = this.getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber); - return previousLinesHeight + previousWhitespacesHeight + this._paddingTop; - } - /** - * The maximum min width for all whitespaces. - */ - getWhitespaceMinWidth() { - this._checkPendingChanges(); - if (this._minWidth === -1) { - let minWidth = 0; - for (let 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. - */ - isAfterLines(verticalOffset) { - this._checkPendingChanges(); - const totalHeight = this.getLinesTotalHeight(); - return verticalOffset > totalHeight; - } - isInTopPadding(verticalOffset) { - if (this._paddingTop === 0) { - return false; - } - this._checkPendingChanges(); - return (verticalOffset < this._paddingTop); - } - isInBottomPadding(verticalOffset) { - if (this._paddingBottom === 0) { - return false; - } - this._checkPendingChanges(); - const totalHeight = this.getLinesTotalHeight(); - return (verticalOffset >= totalHeight - this._paddingBottom); - } - /** - * 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`. - */ - getLineNumberAtOrAfterVerticalOffset(verticalOffset) { - this._checkPendingChanges(); - verticalOffset = verticalOffset | 0; - if (verticalOffset < 0) { - return 1; - } - const linesCount = this._lineCount | 0; - const lineHeight = this._lineHeight; - let minLineNumber = 1; - let maxLineNumber = linesCount; - while (minLineNumber < maxLineNumber) { - const midLineNumber = ((minLineNumber + maxLineNumber) / 2) | 0; - const 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`. - */ - getLinesViewportData(verticalOffset1, verticalOffset2) { - this._checkPendingChanges(); - verticalOffset1 = verticalOffset1 | 0; - verticalOffset2 = verticalOffset2 | 0; - const 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 - const startLineNumber = this.getLineNumberAtOrAfterVerticalOffset(verticalOffset1) | 0; - const startLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(startLineNumber) | 0; - let endLineNumber = this._lineCount | 0; - // Also keep track of what whitespace we've got - let whitespaceIndex = this.getFirstWhitespaceIndexAfterLineNumber(startLineNumber) | 0; - const whitespaceCount = this.getWhitespacesCount() | 0; - let currentWhitespaceHeight; - let currentWhitespaceAfterLineNumber; - if (whitespaceIndex === -1) { - whitespaceIndex = whitespaceCount; - currentWhitespaceAfterLineNumber = endLineNumber + 1; - currentWhitespaceHeight = 0; - } - else { - currentWhitespaceAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0; - currentWhitespaceHeight = this.getHeightForWhitespaceIndex(whitespaceIndex) | 0; - } - let currentVerticalOffset = startLineNumberVerticalOffset; - let currentLineRelativeOffset = currentVerticalOffset; - // IE (all versions) cannot handle units above about 1,533,908 px, so every 500k pixels bring numbers down - const STEP_SIZE = 500000; - let 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; - } - const linesOffsets = []; - const verticalCenter = verticalOffset1 + (verticalOffset2 - verticalOffset1) / 2; - let centeredLineNumber = -1; - // Figure out how far the lines go - for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { - if (centeredLineNumber === -1) { - const currentLineTop = currentVerticalOffset; - const 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; - } - const endLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(endLineNumber) | 0; - let completelyVisibleStartLineNumber = startLineNumber; - let 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 - }; - } - getVerticalOffsetForWhitespaceIndex(whitespaceIndex) { - this._checkPendingChanges(); - whitespaceIndex = whitespaceIndex | 0; - const afterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex); - let previousLinesHeight; - if (afterLineNumber >= 1) { - previousLinesHeight = this._lineHeight * afterLineNumber; - } - else { - previousLinesHeight = 0; - } - let previousWhitespacesHeight; - if (whitespaceIndex > 0) { - previousWhitespacesHeight = this.getWhitespacesAccumulatedHeight(whitespaceIndex - 1); - } - else { - previousWhitespacesHeight = 0; - } - return previousLinesHeight + previousWhitespacesHeight + this._paddingTop; - } - getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset) { - this._checkPendingChanges(); - verticalOffset = verticalOffset | 0; - let minWhitespaceIndex = 0; - let maxWhitespaceIndex = this.getWhitespacesCount() - 1; - if (maxWhitespaceIndex < 0) { - return -1; - } - // Special case: nothing to be found - const maxWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(maxWhitespaceIndex); - const maxWhitespaceHeight = this.getHeightForWhitespaceIndex(maxWhitespaceIndex); - if (verticalOffset >= maxWhitespaceVerticalOffset + maxWhitespaceHeight) { - return -1; - } - while (minWhitespaceIndex < maxWhitespaceIndex) { - const midWhitespaceIndex = Math.floor((minWhitespaceIndex + maxWhitespaceIndex) / 2); - const midWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(midWhitespaceIndex); - const 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. - */ - getWhitespaceAtVerticalOffset(verticalOffset) { - this._checkPendingChanges(); - verticalOffset = verticalOffset | 0; - const candidateIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset); - if (candidateIndex < 0) { - return null; - } - if (candidateIndex >= this.getWhitespacesCount()) { - return null; - } - const candidateTop = this.getVerticalOffsetForWhitespaceIndex(candidateIndex); - if (candidateTop > verticalOffset) { - return null; - } - const candidateHeight = this.getHeightForWhitespaceIndex(candidateIndex); - const candidateId = this.getIdForWhitespaceIndex(candidateIndex); - const 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. - */ - getWhitespaceViewportData(verticalOffset1, verticalOffset2) { - this._checkPendingChanges(); - verticalOffset1 = verticalOffset1 | 0; - verticalOffset2 = verticalOffset2 | 0; - const startIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset1); - const endIndex = this.getWhitespacesCount() - 1; - if (startIndex < 0) { - return []; - } - let result = []; - for (let i = startIndex; i <= endIndex; i++) { - const top = this.getVerticalOffsetForWhitespaceIndex(i); - const height = this.getHeightForWhitespaceIndex(i); - if (top >= verticalOffset2) { - break; - } - result.push({ - id: this.getIdForWhitespaceIndex(i), - afterLineNumber: this.getAfterLineNumberForWhitespaceIndex(i), - verticalOffset: top, - height: height - }); - } - return result; - } - /** - * Get all whitespaces. - */ - getWhitespaces() { - this._checkPendingChanges(); - return this._arr.slice(0); - } - /** - * The number of whitespaces. - */ - getWhitespacesCount() { - 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`. - */ - getIdForWhitespaceIndex(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`. - */ - getAfterLineNumberForWhitespaceIndex(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`. - */ - getHeightForWhitespaceIndex(index) { - this._checkPendingChanges(); - index = index | 0; - return this._arr[index].height; - } - } - exports.LinesLayout = LinesLayout; - LinesLayout.INSTANCE_COUNT = 0; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[114/*vs/editor/common/viewLayout/viewLineRenderer*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,83/*vs/editor/common/core/stringBuilder*/,136/*vs/editor/common/viewLayout/lineDecorations*/]), function (require, exports, strings, stringBuilder_1, lineDecorations_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.renderViewLine2 = exports.RenderLineOutput2 = exports.renderViewLine = exports.RenderLineOutput = exports.CharacterMapping = exports.DomPosition = exports.RenderLineInput = exports.LineRange = void 0; - class LinePart { - constructor(endIndex, type, metadata) { - this._linePartBrand = undefined; - this.endIndex = endIndex; - this.type = type; - this.metadata = metadata; - } - isWhitespace() { - return (this.metadata & 1 /* IS_WHITESPACE_MASK */ ? true : false); - } - isPseudoAfter() { - return (this.metadata & 4 /* PSEUDO_AFTER_MASK */ ? true : false); - } - } - class LineRange { - constructor(startIndex, endIndex) { - this.startOffset = startIndex; - this.endOffset = endIndex; - } - equals(otherLineRange) { - return this.startOffset === otherLineRange.startOffset - && this.endOffset === otherLineRange.endOffset; - } - } - exports.LineRange = LineRange; - class RenderLineInput { - constructor(useMonospaceOptimizations, canUseHalfwidthRightwardsArrow, lineContent, continuesWithWrappedLine, isBasicASCII, containsRTL, fauxIndentLength, lineTokens, lineDecorations, tabSize, startVisibleColumn, spaceWidth, middotWidth, wsmiddotWidth, 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.sort(lineDecorations_1.LineDecoration.compare); - this.tabSize = tabSize; - this.startVisibleColumn = startVisibleColumn; - this.spaceWidth = spaceWidth; - this.stopRenderingLineAfter = stopRenderingLineAfter; - this.renderWhitespace = (renderWhitespace === 'all' - ? 4 /* All */ - : renderWhitespace === 'boundary' - ? 1 /* Boundary */ - : renderWhitespace === 'selection' - ? 2 /* Selection */ - : renderWhitespace === 'trailing' - ? 3 /* Trailing */ - : 0 /* None */); - this.renderControlCharacters = renderControlCharacters; - this.fontLigatures = fontLigatures; - this.selectionsOnLine = selectionsOnLine && selectionsOnLine.sort((a, b) => a.startOffset < b.startOffset ? -1 : 1); - const wsmiddotDiff = Math.abs(wsmiddotWidth - spaceWidth); - const middotDiff = Math.abs(middotWidth - spaceWidth); - if (wsmiddotDiff < middotDiff) { - this.renderSpaceWidth = wsmiddotWidth; - this.renderSpaceCharCode = 0x2E31; // U+2E31 - WORD SEPARATOR MIDDLE DOT - } - else { - this.renderSpaceWidth = middotWidth; - this.renderSpaceCharCode = 0xB7; // U+00B7 - MIDDLE DOT - } - } - sameSelection(otherSelections) { - if (this.selectionsOnLine === null) { - return otherSelections === null; - } - if (otherSelections === null) { - return false; - } - if (otherSelections.length !== this.selectionsOnLine.length) { - return false; - } - for (let i = 0; i < this.selectionsOnLine.length; i++) { - if (!this.selectionsOnLine[i].equals(otherSelections[i])) { - return false; - } - } - return true; - } - equals(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.renderSpaceWidth === other.renderSpaceWidth - && this.renderSpaceCharCode === other.renderSpaceCharCode - && 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)); - } - } - exports.RenderLineInput = RenderLineInput; - class DomPosition { - constructor(partIndex, charIndex) { - this.partIndex = partIndex; - this.charIndex = charIndex; - } - } - exports.DomPosition = DomPosition; - /** - * Provides a both direction mapping between a line's character and its rendered position. - */ - class CharacterMapping { - constructor(length, partCount) { - this.length = length; - this._data = new Uint32Array(this.length); - this._absoluteOffsets = new Uint32Array(this.length); - } - static getPartIndex(partData) { - return (partData & 4294901760 /* PART_INDEX_MASK */) >>> 16 /* PART_INDEX_OFFSET */; - } - static getCharIndex(partData) { - return (partData & 65535 /* CHAR_INDEX_MASK */) >>> 0 /* CHAR_INDEX_OFFSET */; - } - setColumnInfo(column, partIndex, charIndex, partAbsoluteOffset) { - const partData = ((partIndex << 16 /* PART_INDEX_OFFSET */) - | (charIndex << 0 /* CHAR_INDEX_OFFSET */)) >>> 0; - this._data[column - 1] = partData; - this._absoluteOffsets[column - 1] = partAbsoluteOffset + charIndex; - } - getAbsoluteOffset(column) { - if (this._absoluteOffsets.length === 0) { - // No characters on this line - return 0; - } - return this._absoluteOffsets[column - 1]; - } - charOffsetToPartData(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]; - } - getDomPosition(column) { - const partData = this.charOffsetToPartData(column - 1); - const partIndex = CharacterMapping.getPartIndex(partData); - const charIndex = CharacterMapping.getCharIndex(partData); - return new DomPosition(partIndex, charIndex); - } - getColumn(domPosition, partLength) { - const charOffset = this.partDataToCharOffset(domPosition.partIndex, partLength, domPosition.charIndex); - return charOffset + 1; - } - partDataToCharOffset(partIndex, partLength, charIndex) { - if (this.length === 0) { - return 0; - } - let searchEntry = ((partIndex << 16 /* PART_INDEX_OFFSET */) - | (charIndex << 0 /* CHAR_INDEX_OFFSET */)) >>> 0; - let min = 0; - let max = this.length - 1; - while (min + 1 < max) { - let mid = ((min + max) >>> 1); - let midEntry = this._data[mid]; - if (midEntry === searchEntry) { - return mid; - } - else if (midEntry > searchEntry) { - max = mid; - } - else { - min = mid; - } - } - if (min === max) { - return min; - } - let minEntry = this._data[min]; - let maxEntry = this._data[max]; - if (minEntry === searchEntry) { - return min; - } - if (maxEntry === searchEntry) { - return max; - } - let minPartIndex = CharacterMapping.getPartIndex(minEntry); - let minCharIndex = CharacterMapping.getCharIndex(minEntry); - let maxPartIndex = CharacterMapping.getPartIndex(maxEntry); - let maxCharIndex; - if (minPartIndex !== maxPartIndex) { - // sitting between parts - maxCharIndex = partLength; - } - else { - maxCharIndex = CharacterMapping.getCharIndex(maxEntry); - } - let minEntryDistance = charIndex - minCharIndex; - let maxEntryDistance = maxCharIndex - charIndex; - if (minEntryDistance <= maxEntryDistance) { - return min; - } - return max; - } - } - exports.CharacterMapping = CharacterMapping; - class RenderLineOutput { - constructor(characterMapping, containsRTL, containsForeignElements) { - this._renderLineOutputBrand = undefined; - this.characterMapping = characterMapping; - this.containsRTL = containsRTL; - this.containsForeignElements = containsForeignElements; - } - } - exports.RenderLineOutput = RenderLineOutput; - function renderViewLine(input, sb) { - if (input.lineContent.length === 0) { - if (input.lineDecorations.length > 0) { - // This line is empty, but it contains inline decorations - sb.appendASCIIString(``); - let beforeCount = 0; - let afterCount = 0; - let containsForeignElements = 0 /* None */; - for (const lineDecoration of input.lineDecorations) { - if (lineDecoration.type === 1 /* Before */ || lineDecoration.type === 2 /* After */) { - sb.appendASCIIString(``); - if (lineDecoration.type === 1 /* Before */) { - containsForeignElements |= 1 /* Before */; - beforeCount++; - } - if (lineDecoration.type === 2 /* After */) { - containsForeignElements |= 2 /* After */; - afterCount++; - } - } - } - sb.appendASCIIString(``); - const characterMapping = new CharacterMapping(1, beforeCount + afterCount); - characterMapping.setColumnInfo(1, beforeCount, 0, 0); - return new RenderLineOutput(characterMapping, false, containsForeignElements); - } - // completely empty line - sb.appendASCIIString(''); - return new RenderLineOutput(new CharacterMapping(0, 0), false, 0 /* None */); - } - return _renderLine(resolveRenderLineInput(input), sb); - } - exports.renderViewLine = renderViewLine; - class RenderLineOutput2 { - constructor(characterMapping, html, containsRTL, containsForeignElements) { - this.characterMapping = characterMapping; - this.html = html; - this.containsRTL = containsRTL; - this.containsForeignElements = containsForeignElements; - } - } - exports.RenderLineOutput2 = RenderLineOutput2; - function renderViewLine2(input) { - let sb = (0, stringBuilder_1.createStringBuilder)(10000); - let out = renderViewLine(input, sb); - return new RenderLineOutput2(out.characterMapping, sb.build(), out.containsRTL, out.containsForeignElements); - } - exports.renderViewLine2 = renderViewLine2; - class ResolvedRenderLineInput { - constructor(fontIsMonospace, canUseHalfwidthRightwardsArrow, lineContent, len, isOverflowing, parts, containsForeignElements, fauxIndentLength, tabSize, startVisibleColumn, containsRTL, spaceWidth, renderSpaceCharCode, 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.renderSpaceCharCode = renderSpaceCharCode; - this.renderWhitespace = renderWhitespace; - this.renderControlCharacters = renderControlCharacters; - // - } - } - function resolveRenderLineInput(input) { - const lineContent = input.lineContent; - let isOverflowing; - let len; - if (input.stopRenderingLineAfter !== -1 && input.stopRenderingLineAfter < lineContent.length) { - isOverflowing = true; - len = input.stopRenderingLineAfter; - } - else { - isOverflowing = false; - len = lineContent.length; - } - let tokens = transformAndRemoveOverflowing(input.lineTokens, input.fauxIndentLength, len); - if (input.renderWhitespace === 4 /* All */ || - input.renderWhitespace === 1 /* Boundary */ || - (input.renderWhitespace === 2 /* Selection */ && !!input.selectionsOnLine) || - input.renderWhitespace === 3 /* Trailing */) { - tokens = _applyRenderWhitespace(input, lineContent, len, tokens); - } - let containsForeignElements = 0 /* None */; - if (input.lineDecorations.length > 0) { - for (let i = 0, len = input.lineDecorations.length; i < len; i++) { - const 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(input.useMonospaceOptimizations, input.canUseHalfwidthRightwardsArrow, lineContent, len, isOverflowing, tokens, containsForeignElements, input.fauxIndentLength, input.tabSize, input.startVisibleColumn, input.containsRTL, input.spaceWidth, input.renderSpaceCharCode, 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) { - let result = [], resultLen = 0; - // The faux indent part of the line should have no token type - if (fauxIndentLength > 0) { - result[resultLen++] = new LinePart(fauxIndentLength, '', 0); - } - for (let tokenIndex = 0, tokensLen = tokens.getCount(); tokenIndex < tokensLen; tokenIndex++) { - const endIndex = tokens.getEndOffset(tokenIndex); - if (endIndex <= fauxIndentLength) { - // The faux indent part of the line should have no token type - continue; - } - const type = tokens.getClassName(tokenIndex); - if (endIndex >= len) { - result[resultLen++] = new LinePart(len, type, 0); - break; - } - result[resultLen++] = new LinePart(endIndex, type, 0); - } - 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) { - let lastTokenEndIndex = 0; - let result = [], resultLen = 0; - if (onlyAtSpaces) { - // Split only at spaces => we need to walk each character - for (let i = 0, len = tokens.length; i < len; i++) { - const token = tokens[i]; - const tokenEndIndex = token.endIndex; - if (lastTokenEndIndex + 50 /* LongToken */ < tokenEndIndex) { - const tokenType = token.type; - const tokenMetadata = token.metadata; - let lastSpaceOffset = -1; - let currTokenStart = lastTokenEndIndex; - for (let 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, tokenMetadata); - currTokenStart = lastSpaceOffset + 1; - lastSpaceOffset = -1; - } - } - if (currTokenStart !== tokenEndIndex) { - result[resultLen++] = new LinePart(tokenEndIndex, tokenType, tokenMetadata); - } - } - else { - result[resultLen++] = token; - } - lastTokenEndIndex = tokenEndIndex; - } - } - else { - // Split anywhere => we don't need to walk each character - for (let i = 0, len = tokens.length; i < len; i++) { - const token = tokens[i]; - const tokenEndIndex = token.endIndex; - let diff = (tokenEndIndex - lastTokenEndIndex); - if (diff > 50 /* LongToken */) { - const tokenType = token.type; - const tokenMetadata = token.metadata; - const piecesCount = Math.ceil(diff / 50 /* LongToken */); - for (let j = 1; j < piecesCount; j++) { - let pieceEndIndex = lastTokenEndIndex + (j * 50 /* LongToken */); - result[resultLen++] = new LinePart(pieceEndIndex, tokenType, tokenMetadata); - } - result[resultLen++] = new LinePart(tokenEndIndex, tokenType, tokenMetadata); - } - else { - result[resultLen++] = token; - } - lastTokenEndIndex = tokenEndIndex; - } - } - return result; - } - /** - * Whitespace is rendered by "replacing" tokens with a special-purpose `mtkw` 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(input, lineContent, len, tokens) { - const continuesWithWrappedLine = input.continuesWithWrappedLine; - const fauxIndentLength = input.fauxIndentLength; - const tabSize = input.tabSize; - const startVisibleColumn = input.startVisibleColumn; - const useMonospaceOptimizations = input.useMonospaceOptimizations; - const selections = input.selectionsOnLine; - const onlyBoundary = (input.renderWhitespace === 1 /* Boundary */); - const onlyTrailing = (input.renderWhitespace === 3 /* Trailing */); - const generateLinePartForEachWhitespace = (input.renderSpaceWidth !== input.spaceWidth); - let result = [], resultLen = 0; - let tokenIndex = 0; - let tokenType = tokens[tokenIndex].type; - let tokenEndIndex = tokens[tokenIndex].endIndex; - const tokensLength = tokens.length; - let lineIsEmptyOrWhitespace = false; - let firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent); - let lastNonWhitespaceIndex; - if (firstNonWhitespaceIndex === -1) { - lineIsEmptyOrWhitespace = true; - firstNonWhitespaceIndex = len; - lastNonWhitespaceIndex = len; - } - else { - lastNonWhitespaceIndex = strings.lastNonWhitespaceIndex(lineContent); - } - let wasInWhitespace = false; - let currentSelectionIndex = 0; - let currentSelection = selections && selections[currentSelectionIndex]; - let tmpIndent = startVisibleColumn % tabSize; - for (let charIndex = fauxIndentLength; charIndex < len; charIndex++) { - const chCode = lineContent.charCodeAt(charIndex); - if (currentSelection && charIndex >= currentSelection.endOffset) { - currentSelectionIndex++; - currentSelection = selections && selections[currentSelectionIndex]; - } - let isInWhitespace; - 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 { - const 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 rendering only trailing whitespace, check that the charIndex points to trailing whitespace. - if (isInWhitespace && onlyTrailing) { - isInWhitespace = lineIsEmptyOrWhitespace || charIndex > lastNonWhitespaceIndex; - } - if (wasInWhitespace) { - // was in whitespace token - if (!isInWhitespace || (!useMonospaceOptimizations && tmpIndent >= tabSize)) { - // leaving whitespace token or entering a new indent - if (generateLinePartForEachWhitespace) { - const lastEndIndex = (resultLen > 0 ? result[resultLen - 1].endIndex : fauxIndentLength); - for (let i = lastEndIndex + 1; i <= charIndex; i++) { - result[resultLen++] = new LinePart(i, 'mtkw', 1 /* IS_WHITESPACE */); - } - } - else { - result[resultLen++] = new LinePart(charIndex, 'mtkw', 1 /* IS_WHITESPACE */); - } - tmpIndent = tmpIndent % tabSize; - } - } - else { - // was in regular token - if (charIndex === tokenEndIndex || (isInWhitespace && charIndex > fauxIndentLength)) { - result[resultLen++] = new LinePart(charIndex, tokenType, 0); - tmpIndent = tmpIndent % tabSize; - } - } - if (chCode === 9 /* Tab */) { - tmpIndent = tabSize; - } - else if (strings.isFullWidthCharacter(chCode)) { - tmpIndent += 2; - } - else { - tmpIndent++; - } - wasInWhitespace = isInWhitespace; - while (charIndex === tokenEndIndex) { - tokenIndex++; - if (tokenIndex < tokensLength) { - tokenType = tokens[tokenIndex].type; - tokenEndIndex = tokens[tokenIndex].endIndex; - } - else { - break; - } - } - } - let generateWhitespace = false; - if (wasInWhitespace) { - // was in whitespace token - if (continuesWithWrappedLine && onlyBoundary) { - let lastCharCode = (len > 0 ? lineContent.charCodeAt(len - 1) : 0 /* Null */); - let prevCharCode = (len > 1 ? lineContent.charCodeAt(len - 2) : 0 /* Null */); - let isSingleTrailingSpace = (lastCharCode === 32 /* Space */ && (prevCharCode !== 32 /* Space */ && prevCharCode !== 9 /* Tab */)); - if (!isSingleTrailingSpace) { - generateWhitespace = true; - } - } - else { - generateWhitespace = true; - } - } - if (generateWhitespace) { - if (generateLinePartForEachWhitespace) { - const lastEndIndex = (resultLen > 0 ? result[resultLen - 1].endIndex : fauxIndentLength); - for (let i = lastEndIndex + 1; i <= len; i++) { - result[resultLen++] = new LinePart(i, 'mtkw', 1 /* IS_WHITESPACE */); - } - } - else { - result[resultLen++] = new LinePart(len, 'mtkw', 1 /* IS_WHITESPACE */); - } - } - else { - result[resultLen++] = new LinePart(len, tokenType, 0); - } - 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); - const lineDecorations = lineDecorations_1.LineDecorationsNormalizer.normalize(lineContent, _lineDecorations); - const lineDecorationsLen = lineDecorations.length; - let lineDecorationIndex = 0; - let result = [], resultLen = 0, lastResultEndIndex = 0; - for (let tokenIndex = 0, len = tokens.length; tokenIndex < len; tokenIndex++) { - const token = tokens[tokenIndex]; - const tokenEndIndex = token.endIndex; - const tokenType = token.type; - const tokenMetadata = token.metadata; - while (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset < tokenEndIndex) { - const lineDecoration = lineDecorations[lineDecorationIndex]; - if (lineDecoration.startOffset > lastResultEndIndex) { - lastResultEndIndex = lineDecoration.startOffset; - result[resultLen++] = new LinePart(lastResultEndIndex, tokenType, tokenMetadata); - } - 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, tokenMetadata | lineDecoration.metadata); - lineDecorationIndex++; - } - else { - // This line decoration continues on to the next token - lastResultEndIndex = tokenEndIndex; - result[resultLen++] = new LinePart(lastResultEndIndex, tokenType + ' ' + lineDecoration.className, tokenMetadata | lineDecoration.metadata); - break; - } - } - if (tokenEndIndex > lastResultEndIndex) { - lastResultEndIndex = tokenEndIndex; - result[resultLen++] = new LinePart(lastResultEndIndex, tokenType, tokenMetadata); - } - } - const lastTokenEndIndex = tokens[tokens.length - 1].endIndex; - if (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset === lastTokenEndIndex) { - while (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset === lastTokenEndIndex) { - const lineDecoration = lineDecorations[lineDecorationIndex]; - result[resultLen++] = new LinePart(lastResultEndIndex, lineDecoration.className, lineDecoration.metadata); - lineDecorationIndex++; - } - } - 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) { - const fontIsMonospace = input.fontIsMonospace; - const canUseHalfwidthRightwardsArrow = input.canUseHalfwidthRightwardsArrow; - const containsForeignElements = input.containsForeignElements; - const lineContent = input.lineContent; - const len = input.len; - const isOverflowing = input.isOverflowing; - const parts = input.parts; - const fauxIndentLength = input.fauxIndentLength; - const tabSize = input.tabSize; - const startVisibleColumn = input.startVisibleColumn; - const containsRTL = input.containsRTL; - const spaceWidth = input.spaceWidth; - const renderSpaceCharCode = input.renderSpaceCharCode; - const renderWhitespace = input.renderWhitespace; - const renderControlCharacters = input.renderControlCharacters; - const characterMapping = new CharacterMapping(len + 1, parts.length); - let lastCharacterMappingDefined = false; - let charIndex = 0; - let visibleColumn = startVisibleColumn; - let charOffsetInPart = 0; - let partDisplacement = 0; - let prevPartContentCnt = 0; - let partAbsoluteOffset = 0; - if (containsRTL) { - sb.appendASCIIString(''); - } - else { - sb.appendASCIIString(''); - } - for (let partIndex = 0, tokensLen = parts.length; partIndex < tokensLen; partIndex++) { - partAbsoluteOffset += prevPartContentCnt; - const part = parts[partIndex]; - const partEndIndex = part.endIndex; - const partType = part.type; - const partRendersWhitespace = (renderWhitespace !== 0 /* None */ && part.isWhitespace()); - const partRendersWhitespaceWithWidth = partRendersWhitespace && !fontIsMonospace && (partType === 'mtkw' /*only whitespace*/ || !containsForeignElements); - const partIsEmptyAndHasPseudoAfter = (charIndex === partEndIndex && part.isPseudoAfter()); - charOffsetInPart = 0; - sb.appendASCIIString(' 1) { - sb.write1(0x2192); // RIGHTWARDS ARROW - } - else { - sb.write1(0xFFEB); // HALFWIDTH RIGHTWARDS ARROW - } - for (let space = 2; space <= charWidth; space++) { - sb.write1(0xA0); //   - } - } - else { // must be CharCode.Space - charWidth = 1; - sb.write1(renderSpaceCharCode); // · or word separator middle dot - } - charOffsetInPart += charWidth; - if (charIndex >= fauxIndentLength) { - visibleColumn += charWidth; - } - } - prevPartContentCnt = partContentCnt; - } - else { - let partContentCnt = 0; - sb.appendASCII(62 /* GreaterThan */); - for (; charIndex < partEndIndex; charIndex++) { - characterMapping.setColumnInfo(charIndex + 1, partIndex - partDisplacement, charOffsetInPart, partAbsoluteOffset); - partDisplacement = 0; - const charCode = lineContent.charCodeAt(charIndex); - let producedCharacters = 1; - let charWidth = 1; - switch (charCode) { - case 9 /* Tab */: - producedCharacters = (tabSize - (visibleColumn % tabSize)); - charWidth = producedCharacters; - for (let 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 */: - if (renderControlCharacters) { - // See https://unicode-table.com/en/blocks/control-pictures/ - sb.write1(9216); - } - else { - sb.appendASCIIString('�'); - } - break; - case 65279 /* UTF8_BOM */: - case 8232 /* LINE_SEPARATOR */: - case 8233 /* PARAGRAPH_SEPARATOR */: - case 133 /* NEXT_LINE */: - sb.write1(0xFFFD); - break; - default: - if (strings.isFullWidthCharacter(charCode)) { - charWidth++; - } - // See https://unicode-table.com/en/blocks/control-pictures/ - if (renderControlCharacters && charCode < 32) { - sb.write1(9216 + charCode); - } - else if (renderControlCharacters && charCode === 127) { - // DEL - sb.write1(9249); - } - else { - sb.write1(charCode); - } - } - charOffsetInPart += producedCharacters; - partContentCnt += producedCharacters; - if (charIndex >= fauxIndentLength) { - visibleColumn += charWidth; - } - } - prevPartContentCnt = partContentCnt; - } - if (partIsEmptyAndHasPseudoAfter) { - partDisplacement++; - } - else { - partDisplacement = 0; - } - if (charIndex >= len && !lastCharacterMappingDefined && part.isPseudoAfter()) { - lastCharacterMappingDefined = true; - characterMapping.setColumnInfo(charIndex + 1, partIndex, charOffsetInPart, partAbsoluteOffset); - } - sb.appendASCIIString(''); - } - if (!lastCharacterMappingDefined) { - // 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.setColumnInfo(len + 1, 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[395/*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 }); - exports.ViewportData = void 0; - /** - * Contains all data needed to render at a specific viewport. - */ - class ViewportData { - constructor(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)); - } - getViewLineRenderingData(lineNumber) { - return this._model.getViewLineRenderingData(this.visibleRange, lineNumber); - } - getDecorationsInViewport() { - return this._model.getDecorationsInViewport(this.visibleRange); - } - } - 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[224/*vs/editor/common/viewModel/prefixSumComputer*/], __M([0/*require*/,1/*exports*/,129/*vs/base/common/uint*/]), function (require, exports, uint_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.PrefixSumComputer = exports.PrefixSumIndexOfResult = void 0; - class PrefixSumIndexOfResult { - constructor(index, remainder) { - this._prefixSumIndexOfResultBrand = undefined; - this.index = index; - this.remainder = remainder; - } - } - exports.PrefixSumIndexOfResult = PrefixSumIndexOfResult; - class PrefixSumComputer { - constructor(values) { - this.values = values; - this.prefixSum = new Uint32Array(values.length); - this.prefixSumValidIndex = new Int32Array(1); - this.prefixSumValidIndex[0] = -1; - } - insertValues(insertIndex, insertValues) { - insertIndex = (0, uint_1.toUint32)(insertIndex); - const oldValues = this.values; - const oldPrefixSum = this.prefixSum; - const 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; - } - changeValue(index, value) { - index = (0, uint_1.toUint32)(index); - value = (0, 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; - } - removeValues(startIndex, count) { - startIndex = (0, uint_1.toUint32)(startIndex); - count = (0, uint_1.toUint32)(count); - const oldValues = this.values; - const oldPrefixSum = this.prefixSum; - if (startIndex >= oldValues.length) { - return false; - } - let maxCount = oldValues.length - startIndex; - if (count >= maxCount) { - count = maxCount; - } - if (count === 0) { - return false; - } - this.values = new Uint32Array(oldValues.length - count); - this.values.set(oldValues.subarray(0, startIndex), 0); - this.values.set(oldValues.subarray(startIndex + count), 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; - } - getTotalSum() { - if (this.values.length === 0) { - return 0; - } - return this._getPrefixSum(this.values.length - 1); - } - getPrefixSum(index) { - if (index < 0) { - return 0; - } - index = (0, uint_1.toUint32)(index); - return this._getPrefixSum(index); - } - _getPrefixSum(index) { - if (index <= this.prefixSumValidIndex[0]) { - return this.prefixSum[index]; - } - let 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 (let 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]; - } - getIndexOf(sum) { - sum = Math.floor(sum); //@perf - // Compute all sums (to get a fully valid prefixSum) - this.getTotalSum(); - let low = 0; - let high = this.values.length - 1; - let mid = 0; - let midStop = 0; - let midStart = 0; - while (low <= high) { - mid = low + ((high - low) / 2) | 0; - midStop = this.prefixSum[mid]; - midStart = midStop - this.values[mid]; - if (sum < midStart) { - high = mid - 1; - } - else if (sum >= midStop) { - low = mid + 1; - } - else { - break; - } - } - return new PrefixSumIndexOfResult(mid, sum - midStart); - } - } - 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[396/*vs/editor/common/model/mirrorTextModel*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,13/*vs/editor/common/core/position*/,224/*vs/editor/common/viewModel/prefixSumComputer*/]), function (require, exports, strings_1, position_1, prefixSumComputer_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MirrorTextModel = void 0; - class MirrorTextModel { - constructor(uri, lines, eol, versionId) { - this._uri = uri; - this._lines = lines; - this._eol = eol; - this._versionId = versionId; - this._lineStarts = null; - this._cachedTextValue = null; - } - dispose() { - this._lines.length = 0; - } - get version() { - return this._versionId; - } - getText() { - if (this._cachedTextValue === null) { - this._cachedTextValue = this._lines.join(this._eol); - } - return this._cachedTextValue; - } - onEvents(e) { - if (e.eol && e.eol !== this._eol) { - this._eol = e.eol; - this._lineStarts = null; - } - // Update my lines - const changes = e.changes; - for (const change of changes) { - this._acceptDeleteRange(change.range); - this._acceptInsertText(new position_1.Position(change.range.startLineNumber, change.range.startColumn), change.text); - } - this._versionId = e.versionId; - this._cachedTextValue = null; - } - _ensureLineStarts() { - if (!this._lineStarts) { - const eolLength = this._eol.length; - const linesLength = this._lines.length; - const lineStartValues = new Uint32Array(linesLength); - for (let 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 - */ - _setLineText(lineIndex, newValue) { - this._lines[lineIndex] = newValue; - if (this._lineStarts) { - // update prefix sum - this._lineStarts.changeValue(lineIndex, this._lines[lineIndex].length + this._eol.length); - } - } - _acceptDeleteRange(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); - } - } - _acceptInsertText(position, insertText) { - if (insertText.length === 0) { - // Nothing to insert - return; - } - let insertLines = (0, strings_1.splitLines)(insertText); - 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 - let newLengths = new Uint32Array(insertLines.length - 1); - for (let 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); - } - } - } - 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[397/*vs/editor/common/services/editorSimpleWorker*/], __M([0/*require*/,1/*exports*/,128/*vs/base/common/diff/diff*/,17/*vs/base/common/platform*/,24/*vs/base/common/uri*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,377/*vs/editor/common/diff/diffComputer*/,396/*vs/editor/common/model/mirrorTextModel*/,135/*vs/editor/common/model/wordHelper*/,383/*vs/editor/common/modes/linkComputer*/,386/*vs/editor/common/modes/supports/inplaceReplaceSupport*/,222/*vs/editor/common/standalone/standaloneBase*/,20/*vs/base/common/types*/,81/*vs/base/common/stopwatch*/]), function (require, exports, diff_1, platform_1, uri_1, position_1, range_1, diffComputer_1, mirrorTextModel_1, wordHelper_1, linkComputer_1, inplaceReplaceSupport_1, standaloneBase_1, types, stopwatch_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.create = exports.EditorSimpleWorker = void 0; - /** - * @internal - */ - class MirrorModel extends mirrorTextModel_1.MirrorTextModel { - get uri() { - return this._uri; - } - get eol() { - return this._eol; - } - getValue() { - return this.getText(); - } - getLinesContent() { - return this._lines.slice(0); - } - getLineCount() { - return this._lines.length; - } - getLineContent(lineNumber) { - return this._lines[lineNumber - 1]; - } - getWordAtPosition(position, wordDefinition) { - let wordAtText = (0, wordHelper_1.getWordAtText)(position.column, (0, 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; - } - words(wordDefinition) { - const lines = this._lines; - const wordenize = this._wordenize.bind(this); - let lineNumber = 0; - let lineText = ''; - let wordRangesIdx = 0; - let wordRanges = []; - return { - *[Symbol.iterator]() { - while (true) { - if (wordRangesIdx < wordRanges.length) { - const value = lineText.substring(wordRanges[wordRangesIdx].start, wordRanges[wordRangesIdx].end); - wordRangesIdx += 1; - yield value; - } - else { - if (lineNumber < lines.length) { - lineText = lines[lineNumber]; - wordRanges = wordenize(lineText, wordDefinition); - wordRangesIdx = 0; - lineNumber += 1; - } - else { - break; - } - } - } - } - }; - } - getLineWords(lineNumber, wordDefinition) { - let content = this._lines[lineNumber - 1]; - let ranges = this._wordenize(content, wordDefinition); - let words = []; - for (const range of ranges) { - words.push({ - word: content.substring(range.start, range.end), - startColumn: range.start + 1, - endColumn: range.end + 1 - }); - } - return words; - } - _wordenize(content, wordDefinition) { - const result = []; - let 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; - } - getValueInRange(range) { - range = this._validateRange(range); - if (range.startLineNumber === range.endLineNumber) { - return this._lines[range.startLineNumber - 1].substring(range.startColumn - 1, range.endColumn - 1); - } - let lineEnding = this._eol; - let startLineIndex = range.startLineNumber - 1; - let endLineIndex = range.endLineNumber - 1; - let resultLines = []; - resultLines.push(this._lines[startLineIndex].substring(range.startColumn - 1)); - for (let 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); - } - offsetAt(position) { - position = this._validatePosition(position); - this._ensureLineStarts(); - return this._lineStarts.getPrefixSum(position.lineNumber - 2) + (position.column - 1); - } - positionAt(offset) { - offset = Math.floor(offset); - offset = Math.max(0, offset); - this._ensureLineStarts(); - let out = this._lineStarts.getIndexOf(offset); - let lineLength = this._lines[out.index].length; - // Ensure we return a valid position - return { - lineNumber: 1 + out.index, - column: 1 + Math.min(out.remainder, lineLength) - }; - } - _validateRange(range) { - const start = this._validatePosition({ lineNumber: range.startLineNumber, column: range.startColumn }); - const 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; - } - _validatePosition(position) { - if (!position_1.Position.isIPosition(position)) { - throw new Error('bad position'); - } - let { lineNumber, column } = position; - let 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 { - let 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, column }; - } - } - } - /** - * @internal - */ - class EditorSimpleWorker { - constructor(host, foreignModuleFactory) { - this._host = host; - this._models = Object.create(null); - this._foreignModuleFactory = foreignModuleFactory; - this._foreignModule = null; - } - dispose() { - this._models = Object.create(null); - } - _getModel(uri) { - return this._models[uri]; - } - _getModels() { - let all = []; - Object.keys(this._models).forEach((key) => all.push(this._models[key])); - return all; - } - acceptNewModel(data) { - this._models[data.url] = new MirrorModel(uri_1.URI.parse(data.url), data.lines, data.EOL, data.versionId); - } - acceptModelChanged(strURL, e) { - if (!this._models[strURL]) { - return; - } - let model = this._models[strURL]; - model.onEvents(e); - } - acceptRemovedModel(strURL) { - if (!this._models[strURL]) { - return; - } - delete this._models[strURL]; - } - // ---- BEGIN diff -------------------------------------------------------------------------- - computeDiff(originalUrl, modifiedUrl, ignoreTrimWhitespace, maxComputationTime) { - return __awaiter(this, void 0, void 0, function* () { - const original = this._getModel(originalUrl); - const modified = this._getModel(modifiedUrl); - if (!original || !modified) { - return null; - } - const originalLines = original.getLinesContent(); - const modifiedLines = modified.getLinesContent(); - const diffComputer = new diffComputer_1.DiffComputer(originalLines, modifiedLines, { - shouldComputeCharChanges: true, - shouldPostProcessCharChanges: true, - shouldIgnoreTrimWhitespace: ignoreTrimWhitespace, - shouldMakePrettyDiff: true, - maxComputationTime: maxComputationTime - }); - const diffResult = diffComputer.computeDiff(); - const identical = (diffResult.changes.length > 0 ? false : this._modelsAreIdentical(original, modified)); - return { - quitEarly: diffResult.quitEarly, - identical: identical, - changes: diffResult.changes - }; - }); - } - _modelsAreIdentical(original, modified) { - const originalLineCount = original.getLineCount(); - const modifiedLineCount = modified.getLineCount(); - if (originalLineCount !== modifiedLineCount) { - return false; - } - for (let line = 1; line <= originalLineCount; line++) { - const originalLine = original.getLineContent(line); - const modifiedLine = modified.getLineContent(line); - if (originalLine !== modifiedLine) { - return false; - } - } - return true; - } - computeMoreMinimalEdits(modelUrl, edits) { - return __awaiter(this, void 0, void 0, function* () { - const model = this._getModel(modelUrl); - if (!model) { - return edits; - } - const result = []; - let lastEol = undefined; - edits = edits.slice(0).sort((a, b) => { - if (a.range && b.range) { - return range_1.Range.compareRangesUsingStarts(a.range, b.range); - } - // eol only changes should go to the end - let aRng = a.range ? 0 : 1; - let bRng = b.range ? 0 : 1; - return aRng - bRng; - }); - for (let { range, text, eol } of edits) { - if (typeof eol === 'number') { - lastEol = eol; - } - if (range_1.Range.isEmpty(range) && !text) { - // empty change - continue; - } - const 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, text }); - continue; - } - // compute diff between original and edit.text - const changes = (0, diff_1.stringDiff)(original, text, false); - const editOffset = model.offsetAt(range_1.Range.lift(range).getStartPosition()); - for (const change of changes) { - const start = model.positionAt(editOffset + change.originalStart); - const end = model.positionAt(editOffset + change.originalStart + change.originalLength); - const 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 result; - }); - } - // ---- END minimal edits --------------------------------------------------------------- - computeLinks(modelUrl) { - return __awaiter(this, void 0, void 0, function* () { - let model = this._getModel(modelUrl); - if (!model) { - return null; - } - return (0, linkComputer_1.computeLinks)(model); - }); - } - textualSuggest(modelUrls, leadingWord, wordDef, wordDefFlags) { - return __awaiter(this, void 0, void 0, function* () { - const sw = new stopwatch_1.StopWatch(true); - const wordDefRegExp = new RegExp(wordDef, wordDefFlags); - const seen = new Set(); - outer: for (let url of modelUrls) { - const model = this._getModel(url); - if (!model) { - continue; - } - for (let word of model.words(wordDefRegExp)) { - if (word === leadingWord || !isNaN(Number(word))) { - continue; - } - seen.add(word); - if (seen.size > EditorSimpleWorker._suggestionsLimit) { - break outer; - } - } - } - return { words: Array.from(seen), duration: sw.elapsed() }; - }); - } - // ---- END suggest -------------------------------------------------------------------------- - //#region -- word ranges -- - computeWordRanges(modelUrl, range, wordDef, wordDefFlags) { - return __awaiter(this, void 0, void 0, function* () { - let model = this._getModel(modelUrl); - if (!model) { - return Object.create(null); - } - const wordDefRegExp = new RegExp(wordDef, wordDefFlags); - const result = Object.create(null); - for (let line = range.startLineNumber; line < range.endLineNumber; line++) { - let words = model.getLineWords(line, wordDefRegExp); - for (const word of words) { - if (!isNaN(Number(word.word))) { - continue; - } - let array = result[word.word]; - if (!array) { - array = []; - result[word.word] = array; - } - array.push({ - startLineNumber: line, - startColumn: word.startColumn, - endLineNumber: line, - endColumn: word.endColumn - }); - } - } - return result; - }); - } - //#endregion - navigateValueSet(modelUrl, range, up, wordDef, wordDefFlags) { - return __awaiter(this, void 0, void 0, function* () { - let model = this._getModel(modelUrl); - if (!model) { - return null; - } - let wordDefRegExp = new RegExp(wordDef, wordDefFlags); - if (range.startColumn === range.endColumn) { - range = { - startLineNumber: range.startLineNumber, - startColumn: range.startColumn, - endLineNumber: range.endLineNumber, - endColumn: range.endColumn + 1 - }; - } - let selectionText = model.getValueInRange(range); - let wordRange = model.getWordAtPosition({ lineNumber: range.startLineNumber, column: range.startColumn }, wordDefRegExp); - if (!wordRange) { - return null; - } - let word = model.getValueInRange(wordRange); - let result = inplaceReplaceSupport_1.BasicInplaceReplace.INSTANCE.navigateValueSet(range, selectionText, wordRange, word, up); - return result; - }); - } - // ---- BEGIN foreign module support -------------------------------------------------------------------------- - loadForeignModule(moduleId, createData, foreignHostMethods) { - const proxyMethodRequest = (method, args) => { - return this._host.fhr(method, args); - }; - const foreignHost = types.createProxyObject(foreignHostMethods, proxyMethodRequest); - let ctx = { - host: foreignHost, - getMirrorModels: () => { - 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((resolve, reject) => { - require([moduleId], (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 - fmr(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); - } - } - } - exports.EditorSimpleWorker = EditorSimpleWorker; - // ---- END diff -------------------------------------------------------------------------- - // ---- BEGIN minimal edits --------------------------------------------------------------- - EditorSimpleWorker._diffLimit = 100000; - // ---- BEGIN suggest -------------------------------------------------------------------------- - EditorSimpleWorker._suggestionsLimit = 10000; - /** - * 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 = (0, 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[115/*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 }); - exports.ViewEventHandler = void 0; - class ViewEventHandler extends lifecycle_1.Disposable { - constructor() { - super(); - this._shouldRender = true; - } - shouldRender() { - return this._shouldRender; - } - forceShouldRender() { - this._shouldRender = true; - } - setShouldRender() { - this._shouldRender = true; - } - onDidRender() { - this._shouldRender = false; - } - // --- begin event handlers - onCompositionStart(e) { - return false; - } - onCompositionEnd(e) { - return false; - } - onConfigurationChanged(e) { - return false; - } - onCursorStateChanged(e) { - return false; - } - onDecorationsChanged(e) { - return false; - } - onFlushed(e) { - return false; - } - onFocusChanged(e) { - return false; - } - onLanguageConfigurationChanged(e) { - return false; - } - onLineMappingChanged(e) { - return false; - } - onLinesChanged(e) { - return false; - } - onLinesDeleted(e) { - return false; - } - onLinesInserted(e) { - return false; - } - onRevealRangeRequest(e) { - return false; - } - onScrollChanged(e) { - return false; - } - onThemeChanged(e) { - return false; - } - onTokensChanged(e) { - return false; - } - onTokensColorsChanged(e) { - return false; - } - onZonesChanged(e) { - return false; - } - // --- end event handlers - handleEvents(events) { - let shouldRender = false; - for (let i = 0, len = events.length; i < len; i++) { - let e = events[i]; - switch (e.type) { - case 0 /* ViewCompositionStart */: - if (this.onCompositionStart(e)) { - shouldRender = true; - } - break; - case 1 /* ViewCompositionEnd */: - if (this.onCompositionEnd(e)) { - shouldRender = true; - } - break; - case 2 /* ViewConfigurationChanged */: - if (this.onConfigurationChanged(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; - } - } - } - 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[97/*vs/editor/browser/view/dynamicViewOverlay*/], __M([0/*require*/,1/*exports*/,115/*vs/editor/common/viewModel/viewEventHandler*/]), function (require, exports, viewEventHandler_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DynamicViewOverlay = void 0; - class DynamicViewOverlay extends 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[47/*vs/editor/browser/view/viewPart*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/fastDomNode*/,115/*vs/editor/common/viewModel/viewEventHandler*/]), function (require, exports, fastDomNode_1, viewEventHandler_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.PartFingerprints = exports.ViewPart = void 0; - class ViewPart extends viewEventHandler_1.ViewEventHandler { - constructor(context) { - super(); - this._context = context; - this._context.addEventHandler(this); - } - dispose() { - this._context.removeEventHandler(this); - super.dispose(); - } - } - exports.ViewPart = ViewPart; - class PartFingerprints { - static write(target, partId) { - if (target instanceof fastDomNode_1.FastDomNode) { - target.setAttribute('data-mprt', String(partId)); - } - else { - target.setAttribute('data-mprt', String(partId)); - } - } - static read(target) { - const r = target.getAttribute('data-mprt'); - if (r === null) { - return 0 /* None */; - } - return parseInt(r, 10); - } - static collect(child, stopAt) { - let 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; - } - const r = new Uint8Array(resultLen); - for (let i = 0; i < resultLen; i++) { - r[i] = result[resultLen - i - 1]; - } - return r; - } - } - 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[398/*vs/editor/browser/viewParts/contentWidgets/contentWidgets*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,30/*vs/base/browser/fastDomNode*/,47/*vs/editor/browser/view/viewPart*/]), function (require, exports, dom, fastDomNode_1, viewPart_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ViewContentWidgets = void 0; - class Coordinate { - constructor(top, left) { - this._coordinateBrand = undefined; - this.top = top; - this.left = left; - } - } - class ViewContentWidgets extends viewPart_1.ViewPart { - constructor(context, viewDomNode) { - super(context); - this._viewDomNode = viewDomNode; - this._widgets = {}; - this.domNode = (0, 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 = (0, fastDomNode_1.createFastDomNode)(document.createElement('div')); - viewPart_1.PartFingerprints.write(this.overflowingContentWidgetsDomNode, 2 /* OverflowingContentWidgets */); - this.overflowingContentWidgetsDomNode.setClassName('overflowingContentWidgets'); - } - dispose() { - super.dispose(); - this._widgets = {}; - } - // --- begin event handlers - onConfigurationChanged(e) { - const keys = Object.keys(this._widgets); - for (const widgetId of keys) { - this._widgets[widgetId].onConfigurationChanged(e); - } - return true; - } - onDecorationsChanged(e) { - // true for inline decorations that can end up relayouting text - return true; - } - onFlushed(e) { - return true; - } - onLineMappingChanged(e) { - const keys = Object.keys(this._widgets); - for (const widgetId of keys) { - this._widgets[widgetId].onLineMappingChanged(e); - } - return true; - } - onLinesChanged(e) { - return true; - } - onLinesDeleted(e) { - return true; - } - onLinesInserted(e) { - return true; - } - onScrollChanged(e) { - return true; - } - onZonesChanged(e) { - return true; - } - // ---- end view event handlers - addWidget(_widget) { - const 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(); - } - setWidgetPosition(widget, range, preference) { - const myWidget = this._widgets[widget.getId()]; - myWidget.setPosition(range, preference); - this.setShouldRender(); - } - removeWidget(widget) { - const widgetId = widget.getId(); - if (this._widgets.hasOwnProperty(widgetId)) { - const myWidget = this._widgets[widgetId]; - delete this._widgets[widgetId]; - const domNode = myWidget.domNode.domNode; - domNode.parentNode.removeChild(domNode); - domNode.removeAttribute('monaco-visible-content-widget'); - this.setShouldRender(); - } - } - shouldSuppressMouseDownOnWidget(widgetId) { - if (this._widgets.hasOwnProperty(widgetId)) { - return this._widgets[widgetId].suppressMouseDown; - } - return false; - } - onBeforeRender(viewportData) { - const keys = Object.keys(this._widgets); - for (const widgetId of keys) { - this._widgets[widgetId].onBeforeRender(viewportData); - } - } - prepareRender(ctx) { - const keys = Object.keys(this._widgets); - for (const widgetId of keys) { - this._widgets[widgetId].prepareRender(ctx); - } - } - render(ctx) { - const keys = Object.keys(this._widgets); - for (const widgetId of keys) { - this._widgets[widgetId].render(ctx); - } - } - } - exports.ViewContentWidgets = ViewContentWidgets; - class Widget { - constructor(context, viewDomNode, actual) { - this._context = context; - this._viewDomNode = viewDomNode; - this._actual = actual; - this.domNode = (0, fastDomNode_1.createFastDomNode)(this._actual.getDomNode()); - this.id = this._actual.getId(); - this.allowEditorOverflow = this._actual.allowEditorOverflow || false; - this.suppressMouseDown = this._actual.suppressMouseDown || false; - const options = this._context.configuration.options; - const layoutInfo = options.get(129 /* layoutInfo */); - this._fixedOverflowWidgets = options.get(34 /* fixedOverflowWidgets */); - this._contentWidth = layoutInfo.contentWidth; - this._contentLeft = layoutInfo.contentLeft; - this._lineHeight = options.get(57 /* 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); - } - onConfigurationChanged(e) { - const options = this._context.configuration.options; - this._lineHeight = options.get(57 /* lineHeight */); - if (e.hasChanged(129 /* layoutInfo */)) { - const layoutInfo = options.get(129 /* layoutInfo */); - this._contentLeft = layoutInfo.contentLeft; - this._contentWidth = layoutInfo.contentWidth; - this._maxWidth = this._getMaxWidth(); - } - } - onLineMappingChanged(e) { - this._setPosition(this._range); - } - _setPosition(range) { - this._range = range; - this._viewRange = null; - if (this._range) { - // Do not trust that widgets give a valid position - const 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); - } - } - } - _getMaxWidth() { - return (this.allowEditorOverflow - ? window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth - : this._contentWidth); - } - setPosition(range, preference) { - this._setPosition(range); - this._preference = preference; - this._cachedDomNodeClientWidth = -1; - this._cachedDomNodeClientHeight = -1; - } - _layoutBoxInViewport(topLeft, bottomLeft, width, height, ctx) { - // Our visible box is split horizontally by the current line => 2 boxes - // a) the box above the line - const aboveLineTop = topLeft.top; - const heightAboveLine = aboveLineTop; - // b) the box under the line - const underLineTop = bottomLeft.top + this._lineHeight; - const heightUnderLine = ctx.viewportHeight - underLineTop; - const aboveTop = aboveLineTop - height; - const fitsAbove = (heightAboveLine >= height); - const belowTop = underLineTop; - const fitsBelow = (heightUnderLine >= height); - // And its left - let actualAboveLeft = topLeft.left; - let 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, - }; - } - _layoutHorizontalSegmentInPage(windowSize, domNodePosition, left, width) { - // Initially, the limits are defined as the dom node limits - const MIN_LIMIT = Math.max(0, domNodePosition.left - width); - const MAX_LIMIT = Math.min(domNodePosition.left + domNodePosition.width + width, windowSize.width); - let absoluteLeft = domNodePosition.left + left - dom.StandardWindow.scrollX; - if (absoluteLeft + width > MAX_LIMIT) { - const delta = absoluteLeft - (MAX_LIMIT - width); - absoluteLeft -= delta; - left -= delta; - } - if (absoluteLeft < MIN_LIMIT) { - const delta = absoluteLeft - MIN_LIMIT; - absoluteLeft -= delta; - left -= delta; - } - return [left, absoluteLeft]; - } - _layoutBoxInPage(topLeft, bottomLeft, width, height, ctx) { - const aboveTop = topLeft.top - height; - const belowTop = bottomLeft.top + this._lineHeight; - const domNodePosition = dom.getDomNodePagePosition(this._viewDomNode.domNode); - const absoluteAboveTop = domNodePosition.top + aboveTop - dom.StandardWindow.scrollY; - const absoluteBelowTop = domNodePosition.top + belowTop - dom.StandardWindow.scrollY; - const windowSize = dom.getClientArea(document.body); - const [aboveLeft, absoluteAboveLeft] = this._layoutHorizontalSegmentInPage(windowSize, domNodePosition, topLeft.left - ctx.scrollLeft + this._contentLeft, width); - const [belowLeft, absoluteBelowLeft] = this._layoutHorizontalSegmentInPage(windowSize, domNodePosition, bottomLeft.left - ctx.scrollLeft + this._contentLeft, width); - // Leave some clearance to the top/bottom - const TOP_PADDING = 22; - const BOTTOM_PADDING = 22; - const fitsAbove = (absoluteAboveTop >= TOP_PADDING); - const fitsBelow = (absoluteBelowTop + height <= windowSize.height - BOTTOM_PADDING); - if (this._fixedOverflowWidgets) { - return { - fitsAbove, - aboveTop: Math.max(absoluteAboveTop, TOP_PADDING), - aboveLeft: absoluteAboveLeft, - fitsBelow, - belowTop: absoluteBelowTop, - belowLeft: absoluteBelowLeft - }; - } - return { - fitsAbove, - aboveTop: aboveTop, - aboveLeft, - fitsBelow, - belowTop, - belowLeft - }; - } - _prepareRenderWidgetAtExactPositionOverflowing(topLeft) { - return new Coordinate(topLeft.top, topLeft.left + this._contentLeft); - } - /** - * Compute `this._topLeft` - */ - _getTopAndBottomLeft(ctx) { - if (!this._viewRange) { - return [null, null]; - } - const visibleRangesForRange = ctx.linesVisibleRangesForRange(this._viewRange, false); - if (!visibleRangesForRange || visibleRangesForRange.length === 0) { - return [null, null]; - } - let firstLine = visibleRangesForRange[0]; - let lastLine = visibleRangesForRange[0]; - for (const visibleRangesForLine of visibleRangesForRange) { - if (visibleRangesForLine.lineNumber < firstLine.lineNumber) { - firstLine = visibleRangesForLine; - } - if (visibleRangesForLine.lineNumber > lastLine.lineNumber) { - lastLine = visibleRangesForLine; - } - } - let firstLineMinLeft = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; //firstLine.Constants.MAX_SAFE_SMALL_INTEGER; - for (const visibleRange of firstLine.ranges) { - if (visibleRange.left < firstLineMinLeft) { - firstLineMinLeft = visibleRange.left; - } - } - let lastLineMinLeft = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; //lastLine.Constants.MAX_SAFE_SMALL_INTEGER; - for (const visibleRange of lastLine.ranges) { - if (visibleRange.left < lastLineMinLeft) { - lastLineMinLeft = visibleRange.left; - } - } - const topForPosition = ctx.getVerticalOffsetForLineNumber(firstLine.lineNumber) - ctx.scrollTop; - const topLeft = new Coordinate(topForPosition, firstLineMinLeft); - const topForBottomLine = ctx.getVerticalOffsetForLineNumber(lastLine.lineNumber) - ctx.scrollTop; - const bottomLeft = new Coordinate(topForBottomLine, lastLineMinLeft); - return [topLeft, bottomLeft]; - } - _prepareRenderWidget(ctx) { - const [topLeft, bottomLeft] = this._getTopAndBottomLeft(ctx); - if (!topLeft || !bottomLeft) { - return null; - } - if (this._cachedDomNodeClientWidth === -1 || this._cachedDomNodeClientHeight === -1) { - let preferredDimensions = null; - if (typeof this._actual.beforeRender === 'function') { - preferredDimensions = safeInvoke(this._actual.beforeRender, this._actual); - } - if (preferredDimensions) { - this._cachedDomNodeClientWidth = preferredDimensions.width; - this._cachedDomNodeClientHeight = preferredDimensions.height; - } - else { - const domNode = this.domNode.domNode; - this._cachedDomNodeClientWidth = domNode.clientWidth; - this._cachedDomNodeClientHeight = domNode.clientHeight; - } - } - let 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 (let pass = 1; pass <= 2; pass++) { - for (const pref of this._preference) { - // placement - if (pref === 1 /* ABOVE */) { - if (!placement) { - // Widget outside of viewport - return null; - } - if (pass === 2 || placement.fitsAbove) { - return { coordinate: new Coordinate(placement.aboveTop, placement.aboveLeft), position: 1 /* ABOVE */ }; - } - } - else if (pref === 2 /* BELOW */) { - if (!placement) { - // Widget outside of viewport - return null; - } - if (pass === 2 || placement.fitsBelow) { - return { coordinate: new Coordinate(placement.belowTop, placement.belowLeft), position: 2 /* BELOW */ }; - } - } - else { - if (this.allowEditorOverflow) { - return { coordinate: this._prepareRenderWidgetAtExactPositionOverflowing(topLeft), position: 0 /* EXACT */ }; - } - else { - return { coordinate: topLeft, position: 0 /* EXACT */ }; - } - } - } - } - } - return null; - } - /** - * On this first pass, we ensure that the content widget (if it is in the viewport) has the max width set correctly. - */ - onBeforeRender(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); - } - prepareRender(ctx) { - this._renderData = this._prepareRenderWidget(ctx); - } - render(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'); - } - if (typeof this._actual.afterRender === 'function') { - safeInvoke(this._actual.afterRender, this._actual, null); - } - return; - } - // This widget should be visible - if (this.allowEditorOverflow) { - this.domNode.setTop(this._renderData.coordinate.top); - this.domNode.setLeft(this._renderData.coordinate.left); - } - else { - this.domNode.setTop(this._renderData.coordinate.top + ctx.scrollTop - ctx.bigNumbersDelta); - this.domNode.setLeft(this._renderData.coordinate.left); - } - if (!this._isVisible) { - this.domNode.setVisibility('inherit'); - this.domNode.setAttribute('monaco-visible-content-widget', 'true'); - this._isVisible = true; - } - if (typeof this._actual.afterRender === 'function') { - safeInvoke(this._actual.afterRender, this._actual, this._renderData.position); - } - } - } - function safeInvoke(fn, thisArg, ...args) { - try { - return fn.call(thisArg, ...args); - } - catch (_a) { - // ignore - 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[399/*vs/editor/browser/viewParts/decorations/decorations*/], __M([0/*require*/,1/*exports*/,97/*vs/editor/browser/view/dynamicViewOverlay*/,3/*vs/editor/common/core/range*/,113/*vs/editor/common/view/renderingContext*/,327/*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 }); - exports.DecorationsOverlay = void 0; - class DecorationsOverlay extends dynamicViewOverlay_1.DynamicViewOverlay { - constructor(context) { - super(); - this._context = context; - const options = this._context.configuration.options; - this._lineHeight = options.get(57 /* lineHeight */); - this._typicalHalfwidthCharacterWidth = options.get(41 /* fontInfo */).typicalHalfwidthCharacterWidth; - this._renderResult = null; - this._context.addEventHandler(this); - } - dispose() { - this._context.removeEventHandler(this); - this._renderResult = null; - super.dispose(); - } - // --- begin event handlers - onConfigurationChanged(e) { - const options = this._context.configuration.options; - this._lineHeight = options.get(57 /* lineHeight */); - this._typicalHalfwidthCharacterWidth = options.get(41 /* fontInfo */).typicalHalfwidthCharacterWidth; - return true; - } - onDecorationsChanged(e) { - return true; - } - onFlushed(e) { - return true; - } - onLinesChanged(e) { - return true; - } - onLinesDeleted(e) { - return true; - } - onLinesInserted(e) { - return true; - } - onScrollChanged(e) { - return e.scrollTopChanged || e.scrollWidthChanged; - } - onZonesChanged(e) { - return true; - } - // --- end event handlers - prepareRender(ctx) { - const _decorations = ctx.getDecorationsInViewport(); - // Keep only decorations with `className` - let decorations = [], decorationsLen = 0; - for (let i = 0, len = _decorations.length; i < len; i++) { - const d = _decorations[i]; - if (d.options.className) { - decorations[decorationsLen++] = d; - } - } - // Sort decorations for consistent render output - decorations = decorations.sort((a, b) => { - if (a.options.zIndex < b.options.zIndex) { - return -1; - } - if (a.options.zIndex > b.options.zIndex) { - return 1; - } - const aClassName = a.options.className; - const bClassName = b.options.className; - if (aClassName < bClassName) { - return -1; - } - if (aClassName > bClassName) { - return 1; - } - return range_1.Range.compareRangesUsingStarts(a.range, b.range); - }); - const visibleStartLineNumber = ctx.visibleRange.startLineNumber; - const visibleEndLineNumber = ctx.visibleRange.endLineNumber; - const output = []; - for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) { - const 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; - } - _renderWholeLineDecorations(ctx, decorations, output) { - const lineHeight = String(this._lineHeight); - const visibleStartLineNumber = ctx.visibleRange.startLineNumber; - const visibleEndLineNumber = ctx.visibleRange.endLineNumber; - for (let i = 0, lenI = decorations.length; i < lenI; i++) { - const d = decorations[i]; - if (!d.options.isWholeLine) { - continue; - } - const decorationOutput = ('
    '); - const startLineNumber = Math.max(d.range.startLineNumber, visibleStartLineNumber); - const endLineNumber = Math.min(d.range.endLineNumber, visibleEndLineNumber); - for (let j = startLineNumber; j <= endLineNumber; j++) { - const lineIndex = j - visibleStartLineNumber; - output[lineIndex] += decorationOutput; - } - } - } - _renderNormalDecorations(ctx, decorations, output) { - const lineHeight = String(this._lineHeight); - const visibleStartLineNumber = ctx.visibleRange.startLineNumber; - let prevClassName = null; - let prevShowIfCollapsed = false; - let prevRange = null; - for (let i = 0, lenI = decorations.length; i < lenI; i++) { - const d = decorations[i]; - if (d.options.isWholeLine) { - continue; - } - const className = d.options.className; - const showIfCollapsed = Boolean(d.options.showIfCollapsed); - let 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); - } - } - _renderNormalDecoration(ctx, range, className, showIfCollapsed, lineHeight, visibleStartLineNumber, output) { - const linesVisibleRanges = ctx.linesVisibleRangesForRange(range, /*TODO@Alex*/ className === 'findMatch'); - if (!linesVisibleRanges) { - return; - } - for (let j = 0, lenJ = linesVisibleRanges.length; j < lenJ; j++) { - const lineVisibleRanges = linesVisibleRanges[j]; - if (lineVisibleRanges.outsideRenderedLine) { - continue; - } - const lineIndex = lineVisibleRanges.lineNumber - visibleStartLineNumber; - if (showIfCollapsed && lineVisibleRanges.ranges.length === 1) { - const 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 (let k = 0, lenK = lineVisibleRanges.ranges.length; k < lenK; k++) { - const visibleRange = lineVisibleRanges.ranges[k]; - const decorationOutput = ('
    '); - output[lineIndex] += decorationOutput; - } - } - } - render(startLineNumber, lineNumber) { - if (!this._renderResult) { - return ''; - } - const lineIndex = lineNumber - startLineNumber; - if (lineIndex < 0 || lineIndex >= this._renderResult.length) { - return ''; - } - return this._renderResult[lineIndex]; - } - } - 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[176/*vs/editor/browser/viewParts/glyphMargin/glyphMargin*/], __M([0/*require*/,1/*exports*/,97/*vs/editor/browser/view/dynamicViewOverlay*/,328/*vs/css!vs/editor/browser/viewParts/glyphMargin/glyphMargin*/]), function (require, exports, dynamicViewOverlay_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.GlyphMarginOverlay = exports.DedupOverlay = exports.DecorationToRender = void 0; - class DecorationToRender { - constructor(startLineNumber, endLineNumber, className) { - this._decorationToRenderBrand = undefined; - this.startLineNumber = +startLineNumber; - this.endLineNumber = +endLineNumber; - this.className = String(className); - } - } - exports.DecorationToRender = DecorationToRender; - class DedupOverlay extends dynamicViewOverlay_1.DynamicViewOverlay { - _render(visibleStartLineNumber, visibleEndLineNumber, decorations) { - const output = []; - for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) { - const lineIndex = lineNumber - visibleStartLineNumber; - output[lineIndex] = []; - } - if (decorations.length === 0) { - return output; - } - decorations.sort((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); - }); - let prevClassName = null; - let prevEndLineIndex = 0; - for (let i = 0, len = decorations.length; i < len; i++) { - const d = decorations[i]; - const className = d.className; - let startLineIndex = Math.max(d.startLineNumber, visibleStartLineNumber) - visibleStartLineNumber; - const 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 (let i = startLineIndex; i <= prevEndLineIndex; i++) { - output[i].push(prevClassName); - } - } - return output; - } - } - exports.DedupOverlay = DedupOverlay; - class GlyphMarginOverlay extends DedupOverlay { - constructor(context) { - super(); - this._context = context; - const options = this._context.configuration.options; - const layoutInfo = options.get(129 /* layoutInfo */); - this._lineHeight = options.get(57 /* lineHeight */); - this._glyphMargin = options.get(47 /* glyphMargin */); - this._glyphMarginLeft = layoutInfo.glyphMarginLeft; - this._glyphMarginWidth = layoutInfo.glyphMarginWidth; - this._renderResult = null; - this._context.addEventHandler(this); - } - dispose() { - this._context.removeEventHandler(this); - this._renderResult = null; - super.dispose(); - } - // --- begin event handlers - onConfigurationChanged(e) { - const options = this._context.configuration.options; - const layoutInfo = options.get(129 /* layoutInfo */); - this._lineHeight = options.get(57 /* lineHeight */); - this._glyphMargin = options.get(47 /* glyphMargin */); - this._glyphMarginLeft = layoutInfo.glyphMarginLeft; - this._glyphMarginWidth = layoutInfo.glyphMarginWidth; - return true; - } - onDecorationsChanged(e) { - return true; - } - onFlushed(e) { - return true; - } - onLinesChanged(e) { - return true; - } - onLinesDeleted(e) { - return true; - } - onLinesInserted(e) { - return true; - } - onScrollChanged(e) { - return e.scrollTopChanged; - } - onZonesChanged(e) { - return true; - } - // --- end event handlers - _getDecorations(ctx) { - const decorations = ctx.getDecorationsInViewport(); - let r = [], rLen = 0; - for (let i = 0, len = decorations.length; i < len; i++) { - const d = decorations[i]; - const glyphMarginClassName = d.options.glyphMarginClassName; - if (glyphMarginClassName) { - r[rLen++] = new DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, glyphMarginClassName); - } - } - return r; - } - prepareRender(ctx) { - if (!this._glyphMargin) { - this._renderResult = null; - return; - } - const visibleStartLineNumber = ctx.visibleRange.startLineNumber; - const visibleEndLineNumber = ctx.visibleRange.endLineNumber; - const toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx)); - const lineHeight = this._lineHeight.toString(); - const left = this._glyphMarginLeft.toString(); - const width = this._glyphMarginWidth.toString(); - const common = '" style="left:' + left + 'px;width:' + width + 'px' + ';height:' + lineHeight + 'px;">'; - const output = []; - for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) { - const lineIndex = lineNumber - visibleStartLineNumber; - const classNames = toRender[lineIndex]; - if (classNames.length === 0) { - output[lineIndex] = ''; - } - else { - output[lineIndex] = (''; - const output = []; - for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) { - const lineIndex = lineNumber - visibleStartLineNumber; - const classNames = toRender[lineIndex]; - let lineOutput = ''; - for (let i = 0, len = classNames.length; i < len; i++) { - lineOutput += ''; - } - output[lineIndex] = lineOutput; - } - this._renderResult = output; - } - render(startLineNumber, lineNumber) { - if (!this._renderResult) { - return ''; - } - return this._renderResult[lineNumber - startLineNumber]; - } - } - 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[402/*vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/fastDomNode*/,47/*vs/editor/browser/view/viewPart*/,335/*vs/css!vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/]), function (require, exports, fastDomNode_1, viewPart_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ViewOverlayWidgets = void 0; - class ViewOverlayWidgets extends viewPart_1.ViewPart { - constructor(context) { - super(context); - const options = this._context.configuration.options; - const layoutInfo = options.get(129 /* layoutInfo */); - this._widgets = {}; - this._verticalScrollbarWidth = layoutInfo.verticalScrollbarWidth; - this._minimapWidth = layoutInfo.minimap.minimapWidth; - this._horizontalScrollbarHeight = layoutInfo.horizontalScrollbarHeight; - this._editorHeight = layoutInfo.height; - this._editorWidth = layoutInfo.width; - this._domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div')); - viewPart_1.PartFingerprints.write(this._domNode, 4 /* OverlayWidgets */); - this._domNode.setClassName('overlayWidgets'); - } - dispose() { - super.dispose(); - this._widgets = {}; - } - getDomNode() { - return this._domNode; - } - // ---- begin view event handlers - onConfigurationChanged(e) { - const options = this._context.configuration.options; - const layoutInfo = options.get(129 /* layoutInfo */); - this._verticalScrollbarWidth = layoutInfo.verticalScrollbarWidth; - this._minimapWidth = layoutInfo.minimap.minimapWidth; - this._horizontalScrollbarHeight = layoutInfo.horizontalScrollbarHeight; - this._editorHeight = layoutInfo.height; - this._editorWidth = layoutInfo.width; - return true; - } - // ---- end view event handlers - addWidget(widget) { - const domNode = (0, 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(); - } - setWidgetPosition(widget, preference) { - const widgetData = this._widgets[widget.getId()]; - if (widgetData.preference === preference) { - return false; - } - widgetData.preference = preference; - this.setShouldRender(); - return true; - } - removeWidget(widget) { - const widgetId = widget.getId(); - if (this._widgets.hasOwnProperty(widgetId)) { - const widgetData = this._widgets[widgetId]; - const domNode = widgetData.domNode.domNode; - delete this._widgets[widgetId]; - domNode.parentNode.removeChild(domNode); - this.setShouldRender(); - } - } - _renderWidget(widgetData) { - const 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 */) { - const 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%'; - } - } - prepareRender(ctx) { - // Nothing to read - } - render(ctx) { - this._domNode.setWidth(this._editorWidth); - const keys = Object.keys(this._widgets); - for (let i = 0, len = keys.length; i < len; i++) { - const widgetId = keys[i]; - this._renderWidget(this._widgets[widgetId]); - } - } - } - 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[403/*vs/editor/browser/viewParts/overviewRuler/overviewRuler*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/fastDomNode*/,223/*vs/editor/common/view/overviewZoneManager*/,115/*vs/editor/common/viewModel/viewEventHandler*/]), function (require, exports, fastDomNode_1, overviewZoneManager_1, viewEventHandler_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.OverviewRuler = void 0; - class OverviewRuler extends viewEventHandler_1.ViewEventHandler { - constructor(context, cssClassName) { - super(); - this._context = context; - const options = this._context.configuration.options; - this._domNode = (0, 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((lineNumber) => 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(57 /* lineHeight */)); - this._zoneManager.setPixelRatio(options.get(127 /* pixelRatio */)); - this._context.addEventHandler(this); - } - dispose() { - this._context.removeEventHandler(this); - super.dispose(); - } - // ---- begin view event handlers - onConfigurationChanged(e) { - const options = this._context.configuration.options; - if (e.hasChanged(57 /* lineHeight */)) { - this._zoneManager.setLineHeight(options.get(57 /* lineHeight */)); - this._render(); - } - if (e.hasChanged(127 /* pixelRatio */)) { - this._zoneManager.setPixelRatio(options.get(127 /* 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; - } - onFlushed(e) { - this._render(); - return true; - } - onScrollChanged(e) { - if (e.scrollHeightChanged) { - this._zoneManager.setOuterHeight(e.scrollHeight); - this._render(); - } - return true; - } - onZonesChanged(e) { - this._render(); - return true; - } - // ---- end view event handlers - getDomNode() { - return this._domNode.domNode; - } - setLayout(position) { - this._domNode.setTop(position.top); - this._domNode.setRight(position.right); - let 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(); - } - } - setZones(zones) { - this._zoneManager.setZones(zones); - this._render(); - } - _render() { - if (this._zoneManager.getOuterHeight() === 0) { - return false; - } - const width = this._zoneManager.getCanvasWidth(); - const height = this._zoneManager.getCanvasHeight(); - const colorZones = this._zoneManager.resolveColorZones(); - const id2Color = this._zoneManager.getId2Color(); - const ctx = this._domNode.domNode.getContext('2d'); - ctx.clearRect(0, 0, width, height); - if (colorZones.length > 0) { - this._renderOneLane(ctx, colorZones, id2Color, width); - } - return true; - } - _renderOneLane(ctx, colorZones, id2Color, width) { - let currentColorId = 0; - let currentFrom = 0; - let currentTo = 0; - for (const zone of colorZones) { - const zoneColorId = zone.colorId; - const zoneFrom = zone.from; - const 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); - } - } - 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[404/*vs/editor/browser/viewParts/viewZones/viewZones*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/fastDomNode*/,12/*vs/base/common/errors*/,47/*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 }); - exports.ViewZones = void 0; - const invalidFunc = () => { throw new Error(`Invalid change accessor`); }; - class ViewZones extends viewPart_1.ViewPart { - constructor(context) { - super(context); - const options = this._context.configuration.options; - const layoutInfo = options.get(129 /* layoutInfo */); - this._lineHeight = options.get(57 /* lineHeight */); - this._contentWidth = layoutInfo.contentWidth; - this._contentLeft = layoutInfo.contentLeft; - this.domNode = (0, 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 = (0, 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 = {}; - } - dispose() { - super.dispose(); - this._zones = {}; - } - // ---- begin view event handlers - _recomputeWhitespacesProps() { - const whitespaces = this._context.viewLayout.getWhitespaces(); - const oldWhitespaces = new Map(); - for (const whitespace of whitespaces) { - oldWhitespaces.set(whitespace.id, whitespace); - } - let hadAChange = false; - this._context.model.changeWhitespace((whitespaceAccessor) => { - const keys = Object.keys(this._zones); - for (let i = 0, len = keys.length; i < len; i++) { - const id = keys[i]; - const zone = this._zones[id]; - const props = this._computeWhitespaceProps(zone.delegate); - const 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; - } - onConfigurationChanged(e) { - const options = this._context.configuration.options; - const layoutInfo = options.get(129 /* layoutInfo */); - this._lineHeight = options.get(57 /* lineHeight */); - this._contentWidth = layoutInfo.contentWidth; - this._contentLeft = layoutInfo.contentLeft; - if (e.hasChanged(57 /* lineHeight */)) { - this._recomputeWhitespacesProps(); - } - return true; - } - onLineMappingChanged(e) { - return this._recomputeWhitespacesProps(); - } - onLinesDeleted(e) { - return true; - } - onScrollChanged(e) { - return e.scrollTopChanged || e.scrollWidthChanged; - } - onZonesChanged(e) { - return true; - } - onLinesInserted(e) { - return true; - } - // ---- end view event handlers - _getZoneOrdinal(zone) { - if (typeof zone.afterColumn !== 'undefined') { - return zone.afterColumn; - } - return 10000; - } - _computeWhitespaceProps(zone) { - if (zone.afterLineNumber === 0) { - return { - afterViewLineNumber: 0, - heightInPx: this._heightInPixels(zone), - minWidthInPx: this._minWidthInPixels(zone) - }; - } - let zoneAfterModelPosition; - if (typeof zone.afterColumn !== 'undefined') { - zoneAfterModelPosition = this._context.model.validateModelPosition({ - lineNumber: zone.afterLineNumber, - column: zone.afterColumn - }); - } - else { - const validAfterLineNumber = this._context.model.validateModelPosition({ - lineNumber: zone.afterLineNumber, - column: 1 - }).lineNumber; - zoneAfterModelPosition = new position_1.Position(validAfterLineNumber, this._context.model.getModelLineMaxColumn(validAfterLineNumber)); - } - let 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 - }); - } - const viewPosition = this._context.model.coordinatesConverter.convertModelPositionToViewPosition(zoneAfterModelPosition); - const isVisible = this._context.model.coordinatesConverter.modelPositionIsVisible(zoneBeforeModelPosition); - return { - afterViewLineNumber: viewPosition.lineNumber, - heightInPx: (isVisible ? this._heightInPixels(zone) : 0), - minWidthInPx: this._minWidthInPixels(zone) - }; - } - changeViewZones(callback) { - let zonesHaveChanged = false; - this._context.model.changeWhitespace((whitespaceAccessor) => { - const changeAccessor = { - addZone: (zone) => { - zonesHaveChanged = true; - return this._addZone(whitespaceAccessor, zone); - }, - removeZone: (id) => { - if (!id) { - return; - } - zonesHaveChanged = this._removeZone(whitespaceAccessor, id) || zonesHaveChanged; - }, - layoutZone: (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; - } - _addZone(whitespaceAccessor, zone) { - const props = this._computeWhitespaceProps(zone); - const whitespaceId = whitespaceAccessor.insertWhitespace(props.afterViewLineNumber, this._getZoneOrdinal(zone), props.heightInPx, props.minWidthInPx); - const myZone = { - whitespaceId: whitespaceId, - delegate: zone, - isVisible: false, - domNode: (0, fastDomNode_1.createFastDomNode)(zone.domNode), - marginDomNode: zone.marginDomNode ? (0, 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; - } - _removeZone(whitespaceAccessor, id) { - if (this._zones.hasOwnProperty(id)) { - const 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; - } - _layoutZone(whitespaceAccessor, id) { - if (this._zones.hasOwnProperty(id)) { - const zone = this._zones[id]; - const 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; - } - shouldSuppressMouseDownOnViewZone(id) { - if (this._zones.hasOwnProperty(id)) { - const zone = this._zones[id]; - return Boolean(zone.delegate.suppressMouseDown); - } - return false; - } - _heightInPixels(zone) { - if (typeof zone.heightInPx === 'number') { - return zone.heightInPx; - } - if (typeof zone.heightInLines === 'number') { - return this._lineHeight * zone.heightInLines; - } - return this._lineHeight; - } - _minWidthInPixels(zone) { - if (typeof zone.minWidthInPx === 'number') { - return zone.minWidthInPx; - } - return 0; - } - _safeCallOnComputedHeight(zone, height) { - if (typeof zone.onComputedHeight === 'function') { - try { - zone.onComputedHeight(height); - } - catch (e) { - (0, errors_1.onUnexpectedError)(e); - } - } - } - _safeCallOnDomNodeTop(zone, top) { - if (typeof zone.onDomNodeTop === 'function') { - try { - zone.onDomNodeTop(top); - } - catch (e) { - (0, errors_1.onUnexpectedError)(e); - } - } - } - prepareRender(ctx) { - // Nothing to read - } - render(ctx) { - const visibleWhitespaces = ctx.viewportData.whitespaceViewportData; - const visibleZones = {}; - let hasVisibleZone = false; - for (let i = 0, len = visibleWhitespaces.length; i < len; i++) { - visibleZones[visibleWhitespaces[i].id] = visibleWhitespaces[i]; - hasVisibleZone = true; - } - const keys = Object.keys(this._zones); - for (let i = 0, len = keys.length; i < len; i++) { - const id = keys[i]; - const zone = this._zones[id]; - let newTop = 0; - let newHeight = 0; - let 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); - } - } - } - exports.ViewZones = ViewZones; - function safeInvoke1Arg(func, arg1) { - try { - return func(arg1); - } - catch (e) { - (0, 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[62/*vs/editor/common/viewModel/viewModel*/], __M([0/*require*/,1/*exports*/,8/*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 }); - exports.ViewModelDecoration = exports.SingleLineInlineDecoration = exports.InlineDecoration = exports.ViewLineRenderingData = exports.ViewLineData = exports.MinimapLinesRenderingData = exports.InjectedText = exports.LineBreakData = exports.OutputPosition = exports.Viewport = void 0; - class Viewport { - constructor(top, left, width, height) { - this._viewportBrand = undefined; - this.top = top | 0; - this.left = left | 0; - this.width = width | 0; - this.height = height | 0; - } - } - exports.Viewport = Viewport; - class OutputPosition { - constructor(outputLineIndex, outputOffset) { - this.outputLineIndex = outputLineIndex; - this.outputOffset = outputOffset; - } - toString() { - return `${this.outputLineIndex}:${this.outputOffset}`; - } - toPosition(baseLineNumber, wrappedTextIndentLength) { - const delta = (this.outputLineIndex > 0 ? wrappedTextIndentLength : 0); - return new position_1.Position(baseLineNumber + this.outputLineIndex, delta + this.outputOffset + 1); - } - } - exports.OutputPosition = OutputPosition; - class LineBreakData { - constructor(breakOffsets, breakOffsetsVisibleColumn, wrappedTextIndentLength, injectionOffsets, injectionOptions) { - this.breakOffsets = breakOffsets; - this.breakOffsetsVisibleColumn = breakOffsetsVisibleColumn; - this.wrappedTextIndentLength = wrappedTextIndentLength; - this.injectionOffsets = injectionOffsets; - this.injectionOptions = injectionOptions; - } - getInputOffsetOfOutputPosition(outputLineIndex, outputOffset) { - let inputOffset = 0; - if (outputLineIndex === 0) { - inputOffset = outputOffset; - } - else { - inputOffset = this.breakOffsets[outputLineIndex - 1] + outputOffset; - } - if (this.injectionOffsets !== null) { - for (let i = 0; i < this.injectionOffsets.length; i++) { - if (inputOffset > this.injectionOffsets[i]) { - if (inputOffset < this.injectionOffsets[i] + this.injectionOptions[i].content.length) { - // `inputOffset` is within injected text - inputOffset = this.injectionOffsets[i]; - } - else { - inputOffset -= this.injectionOptions[i].content.length; - } - } - else { - break; - } - } - } - return inputOffset; - } - getOutputPositionOfInputOffset(inputOffset, affinity = 2 /* None */) { - let delta = 0; - if (this.injectionOffsets !== null) { - for (let i = 0; i < this.injectionOffsets.length; i++) { - if (inputOffset < this.injectionOffsets[i]) { - break; - } - if (affinity !== 1 /* Right */ && inputOffset === this.injectionOffsets[i]) { - break; - } - delta += this.injectionOptions[i].content.length; - } - } - inputOffset += delta; - return this.getOutputPositionOfOffsetInUnwrappedLine(inputOffset, affinity); - } - getOutputPositionOfOffsetInUnwrappedLine(inputOffset, affinity = 2 /* None */) { - let low = 0; - let high = this.breakOffsets.length - 1; - let mid = 0; - let midStart = 0; - while (low <= high) { - mid = low + ((high - low) / 2) | 0; - const midStop = this.breakOffsets[mid]; - midStart = mid > 0 ? this.breakOffsets[mid - 1] : 0; - if (affinity === 0 /* Left */) { - if (inputOffset <= midStart) { - high = mid - 1; - } - else if (inputOffset > midStop) { - low = mid + 1; - } - else { - break; - } - } - else { - if (inputOffset < midStart) { - high = mid - 1; - } - else if (inputOffset >= midStop) { - low = mid + 1; - } - else { - break; - } - } - } - return new OutputPosition(mid, inputOffset - midStart); - } - outputPositionToOffsetInUnwrappedLine(outputLineIndex, outputOffset) { - let result = (outputLineIndex > 0 ? this.breakOffsets[outputLineIndex - 1] : 0) + outputOffset; - if (outputLineIndex > 0) { - result -= this.wrappedTextIndentLength; - } - return result; - } - normalizeOffsetAroundInjections(offsetInUnwrappedLine, affinity) { - const injectedText = this.getInjectedTextAtOffset(offsetInUnwrappedLine); - if (!injectedText) { - return offsetInUnwrappedLine; - } - if (affinity === 2 /* None */) { - if (offsetInUnwrappedLine === injectedText.offsetInUnwrappedLine + injectedText.length) { - // go to the end of this injected text - return injectedText.offsetInUnwrappedLine + injectedText.length; - } - else { - // go to the start of this injected text - return injectedText.offsetInUnwrappedLine; - } - } - if (affinity === 1 /* Right */) { - let result = injectedText.offsetInUnwrappedLine + injectedText.length; - let index = injectedText.injectedTextIndex; - // traverse all injected text that touch eachother - while (index + 1 < this.injectionOffsets.length && this.injectionOffsets[index + 1] === this.injectionOffsets[index]) { - result += this.injectionOptions[index + 1].content.length; - index++; - } - return result; - } - // affinity is left - let result = injectedText.offsetInUnwrappedLine; - let index = injectedText.injectedTextIndex; - // traverse all injected text that touch eachother - while (index - 1 >= 0 && this.injectionOffsets[index - 1] === this.injectionOffsets[index]) { - result -= this.injectionOptions[index - 1].content.length; - index++; - } - return result; - } - getInjectedText(outputLineIndex, outputOffset) { - const offset = this.outputPositionToOffsetInUnwrappedLine(outputLineIndex, outputOffset); - const injectedText = this.getInjectedTextAtOffset(offset); - if (!injectedText) { - return null; - } - return { - options: this.injectionOptions[injectedText.injectedTextIndex] - }; - } - getInjectedTextAtOffset(offsetInUnwrappedLine) { - const injectionOffsets = this.injectionOffsets; - const injectionOptions = this.injectionOptions; - if (injectionOffsets !== null) { - let totalInjectedTextLengthBefore = 0; - for (let i = 0; i < injectionOffsets.length; i++) { - const length = injectionOptions[i].content.length; - const injectedTextStartOffsetInUnwrappedLine = injectionOffsets[i] + totalInjectedTextLengthBefore; - const injectedTextEndOffsetInUnwrappedLine = injectionOffsets[i] + totalInjectedTextLengthBefore + length; - if (injectedTextStartOffsetInUnwrappedLine > offsetInUnwrappedLine) { - // Injected text starts later. - break; // All later injected texts have an even larger offset. - } - if (offsetInUnwrappedLine <= injectedTextEndOffsetInUnwrappedLine) { - // Injected text ends after or with the given position (but also starts with or before it). - return { - injectedTextIndex: i, - offsetInUnwrappedLine: injectedTextStartOffsetInUnwrappedLine, - length - }; - } - totalInjectedTextLengthBefore += length; - } - } - return undefined; - } - } - exports.LineBreakData = LineBreakData; - class InjectedText { - constructor(options) { - this.options = options; - } - } - exports.InjectedText = InjectedText; - class MinimapLinesRenderingData { - constructor(tabSize, data) { - this.tabSize = tabSize; - this.data = data; - } - } - exports.MinimapLinesRenderingData = MinimapLinesRenderingData; - class ViewLineData { - constructor(content, continuesWithWrappedLine, minColumn, maxColumn, startVisibleColumn, tokens, inlineDecorations) { - this._viewLineDataBrand = undefined; - this.content = content; - this.continuesWithWrappedLine = continuesWithWrappedLine; - this.minColumn = minColumn; - this.maxColumn = maxColumn; - this.startVisibleColumn = startVisibleColumn; - this.tokens = tokens; - this.inlineDecorations = inlineDecorations; - } - } - exports.ViewLineData = ViewLineData; - class ViewLineRenderingData { - constructor(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; - } - static isBasicASCII(lineContent, mightContainNonBasicASCII) { - if (mightContainNonBasicASCII) { - return strings.isBasicASCII(lineContent); - } - return true; - } - static containsRTL(lineContent, isBasicASCII, mightContainRTL) { - if (!isBasicASCII && mightContainRTL) { - return strings.containsRTL(lineContent); - } - return false; - } - } - exports.ViewLineRenderingData = ViewLineRenderingData; - class InlineDecoration { - constructor(range, inlineClassName, type) { - this.range = range; - this.inlineClassName = inlineClassName; - this.type = type; - } - } - exports.InlineDecoration = InlineDecoration; - class SingleLineInlineDecoration { - constructor(startOffset, endOffset, inlineClassName, inlineClassNameAffectsLetterSpacing) { - this.startOffset = startOffset; - this.endOffset = endOffset; - this.inlineClassName = inlineClassName; - this.inlineClassNameAffectsLetterSpacing = inlineClassNameAffectsLetterSpacing; - } - toInlineDecoration(lineNumber) { - return new InlineDecoration(new range_1.Range(lineNumber, this.startOffset + 1, lineNumber, this.endOffset + 1), this.inlineClassName, this.inlineClassNameAffectsLetterSpacing ? 3 /* RegularAffectingLetterSpacing */ : 0 /* Regular */); - } - } - exports.SingleLineInlineDecoration = SingleLineInlineDecoration; - class ViewModelDecoration { - constructor(range, options) { - this._viewModelDecorationBrand = undefined; - this.range = range; - this.options = options; - } - } - 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[405/*vs/editor/common/viewModel/monospaceLineBreaksComputer*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,94/*vs/editor/common/core/characterClassifier*/,62/*vs/editor/common/viewModel/viewModel*/,96/*vs/editor/common/model/textModelEvents*/]), function (require, exports, strings, characterClassifier_1, viewModel_1, textModelEvents_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MonospaceLineBreaksComputerFactory = void 0; - class WrappingCharacterClassifier extends characterClassifier_1.CharacterClassifier { - constructor(BREAK_BEFORE, BREAK_AFTER) { - super(0 /* NONE */); - for (let i = 0; i < BREAK_BEFORE.length; i++) { - this.set(BREAK_BEFORE.charCodeAt(i), 1 /* BREAK_BEFORE */); - } - for (let i = 0; i < BREAK_AFTER.length; i++) { - this.set(BREAK_AFTER.charCodeAt(i), 2 /* BREAK_AFTER */); - } - } - get(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); - } - } - } - let arrPool1 = []; - let arrPool2 = []; - class MonospaceLineBreaksComputerFactory { - constructor(breakBeforeChars, breakAfterChars) { - this.classifier = new WrappingCharacterClassifier(breakBeforeChars, breakAfterChars); - } - static create(options) { - return new MonospaceLineBreaksComputerFactory(options.get(118 /* wordWrapBreakBeforeCharacters */), options.get(117 /* wordWrapBreakAfterCharacters */)); - } - createLineBreaksComputer(fontInfo, tabSize, wrappingColumn, wrappingIndent) { - tabSize = tabSize | 0; //@perf - wrappingColumn = +wrappingColumn; //@perf - const requests = []; - const injectedTexts = []; - const previousBreakingData = []; - return { - addRequest: (lineText, injectedText, previousLineBreakData) => { - requests.push(lineText); - injectedTexts.push(injectedText); - previousBreakingData.push(previousLineBreakData); - }, - finalize: () => { - const columnsForFullWidthChar = fontInfo.typicalFullwidthCharacterWidth / fontInfo.typicalHalfwidthCharacterWidth; //@perf - let result = []; - for (let i = 0, len = requests.length; i < len; i++) { - const injectedText = injectedTexts[i]; - const previousLineBreakData = previousBreakingData[i]; - if (previousLineBreakData && !previousLineBreakData.injectionOptions && !injectedText) { - result[i] = createLineBreaksFromPreviousLineBreaks(this.classifier, previousLineBreakData, requests[i], tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent); - } - else { - result[i] = createLineBreaks(this.classifier, requests[i], injectedText, tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent); - } - } - arrPool1.length = 0; - arrPool2.length = 0; - return result; - } - }; - } - } - exports.MonospaceLineBreaksComputerFactory = MonospaceLineBreaksComputerFactory; - function createLineBreaksFromPreviousLineBreaks(classifier, previousBreakingData, lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent) { - if (firstLineBreakColumn === -1) { - return null; - } - const len = lineText.length; - if (len <= 1) { - return null; - } - const prevBreakingOffsets = previousBreakingData.breakOffsets; - const prevBreakingOffsetsVisibleColumn = previousBreakingData.breakOffsetsVisibleColumn; - const wrappedTextIndentLength = computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent); - const wrappedLineBreakColumn = firstLineBreakColumn - wrappedTextIndentLength; - let breakingOffsets = arrPool1; - let breakingOffsetsVisibleColumn = arrPool2; - let breakingOffsetsCount = 0; - let lastBreakingOffset = 0; - let lastBreakingOffsetVisibleColumn = 0; - let breakingColumn = firstLineBreakColumn; - const prevLen = prevBreakingOffsets.length; - let prevIndex = 0; - if (prevIndex >= 0) { - let bestDistance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex] - breakingColumn); - while (prevIndex + 1 < prevLen) { - const 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) - let prevBreakOffset = prevIndex < 0 ? 0 : prevBreakingOffsets[prevIndex]; - let prevBreakOffsetVisibleColumn = prevIndex < 0 ? 0 : prevBreakingOffsetsVisibleColumn[prevIndex]; - if (lastBreakingOffset > prevBreakOffset) { - prevBreakOffset = lastBreakingOffset; - prevBreakOffsetVisibleColumn = lastBreakingOffsetVisibleColumn; - } - let breakOffset = 0; - let breakOffsetVisibleColumn = 0; - let forcedBreakOffset = 0; - let forcedBreakOffsetVisibleColumn = 0; - // initially, we search as much as possible to the right (if it fits) - if (prevBreakOffsetVisibleColumn <= breakingColumn) { - let visibleColumn = prevBreakOffsetVisibleColumn; - let prevCharCode = prevBreakOffset === 0 ? 0 /* Null */ : lineText.charCodeAt(prevBreakOffset - 1); - let prevCharCodeClass = prevBreakOffset === 0 ? 0 /* NONE */ : classifier.get(prevCharCode); - let entireLineFits = true; - for (let i = prevBreakOffset; i < len; i++) { - const charStartOffset = i; - const charCode = lineText.charCodeAt(i); - let charCodeClass; - let charWidth; - 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 (charStartOffset > lastBreakingOffset && 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 (charStartOffset > lastBreakingOffset) { - forcedBreakOffset = charStartOffset; - forcedBreakOffsetVisibleColumn = visibleColumn - charWidth; - } - else { - // we need to advance at least by one character - forcedBreakOffset = i + 1; - forcedBreakOffsetVisibleColumn = visibleColumn; - } - 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, no need to assign to `lastBreakingOffset` and `lastBreakingOffsetVisibleColumn` - breakingOffsets[breakingOffsetsCount] = prevBreakingOffsets[prevBreakingOffsets.length - 1]; - breakingOffsetsVisibleColumn[breakingOffsetsCount] = prevBreakingOffsetsVisibleColumn[prevBreakingOffsets.length - 1]; - breakingOffsetsCount++; - } - break; - } - } - if (breakOffset === 0) { - // must search left - let visibleColumn = prevBreakOffsetVisibleColumn; - let charCode = lineText.charCodeAt(prevBreakOffset); - let charCodeClass = classifier.get(charCode); - let hitATabCharacter = false; - for (let i = prevBreakOffset - 1; i >= lastBreakingOffset; i--) { - const charStartOffset = i + 1; - const 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; - } - let prevCharCodeClass; - let prevCharWidth; - 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) { - const remainingWidthOfNextLine = wrappedLineBreakColumn - (forcedBreakOffsetVisibleColumn - breakOffsetVisibleColumn); - if (remainingWidthOfNextLine <= tabSize) { - const charCodeAtForcedBreakOffset = lineText.charCodeAt(forcedBreakOffset); - let charWidth; - 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; - } - if (breakOffset <= lastBreakingOffset) { - // Make sure that we are advancing (at least one character) - const charCode = lineText.charCodeAt(lastBreakingOffset); - if (strings.isHighSurrogate(charCode)) { - // A surrogate pair must always be considered as a single unit, so it is never to be broken - breakOffset = lastBreakingOffset + 2; - breakOffsetVisibleColumn = lastBreakingOffsetVisibleColumn + 2; - } - else { - breakOffset = lastBreakingOffset + 1; - breakOffsetVisibleColumn = lastBreakingOffsetVisibleColumn + computeCharWidth(charCode, lastBreakingOffsetVisibleColumn, tabSize, columnsForFullWidthChar); - } - } - lastBreakingOffset = breakOffset; - breakingOffsets[breakingOffsetsCount] = breakOffset; - lastBreakingOffsetVisibleColumn = breakOffsetVisibleColumn; - breakingOffsetsVisibleColumn[breakingOffsetsCount] = breakOffsetVisibleColumn; - breakingOffsetsCount++; - breakingColumn = breakOffsetVisibleColumn + wrappedLineBreakColumn; - while (prevIndex < 0 || (prevIndex < prevLen && prevBreakingOffsetsVisibleColumn[prevIndex] < breakOffsetVisibleColumn)) { - prevIndex++; - } - let bestDistance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex] - breakingColumn); - while (prevIndex + 1 < prevLen) { - const 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, injectedTexts, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent) { - const lineText = textModelEvents_1.LineInjectedText.applyInjectedText(_lineText, injectedTexts); - let injectionOptions; - let injectionOffsets; - if (injectedTexts && injectedTexts.length > 0) { - injectionOptions = injectedTexts.map(t => t.options); - injectionOffsets = injectedTexts.map(text => text.column - 1); - } - else { - injectionOptions = null; - injectionOffsets = null; - } - if (firstLineBreakColumn === -1) { - if (!injectionOptions) { - return null; - } - // creating a `LineBreakData` with an invalid `breakOffsetsVisibleColumn` is OK - // because `breakOffsetsVisibleColumn` will never be used because it contains injected text - return new viewModel_1.LineBreakData([lineText.length], [], 0, injectionOffsets, injectionOptions); - } - const len = lineText.length; - if (len <= 1) { - if (!injectionOptions) { - return null; - } - // creating a `LineBreakData` with an invalid `breakOffsetsVisibleColumn` is OK - // because `breakOffsetsVisibleColumn` will never be used because it contains injected text - return new viewModel_1.LineBreakData([lineText.length], [], 0, injectionOffsets, injectionOptions); - } - const wrappedTextIndentLength = computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent); - const wrappedLineBreakColumn = firstLineBreakColumn - wrappedTextIndentLength; - let breakingOffsets = []; - let breakingOffsetsVisibleColumn = []; - let breakingOffsetsCount = 0; - let breakOffset = 0; - let breakOffsetVisibleColumn = 0; - let breakingColumn = firstLineBreakColumn; - let prevCharCode = lineText.charCodeAt(0); - let prevCharCodeClass = classifier.get(prevCharCode); - let visibleColumn = computeCharWidth(prevCharCode, 0, tabSize, columnsForFullWidthChar); - let 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 (let i = startOffset; i < len; i++) { - const charStartOffset = i; - const charCode = lineText.charCodeAt(i); - let charCodeClass; - let charWidth; - 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 && (!injectedTexts || injectedTexts.length === 0)) { - return null; - } - // Add last segment - breakingOffsets[breakingOffsetsCount] = len; - breakingOffsetsVisibleColumn[breakingOffsetsCount] = visibleColumn; - return new viewModel_1.LineBreakData(breakingOffsets, breakingOffsetsVisibleColumn, wrappedTextIndentLength, injectionOffsets, injectionOptions); - } - function computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar) { - if (charCode === 9 /* Tab */) { - return (tabSize - (visibleColumn % tabSize)); - } - if (strings.isFullWidthCharacter(charCode)) { - return columnsForFullWidthChar; - } - if (charCode < 32) { - // when using `editor.renderControlCharacters`, the substitutions are often wide - 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) { - let wrappedTextIndentLength = 0; - if (wrappingIndent !== 0 /* None */) { - const firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineText); - if (firstNonWhitespaceIndex !== -1) { - // Track existing indent - for (let i = 0; i < firstNonWhitespaceIndex; i++) { - const charWidth = (lineText.charCodeAt(i) === 9 /* Tab */ ? tabCharacterWidth(wrappedTextIndentLength, tabSize) : 1); - wrappedTextIndentLength += charWidth; - } - // Increase indent of continuation lines, if desired - const numberOfAdditionalTabs = (wrappingIndent === 3 /* DeepIndent */ ? 2 : wrappingIndent === 2 /* Indent */ ? 1 : 0); - for (let i = 0; i < numberOfAdditionalTabs; i++) { - const 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[177/*vs/editor/common/viewModel/viewModelEventDispatcher*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/]), function (require, exports, event_1, lifecycle_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ReadOnlyEditAttemptEvent = exports.CursorStateChangedEvent = exports.ViewZonesChangedEvent = exports.ScrollChangedEvent = exports.FocusChangedEvent = exports.ContentSizeChangedEvent = exports.ViewModelEventsCollector = exports.ViewModelEventDispatcher = void 0; - class ViewModelEventDispatcher extends lifecycle_1.Disposable { - constructor() { - super(); - this._onEvent = this._register(new event_1.Emitter()); - this.onEvent = this._onEvent.event; - this._eventHandlers = []; - this._viewEventQueue = null; - this._isConsumingViewEventQueue = false; - this._collector = null; - this._collectorCnt = 0; - this._outgoingEvents = []; - } - emitOutgoingEvent(e) { - this._addOutgoingEvent(e); - this._emitOugoingEvents(); - } - _addOutgoingEvent(e) { - for (let i = 0, len = this._outgoingEvents.length; i < len; i++) { - if (this._outgoingEvents[i].kind === e.kind) { - this._outgoingEvents[i] = this._outgoingEvents[i].merge(e); - return; - } - } - // not merged - this._outgoingEvents.push(e); - } - _emitOugoingEvents() { - while (this._outgoingEvents.length > 0) { - if (this._collector || this._isConsumingViewEventQueue) { - // right now collecting or emitting view events, so let's postpone emitting - return; - } - const event = this._outgoingEvents.shift(); - if (event.isNoOp()) { - continue; - } - this._onEvent.fire(event); - } - } - addViewEventHandler(eventHandler) { - for (let 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); - } - removeViewEventHandler(eventHandler) { - for (let i = 0; i < this._eventHandlers.length; i++) { - if (this._eventHandlers[i] === eventHandler) { - this._eventHandlers.splice(i, 1); - break; - } - } - } - beginEmitViewEvents() { - this._collectorCnt++; - if (this._collectorCnt === 1) { - this._collector = new ViewModelEventsCollector(); - } - return this._collector; - } - endEmitViewEvents() { - this._collectorCnt--; - if (this._collectorCnt === 0) { - const outgoingEvents = this._collector.outgoingEvents; - const viewEvents = this._collector.viewEvents; - this._collector = null; - for (const outgoingEvent of outgoingEvents) { - this._addOutgoingEvent(outgoingEvent); - } - if (viewEvents.length > 0) { - this._emitMany(viewEvents); - } - } - this._emitOugoingEvents(); - } - emitSingleViewEvent(event) { - try { - const eventsCollector = this.beginEmitViewEvents(); - eventsCollector.emitViewEvent(event); - } - finally { - this.endEmitViewEvents(); - } - } - _emitMany(events) { - if (this._viewEventQueue) { - this._viewEventQueue = this._viewEventQueue.concat(events); - } - else { - this._viewEventQueue = events; - } - if (!this._isConsumingViewEventQueue) { - this._consumeViewEventQueue(); - } - } - _consumeViewEventQueue() { - try { - this._isConsumingViewEventQueue = true; - this._doConsumeQueue(); - } - finally { - this._isConsumingViewEventQueue = false; - } - } - _doConsumeQueue() { - while (this._viewEventQueue) { - // Empty event queue, as events might come in while sending these off - const events = this._viewEventQueue; - this._viewEventQueue = null; - // Use a clone of the event handlers list, as they might remove themselves - const eventHandlers = this._eventHandlers.slice(0); - for (const eventHandler of eventHandlers) { - eventHandler.handleEvents(events); - } - } - } - } - exports.ViewModelEventDispatcher = ViewModelEventDispatcher; - class ViewModelEventsCollector { - constructor() { - this.viewEvents = []; - this.outgoingEvents = []; - } - emitViewEvent(event) { - this.viewEvents.push(event); - } - emitOutgoingEvent(e) { - this.outgoingEvents.push(e); - } - } - exports.ViewModelEventsCollector = ViewModelEventsCollector; - class ContentSizeChangedEvent { - constructor(oldContentWidth, oldContentHeight, contentWidth, contentHeight) { - this.kind = 0 /* ContentSizeChanged */; - this._oldContentWidth = oldContentWidth; - this._oldContentHeight = oldContentHeight; - this.contentWidth = contentWidth; - this.contentHeight = contentHeight; - this.contentWidthChanged = (this._oldContentWidth !== this.contentWidth); - this.contentHeightChanged = (this._oldContentHeight !== this.contentHeight); - } - isNoOp() { - return (!this.contentWidthChanged && !this.contentHeightChanged); - } - merge(other) { - if (other.kind !== 0 /* ContentSizeChanged */) { - return this; - } - return new ContentSizeChangedEvent(this._oldContentWidth, this._oldContentHeight, other.contentWidth, other.contentHeight); - } - } - exports.ContentSizeChangedEvent = ContentSizeChangedEvent; - class FocusChangedEvent { - constructor(oldHasFocus, hasFocus) { - this.kind = 1 /* FocusChanged */; - this.oldHasFocus = oldHasFocus; - this.hasFocus = hasFocus; - } - isNoOp() { - return (this.oldHasFocus === this.hasFocus); - } - merge(other) { - if (other.kind !== 1 /* FocusChanged */) { - return this; - } - return new FocusChangedEvent(this.oldHasFocus, other.hasFocus); - } - } - exports.FocusChangedEvent = FocusChangedEvent; - class ScrollChangedEvent { - constructor(oldScrollWidth, oldScrollLeft, oldScrollHeight, oldScrollTop, scrollWidth, scrollLeft, scrollHeight, scrollTop) { - this.kind = 2 /* ScrollChanged */; - this._oldScrollWidth = oldScrollWidth; - this._oldScrollLeft = oldScrollLeft; - this._oldScrollHeight = oldScrollHeight; - this._oldScrollTop = oldScrollTop; - this.scrollWidth = scrollWidth; - this.scrollLeft = scrollLeft; - this.scrollHeight = scrollHeight; - this.scrollTop = scrollTop; - this.scrollWidthChanged = (this._oldScrollWidth !== this.scrollWidth); - this.scrollLeftChanged = (this._oldScrollLeft !== this.scrollLeft); - this.scrollHeightChanged = (this._oldScrollHeight !== this.scrollHeight); - this.scrollTopChanged = (this._oldScrollTop !== this.scrollTop); - } - isNoOp() { - return (!this.scrollWidthChanged && !this.scrollLeftChanged && !this.scrollHeightChanged && !this.scrollTopChanged); - } - merge(other) { - if (other.kind !== 2 /* ScrollChanged */) { - return this; - } - return new ScrollChangedEvent(this._oldScrollWidth, this._oldScrollLeft, this._oldScrollHeight, this._oldScrollTop, other.scrollWidth, other.scrollLeft, other.scrollHeight, other.scrollTop); - } - } - exports.ScrollChangedEvent = ScrollChangedEvent; - class ViewZonesChangedEvent { - constructor() { - this.kind = 3 /* ViewZonesChanged */; - } - isNoOp() { - return false; - } - merge(other) { - return this; - } - } - exports.ViewZonesChangedEvent = ViewZonesChangedEvent; - class CursorStateChangedEvent { - constructor(oldSelections, selections, oldModelVersionId, modelVersionId, source, reason, reachedMaxCursorCount) { - this.kind = 5 /* CursorStateChanged */; - this.oldSelections = oldSelections; - this.selections = selections; - this.oldModelVersionId = oldModelVersionId; - this.modelVersionId = modelVersionId; - this.source = source; - this.reason = reason; - this.reachedMaxCursorCount = reachedMaxCursorCount; - } - static _selectionsAreEqual(a, b) { - if (!a && !b) { - return true; - } - if (!a || !b) { - return false; - } - const aLen = a.length; - const bLen = b.length; - if (aLen !== bLen) { - return false; - } - for (let i = 0; i < aLen; i++) { - if (!a[i].equalsSelection(b[i])) { - return false; - } - } - return true; - } - isNoOp() { - return (CursorStateChangedEvent._selectionsAreEqual(this.oldSelections, this.selections) - && this.oldModelVersionId === this.modelVersionId); - } - merge(other) { - if (other.kind !== 5 /* CursorStateChanged */) { - return this; - } - return new CursorStateChangedEvent(this.oldSelections, other.selections, this.oldModelVersionId, other.modelVersionId, other.source, other.reason, this.reachedMaxCursorCount || other.reachedMaxCursorCount); - } - } - exports.CursorStateChangedEvent = CursorStateChangedEvent; - class ReadOnlyEditAttemptEvent { - constructor() { - this.kind = 4 /* ReadOnlyEditAttempt */; - } - isNoOp() { - return false; - } - merge(other) { - return this; - } - } - exports.ReadOnlyEditAttemptEvent = ReadOnlyEditAttemptEvent; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[406/*vs/editor/common/viewLayout/viewLayout*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,127/*vs/base/common/scrollable*/,394/*vs/editor/common/viewLayout/linesLayout*/,62/*vs/editor/common/viewModel/viewModel*/,177/*vs/editor/common/viewModel/viewModelEventDispatcher*/]), function (require, exports, event_1, lifecycle_1, scrollable_1, linesLayout_1, viewModel_1, viewModelEventDispatcher_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ViewLayout = void 0; - const SMOOTH_SCROLLING_TIME = 125; - class EditorScrollDimensions { - constructor(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); - } - equals(other) { - return (this.width === other.width - && this.contentWidth === other.contentWidth - && this.height === other.height - && this.contentHeight === other.contentHeight); - } - } - class EditorScrollable extends lifecycle_1.Disposable { - constructor(smoothScrollDuration, scheduleAtNextAnimationFrame) { - super(); - 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; - } - getScrollable() { - return this._scrollable; - } - setSmoothScrollDuration(smoothScrollDuration) { - this._scrollable.setSmoothScrollDuration(smoothScrollDuration); - } - validateScrollPosition(scrollPosition) { - return this._scrollable.validateScrollPosition(scrollPosition); - } - getScrollDimensions() { - return this._dimensions; - } - setScrollDimensions(dimensions) { - if (this._dimensions.equals(dimensions)) { - return; - } - const oldDimensions = this._dimensions; - this._dimensions = dimensions; - this._scrollable.setScrollDimensions({ - width: dimensions.width, - scrollWidth: dimensions.scrollWidth, - height: dimensions.height, - scrollHeight: dimensions.scrollHeight - }, true); - const contentWidthChanged = (oldDimensions.contentWidth !== dimensions.contentWidth); - const contentHeightChanged = (oldDimensions.contentHeight !== dimensions.contentHeight); - if (contentWidthChanged || contentHeightChanged) { - this._onDidContentSizeChange.fire(new viewModelEventDispatcher_1.ContentSizeChangedEvent(oldDimensions.contentWidth, oldDimensions.contentHeight, dimensions.contentWidth, dimensions.contentHeight)); - } - } - getFutureScrollPosition() { - return this._scrollable.getFutureScrollPosition(); - } - getCurrentScrollPosition() { - return this._scrollable.getCurrentScrollPosition(); - } - setScrollPositionNow(update) { - this._scrollable.setScrollPositionNow(update); - } - setScrollPositionSmooth(update) { - this._scrollable.setScrollPositionSmooth(update); - } - } - class ViewLayout extends lifecycle_1.Disposable { - constructor(configuration, lineCount, scheduleAtNextAnimationFrame) { - super(); - this._configuration = configuration; - const options = this._configuration.options; - const layoutInfo = options.get(129 /* layoutInfo */); - const padding = options.get(73 /* padding */); - this._linesLayout = new linesLayout_1.LinesLayout(lineCount, options.get(57 /* lineHeight */), padding.top, padding.bottom); - 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(); - } - dispose() { - super.dispose(); - } - getScrollable() { - return this._scrollable.getScrollable(); - } - onHeightMaybeChanged() { - this._updateHeight(); - } - _configureSmoothScrollDuration() { - this._scrollable.setSmoothScrollDuration(this._configuration.options.get(102 /* smoothScrolling */) ? SMOOTH_SCROLLING_TIME : 0); - } - // ---- begin view event handlers - onConfigurationChanged(e) { - const options = this._configuration.options; - if (e.hasChanged(57 /* lineHeight */)) { - this._linesLayout.setLineHeight(options.get(57 /* lineHeight */)); - } - if (e.hasChanged(73 /* padding */)) { - const padding = options.get(73 /* padding */); - this._linesLayout.setPadding(padding.top, padding.bottom); - } - if (e.hasChanged(129 /* layoutInfo */)) { - const layoutInfo = options.get(129 /* layoutInfo */); - const width = layoutInfo.contentWidth; - const height = layoutInfo.height; - const scrollDimensions = this._scrollable.getScrollDimensions(); - const contentWidth = scrollDimensions.contentWidth; - this._scrollable.setScrollDimensions(new EditorScrollDimensions(width, scrollDimensions.contentWidth, height, this._getContentHeight(width, height, contentWidth))); - } - else { - this._updateHeight(); - } - if (e.hasChanged(102 /* smoothScrolling */)) { - this._configureSmoothScrollDuration(); - } - } - onFlushed(lineCount) { - this._linesLayout.onFlushed(lineCount); - } - onLinesDeleted(fromLineNumber, toLineNumber) { - this._linesLayout.onLinesDeleted(fromLineNumber, toLineNumber); - } - onLinesInserted(fromLineNumber, toLineNumber) { - this._linesLayout.onLinesInserted(fromLineNumber, toLineNumber); - } - // ---- end view event handlers - _getHorizontalScrollbarHeight(width, scrollWidth) { - const options = this._configuration.options; - const scrollbar = options.get(91 /* scrollbar */); - if (scrollbar.horizontal === 2 /* Hidden */) { - // horizontal scrollbar not visible - return 0; - } - if (width >= scrollWidth) { - // horizontal scrollbar not visible - return 0; - } - return scrollbar.horizontalScrollbarSize; - } - _getContentHeight(width, height, contentWidth) { - const options = this._configuration.options; - let result = this._linesLayout.getLinesTotalHeight(); - if (options.get(93 /* scrollBeyondLastLine */)) { - result += Math.max(0, height - options.get(57 /* lineHeight */) - options.get(73 /* padding */).bottom); - } - else { - result += this._getHorizontalScrollbarHeight(width, contentWidth); - } - return result; - } - _updateHeight() { - const scrollDimensions = this._scrollable.getScrollDimensions(); - const width = scrollDimensions.width; - const height = scrollDimensions.height; - const contentWidth = scrollDimensions.contentWidth; - this._scrollable.setScrollDimensions(new EditorScrollDimensions(width, scrollDimensions.contentWidth, height, this._getContentHeight(width, height, contentWidth))); - } - // ---- Layouting logic - getCurrentViewport() { - const scrollDimensions = this._scrollable.getScrollDimensions(); - const currentScrollPosition = this._scrollable.getCurrentScrollPosition(); - return new viewModel_1.Viewport(currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height); - } - getFutureViewport() { - const scrollDimensions = this._scrollable.getScrollDimensions(); - const currentScrollPosition = this._scrollable.getFutureScrollPosition(); - return new viewModel_1.Viewport(currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height); - } - _computeContentWidth(maxLineWidth) { - const options = this._configuration.options; - const wrappingInfo = options.get(130 /* wrappingInfo */); - const fontInfo = options.get(41 /* fontInfo */); - if (wrappingInfo.isViewportWrapping) { - const layoutInfo = options.get(129 /* layoutInfo */); - const minimap = options.get(63 /* 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 { - const extraHorizontalSpace = options.get(92 /* scrollBeyondLastColumn */) * fontInfo.typicalHalfwidthCharacterWidth; - const whitespaceMinWidth = this._linesLayout.getWhitespaceMinWidth(); - return Math.max(maxLineWidth + extraHorizontalSpace, whitespaceMinWidth); - } - } - setMaxLineWidth(maxLineWidth) { - const 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 - saveState() { - const currentScrollPosition = this._scrollable.getFutureScrollPosition(); - let scrollTop = currentScrollPosition.scrollTop; - let firstLineNumberInViewport = this._linesLayout.getLineNumberAtOrAfterVerticalOffset(scrollTop); - let whitespaceAboveFirstLine = this._linesLayout.getWhitespaceAccumulatedHeightBeforeLineNumber(firstLineNumberInViewport); - return { - scrollTop: scrollTop, - scrollTopWithoutViewZones: scrollTop - whitespaceAboveFirstLine, - scrollLeft: currentScrollPosition.scrollLeft - }; - } - // ---- IVerticalLayoutProvider - changeWhitespace(callback) { - const hadAChange = this._linesLayout.changeWhitespace(callback); - if (hadAChange) { - this.onHeightMaybeChanged(); - } - return hadAChange; - } - getVerticalOffsetForLineNumber(lineNumber) { - return this._linesLayout.getVerticalOffsetForLineNumber(lineNumber); - } - isAfterLines(verticalOffset) { - return this._linesLayout.isAfterLines(verticalOffset); - } - isInTopPadding(verticalOffset) { - return this._linesLayout.isInTopPadding(verticalOffset); - } - isInBottomPadding(verticalOffset) { - return this._linesLayout.isInBottomPadding(verticalOffset); - } - getLineNumberAtVerticalOffset(verticalOffset) { - return this._linesLayout.getLineNumberAtOrAfterVerticalOffset(verticalOffset); - } - getWhitespaceAtVerticalOffset(verticalOffset) { - return this._linesLayout.getWhitespaceAtVerticalOffset(verticalOffset); - } - getLinesViewportData() { - const visibleBox = this.getCurrentViewport(); - return this._linesLayout.getLinesViewportData(visibleBox.top, visibleBox.top + visibleBox.height); - } - getLinesViewportDataAtScrollTop(scrollTop) { - // do some minimal validations on scrollTop - const 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); - } - getWhitespaceViewportData() { - const visibleBox = this.getCurrentViewport(); - return this._linesLayout.getWhitespaceViewportData(visibleBox.top, visibleBox.top + visibleBox.height); - } - getWhitespaces() { - return this._linesLayout.getWhitespaces(); - } - // ---- IScrollingProvider - getContentWidth() { - const scrollDimensions = this._scrollable.getScrollDimensions(); - return scrollDimensions.contentWidth; - } - getScrollWidth() { - const scrollDimensions = this._scrollable.getScrollDimensions(); - return scrollDimensions.scrollWidth; - } - getContentHeight() { - const scrollDimensions = this._scrollable.getScrollDimensions(); - return scrollDimensions.contentHeight; - } - getScrollHeight() { - const scrollDimensions = this._scrollable.getScrollDimensions(); - return scrollDimensions.scrollHeight; - } - getCurrentScrollLeft() { - const currentScrollPosition = this._scrollable.getCurrentScrollPosition(); - return currentScrollPosition.scrollLeft; - } - getCurrentScrollTop() { - const currentScrollPosition = this._scrollable.getCurrentScrollPosition(); - return currentScrollPosition.scrollTop; - } - validateScrollPosition(scrollPosition) { - return this._scrollable.validateScrollPosition(scrollPosition); - } - setScrollPosition(position, type) { - if (type === 1 /* Immediate */) { - this._scrollable.setScrollPositionNow(position); - } - else { - this._scrollable.setScrollPositionSmooth(position); - } - } - deltaScrollNow(deltaScrollLeft, deltaScrollTop) { - const currentScrollPosition = this._scrollable.getCurrentScrollPosition(); - this._scrollable.setScrollPositionNow({ - scrollLeft: currentScrollPosition.scrollLeft + deltaScrollLeft, - scrollTop: currentScrollPosition.scrollTop + deltaScrollTop - }); - } - } - 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[407/*vs/editor/contrib/caretOperations/moveCaretCommand*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/]), function (require, exports, range_1, selection_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MoveCaretCommand = void 0; - class MoveCaretCommand { - constructor(selection, isMovingLeft) { - this._selection = selection; - this._isMovingLeft = isMovingLeft; - } - getEditOperations(model, builder) { - if (this._selection.startLineNumber !== this._selection.endLineNumber || this._selection.isEmpty()) { - return; - } - const lineNumber = this._selection.startLineNumber; - const startColumn = this._selection.startColumn; - const endColumn = this._selection.endColumn; - if (this._isMovingLeft && startColumn === 1) { - return; - } - if (!this._isMovingLeft && endColumn === model.getLineMaxColumn(lineNumber)) { - return; - } - if (this._isMovingLeft) { - const rangeBefore = new range_1.Range(lineNumber, startColumn - 1, lineNumber, startColumn); - const charBefore = model.getValueInRange(rangeBefore); - builder.addEditOperation(rangeBefore, null); - builder.addEditOperation(new range_1.Range(lineNumber, endColumn, lineNumber, endColumn), charBefore); - } - else { - const rangeAfter = new range_1.Range(lineNumber, endColumn, lineNumber, endColumn + 1); - const charAfter = model.getValueInRange(rangeAfter); - builder.addEditOperation(rangeAfter, null); - builder.addEditOperation(new range_1.Range(lineNumber, startColumn, lineNumber, startColumn), charAfter); - } - } - computeCursorState(model, helper) { - if (this._isMovingLeft) { - return new selection_1.Selection(this._selection.startLineNumber, this._selection.startColumn - 1, this._selection.endLineNumber, this._selection.endColumn - 1); - } - else { - return new selection_1.Selection(this._selection.startLineNumber, this._selection.startColumn + 1, this._selection.endLineNumber, this._selection.endColumn + 1); - } - } - } - 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[137/*vs/editor/contrib/codeAction/types*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CodeActionCommandArgs = exports.filtersAction = exports.mayIncludeActionsOfKind = exports.CodeActionKind = void 0; - class CodeActionKind { - constructor(value) { - this.value = value; - } - equals(other) { - return this.value === other.value; - } - contains(other) { - return this.equals(other) || this.value === '' || other.value.startsWith(this.value + CodeActionKind.sep); - } - intersects(other) { - return this.contains(other) || other.contains(this); - } - append(part) { - return new CodeActionKind(this.value + CodeActionKind.sep + part); - } - } - exports.CodeActionKind = CodeActionKind; - 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'); - 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(exclude => 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) { - const 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(exclude => 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; - } - class CodeActionCommandArgs { - constructor(kind, apply, preferred) { - this.kind = kind; - this.apply = apply; - this.preferred = preferred; - } - static fromUser(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)); - } - static getApplyFromUser(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; - } - } - static getKindFromUser(arg, defaultKind) { - return typeof arg.kind === 'string' - ? new CodeActionKind(arg.kind) - : defaultKind; - } - static getPreferredUser(arg) { - return typeof arg.preferred === 'boolean' - ? arg.preferred - : false; - } - } - 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[408/*vs/editor/contrib/colorPicker/colorPickerModel*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/]), function (require, exports, event_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ColorPickerModel = void 0; - class ColorPickerModel { - constructor(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; - } - get color() { - return this._color; - } - set color(color) { - if (this._color.equals(color)) { - return; - } - this._color = color; - this._onDidChangeColor.fire(color); - } - get presentation() { return this.colorPresentations[this.presentationIndex]; } - get colorPresentations() { - return this._colorPresentations; - } - set colorPresentations(colorPresentations) { - this._colorPresentations = colorPresentations; - if (this.presentationIndex > colorPresentations.length - 1) { - this.presentationIndex = 0; - } - this._onDidChangePresentation.fire(this.presentation); - } - selectNextColorPresentation() { - this.presentationIndex = (this.presentationIndex + 1) % this.colorPresentations.length; - this.flushColor(); - this._onDidChangePresentation.fire(this.presentation); - } - guessColorPresentation(color, originalText) { - for (let i = 0; i < this.colorPresentations.length; i++) { - if (originalText.toLowerCase() === this.colorPresentations[i].label) { - this.presentationIndex = i; - this._onDidChangePresentation.fire(this.presentation); - break; - } - } - } - flushColor() { - this._onColorFlushed.fire(this._color); - } - } - 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[226/*vs/editor/contrib/comment/blockCommentCommand*/], __M([0/*require*/,1/*exports*/,56/*vs/editor/common/core/editOperation*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,45/*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 }); - exports.BlockCommentCommand = void 0; - class BlockCommentCommand { - constructor(selection, insertSpace) { - this._selection = selection; - this._insertSpace = insertSpace; - this._usedEndToken = null; - } - static _haystackHasNeedleAtOffset(haystack, needle, offset) { - if (offset < 0) { - return false; - } - const needleLength = needle.length; - const haystackLength = haystack.length; - if (offset + needleLength > haystackLength) { - return false; - } - for (let i = 0; i < needleLength; i++) { - const codeA = haystack.charCodeAt(offset + i); - const 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; - } - _createOperationsForBlockComment(selection, startToken, endToken, insertSpace, model, builder) { - const startLineNumber = selection.startLineNumber; - const startColumn = selection.startColumn; - const endLineNumber = selection.endLineNumber; - const endColumn = selection.endColumn; - const startLineText = model.getLineContent(startLineNumber); - const endLineText = model.getLineContent(endLineNumber); - let startTokenIndex = startLineText.lastIndexOf(startToken, startColumn - 1 + startToken.length); - let endTokenIndex = endLineText.indexOf(endToken, endColumn - 1 - endToken.length); - if (startTokenIndex !== -1 && endTokenIndex !== -1) { - if (startLineNumber === endLineNumber) { - const lineBetweenTokens = startLineText.substring(startTokenIndex + startToken.length, endTokenIndex); - if (lineBetweenTokens.indexOf(endToken) >= 0) { - // force to add a block comment - startTokenIndex = -1; - endTokenIndex = -1; - } - } - else { - const startLineAfterStartToken = startLineText.substring(startTokenIndex + startToken.length); - const endLineBeforeEndToken = endLineText.substring(0, endTokenIndex); - if (startLineAfterStartToken.indexOf(endToken) >= 0 || endLineBeforeEndToken.indexOf(endToken) >= 0) { - // force to add a block comment - startTokenIndex = -1; - endTokenIndex = -1; - } - } - } - let 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 (const op of ops) { - builder.addTrackedEditOperation(op.range, op.text); - } - } - static _createRemoveBlockCommentOperations(r, startToken, endToken) { - let 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; - } - static _createAddBlockCommentOperations(r, startToken, endToken, insertSpace) { - let 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; - } - getEditOperations(model, builder) { - const startLineNumber = this._selection.startLineNumber; - const startColumn = this._selection.startColumn; - model.tokenizeIfCheap(startLineNumber); - const languageId = model.getLanguageIdAtPosition(startLineNumber, startColumn); - const 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); - } - computeCursorState(model, helper) { - const inverseEditOperations = helper.getInverseEditOperations(); - if (inverseEditOperations.length === 2) { - const startTokenEditOperation = inverseEditOperations[0]; - const endTokenEditOperation = inverseEditOperations[1]; - return new selection_1.Selection(startTokenEditOperation.range.endLineNumber, startTokenEditOperation.range.endColumn, endTokenEditOperation.range.startLineNumber, endTokenEditOperation.range.startColumn); - } - else { - const srcRange = inverseEditOperations[0].range; - const 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); - } - } - } - 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[409/*vs/editor/contrib/comment/lineCommentCommand*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,56/*vs/editor/common/core/editOperation*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/,226/*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 }); - exports.LineCommentCommand = void 0; - class LineCommentCommand { - constructor(selection, tabSize, type, insertSpace, ignoreEmptyLines, ignoreFirstLine) { - this._selection = selection; - this._tabSize = tabSize; - this._type = type; - this._insertSpace = insertSpace; - this._selectionId = null; - this._deltaColumn = 0; - this._moveEndPositionDown = false; - this._ignoreEmptyLines = ignoreEmptyLines; - this._ignoreFirstLine = ignoreFirstLine || 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. - */ - static _gatherPreflightCommentStrings(model, startLineNumber, endLineNumber) { - model.tokenizeIfCheap(startLineNumber); - const languageId = model.getLanguageIdAtPosition(startLineNumber, 1); - const config = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getComments(languageId); - const commentStr = (config ? config.lineCommentToken : null); - if (!commentStr) { - // Mode does not support line comments - return null; - } - let lines = []; - for (let 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. - */ - static _analyzeLines(type, insertSpace, model, lines, startLineNumber, ignoreEmptyLines, ignoreFirstLine) { - let onlyWhitespaceLines = true; - let shouldRemoveComments; - if (type === 0 /* Toggle */) { - shouldRemoveComments = true; - } - else if (type === 1 /* ForceAdd */) { - shouldRemoveComments = false; - } - else { - shouldRemoveComments = true; - } - for (let i = 0, lineCount = lines.length; i < lineCount; i++) { - const lineData = lines[i]; - const lineNumber = startLineNumber + i; - if (lineNumber === startLineNumber && ignoreFirstLine) { - // first line ignored - lineData.ignore = true; - continue; - } - const lineContent = model.getLineContent(lineNumber); - const lineContentStartOffset = strings.firstNonWhitespaceIndex(lineContent); - if (lineContentStartOffset === -1) { - // Empty or whitespace only line - lineData.ignore = ignoreEmptyLines; - 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 - const 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 (let 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 - */ - static _gatherPreflightData(type, insertSpace, model, startLineNumber, endLineNumber, ignoreEmptyLines, ignoreFirstLine) { - const lines = LineCommentCommand._gatherPreflightCommentStrings(model, startLineNumber, endLineNumber); - if (lines === null) { - return { - supported: false - }; - } - return LineCommentCommand._analyzeLines(type, insertSpace, model, lines, startLineNumber, ignoreEmptyLines, ignoreFirstLine); - } - /** - * Given a successful analysis, execute either insert line comments, either remove line comments - */ - _executeLineComments(model, builder, data, s) { - let 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); - } - const cursorPosition = new position_1.Position(s.positionLineNumber, s.positionColumn); - for (let i = 0, len = ops.length; i < len; i++) { - builder.addEditOperation(ops[i].range, ops[i].text); - if (range_1.Range.isEmpty(ops[i].range) && range_1.Range.getStartPosition(ops[i].range).equals(cursorPosition)) { - const lineContent = model.getLineContent(cursorPosition.lineNumber); - if (lineContent.length + 1 === cursorPosition.column) { - this._deltaColumn = (ops[i].text || '').length; - } - } - } - this._selectionId = builder.trackSelection(s); - } - _attemptRemoveBlockComment(model, s, startToken, endToken) { - let startLineNumber = s.startLineNumber; - let endLineNumber = s.endLineNumber; - let startTokenAllowedBeforeColumn = endToken.length + Math.max(model.getLineFirstNonWhitespaceColumn(s.startLineNumber), s.startColumn); - let startTokenIndex = model.getLineContent(startLineNumber).lastIndexOf(startToken, startTokenAllowedBeforeColumn - 1); - let 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 - */ - _executeBlockComment(model, builder, s) { - model.tokenizeIfCheap(s.startLineNumber); - let languageId = model.getLanguageIdAtPosition(s.startLineNumber, 1); - let config = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getComments(languageId); - if (!config || !config.blockCommentStartToken || !config.blockCommentEndToken) { - // Mode does not support block comments - return; - } - const startToken = config.blockCommentStartToken; - const endToken = config.blockCommentEndToken; - let ops = this._attemptRemoveBlockComment(model, s, startToken, endToken); - if (!ops) { - if (s.isEmpty()) { - const lineContent = model.getLineContent(s.startLineNumber); - let 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 (const op of ops) { - builder.addEditOperation(op.range, op.text); - } - } - getEditOperations(model, builder) { - let s = this._selection; - this._moveEndPositionDown = false; - if (s.startLineNumber === s.endLineNumber && this._ignoreFirstLine) { - builder.addEditOperation(new range_1.Range(s.startLineNumber, model.getLineMaxColumn(s.startLineNumber), s.startLineNumber + 1, 1), s.startLineNumber === model.getLineCount() ? '' : '\n'); - this._selectionId = builder.trackSelection(s); - return; - } - if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) { - this._moveEndPositionDown = true; - s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1)); - } - const data = LineCommentCommand._gatherPreflightData(this._type, this._insertSpace, model, s.startLineNumber, s.endLineNumber, this._ignoreEmptyLines, this._ignoreFirstLine); - if (data.supported) { - return this._executeLineComments(model, builder, data, s); - } - return this._executeBlockComment(model, builder, s); - } - computeCursorState(model, helper) { - let 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 - */ - static _createRemoveLineCommentsOperations(lines, startLineNumber) { - let res = []; - for (let i = 0, len = lines.length; i < len; i++) { - const 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 - */ - _createAddLineCommentsOperations(lines, startLineNumber) { - let res = []; - const afterCommentStr = this._insertSpace ? ' ' : ''; - for (let i = 0, len = lines.length; i < len; i++) { - const 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; - } - static nextVisibleColumn(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 - */ - static _normalizeInsertionPoint(model, lines, startLineNumber, tabSize) { - let minVisibleColumn = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; - let j; - let lenJ; - for (let i = 0, len = lines.length; i < len; i++) { - if (lines[i].ignore) { - continue; - } - const lineContent = model.getLineContent(startLineNumber + i); - let currentVisibleColumn = 0; - for (let 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) { - minVisibleColumn = currentVisibleColumn; - } - } - minVisibleColumn = Math.floor(minVisibleColumn / tabSize) * tabSize; - for (let i = 0, len = lines.length; i < len; i++) { - if (lines[i].ignore) { - continue; - } - const lineContent = model.getLineContent(startLineNumber + i); - let 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; - } - } - } - } - 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[410/*vs/editor/contrib/dnd/dragAndDropCommand*/], __M([0/*require*/,1/*exports*/,21/*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 }); - exports.DragAndDropCommand = void 0; - class DragAndDropCommand { - constructor(selection, targetPosition, copy) { - this.selection = selection; - this.targetPosition = targetPosition; - this.copy = copy; - this.targetSelection = null; - } - getEditOperations(model, builder) { - let 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); - } - } - computeCursorState(model, helper) { - return this.targetSelection; - } - } - 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[411/*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 }); - exports.ReplaceAllCommand = void 0; - class ReplaceAllCommand { - constructor(editorSelection, ranges, replaceStrings) { - this._editorSelection = editorSelection; - this._ranges = ranges; - this._replaceStrings = replaceStrings; - this._trackedEditorSelectionId = null; - } - getEditOperations(model, builder) { - if (this._ranges.length > 0) { - // Collect all edit operations - let ops = []; - for (let 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((o1, o2) => { - return range_1.Range.compareRangesUsingStarts(o1.range, o2.range); - }); - // Merge operations that touch each other - let resultOps = []; - let previousOp = ops[0]; - for (let 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 (const op of resultOps) { - builder.addEditOperation(op.range, op.text); - } - } - this._trackedEditorSelectionId = builder.trackSelection(this._editorSelection); - } - computeCursorState(model, helper) { - return helper.getTrackedSelection(this._trackedEditorSelectionId); - } - } - 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[412/*vs/editor/contrib/find/replacePattern*/], __M([0/*require*/,1/*exports*/,293/*vs/base/common/search*/]), function (require, exports, search_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.parseReplaceString = exports.ReplacePiece = exports.ReplacePattern = void 0; - /** - * Assigned when the replace pattern is entirely static. - */ - class StaticValueReplacePattern { - constructor(staticValue) { - this.staticValue = staticValue; - this.kind = 0 /* StaticValue */; - } - } - /** - * Assigned when the replace pattern has replacement patterns. - */ - class DynamicPiecesReplacePattern { - constructor(pieces) { - this.pieces = pieces; - this.kind = 1 /* DynamicPieces */; - } - } - class ReplacePattern { - constructor(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); - } - } - static fromStaticValue(value) { - return new ReplacePattern([ReplacePiece.staticValue(value)]); - } - get hasReplacementPatterns() { - return (this._state.kind === 1 /* DynamicPieces */); - } - buildReplaceString(matches, preserveCase) { - if (this._state.kind === 0 /* StaticValue */) { - if (preserveCase) { - return (0, search_1.buildReplaceStringWithCasePreserved)(matches, this._state.staticValue); - } - else { - return this._state.staticValue; - } - } - let result = ''; - for (let i = 0, len = this._state.pieces.length; i < len; i++) { - let piece = this._state.pieces[i]; - if (piece.staticValue !== null) { - // static value ReplacePiece - result += piece.staticValue; - continue; - } - // match index ReplacePiece - let match = ReplacePattern._substitute(piece.matchIndex, matches); - if (piece.caseOps !== null && piece.caseOps.length > 0) { - let repl = []; - let lenOps = piece.caseOps.length; - let opIdx = 0; - for (let idx = 0, len = match.length; idx < len; idx++) { - if (opIdx >= lenOps) { - repl.push(match.slice(idx)); - break; - } - switch (piece.caseOps[opIdx]) { - case 'U': - repl.push(match[idx].toUpperCase()); - break; - case 'u': - repl.push(match[idx].toUpperCase()); - opIdx++; - break; - case 'L': - repl.push(match[idx].toLowerCase()); - break; - case 'l': - repl.push(match[idx].toLowerCase()); - opIdx++; - break; - default: - repl.push(match[idx]); - } - } - match = repl.join(''); - } - result += match; - } - return result; - } - static _substitute(matchIndex, matches) { - if (matches === null) { - return ''; - } - if (matchIndex === 0) { - return matches[0]; - } - let remainder = ''; - while (matchIndex > 0) { - if (matchIndex < matches.length) { - // A match can be undefined - let match = (matches[matchIndex] || ''); - return match + remainder; - } - remainder = String(matchIndex % 10) + remainder; - matchIndex = Math.floor(matchIndex / 10); - } - return '$' + remainder; - } - } - exports.ReplacePattern = ReplacePattern; - /** - * A replace piece can either be a static string or an index to a specific match. - */ - class ReplacePiece { - constructor(staticValue, matchIndex, caseOps) { - this.staticValue = staticValue; - this.matchIndex = matchIndex; - if (!caseOps || caseOps.length === 0) { - this.caseOps = null; - } - else { - this.caseOps = caseOps.slice(0); - } - } - static staticValue(value) { - return new ReplacePiece(value, -1, null); - } - static caseOps(index, caseOps) { - return new ReplacePiece(null, index, caseOps); - } - } - exports.ReplacePiece = ReplacePiece; - class ReplacePieceBuilder { - constructor(source) { - this._source = source; - this._lastCharIndex = 0; - this._result = []; - this._resultLen = 0; - this._currentStaticPiece = ''; - } - emitUnchanged(toCharIndex) { - this._emitStatic(this._source.substring(this._lastCharIndex, toCharIndex)); - this._lastCharIndex = toCharIndex; - } - emitStatic(value, toCharIndex) { - this._emitStatic(value); - this._lastCharIndex = toCharIndex; - } - _emitStatic(value) { - if (value.length === 0) { - return; - } - this._currentStaticPiece += value; - } - emitMatchIndex(index, toCharIndex, caseOps) { - if (this._currentStaticPiece.length !== 0) { - this._result[this._resultLen++] = ReplacePiece.staticValue(this._currentStaticPiece); - this._currentStaticPiece = ''; - } - this._result[this._resultLen++] = ReplacePiece.caseOps(index, caseOps); - this._lastCharIndex = toCharIndex; - } - finalize() { - 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); - } - } - /** - * \n => inserts a LF - * \t => inserts a TAB - * \\ => inserts a "\". - * \u => upper-cases one character in a match. - * \U => upper-cases ALL remaining characters in a match. - * \l => lower-cases one character in a match. - * \L => lower-cases ALL remaining characters in a match. - * $$ => 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); - } - let caseOps = []; - let result = new ReplacePieceBuilder(replaceString); - for (let i = 0, len = replaceString.length; i < len; i++) { - let chCode = replaceString.charCodeAt(i); - if (chCode === 92 /* Backslash */) { - // move to next char - i++; - if (i >= len) { - // string ends with a \ - break; - } - let 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; - // Case modification of string replacements, patterned after Boost, but only applied - // to the replacement text, not subsequent content. - case 117 /* u */: - // \u => upper-cases one character. - case 85 /* U */: - // \U => upper-cases ALL following characters. - case 108 /* l */: - // \l => lower-cases one character. - case 76 /* L */: - // \L => lower-cases ALL following characters. - result.emitUnchanged(i - 1); - result.emitStatic('', i + 1); - caseOps.push(String.fromCharCode(nextChCode)); - break; - } - continue; - } - if (chCode === 36 /* DollarSign */) { - // move to next char - i++; - if (i >= len) { - // string ends with a $ - break; - } - let 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, caseOps); - caseOps.length = 0; - continue; - } - if (49 /* Digit1 */ <= nextChCode && nextChCode <= 57 /* Digit9 */) { - // $n - let matchIndex = nextChCode - 48 /* Digit0 */; - // peek next char to probe for $nn - if (i + 1 < len) { - let 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, caseOps); - caseOps.length = 0; - continue; - } - } - result.emitUnchanged(i - 1); - result.emitMatchIndex(matchIndex, i + 1, caseOps); - caseOps.length = 0; - 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[178/*vs/editor/contrib/folding/foldingRanges*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.FoldingRegion = exports.FoldingRegions = exports.MAX_LINE_NUMBER = exports.MAX_FOLDING_REGIONS = void 0; - exports.MAX_FOLDING_REGIONS = 0xFFFF; - exports.MAX_LINE_NUMBER = 0xFFFFFF; - const MASK_INDENT = 0xFF000000; - class FoldingRegions { - constructor(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; - } - ensureParentIndices() { - if (!this._parentsComputed) { - this._parentsComputed = true; - let parentIndexes = []; - let isInsideLast = (startLineNumber, endLineNumber) => { - let index = parentIndexes[parentIndexes.length - 1]; - return this.getStartLineNumber(index) <= startLineNumber && this.getEndLineNumber(index) >= endLineNumber; - }; - for (let i = 0, len = this._startIndexes.length; i < len; i++) { - let startLineNumber = this._startIndexes[i]; - let 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.length > 0 && !isInsideLast(startLineNumber, endLineNumber)) { - parentIndexes.pop(); - } - let parentIndex = parentIndexes.length > 0 ? parentIndexes[parentIndexes.length - 1] : -1; - parentIndexes.push(i); - this._startIndexes[i] = startLineNumber + ((parentIndex & 0xFF) << 24); - this._endIndexes[i] = endLineNumber + ((parentIndex & 0xFF00) << 16); - } - } - } - get length() { - return this._startIndexes.length; - } - getStartLineNumber(index) { - return this._startIndexes[index] & exports.MAX_LINE_NUMBER; - } - getEndLineNumber(index) { - return this._endIndexes[index] & exports.MAX_LINE_NUMBER; - } - getType(index) { - return this._types ? this._types[index] : undefined; - } - hasTypes() { - return !!this._types; - } - isCollapsed(index) { - let arrayIndex = (index / 32) | 0; - let bit = index % 32; - return (this._collapseStates[arrayIndex] & (1 << bit)) !== 0; - } - setCollapsed(index, newState) { - let arrayIndex = (index / 32) | 0; - let bit = index % 32; - let value = this._collapseStates[arrayIndex]; - if (newState) { - this._collapseStates[arrayIndex] = value | (1 << bit); - } - else { - this._collapseStates[arrayIndex] = value & ~(1 << bit); - } - } - setCollapsedAllOfType(type, newState) { - let hasChanged = false; - if (this._types) { - for (let i = 0; i < this._types.length; i++) { - if (this._types[i] === type) { - this.setCollapsed(i, newState); - hasChanged = true; - } - } - } - return hasChanged; - } - toRegion(index) { - return new FoldingRegion(this, index); - } - getParentIndex(index) { - this.ensureParentIndices(); - let parent = ((this._startIndexes[index] & MASK_INDENT) >>> 24) + ((this._endIndexes[index] & MASK_INDENT) >>> 16); - if (parent === exports.MAX_FOLDING_REGIONS) { - return -1; - } - return parent; - } - contains(index, line) { - return this.getStartLineNumber(index) <= line && this.getEndLineNumber(index) >= line; - } - findIndex(line) { - let low = 0, high = this._startIndexes.length; - if (high === 0) { - return -1; // no children - } - while (low < high) { - let mid = Math.floor((low + high) / 2); - if (line < this.getStartLineNumber(mid)) { - high = mid; - } - else { - low = mid + 1; - } - } - return low - 1; - } - findRange(line) { - let index = this.findIndex(line); - if (index >= 0) { - let 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; - } - toString() { - let res = []; - for (let i = 0; i < this.length; i++) { - res[i] = `[${this.isCollapsed(i) ? '+' : '-'}] ${this.getStartLineNumber(i)}/${this.getEndLineNumber(i)}`; - } - return res.join(', '); - } - } - exports.FoldingRegions = FoldingRegions; - class FoldingRegion { - constructor(ranges, index) { - this.ranges = ranges; - this.index = index; - } - get startLineNumber() { - return this.ranges.getStartLineNumber(this.index); - } - get endLineNumber() { - return this.ranges.getEndLineNumber(this.index); - } - get regionIndex() { - return this.index; - } - get parentIndex() { - return this.ranges.getParentIndex(this.index); - } - get isCollapsed() { - return this.ranges.isCollapsed(this.index); - } - containedBy(range) { - return range.startLineNumber <= this.startLineNumber && range.endLineNumber >= this.endLineNumber; - } - containsLine(lineNumber) { - return this.startLineNumber <= lineNumber && lineNumber <= this.endLineNumber; - } - } - 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[413/*vs/editor/contrib/folding/foldingModel*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,178/*vs/editor/contrib/folding/foldingRanges*/]), function (require, exports, event_1, foldingRanges_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getNextFoldLine = exports.getPreviousFoldLine = exports.getParentFoldLine = exports.setCollapseStateForType = exports.setCollapseStateForMatchingLines = exports.setCollapseStateForRest = exports.setCollapseStateAtLevel = exports.setCollapseStateUp = exports.setCollapseStateLevelsUp = exports.setCollapseStateLevelsDown = exports.toggleCollapseState = exports.FoldingModel = void 0; - class FoldingModel { - constructor(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; - } - get regions() { return this._regions; } - get textModel() { return this._textModel; } - get isInitialized() { return this._isInitialized; } - toggleCollapseState(toggledRegions) { - if (!toggledRegions.length) { - return; - } - toggledRegions = toggledRegions.sort((r1, r2) => r1.regionIndex - r2.regionIndex); - const processed = {}; - this._decorationProvider.changeDecorations(accessor => { - let k = 0; // index from [0 ... this.regions.length] - let dirtyRegionEndLine = -1; // end of the range where decorations need to be updated - let lastHiddenLine = -1; // the end of the last hidden lines - const updateDecorationsUntil = (index) => { - while (k < index) { - const endLineNumber = this._regions.getEndLineNumber(k); - const isCollapsed = this._regions.isCollapsed(k); - if (endLineNumber <= dirtyRegionEndLine) { - accessor.changeDecorationOptions(this._editorDecorationIds[k], this._decorationProvider.getDecorationOption(isCollapsed, endLineNumber <= lastHiddenLine)); - } - if (isCollapsed && endLineNumber > lastHiddenLine) { - lastHiddenLine = endLineNumber; - } - k++; - } - }; - for (let region of toggledRegions) { - let index = region.regionIndex; - let editorDecorationId = this._editorDecorationIds[index]; - if (editorDecorationId && !processed[editorDecorationId]) { - processed[editorDecorationId] = true; - updateDecorationsUntil(index); // update all decorations up to current index using the old dirtyRegionEndLine - let newCollapseState = !this._regions.isCollapsed(index); - this._regions.setCollapsed(index, newCollapseState); - dirtyRegionEndLine = Math.max(dirtyRegionEndLine, this._regions.getEndLineNumber(index)); - } - } - updateDecorationsUntil(this._regions.length); - }); - this._updateEventEmitter.fire({ model: this, collapseStateChanged: toggledRegions }); - } - update(newRegions, blockedLineNumers = []) { - let newEditorDecorations = []; - let isBlocked = (startLineNumber, endLineNumber) => { - for (let blockedLineNumber of blockedLineNumers) { - if (startLineNumber < blockedLineNumber && blockedLineNumber <= endLineNumber) { // first line is visible - return true; - } - } - return false; - }; - let lastHiddenLine = -1; - let initRange = (index, isCollapsed) => { - const startLineNumber = newRegions.getStartLineNumber(index); - const endLineNumber = newRegions.getEndLineNumber(index); - if (!isCollapsed) { - isCollapsed = newRegions.isCollapsed(index); - } - if (isCollapsed && isBlocked(startLineNumber, endLineNumber)) { - isCollapsed = false; - } - newRegions.setCollapsed(index, isCollapsed); - const maxColumn = this._textModel.getLineMaxColumn(startLineNumber); - const decorationRange = { - startLineNumber: startLineNumber, - startColumn: Math.max(maxColumn - 1, 1), - endLineNumber: startLineNumber, - endColumn: maxColumn - }; - newEditorDecorations.push({ range: decorationRange, options: this._decorationProvider.getDecorationOption(isCollapsed, endLineNumber <= lastHiddenLine) }); - if (isCollapsed && endLineNumber > lastHiddenLine) { - lastHiddenLine = endLineNumber; - } - }; - let i = 0; - let nextCollapsed = () => { - while (i < this._regions.length) { - let isCollapsed = this._regions.isCollapsed(i); - i++; - if (isCollapsed) { - return i - 1; - } - } - return -1; - }; - let k = 0; - let collapsedIndex = nextCollapsed(); - while (collapsedIndex !== -1 && k < newRegions.length) { - // get the latest range - let decRange = this._textModel.getDecorationRange(this._editorDecorationIds[collapsedIndex]); - if (decRange) { - let collapsedStartLineNumber = decRange.startLineNumber; - if (decRange.startColumn === Math.max(decRange.endColumn - 1, 1) && this._textModel.getLineMaxColumn(collapsedStartLineNumber) === decRange.endColumn) { // test that the decoration is still covering the full line else it got deleted - while (k < newRegions.length) { - let 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 - */ - getMemento() { - let collapsedRanges = []; - for (let i = 0; i < this._regions.length; i++) { - if (this._regions.isCollapsed(i)) { - let range = this._textModel.getDecorationRange(this._editorDecorationIds[i]); - if (range) { - let startLineNumber = range.startLineNumber; - let endLineNumber = range.endLineNumber + this._regions.getEndLineNumber(i) - this._regions.getStartLineNumber(i); - collapsedRanges.push({ startLineNumber, endLineNumber }); - } - } - } - if (collapsedRanges.length > 0) { - return collapsedRanges; - } - return undefined; - } - /** - * Apply persisted state, for persistence only - */ - applyMemento(state) { - if (!Array.isArray(state)) { - return; - } - let toToogle = []; - for (let range of state) { - let region = this.getRegionAtLine(range.startLineNumber); - if (region && !region.isCollapsed) { - toToogle.push(region); - } - } - this.toggleCollapseState(toToogle); - } - dispose() { - this._decorationProvider.deltaDecorations(this._editorDecorationIds, []); - } - getAllRegionsAtLine(lineNumber, filter) { - let result = []; - if (this._regions) { - let index = this._regions.findRange(lineNumber); - let level = 1; - while (index >= 0) { - let current = this._regions.toRegion(index); - if (!filter || filter(current, level)) { - result.push(current); - } - level++; - index = current.parentIndex; - } - } - return result; - } - getRegionAtLine(lineNumber) { - if (this._regions) { - let index = this._regions.findRange(lineNumber); - if (index >= 0) { - return this._regions.toRegion(index); - } - } - return null; - } - getRegionsInside(region, filter) { - let result = []; - let index = region ? region.regionIndex + 1 : 0; - let endLineNumber = region ? region.endLineNumber : Number.MAX_VALUE; - if (filter && filter.length === 2) { - const levelStack = []; - for (let i = index, len = this._regions.length; i < len; i++) { - let 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 (let i = index, len = this._regions.length; i < len; i++) { - let current = this._regions.toRegion(i); - if (this._regions.getStartLineNumber(i) < endLineNumber) { - if (!filter || filter(current)) { - result.push(current); - } - } - else { - break; - } - } - } - return result; - } - } - 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) { - let toToggle = []; - for (let lineNumber of lineNumbers) { - let region = foldingModel.getRegionAtLine(lineNumber); - if (region) { - const doCollapse = !region.isCollapsed; - toToggle.push(region); - if (levels > 1) { - let regionsInside = foldingModel.getRegionsInside(region, (r, level) => r.isCollapsed !== doCollapse && level < levels); - toToggle.push(...regionsInside); - } - } - } - foldingModel.toggleCollapseState(toToggle); - } - exports.toggleCollapseState = toggleCollapseState; - /** - * Collapse or expand the regions at the given locations including all children. - * @param doCollapse Whether to collapse 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 = Number.MAX_VALUE, lineNumbers) { - let toToggle = []; - if (lineNumbers && lineNumbers.length > 0) { - for (let lineNumber of lineNumbers) { - let region = foldingModel.getRegionAtLine(lineNumber); - if (region) { - if (region.isCollapsed !== doCollapse) { - toToggle.push(region); - } - if (levels > 1) { - let regionsInside = foldingModel.getRegionsInside(region, (r, level) => r.isCollapsed !== doCollapse && level < levels); - toToggle.push(...regionsInside); - } - } - } - } - else { - let regionsInside = foldingModel.getRegionsInside(null, (r, level) => r.isCollapsed !== doCollapse && level < levels); - toToggle.push(...regionsInside); - } - foldingModel.toggleCollapseState(toToggle); - } - exports.setCollapseStateLevelsDown = setCollapseStateLevelsDown; - /** - * Collapse or expand the regions at the given locations including all parents. - * @param doCollapse Whether to collapse 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) { - let toToggle = []; - for (let lineNumber of lineNumbers) { - let regions = foldingModel.getAllRegionsAtLine(lineNumber, (region, level) => region.isCollapsed !== doCollapse && level <= levels); - toToggle.push(...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 Whether to collapse or expand - * @param lineNumbers the location of the regions to collapse or expand. - */ - function setCollapseStateUp(foldingModel, doCollapse, lineNumbers) { - let toToggle = []; - for (let lineNumber of lineNumbers) { - let regions = foldingModel.getAllRegionsAtLine(lineNumber, (region) => 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 Whether to collapse or expand - */ - function setCollapseStateAtLevel(foldingModel, foldLevel, doCollapse, blockedLineNumbers) { - let filter = (region, level) => level === foldLevel && region.isCollapsed !== doCollapse && !blockedLineNumbers.some(line => region.containsLine(line)); - let toToggle = foldingModel.getRegionsInside(null, filter); - foldingModel.toggleCollapseState(toToggle); - } - exports.setCollapseStateAtLevel = setCollapseStateAtLevel; - /** - * Folds or unfolds all regions, except if they contain or are contained by a region of one of the blocked lines. - * @param doCollapse Whether to collapse or expand - * @param blockedLineNumbers the location of regions to not collapse or expand - */ - function setCollapseStateForRest(foldingModel, doCollapse, blockedLineNumbers) { - let filteredRegions = []; - for (let lineNumber of blockedLineNumbers) { - filteredRegions.push(foldingModel.getAllRegionsAtLine(lineNumber, undefined)[0]); - } - let filter = (region) => filteredRegions.every((filteredRegion) => !filteredRegion.containedBy(region) && !region.containedBy(filteredRegion)) && region.isCollapsed !== doCollapse; - let toToggle = foldingModel.getRegionsInside(null, filter); - foldingModel.toggleCollapseState(toToggle); - } - exports.setCollapseStateForRest = setCollapseStateForRest; - /** - * Folds all regions for which the lines start with a given regex - * @param foldingModel the folding model - */ - function setCollapseStateForMatchingLines(foldingModel, regExp, doCollapse) { - let editorModel = foldingModel.textModel; - let regions = foldingModel.regions; - let toToggle = []; - for (let i = regions.length - 1; i >= 0; i--) { - if (doCollapse !== regions.isCollapsed(i)) { - let 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) { - let regions = foldingModel.regions; - let toToggle = []; - for (let 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; - /** - * Get line to go to for parent fold of current line - * @param lineNumber the current line number - * @param foldingModel the folding model - * - * @return Parent fold start line - */ - function getParentFoldLine(lineNumber, foldingModel) { - let startLineNumber = null; - let foldingRegion = foldingModel.getRegionAtLine(lineNumber); - if (foldingRegion !== null) { - startLineNumber = foldingRegion.startLineNumber; - // If current line is not the start of the current fold, go to top line of current fold. If not, go to parent fold - if (lineNumber === startLineNumber) { - let parentFoldingIdx = foldingRegion.parentIndex; - if (parentFoldingIdx !== -1) { - startLineNumber = foldingModel.regions.getStartLineNumber(parentFoldingIdx); - } - else { - startLineNumber = null; - } - } - } - return startLineNumber; - } - exports.getParentFoldLine = getParentFoldLine; - /** - * Get line to go to for previous fold at the same level of current line - * @param lineNumber the current line number - * @param foldingModel the folding model - * - * @return Previous fold start line - */ - function getPreviousFoldLine(lineNumber, foldingModel) { - let foldingRegion = foldingModel.getRegionAtLine(lineNumber); - if (foldingRegion !== null) { - // If current line is not the start of the current fold, go to top line of current fold. If not, go to previous fold. - if (lineNumber !== foldingRegion.startLineNumber) { - return foldingRegion.startLineNumber; - } - else { - // Find min line number to stay within parent. - let expectedParentIndex = foldingRegion.parentIndex; - if (expectedParentIndex === -1) { - return null; - } - let minLineNumber = foldingModel.regions.getStartLineNumber(foldingRegion.parentIndex); - // Find fold at same level. - while (foldingRegion !== null) { - if (foldingRegion.regionIndex > 0) { - foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex - 1); - // Keep at same level. - if (foldingRegion.startLineNumber <= minLineNumber) { - return null; - } - else if (foldingRegion.parentIndex === expectedParentIndex) { - return foldingRegion.startLineNumber; - } - } - else { - return null; - } - } - } - } - return null; - } - exports.getPreviousFoldLine = getPreviousFoldLine; - /** - * Get line to go to next fold at the same level of current line - * @param lineNumber the current line number - * @param foldingModel the folding model - * - * @return Next fold start line - */ - function getNextFoldLine(lineNumber, foldingModel) { - let foldingRegion = foldingModel.getRegionAtLine(lineNumber); - if (foldingRegion !== null) { - // Find max line number to stay within parent. - let expectedParentIndex = foldingRegion.parentIndex; - if (expectedParentIndex === -1) { - return null; - } - let maxLineNumber = foldingModel.regions.getEndLineNumber(foldingRegion.parentIndex); - // Find fold at same level. - while (foldingRegion !== null) { - if (foldingRegion.regionIndex < foldingModel.regions.length) { - foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex + 1); - // Keep at same level. - if (foldingRegion.startLineNumber >= maxLineNumber) { - return null; - } - else if (foldingRegion.parentIndex === expectedParentIndex) { - return foldingRegion.startLineNumber; - } - } - else { - return null; - } - } - } - return null; - } - exports.getNextFoldLine = getNextFoldLine; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/editor/contrib/folding/hiddenRangeModel*/], __M([0/*require*/,1/*exports*/,6/*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 }); - exports.HiddenRangeModel = void 0; - class HiddenRangeModel { - constructor(model) { - this._updateEventEmitter = new event_1.Emitter(); - this._foldingModel = model; - this._foldingModelListener = model.onDidChange(_ => this.updateHiddenRanges()); - this._hiddenRanges = []; - if (model.regions.length) { - this.updateHiddenRanges(); - } - } - get onDidChange() { return this._updateEventEmitter.event; } - get hiddenRanges() { return this._hiddenRanges; } - updateHiddenRanges() { - let updateHiddenAreas = false; - let newHiddenAreas = []; - let i = 0; // index into hidden - let k = 0; - let lastCollapsedStart = Number.MAX_VALUE; - let lastCollapsedEnd = -1; - let ranges = this._foldingModel.regions; - for (; i < ranges.length; i++) { - if (!ranges.isCollapsed(i)) { - continue; - } - let startLineNumber = ranges.getStartLineNumber(i) + 1; // the first line is not hidden - let 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); - } - } - applyMemento(state) { - if (!Array.isArray(state) || state.length === 0) { - return false; - } - let hiddenRanges = []; - for (let r of state) { - 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 - */ - getMemento() { - return this._hiddenRanges.map(r => ({ startLineNumber: r.startLineNumber - 1, endLineNumber: r.endLineNumber })); - } - applyHiddenRanges(newHiddenAreas) { - this._hiddenRanges = newHiddenAreas; - this._updateEventEmitter.fire(newHiddenAreas); - } - hasRanges() { - return this._hiddenRanges.length > 0; - } - isHidden(line) { - return findRange(this._hiddenRanges, line) !== null; - } - adjustSelections(selections) { - let hasChanges = false; - let editorModel = this._foldingModel.textModel; - let lastRange = null; - let adjustLine = (line) => { - if (!lastRange || !isInside(line, lastRange)) { - lastRange = findRange(this._hiddenRanges, line); - } - if (lastRange) { - return lastRange.startLineNumber - 1; - } - return null; - }; - for (let i = 0, len = selections.length; i < len; i++) { - let selection = selections[i]; - let adjustedStartLine = adjustLine(selection.startLineNumber); - if (adjustedStartLine) { - selection = selection.setStartPosition(adjustedStartLine, editorModel.getLineMaxColumn(adjustedStartLine)); - hasChanges = true; - } - let adjustedEndLine = adjustLine(selection.endLineNumber); - if (adjustedEndLine) { - selection = selection.setEndPosition(adjustedEndLine, editorModel.getLineMaxColumn(adjustedEndLine)); - hasChanges = true; - } - selections[i] = selection; - } - return hasChanges; - } - dispose() { - if (this.hiddenRanges.length > 0) { - this._hiddenRanges = []; - this._updateEventEmitter.fire(this._hiddenRanges); - } - if (this._foldingModelListener) { - this._foldingModelListener.dispose(); - this._foldingModelListener = null; - } - } - } - exports.HiddenRangeModel = HiddenRangeModel; - function isInside(line, range) { - return line >= range.startLineNumber && line <= range.endLineNumber; - } - function findRange(ranges, line) { - let i = (0, arrays_1.findFirstInSorted)(ranges, r => 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[227/*vs/editor/contrib/folding/syntaxRangeProvider*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,178/*vs/editor/contrib/folding/foldingRanges*/,2/*vs/base/common/lifecycle*/]), function (require, exports, errors_1, foldingRanges_1, lifecycle_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.sanitizeRanges = exports.RangesCollector = exports.SyntaxRangeProvider = exports.ID_SYNTAX_PROVIDER = void 0; - const MAX_FOLDING_REGIONS = 5000; - const foldingContext = {}; - exports.ID_SYNTAX_PROVIDER = 'syntax'; - class SyntaxRangeProvider { - constructor(editorModel, providers, handleFoldingRangesChange, limit = MAX_FOLDING_REGIONS) { - this.editorModel = editorModel; - this.providers = providers; - this.limit = limit; - this.id = exports.ID_SYNTAX_PROVIDER; - for (const provider of providers) { - if (typeof provider.onDidChange === 'function') { - if (!this.disposables) { - this.disposables = new lifecycle_1.DisposableStore(); - } - this.disposables.add(provider.onDidChange(handleFoldingRangesChange)); - } - } - } - compute(cancellationToken) { - return collectSyntaxRanges(this.providers, this.editorModel, cancellationToken).then(ranges => { - if (ranges) { - let res = sanitizeRanges(ranges, this.limit); - return res; - } - return null; - }); - } - dispose() { - var _a; - (_a = this.disposables) === null || _a === void 0 ? void 0 : _a.dispose(); - } - } - exports.SyntaxRangeProvider = SyntaxRangeProvider; - function collectSyntaxRanges(providers, model, cancellationToken) { - let rangeData = null; - let promises = providers.map((provider, i) => { - return Promise.resolve(provider.provideFoldingRanges(model, foldingContext, cancellationToken)).then(ranges => { - if (cancellationToken.isCancellationRequested) { - return; - } - if (Array.isArray(ranges)) { - if (!Array.isArray(rangeData)) { - rangeData = []; - } - let nLines = model.getLineCount(); - for (let r of ranges) { - 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(_ => { - return rangeData; - }); - } - class RangesCollector { - constructor(foldingRangesLimit) { - this._startIndexes = []; - this._endIndexes = []; - this._nestingLevels = []; - this._nestingLevelCounts = []; - this._types = []; - this._length = 0; - this._foldingRangesLimit = foldingRangesLimit; - } - add(startLineNumber, endLineNumber, type, nestingLevel) { - if (startLineNumber > foldingRanges_1.MAX_LINE_NUMBER || endLineNumber > foldingRanges_1.MAX_LINE_NUMBER) { - return; - } - let 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; - } - } - toIndentRanges() { - if (this._length <= this._foldingRangesLimit) { - let startIndexes = new Uint32Array(this._length); - let endIndexes = new Uint32Array(this._length); - for (let 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 { - let entries = 0; - let maxLevel = this._nestingLevelCounts.length; - for (let i = 0; i < this._nestingLevelCounts.length; i++) { - let n = this._nestingLevelCounts[i]; - if (n) { - if (n + entries > this._foldingRangesLimit) { - maxLevel = i; - break; - } - entries += n; - } - } - let startIndexes = new Uint32Array(this._foldingRangesLimit); - let endIndexes = new Uint32Array(this._foldingRangesLimit); - let types = []; - for (let i = 0, k = 0; i < this._length; i++) { - let 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); - } - } - } - exports.RangesCollector = RangesCollector; - function sanitizeRanges(rangeData, limit) { - let sorted = rangeData.sort((d1, d2) => { - let diff = d1.start - d2.start; - if (diff === 0) { - diff = d1.rank - d2.rank; - } - return diff; - }); - let collector = new RangesCollector(limit); - let top = undefined; - let previous = []; - for (let entry of sorted) { - 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[415/*vs/editor/contrib/folding/intializingRangeProvider*/], __M([0/*require*/,1/*exports*/,227/*vs/editor/contrib/folding/syntaxRangeProvider*/]), function (require, exports, syntaxRangeProvider_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.InitializingRangeProvider = exports.ID_INIT_PROVIDER = void 0; - exports.ID_INIT_PROVIDER = 'init'; - class InitializingRangeProvider { - constructor(editorModel, initialRanges, onTimeout, timeoutTime) { - this.editorModel = editorModel; - this.id = exports.ID_INIT_PROVIDER; - if (initialRanges.length) { - let toDecorationRange = (range) => { - return { - range: { - startLineNumber: range.startLineNumber, - startColumn: 0, - endLineNumber: range.endLineNumber, - endColumn: editorModel.getLineLength(range.endLineNumber) - }, - options: { - description: 'folding-initializing-range-provider', - stickiness: 1 /* NeverGrowsWhenTypingAtEdges */ - } - }; - }; - this.decorationIds = editorModel.deltaDecorations([], initialRanges.map(toDecorationRange)); - this.timeout = setTimeout(onTimeout, timeoutTime); - } - } - dispose() { - if (this.decorationIds) { - this.editorModel.deltaDecorations(this.decorationIds, []); - this.decorationIds = undefined; - } - if (typeof this.timeout === 'number') { - clearTimeout(this.timeout); - this.timeout = undefined; - } - } - compute(cancelationToken) { - let foldingRangeData = []; - if (this.decorationIds) { - for (let id of this.decorationIds) { - let range = this.editorModel.getDecorationRange(id); - if (range) { - foldingRangeData.push({ start: range.startLineNumber, end: range.endLineNumber, rank: 1 }); - } - } - } - return Promise.resolve((0, syntaxRangeProvider_1.sanitizeRanges)(foldingRangeData, Number.MAX_VALUE)); - } - } - 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[228/*vs/editor/contrib/format/formattingEdit*/], __M([0/*require*/,1/*exports*/,56/*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 }); - exports.FormattingEdit = void 0; - class FormattingEdit { - static _handleEolEdits(editor, edits) { - let newEol = undefined; - let singleEdits = []; - for (let edit of edits) { - 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; - } - static _isFullModelReplaceEdit(editor, edit) { - if (!editor.hasModel()) { - return false; - } - const model = editor.getModel(); - const editRange = model.validateRange(edit.range); - const fullModelRange = model.getFullModelRange(); - return fullModelRange.equalsRange(editRange); - } - static execute(editor, _edits, addUndoStops) { - if (addUndoStops) { - editor.pushUndoStop(); - } - const 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(edit => editOperation_1.EditOperation.replace(range_1.Range.lift(edit.range), edit.text))); - } - else { - editor.executeEdits('formatEditsCommand', edits.map(edit => editOperation_1.EditOperation.replaceMove(range_1.Range.lift(edit.range), edit.text))); - } - if (addUndoStops) { - editor.pushUndoStop(); - } - } - } - 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[229/*vs/editor/contrib/gotoSymbol/link/clickLinkGesture*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,6/*vs/base/common/event*/,17/*vs/base/common/platform*/]), function (require, exports, lifecycle_1, event_1, platform) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ClickLinkGesture = exports.ClickLinkOptions = exports.ClickLinkKeyboardEvent = exports.ClickLinkMouseEvent = void 0; - function hasModifier(e, modifier) { - return !!e[modifier]; - } - /** - * An event that encapsulates the various trigger modifiers logic needed for go to definition. - */ - class ClickLinkMouseEvent { - constructor(source, opts) { - this.target = source.target; - this.hasTriggerModifier = hasModifier(source.event, opts.triggerModifier); - this.hasSideBySideModifier = hasModifier(source.event, opts.triggerSideBySideModifier); - this.isNoneOrSingleMouseDown = (source.event.detail <= 1); - } - } - exports.ClickLinkMouseEvent = ClickLinkMouseEvent; - /** - * An event that encapsulates the various trigger modifiers logic needed for go to definition. - */ - class ClickLinkKeyboardEvent { - constructor(source, opts) { - this.keyCodeIsTriggerKey = (source.keyCode === opts.triggerKey); - this.keyCodeIsSideBySideKey = (source.keyCode === opts.triggerSideBySideKey); - this.hasTriggerModifier = hasModifier(source, opts.triggerModifier); - } - } - exports.ClickLinkKeyboardEvent = ClickLinkKeyboardEvent; - class ClickLinkOptions { - constructor(triggerKey, triggerModifier, triggerSideBySideKey, triggerSideBySideModifier) { - this.triggerKey = triggerKey; - this.triggerModifier = triggerModifier; - this.triggerSideBySideKey = triggerSideBySideKey; - this.triggerSideBySideModifier = triggerSideBySideModifier; - } - equals(other) { - return (this.triggerKey === other.triggerKey - && this.triggerModifier === other.triggerModifier - && this.triggerSideBySideKey === other.triggerSideBySideKey - && this.triggerSideBySideModifier === other.triggerSideBySideModifier); - } - } - 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'); - } - class ClickLinkGesture extends lifecycle_1.Disposable { - constructor(editor) { - super(); - 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(68 /* multiCursorModifier */)); - this._lastMouseMoveEvent = null; - this._hasTriggerKeyOnMouseDown = false; - this._lineNumberOnMouseDown = 0; - this._register(this._editor.onDidChangeConfiguration((e) => { - if (e.hasChanged(68 /* multiCursorModifier */)) { - const newOpts = createOptions(this._editor.getOption(68 /* multiCursorModifier */)); - if (this._opts.equals(newOpts)) { - return; - } - this._opts = newOpts; - this._lastMouseMoveEvent = null; - this._hasTriggerKeyOnMouseDown = false; - this._lineNumberOnMouseDown = 0; - this._onCancel.fire(); - } - })); - this._register(this._editor.onMouseMove((e) => this._onEditorMouseMove(new ClickLinkMouseEvent(e, this._opts)))); - this._register(this._editor.onMouseDown((e) => this._onEditorMouseDown(new ClickLinkMouseEvent(e, this._opts)))); - this._register(this._editor.onMouseUp((e) => this._onEditorMouseUp(new ClickLinkMouseEvent(e, this._opts)))); - this._register(this._editor.onKeyDown((e) => this._onEditorKeyDown(new ClickLinkKeyboardEvent(e, this._opts)))); - this._register(this._editor.onKeyUp((e) => this._onEditorKeyUp(new ClickLinkKeyboardEvent(e, this._opts)))); - this._register(this._editor.onMouseDrag(() => this._resetHandler())); - this._register(this._editor.onDidChangeCursorSelection((e) => this._onDidChangeCursorSelection(e))); - this._register(this._editor.onDidChangeModel((e) => this._resetHandler())); - this._register(this._editor.onDidChangeModelContent(() => this._resetHandler())); - this._register(this._editor.onDidScrollChange((e) => { - if (e.scrollTopChanged || e.scrollLeftChanged) { - this._resetHandler(); - } - })); - } - _onDidChangeCursorSelection(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) - } - } - _onEditorMouseMove(mouseEvent) { - this._lastMouseMoveEvent = mouseEvent; - this._onMouseMoveOrRelevantKeyDown.fire([mouseEvent, null]); - } - _onEditorMouseDown(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; - this._lineNumberOnMouseDown = mouseEvent.target.position ? mouseEvent.target.position.lineNumber : 0; - } - _onEditorMouseUp(mouseEvent) { - const currentLineNumber = mouseEvent.target.position ? mouseEvent.target.position.lineNumber : 0; - if (this._hasTriggerKeyOnMouseDown && this._lineNumberOnMouseDown && this._lineNumberOnMouseDown === currentLineNumber) { - this._onExecute.fire(mouseEvent); - } - } - _onEditorKeyDown(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 - } - } - _onEditorKeyUp(e) { - if (e.keyCodeIsTriggerKey) { - this._onCancel.fire(); - } - } - _resetHandler() { - this._lastMouseMoveEvent = null; - this._hasTriggerKeyOnMouseDown = false; - this._onCancel.fire(); - } - } - 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[230/*vs/editor/contrib/hover/hoverOperation*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,12/*vs/base/common/errors*/]), function (require, exports, async_1, errors_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.HoverOperation = void 0; - class HoverOperation { - constructor(computer, success, error, progress, hoverTime) { - this._computer = computer; - this._state = 0 /* IDLE */; - this._hoverTime = hoverTime; - this._firstWaitScheduler = new async_1.RunOnceScheduler(() => this._triggerAsyncComputation(), 0); - this._secondWaitScheduler = new async_1.RunOnceScheduler(() => this._triggerSyncComputation(), 0); - this._loadingMessageScheduler = new async_1.RunOnceScheduler(() => this._showLoadingMessage(), 0); - this._asyncComputationPromise = null; - this._asyncComputationPromiseDone = false; - this._completeCallback = success; - this._errorCallback = error; - this._progressCallback = progress; - } - setHoverTime(hoverTime) { - this._hoverTime = hoverTime; - } - _firstWaitTime() { - return this._hoverTime / 2; - } - _secondWaitTime() { - return this._hoverTime / 2; - } - _loadingMessageTime() { - return 3 * this._hoverTime; - } - _triggerAsyncComputation() { - this._state = 2 /* SECOND_WAIT */; - this._secondWaitScheduler.schedule(this._secondWaitTime()); - if (this._computer.computeAsync) { - this._asyncComputationPromiseDone = false; - this._asyncComputationPromise = (0, async_1.createCancelablePromise)(token => this._computer.computeAsync(token)); - this._asyncComputationPromise.then((asyncResult) => { - this._asyncComputationPromiseDone = true; - this._withAsyncResult(asyncResult); - }, (e) => this._onError(e)); - } - else { - this._asyncComputationPromiseDone = true; - } - } - _triggerSyncComputation() { - 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()); - } - } - _showLoadingMessage() { - if (this._state === 3 /* WAITING_FOR_ASYNC_COMPUTATION */) { - this._onProgress(this._computer.getResultWithLoadingMessage()); - } - } - _withAsyncResult(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()); - } - } - _onComplete(value) { - this._completeCallback(value); - } - _onError(error) { - if (this._errorCallback) { - this._errorCallback(error); - } - else { - (0, errors_1.onUnexpectedError)(error); - } - } - _onProgress(value) { - this._progressCallback(value); - } - start(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; - } - } - } - cancel() { - 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 */; - } - } - 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. - *--------------------------------------------------------------------------------------------*/ -define(__m[231/*vs/editor/contrib/hover/hoverTypes*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.HoverForeignElementAnchor = exports.HoverRangeAnchor = void 0; - class HoverRangeAnchor { - constructor(priority, range) { - this.priority = priority; - this.range = range; - this.type = 1 /* Range */; - } - equals(other) { - return (other.type === 1 /* Range */ && this.range.equalsRange(other.range)); - } - canAdoptVisibleHover(lastAnchor, showAtPosition) { - return (lastAnchor.type === 1 /* Range */ && showAtPosition.lineNumber === this.range.startLineNumber); - } - } - exports.HoverRangeAnchor = HoverRangeAnchor; - class HoverForeignElementAnchor { - constructor(priority, owner, range) { - this.priority = priority; - this.owner = owner; - this.range = range; - this.type = 2 /* ForeignElement */; - } - equals(other) { - return (other.type === 2 /* ForeignElement */ && this.owner === other.owner); - } - canAdoptVisibleHover(lastAnchor, showAtPosition) { - return (lastAnchor.type === 2 /* ForeignElement */ && this.owner === lastAnchor.owner); - } - } - exports.HoverForeignElementAnchor = HoverForeignElementAnchor; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[416/*vs/editor/contrib/hover/hoverWidgets*/], __M([0/*require*/,1/*exports*/,52/*vs/base/browser/ui/widget*/]), function (require, exports, widget_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.GlyphHoverWidget = void 0; - class GlyphHoverWidget extends widget_1.Widget { - constructor(id, editor) { - super(); - this._id = id; - this._editor = editor; - this._isVisible = false; - this._domNode = document.createElement('div'); - this._domNode.className = 'monaco-hover hidden'; - this._domNode.setAttribute('aria-hidden', 'true'); - this._domNode.setAttribute('role', 'tooltip'); - this._showAtLineNumber = -1; - this._register(this._editor.onDidChangeConfiguration((e) => { - if (e.hasChanged(41 /* fontInfo */)) { - this.updateFont(); - } - })); - this._editor.addOverlayWidget(this); - } - get isVisible() { - return this._isVisible; - } - set isVisible(value) { - this._isVisible = value; - this._domNode.classList.toggle('hidden', !this._isVisible); - } - getId() { - return this._id; - } - getDomNode() { - return this._domNode; - } - showAt(lineNumber) { - this._showAtLineNumber = lineNumber; - if (!this.isVisible) { - this.isVisible = true; - } - const editorLayout = this._editor.getLayoutInfo(); - const topForLineNumber = this._editor.getTopForLineNumber(this._showAtLineNumber); - const editorScrollTop = this._editor.getScrollTop(); - const lineHeight = this._editor.getOption(57 /* lineHeight */); - const nodeHeight = this._domNode.clientHeight; - const 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`; - } - hide() { - if (!this.isVisible) { - return; - } - this.isVisible = false; - } - getPosition() { - return null; - } - dispose() { - this._editor.removeOverlayWidget(this); - super.dispose(); - } - updateFont() { - const codeTags = Array.prototype.slice.call(this._domNode.getElementsByTagName('code')); - const codeClasses = Array.prototype.slice.call(this._domNode.getElementsByClassName('code')); - [...codeTags, ...codeClasses].forEach(node => this._editor.applyFontInfo(node)); - } - updateContents(node) { - this._domNode.textContent = ''; - this._domNode.appendChild(node); - this.updateFont(); - } - } - 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[417/*vs/editor/contrib/inPlaceReplace/inPlaceReplaceCommand*/], __M([0/*require*/,1/*exports*/,21/*vs/editor/common/core/selection*/]), function (require, exports, selection_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.InPlaceReplaceCommand = void 0; - class InPlaceReplaceCommand { - constructor(editRange, originalSelection, text) { - this._editRange = editRange; - this._originalSelection = originalSelection; - this._text = text; - } - getEditOperations(model, builder) { - builder.addTrackedEditOperation(this._editRange, this._text); - } - computeCursorState(model, helper) { - const inverseEditOperations = helper.getInverseEditOperations(); - const 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)); - } - } - 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[232/*vs/editor/contrib/indentation/indentUtils*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.generateIndent = exports.getSpaceCnt = void 0; - function getSpaceCnt(str, tabSize) { - let spacesCnt = 0; - for (let 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; - let result = ''; - if (!insertSpaces) { - let tabsCnt = Math.floor(spacesCnt / tabSize); - spacesCnt = spacesCnt % tabSize; - for (let i = 0; i < tabsCnt; i++) { - result += '\t'; - } - } - for (let 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[233/*vs/editor/contrib/inlineCompletions/ghostText*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/]), function (require, exports, event_1, lifecycle_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.BaseGhostTextWidgetModel = exports.GhostTextPart = exports.GhostText = void 0; - class GhostText { - constructor(lineNumber, parts, additionalReservedLineCount = 0) { - this.lineNumber = lineNumber; - this.parts = parts; - this.additionalReservedLineCount = additionalReservedLineCount; - } - static equals(a, b) { - return a === b || (!!a && !!b && a.equals(b)); - } - equals(other) { - return this.lineNumber === other.lineNumber && - this.parts.length === other.parts.length && - this.parts.every((part, index) => part.equals(other.parts[index])); - } - } - exports.GhostText = GhostText; - class GhostTextPart { - constructor(column, lines) { - this.column = column; - this.lines = lines; - } - equals(other) { - return this.column === other.column && - this.lines.length === other.lines.length && - this.lines.every((line, index) => line === other.lines[index]); - } - } - exports.GhostTextPart = GhostTextPart; - class BaseGhostTextWidgetModel extends lifecycle_1.Disposable { - constructor(editor) { - super(); - this.editor = editor; - this._expanded = undefined; - this.onDidChangeEmitter = new event_1.Emitter(); - this.onDidChange = this.onDidChangeEmitter.event; - this._register(editor.onDidChangeConfiguration((e) => { - if (e.hasChanged(105 /* suggest */) && this._expanded === undefined) { - this.onDidChangeEmitter.fire(); - } - })); - } - get expanded() { - if (this._expanded === undefined) { - // TODO this should use a global hidden setting. - // See https://github.com/microsoft/vscode/issues/125037. - return true; - } - return this._expanded; - } - setExpanded(expanded) { - this._expanded = true; - this.onDidChangeEmitter.fire(); - } - } - exports.BaseGhostTextWidgetModel = BaseGhostTextWidgetModel; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[418/*vs/editor/contrib/inlineCompletions/utils*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.createDisposableRef = void 0; - function createDisposableRef(object, disposable) { - return { - object, - dispose: () => disposable === null || disposable === void 0 ? void 0 : disposable.dispose(), - }; - } - exports.createDisposableRef = createDisposableRef; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[419/*vs/editor/contrib/linesOperations/copyLinesCommand*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/]), function (require, exports, range_1, selection_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CopyLinesCommand = void 0; - class CopyLinesCommand { - constructor(selection, isCopyingDown, noop) { - this._selection = selection; - this._isCopyingDown = isCopyingDown; - this._noop = noop || false; - this._selectionDirection = 0 /* LTR */; - this._selectionId = null; - this._startLineNumberDelta = 0; - this._endLineNumberDelta = 0; - } - getEditOperations(model, builder) { - let 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)); - } - let sourceLines = []; - for (let i = s.startLineNumber; i <= s.endLineNumber; i++) { - sourceLines.push(model.getLineContent(i)); - } - const sourceText = sourceLines.join('\n'); - if (sourceText === '') { - // Duplicating empty line - if (this._isCopyingDown) { - this._startLineNumberDelta++; - this._endLineNumberDelta++; - } - } - if (this._noop) { - builder.addEditOperation(new range_1.Range(s.endLineNumber, model.getLineMaxColumn(s.endLineNumber), s.endLineNumber + 1, 1), s.endLineNumber === model.getLineCount() ? '' : '\n'); - } - else { - 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(); - } - computeCursorState(model, helper) { - let result = helper.getTrackedSelection(this._selectionId); - if (this._startLineNumberDelta !== 0 || this._endLineNumberDelta !== 0) { - let startLineNumber = result.startLineNumber; - let startColumn = result.startColumn; - let endLineNumber = result.endLineNumber; - let 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; - } - } - 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[420/*vs/editor/contrib/linesOperations/sortLinesCommand*/], __M([0/*require*/,1/*exports*/,56/*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 }); - exports.SortLinesCommand = void 0; - class SortLinesCommand { - constructor(selection, descending) { - this.selection = selection; - this.descending = descending; - this.selectionId = null; - } - static getCollator() { - if (!SortLinesCommand._COLLATOR) { - SortLinesCommand._COLLATOR = new Intl.Collator(); - } - return SortLinesCommand._COLLATOR; - } - getEditOperations(model, builder) { - let op = sortLines(model, this.selection, this.descending); - if (op) { - builder.addEditOperation(op.range, op.text); - } - this.selectionId = builder.trackSelection(this.selection); - } - computeCursorState(model, helper) { - return helper.getTrackedSelection(this.selectionId); - } - static canRun(model, selection, descending) { - if (model === null) { - return false; - } - let data = getSortData(model, selection, descending); - if (!data) { - return false; - } - for (let i = 0, len = data.before.length; i < len; i++) { - if (data.before[i] !== data.after[i]) { - return true; - } - } - return false; - } - } - exports.SortLinesCommand = SortLinesCommand; - SortLinesCommand._COLLATOR = null; - function getSortData(model, selection, descending) { - let startLineNumber = selection.startLineNumber; - let endLineNumber = selection.endLineNumber; - if (selection.endColumn === 1) { - endLineNumber--; - } - // Nothing to sort if user didn't select anything. - if (startLineNumber >= endLineNumber) { - return null; - } - let linesToSort = []; - // Get the contents of the selection to be sorted. - for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { - linesToSort.push(model.getLineContent(lineNumber)); - } - let 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) { - let 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[234/*vs/editor/contrib/smartSelect/bracketSelections*/], __M([0/*require*/,1/*exports*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,72/*vs/base/common/linkedList*/]), function (require, exports, position_1, range_1, linkedList_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.BracketSelectionRangeProvider = void 0; - class BracketSelectionRangeProvider { - provideSelectionRanges(model, positions) { - return __awaiter(this, void 0, void 0, function* () { - const result = []; - for (const position of positions) { - const bucket = []; - result.push(bucket); - const ranges = new Map(); - yield new Promise(resolve => BracketSelectionRangeProvider._bracketsRightYield(resolve, 0, model, position, ranges)); - yield new Promise(resolve => BracketSelectionRangeProvider._bracketsLeftYield(resolve, 0, model, position, ranges, bucket)); - } - return result; - }); - } - static _bracketsRightYield(resolve, round, model, pos, ranges) { - const counts = new Map(); - const t1 = Date.now(); - while (true) { - if (round >= BracketSelectionRangeProvider._maxRounds) { - resolve(); - break; - } - if (!pos) { - resolve(); - break; - } - let bracket = model.findNextBracket(pos); - if (!bracket) { - resolve(); - break; - } - let d = Date.now() - t1; - if (d > BracketSelectionRangeProvider._maxDuration) { - setTimeout(() => BracketSelectionRangeProvider._bracketsRightYield(resolve, round + 1, model, pos, ranges)); - break; - } - const key = bracket.close[0]; - if (bracket.isOpen) { - // wait for closing - let val = counts.has(key) ? counts.get(key) : 0; - counts.set(key, val + 1); - } - else { - // process closing - let val = counts.has(key) ? counts.get(key) : 0; - val -= 1; - counts.set(key, Math.max(0, val)); - if (val < 0) { - let list = ranges.get(key); - if (!list) { - list = new linkedList_1.LinkedList(); - ranges.set(key, list); - } - list.push(bracket.range); - } - } - pos = bracket.range.getEndPosition(); - } - } - static _bracketsLeftYield(resolve, round, model, pos, ranges, bucket) { - const counts = new Map(); - const t1 = Date.now(); - while (true) { - if (round >= BracketSelectionRangeProvider._maxRounds && ranges.size === 0) { - resolve(); - break; - } - if (!pos) { - resolve(); - break; - } - let bracket = model.findPrevBracket(pos); - if (!bracket) { - resolve(); - break; - } - let d = Date.now() - t1; - if (d > BracketSelectionRangeProvider._maxDuration) { - setTimeout(() => BracketSelectionRangeProvider._bracketsLeftYield(resolve, round + 1, model, pos, ranges, bucket)); - break; - } - const key = bracket.close[0]; - if (!bracket.isOpen) { - // wait for opening - let val = counts.has(key) ? counts.get(key) : 0; - counts.set(key, val + 1); - } - else { - // opening - let val = counts.has(key) ? counts.get(key) : 0; - val -= 1; - counts.set(key, Math.max(0, val)); - if (val < 0) { - let list = ranges.get(key); - if (list) { - let closing = list.shift(); - if (list.size === 0) { - ranges.delete(key); - } - const innerBracket = range_1.Range.fromPositions(bracket.range.getEndPosition(), closing.getStartPosition()); - const 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(); - } - } - static _addBracketLeading(model, bracket, bucket) { - if (bracket.startLineNumber === bracket.endLineNumber) { - return; - } - // xxxxxxxx { - // - // } - const startLine = bracket.startLineNumber; - const 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 - // { - // - // } - const aboveLine = startLine - 1; - if (aboveLine > 0) { - const column = model.getLineFirstNonWhitespaceColumn(aboveLine); - if (column === bracket.startColumn && column !== model.getLineLastNonWhitespaceColumn(aboveLine)) { - bucket.push({ range: range_1.Range.fromPositions(new position_1.Position(aboveLine, column), bracket.getEndPosition()) }); - bucket.push({ range: range_1.Range.fromPositions(new position_1.Position(aboveLine, 1), bracket.getEndPosition()) }); - } - } - } - } - exports.BracketSelectionRangeProvider = BracketSelectionRangeProvider; - BracketSelectionRangeProvider._maxDuration = 30; - BracketSelectionRangeProvider._maxRounds = 2; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/contrib/smartSelect/wordSelections*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/,8/*vs/base/common/strings*/]), function (require, exports, range_1, strings_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.WordSelectionRangeProvider = void 0; - class WordSelectionRangeProvider { - provideSelectionRanges(model, positions) { - const result = []; - for (const position of positions) { - const 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; - } - _addInWordRanges(bucket, model, pos) { - const obj = model.getWordAtPosition(pos); - if (!obj) { - return; - } - let { word, startColumn } = obj; - let offset = pos.column - startColumn; - let start = offset; - let end = offset; - let lastCh = 0; - // LEFT anchor (start) - for (; start >= 0; start--) { - let ch = word.charCodeAt(start); - if ((start !== offset) && (ch === 95 /* Underline */ || ch === 45 /* Dash */)) { - // foo-bar OR foo_bar - break; - } - else if ((0, strings_1.isLowerAsciiLetter)(ch) && (0, strings_1.isUpperAsciiLetter)(lastCh)) { - // fooBar - break; - } - lastCh = ch; - } - start += 1; - // RIGHT anchor (end) - for (; end < word.length; end++) { - let ch = word.charCodeAt(end); - if ((0, strings_1.isUpperAsciiLetter)(ch) && (0, 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) }); - } - } - _addWordRanges(bucket, model, pos) { - const word = model.getWordAtPosition(pos); - if (word) { - bucket.push({ range: new range_1.Range(pos.lineNumber, word.startColumn, pos.lineNumber, word.endColumn) }); - } - } - _addWhitespaceLine(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)) }); - } - } - } - 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. - *--------------------------------------------------------------------------------------------*/ -define(__m[116/*vs/editor/contrib/snippet/snippetParser*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.SnippetParser = exports.TextmateSnippet = exports.Variable = exports.FormatString = exports.Transform = exports.Choice = exports.Placeholder = exports.TransformableMarker = exports.Text = exports.Marker = exports.Scanner = void 0; - class Scanner { - constructor() { - this.value = ''; - this.pos = 0; - } - static isDigitCharacter(ch) { - return ch >= 48 /* Digit0 */ && ch <= 57 /* Digit9 */; - } - static isVariableCharacter(ch) { - return ch === 95 /* Underline */ - || (ch >= 97 /* a */ && ch <= 122 /* z */) - || (ch >= 65 /* A */ && ch <= 90 /* Z */); - } - text(value) { - this.value = value; - this.pos = 0; - } - tokenText(token) { - return this.value.substr(token.pos, token.len); - } - next() { - if (this.pos >= this.value.length) { - return { type: 14 /* EOF */, pos: this.pos, len: 0 }; - } - let pos = this.pos; - let len = 0; - let ch = this.value.charCodeAt(pos); - let type; - // static types - type = Scanner._table[ch]; - if (typeof type === 'number') { - this.pos += 1; - return { type, 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, pos, 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, pos, 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, pos, len }; - } - } - exports.Scanner = Scanner; - Scanner._table = { - [36 /* DollarSign */]: 0 /* Dollar */, - [58 /* Colon */]: 1 /* Colon */, - [44 /* Comma */]: 2 /* Comma */, - [123 /* OpenCurlyBrace */]: 3 /* CurlyOpen */, - [125 /* CloseCurlyBrace */]: 4 /* CurlyClose */, - [92 /* Backslash */]: 5 /* Backslash */, - [47 /* Slash */]: 6 /* Forwardslash */, - [124 /* Pipe */]: 7 /* Pipe */, - [43 /* Plus */]: 11 /* Plus */, - [45 /* Dash */]: 12 /* Dash */, - [63 /* QuestionMark */]: 13 /* QuestionMark */, - }; - class Marker { - constructor() { - this._children = []; - } - appendChild(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; - } - replace(child, others) { - const { parent } = child; - const idx = parent.children.indexOf(child); - const newChildren = parent.children.slice(0); - newChildren.splice(idx, 1, ...others); - parent._children = newChildren; - (function _fixParent(children, parent) { - for (const child of children) { - child.parent = parent; - _fixParent(child.children, child); - } - })(others, parent); - } - get children() { - return this._children; - } - get snippet() { - let candidate = this; - while (true) { - if (!candidate) { - return undefined; - } - if (candidate instanceof TextmateSnippet) { - return candidate; - } - candidate = candidate.parent; - } - } - toString() { - return this.children.reduce((prev, cur) => prev + cur.toString(), ''); - } - len() { - return 0; - } - } - exports.Marker = Marker; - class Text extends Marker { - constructor(value) { - super(); - this.value = value; - } - toString() { - return this.value; - } - len() { - return this.value.length; - } - clone() { - return new Text(this.value); - } - } - exports.Text = Text; - class TransformableMarker extends Marker { - } - exports.TransformableMarker = TransformableMarker; - class Placeholder extends TransformableMarker { - constructor(index) { - super(); - this.index = index; - } - static compareByIndex(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; - } - } - get isFinalTabstop() { - return this.index === 0; - } - get choice() { - return this._children.length === 1 && this._children[0] instanceof Choice - ? this._children[0] - : undefined; - } - clone() { - let ret = new Placeholder(this.index); - if (this.transform) { - ret.transform = this.transform.clone(); - } - ret._children = this.children.map(child => child.clone()); - return ret; - } - } - exports.Placeholder = Placeholder; - class Choice extends Marker { - constructor() { - super(...arguments); - this.options = []; - } - appendChild(marker) { - if (marker instanceof Text) { - marker.parent = this; - this.options.push(marker); - } - return this; - } - toString() { - return this.options[0].value; - } - len() { - return this.options[0].len(); - } - clone() { - let ret = new Choice(); - this.options.forEach(ret.appendChild, ret); - return ret; - } - } - exports.Choice = Choice; - class Transform extends Marker { - constructor() { - super(...arguments); - this.regexp = new RegExp(''); - } - resolve(value) { - const _this = this; - let didMatch = false; - let 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(child => child instanceof FormatString && Boolean(child.elseValue))) { - ret = this._replace([]); - } - return ret; - } - _replace(groups) { - let ret = ''; - for (const marker of this._children) { - if (marker instanceof FormatString) { - let value = groups[marker.index] || ''; - value = marker.resolve(value); - ret += value; - } - else { - ret += marker.toString(); - } - } - return ret; - } - toString() { - return ''; - } - clone() { - let ret = new Transform(); - ret.regexp = new RegExp(this.regexp.source, '' + (this.regexp.ignoreCase ? 'i' : '') + (this.regexp.global ? 'g' : '')); - ret._children = this.children.map(child => child.clone()); - return ret; - } - } - exports.Transform = Transform; - class FormatString extends Marker { - constructor(index, shorthandName, ifValue, elseValue) { - super(); - this.index = index; - this.shorthandName = shorthandName; - this.ifValue = ifValue; - this.elseValue = elseValue; - } - resolve(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 (this.shorthandName === 'camelcase') { - return !value ? '' : this._toCamelCase(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 || ''; - } - } - _toPascalCase(value) { - const match = value.match(/[a-z0-9]+/gi); - if (!match) { - return value; - } - return match.map(word => { - return word.charAt(0).toUpperCase() - + word.substr(1).toLowerCase(); - }) - .join(''); - } - _toCamelCase(value) { - const match = value.match(/[a-z0-9]+/gi); - if (!match) { - return value; - } - return match.map((word, index) => { - if (index === 0) { - return word.toLowerCase(); - } - else { - return word.charAt(0).toUpperCase() - + word.substr(1).toLowerCase(); - } - }) - .join(''); - } - clone() { - let ret = new FormatString(this.index, this.shorthandName, this.ifValue, this.elseValue); - return ret; - } - } - exports.FormatString = FormatString; - class Variable extends TransformableMarker { - constructor(name) { - super(); - this.name = name; - } - resolve(resolver) { - let value = resolver.resolve(this); - if (this.transform) { - value = this.transform.resolve(value || ''); - } - if (value !== undefined) { - this._children = [new Text(value)]; - return true; - } - return false; - } - clone() { - const ret = new Variable(this.name); - if (this.transform) { - ret.transform = this.transform.clone(); - } - ret._children = this.children.map(child => child.clone()); - return ret; - } - } - exports.Variable = Variable; - function walk(marker, visitor) { - const stack = [...marker]; - while (stack.length > 0) { - const marker = stack.shift(); - const recurse = visitor(marker); - if (!recurse) { - break; - } - stack.unshift(...marker.children); - } - } - class TextmateSnippet extends Marker { - get placeholderInfo() { - if (!this._placeholders) { - // fill in placeholders - let all = []; - let last; - this.walk(function (candidate) { - if (candidate instanceof Placeholder) { - all.push(candidate); - last = !last || last.index < candidate.index ? candidate : last; - } - return true; - }); - this._placeholders = { all, last }; - } - return this._placeholders; - } - get placeholders() { - const { all } = this.placeholderInfo; - return all; - } - offset(marker) { - let pos = 0; - let found = false; - this.walk(candidate => { - if (candidate === marker) { - found = true; - return false; - } - pos += candidate.len(); - return true; - }); - if (!found) { - return -1; - } - return pos; - } - fullLen(marker) { - let ret = 0; - walk([marker], marker => { - ret += marker.len(); - return true; - }); - return ret; - } - enclosingPlaceholders(placeholder) { - let ret = []; - let { parent } = placeholder; - while (parent) { - if (parent instanceof Placeholder) { - ret.push(parent); - } - parent = parent.parent; - } - return ret; - } - resolveVariables(resolver) { - this.walk(candidate => { - if (candidate instanceof Variable) { - if (candidate.resolve(resolver)) { - this._placeholders = undefined; - } - } - return true; - }); - return this; - } - appendChild(child) { - this._placeholders = undefined; - return super.appendChild(child); - } - replace(child, others) { - this._placeholders = undefined; - return super.replace(child, others); - } - clone() { - let ret = new TextmateSnippet(); - this._children = this.children.map(child => child.clone()); - return ret; - } - walk(visitor) { - walk(this.children, visitor); - } - } - exports.TextmateSnippet = TextmateSnippet; - class SnippetParser { - constructor() { - this._scanner = new Scanner(); - this._token = { type: 14 /* EOF */, pos: 0, len: 0 }; - } - static escape(value) { - return value.replace(/\$|}|\\/g, '\\$&'); - } - static guessNeedsClipboard(template) { - return /\${?CLIPBOARD/.test(template); - } - parse(value, insertFinalTabstop, enforceFinalTabstop) { - this._scanner.text(value); - this._token = this._scanner.next(); - const 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 - const placeholderDefaultValues = new Map(); - const incompletePlaceholders = []; - let placeholderCount = 0; - snippet.walk(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 (const placeholder of incompletePlaceholders) { - const defaultValues = placeholderDefaultValues.get(placeholder.index); - if (defaultValues) { - const clone = new Placeholder(placeholder.index); - clone.transform = placeholder.transform; - for (const child of defaultValues) { - 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; - } - _accept(type, value) { - if (type === undefined || this._token.type === type) { - let ret = !value ? true : this._scanner.tokenText(this._token); - this._token = this._scanner.next(); - return ret; - } - return false; - } - _backTo(token) { - this._scanner.pos = token.pos + token.len; - this._token = token; - return false; - } - _until(type) { - const start = this._token; - while (this._token.type !== type) { - if (this._token.type === 14 /* EOF */) { - return false; - } - else if (this._token.type === 5 /* Backslash */) { - const nextToken = this._scanner.next(); - if (nextToken.type !== 0 /* Dollar */ - && nextToken.type !== 4 /* CurlyClose */ - && nextToken.type !== 5 /* Backslash */) { - return false; - } - } - this._token = this._scanner.next(); - } - const value = this._scanner.value.substring(start.pos, this._token.pos).replace(/\\(\$|}|\\)/g, '$1'); - this._token = this._scanner.next(); - return value; - } - _parse(marker) { - return this._parseEscaped(marker) - || this._parseTabstopOrVariableName(marker) - || this._parseComplexPlaceholder(marker) - || this._parseComplexVariable(marker) - || this._parseAnything(marker); - } - // \$, \\, \} -> just text - _parseEscaped(marker) { - let 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 - _parseTabstopOrVariableName(parent) { - let value; - const token = this._token; - const 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 - _parseComplexPlaceholder(parent) { - let index; - const token = this._token; - const match = this._accept(0 /* Dollar */) - && this._accept(3 /* CurlyOpen */) - && (index = this._accept(8 /* Int */, true)); - if (!match) { - return this._backTo(token); - } - const 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|} - const 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); - } - } - _parseChoiceElement(parent) { - const token = this._token; - const values = []; - while (true) { - if (this._token.type === 2 /* Comma */ || this._token.type === 7 /* Pipe */) { - break; - } - let value; - 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 - _parseComplexVariable(parent) { - let name; - const token = this._token; - const match = this._accept(0 /* Dollar */) - && this._accept(3 /* CurlyOpen */) - && (name = this._accept(9 /* VariableName */, true)); - if (!match) { - return this._backTo(token); - } - const 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); - } - } - _parseTransform(parent) { - // ...//} - let transform = new Transform(); - let regexValue = ''; - let regexOptions = ''; - // (1) /regex - while (true) { - if (this._accept(6 /* Forwardslash */)) { - break; - } - let escaped; - 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; - } - let escaped; - 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; - } - _parseFormatString(parent) { - const token = this._token; - if (!this._accept(0 /* Dollar */)) { - return false; - } - let complex = false; - if (this._accept(3 /* CurlyOpen */)) { - complex = true; - } - let 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} - let 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:+} - let 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:-} - let 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:?:} - let ifValue = this._until(1 /* Colon */); - if (ifValue) { - let elseValue = this._until(4 /* CurlyClose */); - if (elseValue) { - parent.appendChild(new FormatString(Number(index), undefined, ifValue, elseValue)); - return true; - } - } - } - else { - // ${1:} - let elseValue = this._until(4 /* CurlyClose */); - if (elseValue) { - parent.appendChild(new FormatString(Number(index), undefined, undefined, elseValue)); - return true; - } - } - this._backTo(token); - return false; - } - _parseAnything(marker) { - if (this._token.type !== 14 /* EOF */) { - marker.appendChild(new Text(this._scanner.tokenText(this._token))); - this._accept(undefined); - return true; - } - return false; - } - } - 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[422/*vs/editor/contrib/suggest/completionModel*/], __M([0/*require*/,1/*exports*/,67/*vs/base/common/filters*/,8/*vs/base/common/strings*/,19/*vs/base/common/arrays*/]), function (require, exports, filters_1, strings_1, arrays_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CompletionModel = exports.LineContext = void 0; - class LineContext { - constructor(leadingLineContent, characterCountDelta) { - this.leadingLineContent = leadingLineContent; - this.characterCountDelta = characterCountDelta; - } - } - exports.LineContext = LineContext; - /** - * Sorted, filtered completion view model - * */ - class CompletionModel { - constructor(items, column, lineContext, wordDistance, options, snippetSuggestions, clipboardText) { - this.clipboardText = clipboardText; - 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; - } - } - get lineContext() { - return this._lineContext; - } - set lineContext(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; - } - } - get items() { - this._ensureCachedState(); - return this._filteredItems; - } - get allProvider() { - this._ensureCachedState(); - return this._providerInfo.keys(); - } - get incomplete() { - this._ensureCachedState(); - const result = new Set(); - for (let [provider, incomplete] of this._providerInfo) { - if (incomplete) { - result.add(provider); - } - } - return result; - } - adopt(except) { - let res = []; - for (let 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; - } - get stats() { - this._ensureCachedState(); - return this._stats; - } - _ensureCachedState() { - if (this._refilterKind !== 0 /* Nothing */) { - this._createCachedState(); - } - } - _createCachedState() { - this._providerInfo = new Map(); - const labelLengths = []; - const { leadingLineContent, characterCountDelta } = this._lineContext; - let word = ''; - let wordLow = ''; - // incrementally filter less - const source = this._refilterKind === 1 /* All */ ? this._items : this._filteredItems; - const target = []; - // picks a score function based on the number of - // items that we have to score/filter and based on the - // user-configuration - const scoreFn = (!this._options.filterGraceful || source.length > 2000) ? filters_1.fuzzyScore : filters_1.fuzzyScoreGracefulAggressive; - for (let i = 0; i < source.length; i++) { - const item = source[i]; - if (item.isInvalid) { - continue; // SKIP invalid items - } - // collect all support, know if their result is incomplete - this._providerInfo.set(item.provider, Boolean(item.container.incomplete)); - // '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 - const overwriteBefore = item.position.column - item.editStart.column; - const 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) - let wordPos = 0; - while (wordPos < overwriteBefore) { - const ch = word.charCodeAt(wordPos); - if (ch === 32 /* Space */ || ch === 9 /* Tab */) { - wordPos += 1; - } - else { - break; - } - } - 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 - let match = scoreFn(word, wordLow, wordPos, item.completion.filterText, item.filterTextLow, 0, false); - if (!match) { - continue; // NO match - } - if ((0, strings_1.compareIgnoreCase)(item.completion.filterText, item.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 = (0, filters_1.anyScore)(word, wordLow, wordPos, item.textLabel, item.labelLow, 0); - item.score[0] = match[0]; // use score from filterText - } - } - else { - // by default match `word` against the `label` - let match = scoreFn(word, wordLow, wordPos, item.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 - labelLengths.push(item.textLabel.length); - } - this._filteredItems = target.sort(this._snippetCompareFn); - this._refilterKind = 0 /* Nothing */; - this._stats = { - pLabelLen: labelLengths.length ? - (0, arrays_1.quickSelect)(labelLengths.length - .85, labelLengths, (a, b) => a - b) - : 0 - }; - } - static _compareCompletionItems(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; - } - } - static _compareCompletionItemsSnippetsDown(a, b) { - if (a.completion.kind !== b.completion.kind) { - if (a.completion.kind === 27 /* Snippet */) { - return 1; - } - else if (b.completion.kind === 27 /* Snippet */) { - return -1; - } - } - return CompletionModel._compareCompletionItems(a, b); - } - static _compareCompletionItemsSnippetsUp(a, b) { - if (a.completion.kind !== b.completion.kind) { - if (a.completion.kind === 27 /* Snippet */) { - return -1; - } - else if (b.completion.kind === 27 /* Snippet */) { - return 1; - } - } - return CompletionModel._compareCompletionItems(a, b); - } - } - 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[235/*vs/editor/contrib/suggest/resizable*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,7/*vs/base/browser/dom*/,107/*vs/base/browser/ui/sash/sash*/]), function (require, exports, event_1, lifecycle_1, dom_1, sash_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ResizableHTMLElement = void 0; - class ResizableHTMLElement { - constructor() { - this._onDidWillResize = new event_1.Emitter(); - this.onDidWillResize = this._onDidWillResize.event; - this._onDidResize = new event_1.Emitter(); - this.onDidResize = this._onDidResize.event; - this._sashListener = new lifecycle_1.DisposableStore(); - this._size = new dom_1.Dimension(0, 0); - this._minSize = new dom_1.Dimension(0, 0); - this._maxSize = new dom_1.Dimension(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER); - this.domNode = document.createElement('div'); - this._eastSash = new sash_1.Sash(this.domNode, { getVerticalSashLeft: () => this._size.width }, { orientation: 0 /* VERTICAL */ }); - this._westSash = new sash_1.Sash(this.domNode, { getVerticalSashLeft: () => 0 }, { orientation: 0 /* VERTICAL */ }); - this._northSash = new sash_1.Sash(this.domNode, { getHorizontalSashTop: () => 0 }, { orientation: 1 /* HORIZONTAL */, orthogonalEdge: sash_1.OrthogonalEdge.North }); - this._southSash = new sash_1.Sash(this.domNode, { getHorizontalSashTop: () => this._size.height }, { orientation: 1 /* HORIZONTAL */, orthogonalEdge: sash_1.OrthogonalEdge.South }); - this._northSash.orthogonalStartSash = this._westSash; - this._northSash.orthogonalEndSash = this._eastSash; - this._southSash.orthogonalStartSash = this._westSash; - this._southSash.orthogonalEndSash = this._eastSash; - let currentSize; - let deltaY = 0; - let deltaX = 0; - this._sashListener.add(event_1.Event.any(this._northSash.onDidStart, this._eastSash.onDidStart, this._southSash.onDidStart, this._westSash.onDidStart)(() => { - if (currentSize === undefined) { - this._onDidWillResize.fire(); - currentSize = this._size; - deltaY = 0; - deltaX = 0; - } - })); - this._sashListener.add(event_1.Event.any(this._northSash.onDidEnd, this._eastSash.onDidEnd, this._southSash.onDidEnd, this._westSash.onDidEnd)(() => { - if (currentSize !== undefined) { - currentSize = undefined; - deltaY = 0; - deltaX = 0; - this._onDidResize.fire({ dimension: this._size, done: true }); - } - })); - this._sashListener.add(this._eastSash.onDidChange(e => { - if (currentSize) { - deltaX = e.currentX - e.startX; - this.layout(currentSize.height + deltaY, currentSize.width + deltaX); - this._onDidResize.fire({ dimension: this._size, done: false, east: true }); - } - })); - this._sashListener.add(this._westSash.onDidChange(e => { - if (currentSize) { - deltaX = -(e.currentX - e.startX); - this.layout(currentSize.height + deltaY, currentSize.width + deltaX); - this._onDidResize.fire({ dimension: this._size, done: false, west: true }); - } - })); - this._sashListener.add(this._northSash.onDidChange(e => { - if (currentSize) { - deltaY = -(e.currentY - e.startY); - this.layout(currentSize.height + deltaY, currentSize.width + deltaX); - this._onDidResize.fire({ dimension: this._size, done: false, north: true }); - } - })); - this._sashListener.add(this._southSash.onDidChange(e => { - if (currentSize) { - deltaY = e.currentY - e.startY; - this.layout(currentSize.height + deltaY, currentSize.width + deltaX); - this._onDidResize.fire({ dimension: this._size, done: false, south: true }); - } - })); - this._sashListener.add(event_1.Event.any(this._eastSash.onDidReset, this._westSash.onDidReset)(e => { - if (this._preferredSize) { - this.layout(this._size.height, this._preferredSize.width); - this._onDidResize.fire({ dimension: this._size, done: true }); - } - })); - this._sashListener.add(event_1.Event.any(this._northSash.onDidReset, this._southSash.onDidReset)(e => { - if (this._preferredSize) { - this.layout(this._preferredSize.height, this._size.width); - this._onDidResize.fire({ dimension: this._size, done: true }); - } - })); - } - dispose() { - this._northSash.dispose(); - this._southSash.dispose(); - this._eastSash.dispose(); - this._westSash.dispose(); - this._sashListener.dispose(); - this._onDidResize.dispose(); - this._onDidWillResize.dispose(); - this.domNode.remove(); - } - enableSashes(north, east, south, west) { - this._northSash.state = north ? 3 /* Enabled */ : 0 /* Disabled */; - this._eastSash.state = east ? 3 /* Enabled */ : 0 /* Disabled */; - this._southSash.state = south ? 3 /* Enabled */ : 0 /* Disabled */; - this._westSash.state = west ? 3 /* Enabled */ : 0 /* Disabled */; - } - layout(height = this.size.height, width = this.size.width) { - const { height: minHeight, width: minWidth } = this._minSize; - const { height: maxHeight, width: maxWidth } = this._maxSize; - height = Math.max(minHeight, Math.min(maxHeight, height)); - width = Math.max(minWidth, Math.min(maxWidth, width)); - const newSize = new dom_1.Dimension(width, height); - if (!dom_1.Dimension.equals(newSize, this._size)) { - this.domNode.style.height = height + 'px'; - this.domNode.style.width = width + 'px'; - this._size = newSize; - this._northSash.layout(); - this._eastSash.layout(); - this._southSash.layout(); - this._westSash.layout(); - } - } - clearSashHoverState() { - this._eastSash.clearSashHoverState(); - this._westSash.clearSashHoverState(); - this._northSash.clearSashHoverState(); - this._southSash.clearSashHoverState(); - } - get size() { - return this._size; - } - set maxSize(value) { - this._maxSize = value; - } - get maxSize() { - return this._maxSize; - } - set minSize(value) { - this._minSize = value; - } - get minSize() { - return this._minSize; - } - set preferredSize(value) { - this._preferredSize = value; - } - get preferredSize() { - return this._preferredSize; - } - } - exports.ResizableHTMLElement = ResizableHTMLElement; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[423/*vs/editor/contrib/suggest/suggestCommitCharacters*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/,94/*vs/editor/common/core/characterClassifier*/]), function (require, exports, arrays_1, lifecycle_1, characterClassifier_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CommitCharacterController = void 0; - class CommitCharacterController { - constructor(editor, widget, accept) { - this._disposables = new lifecycle_1.DisposableStore(); - this._disposables.add(widget.onDidShow(() => 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(text => { - if (this._active && !widget.isFrozen()) { - const ch = text.charCodeAt(text.length - 1); - if (this._active.acceptCharacters.has(ch) && editor.getOption(0 /* acceptSuggestionOnCommitCharacter */)) { - accept(this._active.item); - } - } - })); - } - _onItem(selected) { - if (!selected || !(0, 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 - const acceptCharacters = new characterClassifier_1.CharacterSet(); - for (const ch of selected.item.completion.commitCharacters) { - if (ch.length > 0) { - acceptCharacters.add(ch.charCodeAt(0)); - } - } - this._active = { acceptCharacters, item: selected }; - } - reset() { - this._active = undefined; - } - dispose() { - this._disposables.dispose(); - } - } - 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[424/*vs/editor/contrib/suggest/suggestOvertypingCapturer*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/]), function (require, exports, lifecycle_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.OvertypingCapturer = void 0; - class OvertypingCapturer { - constructor(editor, suggestModel) { - this._disposables = new lifecycle_1.DisposableStore(); - this._lastOvertyped = []; - this._empty = true; - this._disposables.add(editor.onWillType(() => { - if (!this._empty) { - return; - } - if (!editor.hasModel()) { - return; - } - const selections = editor.getSelections(); - const selectionsLength = selections.length; - // Check if it will overtype any selections - let willOvertype = false; - for (let i = 0; i < selectionsLength; i++) { - if (!selections[i].isEmpty()) { - willOvertype = true; - break; - } - } - if (!willOvertype) { - return; - } - this._lastOvertyped = []; - const model = editor.getModel(); - for (let i = 0; i < selectionsLength; i++) { - const selection = selections[i]; - // Check for overtyping capturer restrictions - if (model.getValueLengthInRange(selection) > OvertypingCapturer._maxSelectionLength) { - return; - } - this._lastOvertyped[i] = { value: model.getValueInRange(selection), multiline: selection.startLineNumber !== selection.endLineNumber }; - } - this._empty = false; - })); - this._disposables.add(suggestModel.onDidCancel(e => { - if (!this._empty && !e.retrigger) { - this._empty = true; - } - })); - } - getLastOvertypedInfo(idx) { - if (!this._empty && idx >= 0 && idx < this._lastOvertyped.length) { - return this._lastOvertyped[idx]; - } - return undefined; - } - dispose() { - this._disposables.dispose(); - } - } - exports.OvertypingCapturer = OvertypingCapturer; - OvertypingCapturer._maxSelectionLength = 51200; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - - - - - - - - - -define(__m[425/*vs/editor/contrib/suggest/wordDistance*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,3/*vs/editor/common/core/range*/,234/*vs/editor/contrib/smartSelect/bracketSelections*/]), function (require, exports, arrays_1, range_1, bracketSelections_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.WordDistance = void 0; - class WordDistance { - static create(service, editor) { - return __awaiter(this, void 0, void 0, function* () { - if (!editor.getOption(105 /* suggest */).localityBonus) { - return WordDistance.None; - } - if (!editor.hasModel()) { - return WordDistance.None; - } - const model = editor.getModel(); - const position = editor.getPosition(); - if (!service.canComputeWordRanges(model.uri)) { - return WordDistance.None; - } - const [ranges] = yield new bracketSelections_1.BracketSelectionRangeProvider().provideSelectionRanges(model, [position]); - if (ranges.length === 0) { - return WordDistance.None; - } - const wordRanges = yield service.computeWordRanges(model.uri, ranges[0].range); - if (!wordRanges) { - return WordDistance.None; - } - // remove current word - const wordUntilPos = model.getWordUntilPosition(position); - delete wordRanges[wordUntilPos.word]; - return new class extends WordDistance { - distance(anchor, item) { - if (!position.equals(editor.getPosition())) { - return 0; - } - if (item.kind === 17 /* Keyword */) { - return 2 << 20; - } - let word = typeof item.label === 'string' ? item.label : item.label.label; - let wordLines = wordRanges[word]; - if ((0, arrays_1.isFalsyOrEmpty)(wordLines)) { - return 2 << 20; - } - let idx = (0, arrays_1.binarySearch)(wordLines, range_1.Range.fromPositions(anchor), range_1.Range.compareRangesUsingStarts); - let bestWordRange = idx >= 0 ? wordLines[idx] : wordLines[Math.max(0, ~idx - 1)]; - let blockDistance = ranges.length; - for (const range of ranges) { - if (!range_1.Range.containsRange(range.range, bestWordRange)) { - break; - } - blockDistance -= 1; - } - return blockDistance; - } - }; - }); - } - } - exports.WordDistance = WordDistance; - WordDistance.None = new class extends WordDistance { - distance() { return 0; } - }; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[236/*vs/editor/standalone/common/monarch/monarchCommon*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.stateExists = exports.findRules = exports.substituteMatches = exports.createError = exports.log = exports.sanitize = exports.fixCase = exports.empty = exports.isIAction = exports.isString = exports.isFuzzyAction = exports.isFuzzyActionArr = void 0; - 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) { - const re = /\$((\$)|(#)|(\d\d?)|[sS](\d\d?)|@(\w+))/g; - let 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) { - let state = inState; - while (state && state.length > 0) { - const rules = lexer.tokenizer[state]; - if (rules) { - return rules; - } - const 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) { - let state = inState; - while (state && state.length > 0) { - const exist = lexer.stateNames[state]; - if (exist) { - return true; - } - const 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[426/*vs/editor/standalone/common/monarch/monarchCompile*/], __M([0/*require*/,1/*exports*/,236/*vs/editor/standalone/common/monarch/monarchCommon*/]), function (require, exports, monarchCommon) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.compile = void 0; - /* - * 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 (const el of obj) { - 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) { - const result = {}; - for (const e of array) { - result[e] = true; - } - return result; - } - function createKeywordMatcher(arr, caseInsensitive = false) { - if (caseInsensitive) { - arr = arr.map(function (x) { return x.toLowerCase(); }); - } - const 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, and the 'u' flag if 'unicode' is set. - * Also replaces @\w+ or sequences with the content of the specified attribute - * @\w+ replacement can be avoided by escaping `@` signs with another `@` sign. - * @example /@attr/ will be replaced with the value of lexer[attr] - * @example /@@text/ will not be replaced and will become /@text/. - */ - function compileRegExp(lexer, str) { - // @@ must be interpreted as a literal @, so we replace all occurences of @@ with a placeholder character - str = str.replace(/@@/g, `\x01`); - let n = 0; - let hadExpansion; - do { - hadExpansion = false; - str = str.replace(/@(\w+)/g, function (s, attr) { - hadExpansion = true; - let 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 + ')'); - }); - n++; - } while (hadExpansion && n < 5); - // handle escaped @@ - str = str.replace(/\x01/g, '@'); - let flags = (lexer.ignoreCase ? 'i' : '') + (lexer.unicode ? 'u' : ''); - return new RegExp(str, flags); - } - /** - * 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; - let 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 - let scrut = -1; // -1: $!, 0-99: $n, 100+n: $Sn - let oppat = tkey; - let 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 - let op = '~'; - let 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 - let tester; - // special case a regexp that matches just words - if ((op === '~' || op === '!~') && /^(\w|\|)*$/.test(pat)) { - let inWords = createKeywordMatcher(pat.split('|'), lexer.ignoreCase); - tester = function (s) { return (op === '~' ? inWords(s) : !inWords(s)); }; - } - else if (op === '@' || op === '!@') { - let 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); - } - let inWords = createKeywordMatcher(words, lexer.ignoreCase); - tester = function (s) { return (op === '@' ? inWords(s) : !inWords(s)); }; - } - else if (op === '~' || op === '!~') { - if (pat.indexOf('$') < 0) { - // precompile regular expression - let re = compileRegExp(lexer, '^' + pat + '$'); - tester = function (s) { return (op === '~' ? re.test(s) : !re.test(s)); }; - } - else { - tester = function (s, id, matches, state) { - let re = compileRegExp(lexer, '^' + monarchCommon.substituteMatches(lexer, pat, id, matches, state) + '$'); - return re.test(s); - }; - } - } - else { // if (op==='==' || op==='!=') { - if (pat.indexOf('$') < 0) { - let patx = monarchCommon.fixCase(lexer, pat); - tester = function (s) { return (op === '==' ? s === patx : s !== patx); }; - } - else { - let patx = monarchCommon.fixCase(lexer, pat); - tester = function (s, id, matches, state, eos) { - let patexp = monarchCommon.substituteMatches(lexer, patx, 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) { - let 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) - let 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 { - let 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)) { - let results = []; - for (let 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 - let cases = []; - // for each case, push a test function and result value - for (let tkey in action.cases) { - if (action.cases.hasOwnProperty(tkey)) { - const val = compileAction(lexer, ruleName, action.cases[tkey]); - // what kind of case - if (tkey === '@default' || tkey === '@' || tkey === '') { - cases.push({ test: undefined, value: val, name: tkey }); - } - else if (tkey === '@eos') { - cases.push({ test: function (id, matches, state, eos) { return eos; }, value: val, name: tkey }); - } - else { - cases.push(createGuard(lexer, ruleName, tkey, val)); // call separate function to avoid local variable capture - } - } - } - // create a matching function - const def = lexer.defaultToken; - return { - test: function (id, matches, state, eos) { - for (const _case of cases) { - const didmatch = (!_case.test || _case.test(id, matches, state, eos)); - if (didmatch) { - return _case.value; - } - } - return def; - } - }; - } - 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 - */ - class Rule { - constructor(name) { - this.regex = new RegExp(''); - this.action = { token: '' }; - this.matchOnlyAtLineStart = false; - this.name = ''; - this.name = name; - } - setRegex(lexer, re) { - let 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) + ')'); - } - setAction(lexer, act) { - this.action = compileAction(lexer, this.name, act); - } - } - /** - * 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 - let lexer = {}; - lexer.languageId = languageId; - lexer.includeLF = bool(json.includeLF, false); - 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.unicode = bool(json.unicode, 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 - let lexerMin = json; - lexerMin.languageId = languageId; - lexerMin.includeLF = lexer.includeLF; - lexerMin.ignoreCase = lexer.ignoreCase; - lexerMin.unicode = lexer.unicode; - 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 (const rule of rules) { - let 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 { - const 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') { - const 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 (let key in json.tokenizer) { - if (json.tokenizer.hasOwnProperty(key)) { - if (!lexer.start) { - lexer.start = key; - } - const 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' } - ]; - } - let brackets = []; - for (let el of json.brackets) { - let 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[427/*vs/nls!vs/base/browser/ui/actionbar/actionViewItems*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/actionbar/actionViewItems", data); }); -define(__m[428/*vs/nls!vs/base/browser/ui/findinput/findInput*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/findinput/findInput", data); }); -define(__m[429/*vs/nls!vs/base/browser/ui/findinput/findInputCheckboxes*/], __M([4/*vs/nls*/,5/*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[237/*vs/base/browser/ui/findinput/findInputCheckboxes*/], __M([0/*require*/,1/*exports*/,165/*vs/base/browser/ui/checkbox/checkbox*/,429/*vs/nls!vs/base/browser/ui/findinput/findInputCheckboxes*/,27/*vs/base/common/codicons*/]), function (require, exports, checkbox_1, nls, codicons_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.RegexCheckbox = exports.WholeWordsCheckbox = exports.CaseSensitiveCheckbox = void 0; - const NLS_CASE_SENSITIVE_CHECKBOX_LABEL = nls.localize(0, null); - const NLS_WHOLE_WORD_CHECKBOX_LABEL = nls.localize(1, null); - const NLS_REGEX_CHECKBOX_LABEL = nls.localize(2, null); - class CaseSensitiveCheckbox extends checkbox_1.Checkbox { - constructor(opts) { - super({ - icon: codicons_1.Codicon.caseSensitive, - title: NLS_CASE_SENSITIVE_CHECKBOX_LABEL + opts.appendTitle, - isChecked: opts.isChecked, - inputActiveOptionBorder: opts.inputActiveOptionBorder, - inputActiveOptionForeground: opts.inputActiveOptionForeground, - inputActiveOptionBackground: opts.inputActiveOptionBackground - }); - } - } - exports.CaseSensitiveCheckbox = CaseSensitiveCheckbox; - class WholeWordsCheckbox extends checkbox_1.Checkbox { - constructor(opts) { - super({ - icon: codicons_1.Codicon.wholeWord, - title: NLS_WHOLE_WORD_CHECKBOX_LABEL + opts.appendTitle, - isChecked: opts.isChecked, - inputActiveOptionBorder: opts.inputActiveOptionBorder, - inputActiveOptionForeground: opts.inputActiveOptionForeground, - inputActiveOptionBackground: opts.inputActiveOptionBackground - }); - } - } - exports.WholeWordsCheckbox = WholeWordsCheckbox; - class RegexCheckbox extends checkbox_1.Checkbox { - constructor(opts) { - super({ - icon: codicons_1.Codicon.regex, - title: NLS_REGEX_CHECKBOX_LABEL + opts.appendTitle, - isChecked: opts.isChecked, - inputActiveOptionBorder: opts.inputActiveOptionBorder, - inputActiveOptionForeground: opts.inputActiveOptionForeground, - inputActiveOptionBackground: opts.inputActiveOptionBackground - }); - } - } - exports.RegexCheckbox = RegexCheckbox; -}); - -define(__m[430/*vs/nls!vs/base/browser/ui/findinput/replaceInput*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/findinput/replaceInput", data); }); -define(__m[431/*vs/nls!vs/base/browser/ui/iconLabel/iconLabelHover*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/iconLabel/iconLabelHover", 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[432/*vs/base/browser/ui/iconLabel/iconLabelHover*/], __M([0/*require*/,1/*exports*/,20/*vs/base/common/types*/,7/*vs/base/browser/dom*/,23/*vs/base/common/cancellation*/,2/*vs/base/common/lifecycle*/,431/*vs/nls!vs/base/browser/ui/iconLabel/iconLabelHover*/,15/*vs/base/common/async*/]), function (require, exports, types_1, dom, cancellation_1, lifecycle_1, nls_1, async_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.setupCustomHover = exports.setupNativeHover = void 0; - function setupNativeHover(htmlElement, tooltip) { - if ((0, types_1.isString)(tooltip)) { - htmlElement.title = tooltip; - } - else if (tooltip === null || tooltip === void 0 ? void 0 : tooltip.markdownNotSupportedFallback) { - htmlElement.title = tooltip.markdownNotSupportedFallback; - } - else { - htmlElement.removeAttribute('title'); - } - } - exports.setupNativeHover = setupNativeHover; - function setupCustomHover(hoverDelegate, htmlElement, markdownTooltip) { - if (!markdownTooltip) { - return undefined; - } - const tooltip = getTooltipForCustom(markdownTooltip); - let hoverPreparation; - let hoverWidget; - const mouseEnter = (e) => { - if (hoverPreparation) { - return; - } - const tokenSource = new cancellation_1.CancellationTokenSource(); - const mouseLeaveOrDown = (e) => { - const isMouseDown = e.type === dom.EventType.MOUSE_DOWN; - if (isMouseDown) { - hoverWidget === null || hoverWidget === void 0 ? void 0 : hoverWidget.dispose(); - hoverWidget = undefined; - } - if (isMouseDown || e.fromElement === htmlElement) { - hoverPreparation === null || hoverPreparation === void 0 ? void 0 : hoverPreparation.dispose(); - hoverPreparation = undefined; - } - }; - const mouseLeaveDomListener = dom.addDisposableListener(htmlElement, dom.EventType.MOUSE_LEAVE, mouseLeaveOrDown, true); - const mouseDownDownListener = dom.addDisposableListener(htmlElement, dom.EventType.MOUSE_DOWN, mouseLeaveOrDown, true); - const target = { - targetElements: [htmlElement], - dispose: () => { } - }; - let mouseMoveDomListener; - if (hoverDelegate.placement === undefined || hoverDelegate.placement === 'mouse') { - const mouseMove = (e) => target.x = e.x + 10; - mouseMoveDomListener = dom.addDisposableListener(htmlElement, dom.EventType.MOUSE_MOVE, mouseMove, true); - } - const showHover = () => __awaiter(this, void 0, void 0, function* () { - var _a; - if (hoverPreparation) { - const hoverOptions = { - text: (0, nls_1.localize)(0, null), - target, - hoverPosition: 2 /* BELOW */ - }; - hoverWidget === null || hoverWidget === void 0 ? void 0 : hoverWidget.dispose(); - hoverWidget = hoverDelegate.showHover(hoverOptions); - const resolvedTooltip = (_a = (yield tooltip(tokenSource.token))) !== null && _a !== void 0 ? _a : (!(0, types_1.isString)(markdownTooltip) ? markdownTooltip.markdownNotSupportedFallback : undefined); - hoverWidget === null || hoverWidget === void 0 ? void 0 : hoverWidget.dispose(); - hoverWidget = undefined; - // awaiting the tooltip could take a while. Make sure we're still preparing to hover. - if (resolvedTooltip && hoverPreparation) { - const hoverOptions = { - text: resolvedTooltip, - target, - showPointer: hoverDelegate.placement === 'element', - hoverPosition: 2 /* BELOW */ - }; - hoverWidget = hoverDelegate.showHover(hoverOptions); - } - } - mouseMoveDomListener === null || mouseMoveDomListener === void 0 ? void 0 : mouseMoveDomListener.dispose(); - }); - const timeout = new async_1.RunOnceScheduler(showHover, hoverDelegate.delay); - timeout.schedule(); - hoverPreparation = (0, lifecycle_1.toDisposable)(() => { - timeout.dispose(); - mouseMoveDomListener === null || mouseMoveDomListener === void 0 ? void 0 : mouseMoveDomListener.dispose(); - mouseDownDownListener.dispose(); - mouseLeaveDomListener.dispose(); - tokenSource.dispose(true); - }); - }; - const mouseOverDomEmitter = dom.addDisposableListener(htmlElement, dom.EventType.MOUSE_OVER, mouseEnter, true); - return (0, lifecycle_1.toDisposable)(() => { - mouseOverDomEmitter.dispose(); - hoverPreparation === null || hoverPreparation === void 0 ? void 0 : hoverPreparation.dispose(); - hoverWidget === null || hoverWidget === void 0 ? void 0 : hoverWidget.dispose(); - }); - } - exports.setupCustomHover = setupCustomHover; - function getTooltipForCustom(markdownTooltip) { - if ((0, types_1.isString)(markdownTooltip)) { - return () => __awaiter(this, void 0, void 0, function* () { return markdownTooltip; }); - } - else if ((0, types_1.isFunction)(markdownTooltip.markdown)) { - return markdownTooltip.markdown; - } - else { - const markdown = markdownTooltip.markdown; - return () => __awaiter(this, void 0, void 0, function* () { return markdown; }); - } - } -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[179/*vs/base/browser/ui/iconLabel/iconLabel*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,161/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/,2/*vs/base/common/lifecycle*/,126/*vs/base/common/range*/,42/*vs/base/common/objects*/,432/*vs/base/browser/ui/iconLabel/iconLabelHover*/,311/*vs/css!vs/base/browser/ui/iconLabel/iconlabel*/]), function (require, exports, dom, highlightedLabel_1, lifecycle_1, range_1, objects_1, iconLabelHover_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.IconLabel = void 0; - class FastLabelNode { - constructor(_element) { - this._element = _element; - } - get element() { - return this._element; - } - set textContent(content) { - if (this.disposed || content === this._textContent) { - return; - } - this._textContent = content; - this._element.textContent = content; - } - set className(className) { - if (this.disposed || className === this._className) { - return; - } - this._className = className; - this._element.className = className; - } - set empty(empty) { - if (this.disposed || empty === this._empty) { - return; - } - this._empty = empty; - this._element.style.marginLeft = empty ? '0' : ''; - } - dispose() { - this.disposed = true; - } - } - class IconLabel extends lifecycle_1.Disposable { - constructor(container, options) { - super(); - this.customHovers = new Map(); - this.domNode = this._register(new FastLabelNode(dom.append(container, dom.$('.monaco-icon-label')))); - this.labelContainer = dom.append(this.domNode.element, dom.$('.monaco-icon-label-container')); - const nameContainer = dom.append(this.labelContainer, dom.$('span.monaco-icon-name-container')); - this.descriptionContainer = this._register(new FastLabelNode(dom.append(this.labelContainer, dom.$('span.monaco-icon-description-container')))); - if ((options === null || options === void 0 ? void 0 : options.supportHighlights) || (options === null || options === void 0 ? void 0 : options.supportIcons)) { - this.nameNode = new LabelWithHighlights(nameContainer, !!options.supportIcons); - } - else { - this.nameNode = new Label(nameContainer); - } - if (options === null || options === void 0 ? void 0 : options.supportDescriptionHighlights) { - this.descriptionNodeFactory = () => new highlightedLabel_1.HighlightedLabel(dom.append(this.descriptionContainer.element, dom.$('span.label-description')), !!options.supportIcons); - } - else { - this.descriptionNodeFactory = () => this._register(new FastLabelNode(dom.append(this.descriptionContainer.element, dom.$('span.label-description')))); - } - this.hoverDelegate = options === null || options === void 0 ? void 0 : options.hoverDelegate; - } - setLabel(label, description, options) { - const classes = ['monaco-icon-label']; - if (options) { - if (options.extraClasses) { - classes.push(...options.extraClasses); - } - if (options.italic) { - classes.push('italic'); - } - if (options.strikethrough) { - classes.push('strikethrough'); - } - } - this.domNode.className = classes.join(' '); - this.setupHover(this.labelContainer, 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); - this.setupHover(this.descriptionNode.element, options === null || options === void 0 ? void 0 : options.descriptionTitle); - } - else { - this.descriptionNode.textContent = description || ''; - this.setupHover(this.descriptionNode.element, (options === null || options === void 0 ? void 0 : options.descriptionTitle) || ''); - this.descriptionNode.empty = !description; - } - } - } - setupHover(htmlElement, tooltip) { - const previousCustomHover = this.customHovers.get(htmlElement); - if (previousCustomHover) { - previousCustomHover.dispose(); - this.customHovers.delete(htmlElement); - } - if (!tooltip) { - htmlElement.removeAttribute('title'); - return; - } - if (!this.hoverDelegate) { - (0, iconLabelHover_1.setupNativeHover)(htmlElement, tooltip); - } - else { - const hoverDisposable = (0, iconLabelHover_1.setupCustomHover)(this.hoverDelegate, htmlElement, tooltip); - if (hoverDisposable) { - this.customHovers.set(htmlElement, hoverDisposable); - } - } - } - dispose() { - super.dispose(); - for (const disposable of this.customHovers.values()) { - disposable.dispose(); - } - this.customHovers.clear(); - } - } - exports.IconLabel = IconLabel; - class Label { - constructor(container) { - this.container = container; - this.label = undefined; - this.singleLabel = undefined; - } - setLabel(label, options) { - if (this.label === label && (0, objects_1.equals)(this.options, options)) { - return; - } - this.label = label; - this.options = options; - if (typeof label === 'string') { - if (!this.singleLabel) { - this.container.innerText = ''; - this.container.classList.remove('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.innerText = ''; - this.container.classList.add('multiple'); - this.singleLabel = undefined; - for (let i = 0; i < label.length; i++) { - const l = label[i]; - const 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, 'data-icon-label-count': label.length, 'data-icon-label-index': i, 'role': 'treeitem' }, l)); - if (i < label.length - 1) { - dom.append(this.container, dom.$('span.label-separator', undefined, (options === null || options === void 0 ? void 0 : options.separator) || '/')); - } - } - } - } - } - function splitMatches(labels, separator, matches) { - if (!matches) { - return undefined; - } - let labelStart = 0; - return labels.map(label => { - const labelRange = { start: labelStart, end: labelStart + label.length }; - const result = matches - .map(match => range_1.Range.intersect(labelRange, match)) - .filter(range => !range_1.Range.isEmpty(range)) - .map(({ start, end }) => ({ start: start - labelStart, end: end - labelStart })); - labelStart = labelRange.end + separator.length; - return result; - }); - } - class LabelWithHighlights { - constructor(container, supportIcons) { - this.container = container; - this.supportIcons = supportIcons; - this.label = undefined; - this.singleLabel = undefined; - } - setLabel(label, options) { - if (this.label === label && (0, objects_1.equals)(this.options, options)) { - return; - } - this.label = label; - this.options = options; - if (typeof label === 'string') { - if (!this.singleLabel) { - this.container.innerText = ''; - this.container.classList.remove('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.supportIcons); - } - this.singleLabel.set(label, options === null || options === void 0 ? void 0 : options.matches, undefined, options === null || options === void 0 ? void 0 : options.labelEscapeNewLines); - } - else { - this.container.innerText = ''; - this.container.classList.add('multiple'); - this.singleLabel = undefined; - const separator = (options === null || options === void 0 ? void 0 : options.separator) || '/'; - const matches = splitMatches(label, separator, options === null || options === void 0 ? void 0 : options.matches); - for (let i = 0; i < label.length; i++) { - const l = label[i]; - const m = matches ? matches[i] : undefined; - const id = (options === null || options === void 0 ? void 0 : options.domId) && `${options === null || options === void 0 ? void 0 : options.domId}_${i}`; - const name = dom.$('a.label-name', { id, 'data-icon-label-count': label.length, 'data-icon-label-index': i, 'role': 'treeitem' }); - const highlightedLabel = new highlightedLabel_1.HighlightedLabel(dom.append(this.container, name), this.supportIcons); - highlightedLabel.set(l, m, undefined, options === null || options === void 0 ? void 0 : options.labelEscapeNewLines); - if (i < label.length - 1) { - dom.append(name, dom.$('span.label-separator', undefined, separator)); - } - } - } - } - } -}); - -define(__m[433/*vs/nls!vs/base/browser/ui/inputbox/inputBox*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/inputbox/inputBox", data); }); -define(__m[434/*vs/nls!vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/keybindingLabel/keybindingLabel", data); }); -define(__m[435/*vs/nls!vs/base/browser/ui/menu/menu*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/menu/menu", data); }); -define(__m[436/*vs/nls!vs/base/browser/ui/tree/abstractTree*/], __M([4/*vs/nls*/,5/*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. - *--------------------------------------------------------------------------------------------*/ -define(__m[180/*vs/base/browser/ui/tree/abstractTree*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,108/*vs/base/browser/ui/list/listWidget*/,7/*vs/base/browser/dom*/,6/*vs/base/common/event*/,51/*vs/base/browser/keyboardEvent*/,101/*vs/base/browser/ui/tree/tree*/,164/*vs/base/browser/dnd*/,19/*vs/base/common/arrays*/,166/*vs/base/browser/ui/list/listView*/,91/*vs/base/browser/event*/,67/*vs/base/common/filters*/,158/*vs/base/browser/ui/tree/indexTreeModel*/,436/*vs/nls!vs/base/browser/ui/tree/abstractTree*/,15/*vs/base/common/async*/,17/*vs/base/common/platform*/,102/*vs/base/common/numbers*/,199/*vs/base/common/collections*/,200/*vs/base/browser/ui/tree/treeIcons*/,324/*vs/css!vs/base/browser/ui/tree/media/tree*/]), function (require, exports, lifecycle_1, listWidget_1, dom_1, event_1, keyboardEvent_1, tree_1, dnd_1, arrays_1, listView_1, event_2, filters_1, indexTreeModel_1, nls_1, async_1, platform_1, numbers_1, collections_1, treeIcons_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.AbstractTree = exports.RenderIndentGuides = exports.ComposedTreeDelegate = void 0; - class TreeElementsDragAndDropData extends listView_1.ElementsDragAndDropData { - constructor(data) { - super(data.elements.map(node => node.element)); - this.data = data; - } - } - function asTreeDragAndDropData(data) { - if (data instanceof listView_1.ElementsDragAndDropData) { - return new TreeElementsDragAndDropData(data); - } - return data; - } - class TreeNodeListDragAndDrop { - constructor(modelProvider, dnd) { - this.modelProvider = modelProvider; - this.dnd = dnd; - this.autoExpandDisposable = lifecycle_1.Disposable.None; - } - getDragURI(node) { - return this.dnd.getDragURI(node.element); - } - getDragLabel(nodes, originalEvent) { - if (this.dnd.getDragLabel) { - return this.dnd.getDragLabel(nodes.map(node => node.element), originalEvent); - } - return undefined; - } - onDragStart(data, originalEvent) { - if (this.dnd.onDragStart) { - this.dnd.onDragStart(asTreeDragAndDropData(data), originalEvent); - } - } - onDragOver(data, targetNode, targetIndex, originalEvent, raw = true) { - const result = this.dnd.onDragOver(asTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent); - const 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 = (0, async_1.disposableTimeout)(() => { - const model = this.modelProvider(); - const 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) { - const accept = typeof result === 'boolean' ? result : result.accept; - const effect = typeof result === 'boolean' ? undefined : result.effect; - return { accept, effect, feedback: [targetIndex] }; - } - return result; - } - if (result.bubble === 1 /* Up */) { - const model = this.modelProvider(); - const ref = model.getNodeLocation(targetNode); - const parentRef = model.getParentNodeLocation(ref); - const parentNode = model.getNode(parentRef); - const parentIndex = parentRef && model.getListIndex(parentRef); - return this.onDragOver(data, parentNode, parentIndex, originalEvent, false); - } - const model = this.modelProvider(); - const ref = model.getNodeLocation(targetNode); - const start = model.getListIndex(ref); - const length = model.getListRenderCount(ref); - return Object.assign(Object.assign({}, result), { feedback: (0, arrays_1.range)(start, start + length) }); - } - drop(data, targetNode, targetIndex, originalEvent) { - this.autoExpandDisposable.dispose(); - this.autoExpandNode = undefined; - this.dnd.drop(asTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent); - } - onDragEnd(originalEvent) { - if (this.dnd.onDragEnd) { - this.dnd.onDragEnd(originalEvent); - } - } - } - function asListOptions(modelProvider, options) { - return options && Object.assign(Object.assign({}, options), { identityProvider: options.identityProvider && { - getId(el) { - return options.identityProvider.getId(el.element); - } - }, dnd: options.dnd && new TreeNodeListDragAndDrop(modelProvider, options.dnd), multipleSelectionController: options.multipleSelectionController && { - isSelectionSingleChangeEvent(e) { - return options.multipleSelectionController.isSelectionSingleChangeEvent(Object.assign(Object.assign({}, e), { element: e.element })); - }, - isSelectionRangeChangeEvent(e) { - return options.multipleSelectionController.isSelectionRangeChangeEvent(Object.assign(Object.assign({}, e), { element: e.element })); - } - }, accessibilityProvider: options.accessibilityProvider && Object.assign(Object.assign({}, options.accessibilityProvider), { getSetSize(node) { - const model = modelProvider(); - const ref = model.getNodeLocation(node); - const parentRef = model.getParentNodeLocation(ref); - const parentNode = model.getNode(parentRef); - return parentNode.visibleChildrenCount; - }, - getPosInSet(node) { - return node.visibleChildIndex + 1; - }, isChecked: options.accessibilityProvider && options.accessibilityProvider.isChecked ? (node) => { - return options.accessibilityProvider.isChecked(node.element); - } : undefined, getRole: options.accessibilityProvider && options.accessibilityProvider.getRole ? (node) => { - return options.accessibilityProvider.getRole(node.element); - } : () => 'treeitem', getAriaLabel(e) { - return options.accessibilityProvider.getAriaLabel(e.element); - }, - getWidgetAriaLabel() { - return options.accessibilityProvider.getWidgetAriaLabel(); - }, getWidgetRole: options.accessibilityProvider && options.accessibilityProvider.getWidgetRole ? () => options.accessibilityProvider.getWidgetRole() : () => 'tree', getAriaLevel: options.accessibilityProvider && options.accessibilityProvider.getAriaLevel ? (node) => options.accessibilityProvider.getAriaLevel(node.element) : (node) => { - return node.depth; - }, getActiveDescendantId: options.accessibilityProvider.getActiveDescendantId && (node => { - return options.accessibilityProvider.getActiveDescendantId(node.element); - }) }), keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && Object.assign(Object.assign({}, options.keyboardNavigationLabelProvider), { getKeyboardNavigationLabel(node) { - return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(node.element); - } }), enableKeyboardNavigation: options.simpleKeyboardNavigation }); - } - class ComposedTreeDelegate { - constructor(delegate) { - this.delegate = delegate; - } - getHeight(element) { - return this.delegate.getHeight(element.element); - } - getTemplateId(element) { - return this.delegate.getTemplateId(element.element); - } - hasDynamicHeight(element) { - return !!this.delegate.hasDynamicHeight && this.delegate.hasDynamicHeight(element.element); - } - setDynamicHeight(element, height) { - if (this.delegate.setDynamicHeight) { - this.delegate.setDynamicHeight(element.element, height); - } - } - } - exports.ComposedTreeDelegate = ComposedTreeDelegate; - var RenderIndentGuides; - (function (RenderIndentGuides) { - RenderIndentGuides["None"] = "none"; - RenderIndentGuides["OnHover"] = "onHover"; - RenderIndentGuides["Always"] = "always"; - })(RenderIndentGuides = exports.RenderIndentGuides || (exports.RenderIndentGuides = {})); - class EventCollection { - constructor(onDidChange, _elements = []) { - this._elements = _elements; - this.onDidChange = event_1.Event.forEach(onDidChange, elements => this._elements = elements); - } - get elements() { - return this._elements; - } - } - class TreeRenderer { - constructor(renderer, modelProvider, onDidChangeCollapseState, activeNodes, 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, e => e.node)(this.onDidChangeNodeTwistieState, this, this.disposables); - if (renderer.onDidChangeTwistieState) { - renderer.onDidChangeTwistieState(this.onDidChangeTwistieState, this, this.disposables); - } - } - updateOptions(options = {}) { - if (typeof options.indent !== 'undefined') { - this.indent = (0, numbers_1.clamp)(options.indent, 0, 40); - } - if (typeof options.renderIndentGuides !== 'undefined') { - const shouldRenderIndentGuides = options.renderIndentGuides !== RenderIndentGuides.None; - if (shouldRenderIndentGuides !== this.shouldRenderIndentGuides) { - this.shouldRenderIndentGuides = shouldRenderIndentGuides; - this.indentGuidesDisposable.dispose(); - if (shouldRenderIndentGuides) { - const 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; - } - } - renderTemplate(container) { - const el = (0, dom_1.append)(container, (0, dom_1.$)('.monaco-tl-row')); - const indent = (0, dom_1.append)(el, (0, dom_1.$)('.monaco-tl-indent')); - const twistie = (0, dom_1.append)(el, (0, dom_1.$)('.monaco-tl-twistie')); - const contents = (0, dom_1.append)(el, (0, dom_1.$)('.monaco-tl-contents')); - const templateData = this.renderer.renderTemplate(contents); - return { container, indent, twistie, indentGuidesDisposable: lifecycle_1.Disposable.None, templateData }; - } - renderElement(node, index, templateData, height) { - if (typeof height === 'number') { - this.renderedNodes.set(node, { templateData, height }); - this.renderedElements.set(node.element, node); - } - const 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); - } - disposeElement(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); - } - } - disposeTemplate(templateData) { - this.renderer.disposeTemplate(templateData.templateData); - } - onDidChangeTwistieState(element) { - const node = this.renderedElements.get(element); - if (!node) { - return; - } - this.onDidChangeNodeTwistieState(node); - } - onDidChangeNodeTwistieState(node) { - const data = this.renderedNodes.get(node); - if (!data) { - return; - } - this.renderTwistie(node, data.templateData); - this._onDidChangeActiveNodes(this.activeNodes.elements); - this.renderIndentGuides(node, data.templateData); - } - renderTwistie(node, templateData) { - templateData.twistie.classList.remove(...treeIcons_1.treeItemExpandedIcon.classNamesArray); - let twistieRendered = false; - if (this.renderer.renderTwistie) { - twistieRendered = this.renderer.renderTwistie(node.element, templateData.twistie); - } - if (node.collapsible && (!this.hideTwistiesOfChildlessElements || node.visibleChildrenCount > 0)) { - if (!twistieRendered) { - templateData.twistie.classList.add(...treeIcons_1.treeItemExpandedIcon.classNamesArray); - } - templateData.twistie.classList.add('collapsible'); - templateData.twistie.classList.toggle('collapsed', node.collapsed); - } - else { - templateData.twistie.classList.remove('collapsible', 'collapsed'); - } - if (node.collapsible) { - templateData.container.setAttribute('aria-expanded', String(!node.collapsed)); - } - else { - templateData.container.removeAttribute('aria-expanded'); - } - } - renderIndentGuides(target, templateData) { - (0, dom_1.clearNode)(templateData.indent); - templateData.indentGuidesDisposable.dispose(); - if (!this.shouldRenderIndentGuides) { - return; - } - const disposableStore = new lifecycle_1.DisposableStore(); - const model = this.modelProvider(); - let node = target; - while (true) { - const ref = model.getNodeLocation(node); - const parentRef = model.getParentNodeLocation(ref); - if (!parentRef) { - break; - } - const parent = model.getNode(parentRef); - const guide = (0, dom_1.$)('.indent-guide', { style: `width: ${this.indent}px` }); - if (this.activeIndentNodes.has(parent)) { - guide.classList.add('active'); - } - if (templateData.indent.childElementCount === 0) { - templateData.indent.appendChild(guide); - } - else { - templateData.indent.insertBefore(guide, templateData.indent.firstElementChild); - } - this.renderedIndentGuides.add(parent, guide); - disposableStore.add((0, lifecycle_1.toDisposable)(() => this.renderedIndentGuides.delete(parent, guide))); - node = parent; - } - templateData.indentGuidesDisposable = disposableStore; - } - _onDidChangeActiveNodes(nodes) { - if (!this.shouldRenderIndentGuides) { - return; - } - const set = new Set(); - const model = this.modelProvider(); - nodes.forEach(node => { - const ref = model.getNodeLocation(node); - try { - const 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(node => { - if (!set.has(node)) { - this.renderedIndentGuides.forEach(node, line => line.classList.remove('active')); - } - }); - set.forEach(node => { - if (!this.activeIndentNodes.has(node)) { - this.renderedIndentGuides.forEach(node, line => line.classList.add('active')); - } - }); - this.activeIndentNodes = set; - } - dispose() { - this.renderedNodes.clear(); - this.renderedElements.clear(); - this.indentGuidesDisposable.dispose(); - (0, lifecycle_1.dispose)(this.disposables); - } - } - TreeRenderer.DefaultIndent = 8; - class TypeFilter { - constructor(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); - } - get totalCount() { return this._totalCount; } - get matchCount() { return this._matchCount; } - set pattern(pattern) { - this._pattern = pattern; - this._lowercasePattern = pattern.toLowerCase(); - } - filter(element, parentVisibility) { - if (this._filter) { - const result = this._filter.filter(element, parentVisibility); - if (this.tree.options.simpleKeyboardNavigation) { - return result; - } - let visibility; - if (typeof result === 'boolean') { - visibility = result ? 1 /* Visible */ : 0 /* Hidden */; - } - else if ((0, indexTreeModel_1.isFilterResult)(result)) { - visibility = (0, 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 }; - } - const label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(element); - const labels = Array.isArray(label) ? label : [label]; - for (const l of labels) { - const labelStr = l && l.toString(); - if (typeof labelStr === 'undefined') { - return { data: filters_1.FuzzyScore.Default, visibility: true }; - } - const score = (0, filters_1.fuzzyScore)(this._pattern, this._lowercasePattern, 0, labelStr, labelStr.toLowerCase(), 0, true); - if (score) { - this._matchCount++; - return labels.length === 1 ? - { data: score, visibility: true } : - { data: { label: labelStr, score: score }, visibility: true }; - } - } - if (this.tree.options.filterOnType) { - return 2 /* Recurse */; - } - else { - return { data: filters_1.FuzzyScore.Default, visibility: true }; - } - } - reset() { - this._totalCount = 0; - this._matchCount = 0; - } - dispose() { - (0, lifecycle_1.dispose)(this.disposables); - } - } - class TypeFilterController { - constructor(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 = (0, dom_1.$)(`.monaco-list-type-filter.${this.positionClassName}`); - this.domNode.draggable = true; - this.disposables.add((0, dom_1.addDisposableListener)(this.domNode, 'dragstart', () => this.onDragStart())); - this.messageDomNode = (0, dom_1.append)(view.getHTMLElement(), (0, dom_1.$)(`.monaco-list-type-filter-message`)); - this.labelDomNode = (0, dom_1.append)(this.domNode, (0, dom_1.$)('span.label')); - const controls = (0, dom_1.append)(this.domNode, (0, dom_1.$)('.controls')); - this._filterOnType = !!tree.options.filterOnType; - this.filterOnTypeDomNode = (0, dom_1.append)(controls, (0, dom_1.$)('input.filter')); - this.filterOnTypeDomNode.type = 'checkbox'; - this.filterOnTypeDomNode.checked = this._filterOnType; - this.filterOnTypeDomNode.tabIndex = -1; - this.updateFilterOnTypeTitleAndIcon(); - this.disposables.add((0, dom_1.addDisposableListener)(this.filterOnTypeDomNode, 'input', () => this.onDidChangeFilterOnType())); - this.clearDomNode = (0, dom_1.append)(controls, (0, dom_1.$)('button.clear' + treeIcons_1.treeFilterClearIcon.cssSelector)); - this.clearDomNode.tabIndex = -1; - this.clearDomNode.title = (0, nls_1.localize)(0, null); - this.keyboardNavigationEventFilter = tree.options.keyboardNavigationEventFilter; - model.onDidSplice(this.onDidSpliceModel, this, this.disposables); - this.updateOptions(tree.options); - } - get enabled() { return this._enabled; } - get pattern() { return this._pattern; } - get filterOnType() { return this._filterOnType; } - updateOptions(options) { - if (options.simpleKeyboardNavigation) { - this.disable(); - } - else { - this.enable(); - } - if (typeof options.filterOnType !== 'undefined') { - this._filterOnType = !!options.filterOnType; - this.filterOnTypeDomNode.checked = this._filterOnType; - this.updateFilterOnTypeTitleAndIcon(); - } - if (typeof options.automaticKeyboardNavigation !== 'undefined') { - this.automaticKeyboardNavigation = options.automaticKeyboardNavigation; - } - this.tree.refilter(); - this.render(); - if (!this.automaticKeyboardNavigation) { - this.onEventOrInput(''); - } - } - enable() { - if (this._enabled) { - return; - } - const onRawKeyDown = this.enabledDisposables.add(new event_2.DomEmitter(this.view.getHTMLElement(), 'keydown')); - const onKeyDown = event_1.Event.chain(onRawKeyDown.event) - .filter(e => !(0, listWidget_1.isInputElement)(e.target) || e.target === this.filterOnTypeDomNode) - .filter(e => e.key !== 'Dead' && !/^Media/.test(e.key)) - .map(e => new keyboardEvent_1.StandardKeyboardEvent(e)) - .filter(this.keyboardNavigationEventFilter || (() => true)) - .filter(() => this.automaticKeyboardNavigation || this.triggered) - .filter(e => (this.keyboardNavigationDelegate.mightProducePrintableCharacter(e) && !(e.keyCode === 18 /* DownArrow */ || e.keyCode === 16 /* UpArrow */ || e.keyCode === 15 /* LeftArrow */ || e.keyCode === 17 /* RightArrow */)) || ((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(e => { e.stopPropagation(); e.preventDefault(); }) - .event; - const onClearClick = this.enabledDisposables.add(new event_2.DomEmitter(this.clearDomNode, 'click')); - event_1.Event.chain(event_1.Event.any(onKeyDown, onClearClick.event)) - .event(this.onEventOrInput, this, this.enabledDisposables); - this.filter.pattern = ''; - this.tree.refilter(); - this.render(); - this._enabled = true; - this.triggered = false; - } - disable() { - if (!this._enabled) { - return; - } - this.domNode.remove(); - this.enabledDisposables.clear(); - this.tree.refilter(); - this.render(); - this._enabled = false; - this.triggered = false; - } - onEventOrInput(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); - } - } - onInput(pattern) { - const 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, node => !filters_1.FuzzyScore.isDefault(node.filterData)); - } - const focus = this.tree.getFocus(); - if (focus.length > 0) { - const element = focus[0]; - if (this.tree.getRelativeTop(element) === null) { - this.tree.reveal(element, 0.5); - } - } - this.render(); - if (!pattern) { - this.triggered = false; - } - } - onDragStart() { - const container = this.view.getHTMLElement(); - const { left } = (0, dom_1.getDomNodePagePosition)(container); - const containerWidth = container.clientWidth; - const midContainerWidth = containerWidth / 2; - const width = this.domNode.clientWidth; - const disposables = new lifecycle_1.DisposableStore(); - let positionClassName = this.positionClassName; - const updatePosition = () => { - 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; - } - }; - const onDragOver = (event) => { - event.preventDefault(); // needed so that the drop event fires (https://stackoverflow.com/questions/21339924/drop-event-not-firing-in-chrome) - const x = event.clientX - left; - if (event.dataTransfer) { - event.dataTransfer.dropEffect = 'none'; - } - if (x < midContainerWidth) { - positionClassName = 'nw'; - } - else { - positionClassName = 'ne'; - } - updatePosition(); - }; - const onDragEnd = () => { - this.positionClassName = positionClassName; - this.domNode.className = `monaco-list-type-filter ${this.positionClassName}`; - this.domNode.style.top = ''; - this.domNode.style.left = ''; - (0, lifecycle_1.dispose)(disposables); - }; - updatePosition(); - this.domNode.classList.remove(positionClassName); - this.domNode.classList.add('dragging'); - disposables.add((0, lifecycle_1.toDisposable)(() => this.domNode.classList.remove('dragging'))); - disposables.add((0, dom_1.addDisposableListener)(document, 'dragover', e => onDragOver(e))); - disposables.add((0, dom_1.addDisposableListener)(this.domNode, 'dragend', () => onDragEnd())); - dnd_1.StaticDND.CurrentDragAndDropData = new dnd_1.DragAndDropData('vscode-ui'); - disposables.add((0, lifecycle_1.toDisposable)(() => dnd_1.StaticDND.CurrentDragAndDropData = undefined)); - } - onDidSpliceModel() { - if (!this._enabled || this.pattern.length === 0) { - return; - } - this.tree.refilter(); - this.render(); - } - onDidChangeFilterOnType() { - this.tree.updateOptions({ filterOnType: this.filterOnTypeDomNode.checked }); - this.tree.refilter(); - this.tree.domFocus(); - this.render(); - this.updateFilterOnTypeTitleAndIcon(); - } - updateFilterOnTypeTitleAndIcon() { - if (this.filterOnType) { - this.filterOnTypeDomNode.classList.remove(...treeIcons_1.treeFilterOnTypeOffIcon.classNamesArray); - this.filterOnTypeDomNode.classList.add(...treeIcons_1.treeFilterOnTypeOnIcon.classNamesArray); - this.filterOnTypeDomNode.title = (0, nls_1.localize)(1, null); - } - else { - this.filterOnTypeDomNode.classList.remove(...treeIcons_1.treeFilterOnTypeOnIcon.classNamesArray); - this.filterOnTypeDomNode.classList.add(...treeIcons_1.treeFilterOnTypeOffIcon.classNamesArray); - this.filterOnTypeDomNode.title = (0, nls_1.localize)(2, null); - } - } - render() { - const noMatches = this.filter.totalCount > 0 && this.filter.matchCount === 0; - if (this.pattern && this.tree.options.filterOnType && noMatches) { - this.messageDomNode.textContent = (0, nls_1.localize)(3, null); - this._empty = true; - } - else { - this.messageDomNode.innerText = ''; - this._empty = false; - } - this.domNode.classList.toggle('no-matches', noMatches); - this.domNode.title = (0, 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); - } - shouldAllowFocus(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); - } - dispose() { - if (this._enabled) { - this.domNode.remove(); - this.enabledDisposables.dispose(); - this._enabled = false; - this.triggered = false; - } - this._onDidChangePattern.dispose(); - (0, lifecycle_1.dispose)(this.disposables); - } - } - function asTreeMouseEvent(event) { - let target = tree_1.TreeMouseEventTarget.Unknown; - if ((0, dom_1.hasParentWithClass)(event.browserEvent.target, 'monaco-tl-twistie', 'monaco-tl-row')) { - target = tree_1.TreeMouseEventTarget.Twistie; - } - else if ((0, dom_1.hasParentWithClass)(event.browserEvent.target, 'monaco-tl-contents', 'monaco-tl-row')) { - target = tree_1.TreeMouseEventTarget.Element; - } - return { - browserEvent: event.browserEvent, - element: event.element ? event.element.element : null, - target - }; - } - function dfs(node, fn) { - fn(node); - node.children.forEach(child => dfs(child, fn)); - } - /** - * The trait concept needs to exist at the tree level, because collapsed - * tree nodes will not be known by the list. - */ - class Trait { - constructor(getFirstViewElementWithTrait, identityProvider) { - this.getFirstViewElementWithTrait = getFirstViewElementWithTrait; - this.identityProvider = identityProvider; - this.nodes = []; - this._onDidChange = new event_1.Emitter(); - this.onDidChange = this._onDidChange.event; - } - get nodeSet() { - if (!this._nodeSet) { - this._nodeSet = this.createNodeSet(); - } - return this._nodeSet; - } - set(nodes, browserEvent) { - var _a; - if (!((_a = browserEvent) === null || _a === void 0 ? void 0 : _a.__forceEvent) && (0, arrays_1.equals)(this.nodes, nodes)) { - return; - } - this._set(nodes, false, browserEvent); - } - _set(nodes, silent, browserEvent) { - this.nodes = [...nodes]; - this.elements = undefined; - this._nodeSet = undefined; - if (!silent) { - const that = this; - this._onDidChange.fire({ get elements() { return that.get(); }, browserEvent }); - } - } - get() { - if (!this.elements) { - this.elements = this.nodes.map(node => node.element); - } - return [...this.elements]; - } - getNodes() { - return this.nodes; - } - has(node) { - return this.nodeSet.has(node); - } - onDidModelSplice({ insertedNodes, deletedNodes }) { - if (!this.identityProvider) { - const set = this.createNodeSet(); - const visit = (node) => set.delete(node); - deletedNodes.forEach(node => dfs(node, visit)); - this.set([...set.values()]); - return; - } - const deletedNodesIdSet = new Set(); - const deletedNodesVisitor = (node) => deletedNodesIdSet.add(this.identityProvider.getId(node.element).toString()); - deletedNodes.forEach(node => dfs(node, deletedNodesVisitor)); - const insertedNodesMap = new Map(); - const insertedNodesVisitor = (node) => insertedNodesMap.set(this.identityProvider.getId(node.element).toString(), node); - insertedNodes.forEach(node => dfs(node, insertedNodesVisitor)); - const nodes = []; - for (const node of this.nodes) { - const id = this.identityProvider.getId(node.element).toString(); - const wasDeleted = deletedNodesIdSet.has(id); - if (!wasDeleted) { - nodes.push(node); - } - else { - const insertedNode = insertedNodesMap.get(id); - if (insertedNode) { - nodes.push(insertedNode); - } - } - } - if (this.nodes.length > 0 && nodes.length === 0) { - const node = this.getFirstViewElementWithTrait(); - if (node) { - nodes.push(node); - } - } - this._set(nodes, true); - } - createNodeSet() { - const set = new Set(); - for (const node of this.nodes) { - set.add(node); - } - return set; - } - } - class TreeNodeListMouseController extends listWidget_1.MouseController { - constructor(list, tree) { - super(list); - this.tree = tree; - } - onViewPointer(e) { - if ((0, listWidget_1.isInputElement)(e.browserEvent.target) || (0, listWidget_1.isMonacoEditor)(e.browserEvent.target)) { - return; - } - const node = e.element; - if (!node) { - return super.onViewPointer(e); - } - if (this.isSelectionRangeChangeEvent(e) || this.isSelectionSingleChangeEvent(e)) { - return super.onViewPointer(e); - } - const target = e.browserEvent.target; - const onTwistie = target.classList.contains('monaco-tl-twistie') - || (target.classList.contains('monaco-icon-label') && target.classList.contains('folder-icon') && e.browserEvent.offsetX < 16); - let expandOnlyOnTwistieClick = false; - if (typeof this.tree.expandOnlyOnTwistieClick === 'function') { - expandOnlyOnTwistieClick = this.tree.expandOnlyOnTwistieClick(node.element); - } - else { - expandOnlyOnTwistieClick = !!this.tree.expandOnlyOnTwistieClick; - } - if (expandOnlyOnTwistieClick && !onTwistie && e.browserEvent.detail !== 2) { - return super.onViewPointer(e); - } - if (!this.tree.expandOnDoubleClick && e.browserEvent.detail === 2) { - return super.onViewPointer(e); - } - if (node.collapsible) { - const model = this.tree.model; // internal - const location = model.getNodeLocation(node); - const recursive = e.browserEvent.altKey; - this.tree.setFocus([location]); - model.setCollapsed(location, undefined, recursive); - if (expandOnlyOnTwistieClick && onTwistie) { - return; - } - } - super.onViewPointer(e); - } - onDoubleClick(e) { - const onTwistie = e.browserEvent.target.classList.contains('monaco-tl-twistie'); - if (onTwistie || !this.tree.expandOnDoubleClick) { - return; - } - super.onDoubleClick(e); - } - } - /** - * We use this List subclass to restore selection and focus as nodes - * get rendered in the list, possibly due to a node expand() call. - */ - class TreeNodeList extends listWidget_1.List { - constructor(user, container, virtualDelegate, renderers, focusTrait, selectionTrait, anchorTrait, options) { - super(user, container, virtualDelegate, renderers, options); - this.focusTrait = focusTrait; - this.selectionTrait = selectionTrait; - this.anchorTrait = anchorTrait; - } - createMouseController(options) { - return new TreeNodeListMouseController(this, options.tree); - } - splice(start, deleteCount, elements = []) { - super.splice(start, deleteCount, elements); - if (elements.length === 0) { - return; - } - const additionalFocus = []; - const additionalSelection = []; - let anchor; - elements.forEach((node, index) => { - if (this.focusTrait.has(node)) { - additionalFocus.push(start + index); - } - if (this.selectionTrait.has(node)) { - additionalSelection.push(start + index); - } - if (this.anchorTrait.has(node)) { - anchor = start + index; - } - }); - if (additionalFocus.length > 0) { - super.setFocus((0, arrays_1.distinctES6)([...super.getFocus(), ...additionalFocus])); - } - if (additionalSelection.length > 0) { - super.setSelection((0, arrays_1.distinctES6)([...super.getSelection(), ...additionalSelection])); - } - if (typeof anchor === 'number') { - super.setAnchor(anchor); - } - } - setFocus(indexes, browserEvent, fromAPI = false) { - super.setFocus(indexes, browserEvent); - if (!fromAPI) { - this.focusTrait.set(indexes.map(i => this.element(i)), browserEvent); - } - } - setSelection(indexes, browserEvent, fromAPI = false) { - super.setSelection(indexes, browserEvent); - if (!fromAPI) { - this.selectionTrait.set(indexes.map(i => this.element(i)), browserEvent); - } - } - setAnchor(index, fromAPI = false) { - super.setAnchor(index); - if (!fromAPI) { - if (typeof index === 'undefined') { - this.anchorTrait.set([]); - } - else { - this.anchorTrait.set([this.element(index)]); - } - } - } - } - class AbstractTree { - constructor(user, container, delegate, renderers, _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(); - const treeDelegate = new ComposedTreeDelegate(delegate); - const onDidChangeCollapseStateRelay = new event_1.Relay(); - const onDidChangeActiveNodes = new event_1.Relay(); - const activeNodes = new EventCollection(onDidChangeActiveNodes.event); - this.renderers = renderers.map(r => new TreeRenderer(r, () => this.model, onDidChangeCollapseStateRelay.event, activeNodes, _options)); - for (let r of this.renderers) { - this.disposables.add(r); - } - let filter; - if (_options.keyboardNavigationLabelProvider) { - filter = new TypeFilter(this, _options.keyboardNavigationLabelProvider, _options.filter); - _options = Object.assign(Object.assign({}, _options), { filter: filter }); // TODO need typescript help here - this.disposables.add(filter); - } - this.focus = new Trait(() => this.view.getFocusedElements()[0], _options.identityProvider); - this.selection = new Trait(() => this.view.getSelectedElements()[0], _options.identityProvider); - this.anchor = new Trait(() => this.view.getAnchorElement(), _options.identityProvider); - this.view = new TreeNodeList(user, container, treeDelegate, this.renderers, this.focus, this.selection, this.anchor, Object.assign(Object.assign({}, asListOptions(() => this.model, _options)), { tree: this })); - this.model = this.createModel(user, this.view, _options); - onDidChangeCollapseStateRelay.input = this.model.onDidChangeCollapseState; - const onDidModelSplice = event_1.Event.forEach(this.model.onDidSplice, e => { - this.eventBufferer.bufferEvents(() => { - this.focus.onDidModelSplice(e); - this.selection.onDidModelSplice(e); - }); - }); - // Make sure the `forEach` always runs - onDidModelSplice(() => 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(() => null, 0) - .map(() => { - const set = new Set(); - for (const node of this.focus.getNodes()) { - set.add(node); - } - for (const node of this.selection.getNodes()) { - set.add(node); - } - return [...set.values()]; - }).event; - if (_options.keyboardSupport !== false) { - const onKeyDown = event_1.Event.chain(this.view.onKeyDown) - .filter(e => !(0, listWidget_1.isInputElement)(e.target)) - .map(e => new keyboardEvent_1.StandardKeyboardEvent(e)); - onKeyDown.filter(e => e.keyCode === 15 /* LeftArrow */).on(this.onLeftArrow, this, this.disposables); - onKeyDown.filter(e => e.keyCode === 17 /* RightArrow */).on(this.onRightArrow, this, this.disposables); - onKeyDown.filter(e => e.keyCode === 10 /* Space */).on(this.onSpace, this, this.disposables); - } - if (_options.keyboardNavigationLabelProvider) { - const delegate = _options.keyboardNavigationDelegate || listWidget_1.DefaultKeyboardNavigationDelegate; - this.typeFilterController = new TypeFilterController(this, this.model, this.view, filter, delegate); - this.focusNavigationFilter = node => this.typeFilterController.shouldAllowFocus(node); - this.disposables.add(this.typeFilterController); - } - this.styleElement = (0, dom_1.createStyleSheet)(this.view.getHTMLElement()); - this.getHTMLElement().classList.toggle('always', this._options.renderIndentGuides === RenderIndentGuides.Always); - } - get onDidChangeFocus() { return this.eventBufferer.wrapEvent(this.focus.onDidChange); } - get onDidChangeSelection() { return this.eventBufferer.wrapEvent(this.selection.onDidChange); } - get onMouseDblClick() { return event_1.Event.map(this.view.onMouseDblClick, asTreeMouseEvent); } - get onPointer() { return event_1.Event.map(this.view.onPointer, asTreeMouseEvent); } - get onDidFocus() { return this.view.onDidFocus; } - get onDidChangeCollapseState() { return this.model.onDidChangeCollapseState; } - get expandOnDoubleClick() { return typeof this._options.expandOnDoubleClick === 'undefined' ? true : this._options.expandOnDoubleClick; } - get expandOnlyOnTwistieClick() { return typeof this._options.expandOnlyOnTwistieClick === 'undefined' ? true : this._options.expandOnlyOnTwistieClick; } - get onDidDispose() { return this.view.onDidDispose; } - updateOptions(optionsUpdate = {}) { - this._options = Object.assign(Object.assign({}, this._options), optionsUpdate); - for (const renderer of this.renderers) { - renderer.updateOptions(optionsUpdate); - } - this.view.updateOptions(Object.assign(Object.assign({}, this._options), { enableKeyboardNavigation: this._options.simpleKeyboardNavigation })); - if (this.typeFilterController) { - this.typeFilterController.updateOptions(this._options); - } - this._onDidUpdateOptions.fire(this._options); - this.getHTMLElement().classList.toggle('always', this._options.renderIndentGuides === RenderIndentGuides.Always); - } - get options() { - return this._options; - } - // Widget - getHTMLElement() { - return this.view.getHTMLElement(); - } - get scrollTop() { - return this.view.scrollTop; - } - set scrollTop(scrollTop) { - this.view.scrollTop = scrollTop; - } - domFocus() { - this.view.domFocus(); - } - layout(height, width) { - this.view.layout(height, width); - } - style(styles) { - const suffix = `.${this.view.domId}`; - const 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}; }`); - } - this.styleElement.textContent = content.join('\n'); - this.view.style(styles); - } - collapse(location, recursive = false) { - return this.model.setCollapsed(location, true, recursive); - } - expand(location, recursive = false) { - return this.model.setCollapsed(location, false, recursive); - } - isCollapsible(location) { - return this.model.isCollapsible(location); - } - setCollapsible(location, collapsible) { - return this.model.setCollapsible(location, collapsible); - } - isCollapsed(location) { - return this.model.isCollapsed(location); - } - refilter() { - this._onWillRefilter.fire(undefined); - this.model.refilter(); - } - setSelection(elements, browserEvent) { - const nodes = elements.map(e => this.model.getNode(e)); - this.selection.set(nodes, browserEvent); - const indexes = elements.map(e => this.model.getListIndex(e)).filter(i => i > -1); - this.view.setSelection(indexes, browserEvent, true); - } - getSelection() { - return this.selection.get(); - } - setFocus(elements, browserEvent) { - const nodes = elements.map(e => this.model.getNode(e)); - this.focus.set(nodes, browserEvent); - const indexes = elements.map(e => this.model.getListIndex(e)).filter(i => i > -1); - this.view.setFocus(indexes, browserEvent, true); - } - focusNext(n = 1, loop = false, browserEvent, filter = this.focusNavigationFilter) { - this.view.focusNext(n, loop, browserEvent, filter); - } - getFocus() { - return this.focus.get(); - } - reveal(location, relativeTop) { - this.model.expandTo(location); - const 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. - */ - getRelativeTop(location) { - const index = this.model.getListIndex(location); - if (index === -1) { - return null; - } - return this.view.getRelativeTop(index); - } - // List - onLeftArrow(e) { - e.preventDefault(); - e.stopPropagation(); - const nodes = this.view.getFocusedElements(); - if (nodes.length === 0) { - return; - } - const node = nodes[0]; - const location = this.model.getNodeLocation(node); - const didChange = this.model.setCollapsed(location, true); - if (!didChange) { - const parentLocation = this.model.getParentNodeLocation(location); - if (!parentLocation) { - return; - } - const parentListIndex = this.model.getListIndex(parentLocation); - this.view.reveal(parentListIndex); - this.view.setFocus([parentListIndex]); - } - } - onRightArrow(e) { - e.preventDefault(); - e.stopPropagation(); - const nodes = this.view.getFocusedElements(); - if (nodes.length === 0) { - return; - } - const node = nodes[0]; - const location = this.model.getNodeLocation(node); - const didChange = this.model.setCollapsed(location, false); - if (!didChange) { - if (!node.children.some(child => child.visible)) { - return; - } - const [focusedIndex] = this.view.getFocus(); - const firstChildIndex = focusedIndex + 1; - this.view.reveal(firstChildIndex); - this.view.setFocus([firstChildIndex]); - } - } - onSpace(e) { - e.preventDefault(); - e.stopPropagation(); - const nodes = this.view.getFocusedElements(); - if (nodes.length === 0) { - return; - } - const node = nodes[0]; - const location = this.model.getNodeLocation(node); - const recursive = e.browserEvent.altKey; - this.model.setCollapsed(location, undefined, recursive); - } - dispose() { - (0, lifecycle_1.dispose)(this.disposables); - this.view.dispose(); - } - } - 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[437/*vs/base/browser/ui/tree/dataTree*/], __M([0/*require*/,1/*exports*/,180/*vs/base/browser/ui/tree/abstractTree*/,159/*vs/base/browser/ui/tree/objectTreeModel*/]), function (require, exports, abstractTree_1, objectTreeModel_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DataTree = void 0; - class DataTree extends abstractTree_1.AbstractTree { - constructor(user, container, delegate, renderers, dataSource, options = {}) { - super(user, container, delegate, renderers, options); - this.user = user; - this.dataSource = dataSource; - this.identityProvider = options.identityProvider; - } - createModel(user, view, options) { - return new objectTreeModel_1.ObjectTreeModel(user, view, options); - } - } - 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[238/*vs/base/browser/ui/tree/objectTree*/], __M([0/*require*/,1/*exports*/,54/*vs/base/common/iterator*/,180/*vs/base/browser/ui/tree/abstractTree*/,159/*vs/base/browser/ui/tree/objectTreeModel*/,292/*vs/base/browser/ui/tree/compressedObjectTreeModel*/,90/*vs/base/common/decorators*/]), function (require, exports, iterator_1, abstractTree_1, objectTreeModel_1, compressedObjectTreeModel_1, decorators_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CompressibleObjectTree = exports.ObjectTree = void 0; - class ObjectTree extends abstractTree_1.AbstractTree { - constructor(user, container, delegate, renderers, options = {}) { - super(user, container, delegate, renderers, options); - } - get onDidChangeCollapseState() { return this.model.onDidChangeCollapseState; } - setChildren(element, children = iterator_1.Iterable.empty(), options) { - this.model.setChildren(element, children, options); - } - rerender(element) { - if (element === undefined) { - this.view.rerender(); - return; - } - this.model.rerender(element); - } - hasElement(element) { - return this.model.has(element); - } - createModel(user, view, options) { - return new objectTreeModel_1.ObjectTreeModel(user, view, options); - } - } - exports.ObjectTree = ObjectTree; - class CompressibleRenderer { - constructor(_compressedTreeNodeProvider, renderer) { - this._compressedTreeNodeProvider = _compressedTreeNodeProvider; - this.renderer = renderer; - this.templateId = renderer.templateId; - if (renderer.onDidChangeTwistieState) { - this.onDidChangeTwistieState = renderer.onDidChangeTwistieState; - } - } - get compressedTreeNodeProvider() { - return this._compressedTreeNodeProvider(); - } - renderTemplate(container) { - const data = this.renderer.renderTemplate(container); - return { compressedTreeNode: undefined, data }; - } - renderElement(node, index, templateData, height) { - const 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); - } - } - disposeElement(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); - } - } - } - disposeTemplate(templateData) { - this.renderer.disposeTemplate(templateData.data); - } - renderTwistie(element, twistieElement) { - if (this.renderer.renderTwistie) { - return this.renderer.renderTwistie(element, twistieElement); - } - return false; - } - } - __decorate([ - decorators_1.memoize - ], CompressibleRenderer.prototype, "compressedTreeNodeProvider", null); - function asObjectTreeOptions(compressedTreeNodeProvider, options) { - return options && Object.assign(Object.assign({}, options), { keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && { - getKeyboardNavigationLabel(e) { - let 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); - } - } - } }); - } - class CompressibleObjectTree extends ObjectTree { - constructor(user, container, delegate, renderers, options = {}) { - const compressedTreeNodeProvider = () => this; - const compressibleRenderers = renderers.map(r => new CompressibleRenderer(compressedTreeNodeProvider, r)); - super(user, container, delegate, compressibleRenderers, asObjectTreeOptions(compressedTreeNodeProvider, options)); - } - setChildren(element, children = iterator_1.Iterable.empty(), options) { - this.model.setChildren(element, children, options); - } - createModel(user, view, options) { - return new compressedObjectTreeModel_1.CompressibleObjectTreeModel(user, view, options); - } - updateOptions(optionsUpdate = {}) { - super.updateOptions(optionsUpdate); - if (typeof optionsUpdate.compressionEnabled !== 'undefined') { - this.model.setCompressionEnabled(optionsUpdate.compressionEnabled); - } - } - getCompressedTreeNode(element = null) { - return this.model.getCompressedTreeNode(element); - } - } - 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. - *--------------------------------------------------------------------------------------------*/ - - - - - - - - - -define(__m[438/*vs/base/browser/ui/tree/asyncDataTree*/], __M([0/*require*/,1/*exports*/,180/*vs/base/browser/ui/tree/abstractTree*/,238/*vs/base/browser/ui/tree/objectTree*/,101/*vs/base/browser/ui/tree/tree*/,2/*vs/base/common/lifecycle*/,6/*vs/base/common/event*/,15/*vs/base/common/async*/,54/*vs/base/common/iterator*/,166/*vs/base/browser/ui/list/listView*/,12/*vs/base/common/errors*/,158/*vs/base/browser/ui/tree/indexTreeModel*/,200/*vs/base/browser/ui/tree/treeIcons*/]), function (require, exports, abstractTree_1, objectTree_1, tree_1, lifecycle_1, event_1, async_1, iterator_1, listView_1, errors_1, indexTreeModel_1, treeIcons_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CompressibleAsyncDataTree = exports.AsyncDataTree = void 0; - function createAsyncDataTreeNode(props) { - return Object.assign(Object.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); - } - class AsyncDataTreeNodeWrapper { - constructor(node) { - this.node = node; - } - get element() { return this.node.element.element; } - get children() { return this.node.children.map(node => new AsyncDataTreeNodeWrapper(node)); } - get depth() { return this.node.depth; } - get visibleChildrenCount() { return this.node.visibleChildrenCount; } - get visibleChildIndex() { return this.node.visibleChildIndex; } - get collapsible() { return this.node.collapsible; } - get collapsed() { return this.node.collapsed; } - get visible() { return this.node.visible; } - get filterData() { return this.node.filterData; } - } - class AsyncDataTreeRenderer { - constructor(renderer, nodeMapper, onDidChangeTwistieState) { - this.renderer = renderer; - this.nodeMapper = nodeMapper; - this.onDidChangeTwistieState = onDidChangeTwistieState; - this.renderedNodes = new Map(); - this.templateId = renderer.templateId; - } - renderTemplate(container) { - const templateData = this.renderer.renderTemplate(container); - return { templateData }; - } - renderElement(node, index, templateData, height) { - this.renderer.renderElement(this.nodeMapper.map(node), index, templateData.templateData, height); - } - renderTwistie(element, twistieElement) { - if (element.slow) { - twistieElement.classList.add(...treeIcons_1.treeItemLoadingIcon.classNamesArray); - return true; - } - else { - twistieElement.classList.remove(...treeIcons_1.treeItemLoadingIcon.classNamesArray); - return false; - } - } - disposeElement(node, index, templateData, height) { - if (this.renderer.disposeElement) { - this.renderer.disposeElement(this.nodeMapper.map(node), index, templateData.templateData, height); - } - } - disposeTemplate(templateData) { - this.renderer.disposeTemplate(templateData.templateData); - } - dispose() { - this.renderedNodes.clear(); - } - } - function asTreeEvent(e) { - return { - browserEvent: e.browserEvent, - elements: e.elements.map(e => e.element) - }; - } - function asTreeMouseEvent(e) { - return { - browserEvent: e.browserEvent, - element: e.element && e.element.element, - target: e.target - }; - } - class AsyncDataTreeElementsDragAndDropData extends listView_1.ElementsDragAndDropData { - constructor(data) { - super(data.elements.map(node => node.element)); - this.data = data; - } - } - function asAsyncDataTreeDragAndDropData(data) { - if (data instanceof listView_1.ElementsDragAndDropData) { - return new AsyncDataTreeElementsDragAndDropData(data); - } - return data; - } - class AsyncDataTreeNodeListDragAndDrop { - constructor(dnd) { - this.dnd = dnd; - } - getDragURI(node) { - return this.dnd.getDragURI(node.element); - } - getDragLabel(nodes, originalEvent) { - if (this.dnd.getDragLabel) { - return this.dnd.getDragLabel(nodes.map(node => node.element), originalEvent); - } - return undefined; - } - onDragStart(data, originalEvent) { - if (this.dnd.onDragStart) { - this.dnd.onDragStart(asAsyncDataTreeDragAndDropData(data), originalEvent); - } - } - onDragOver(data, targetNode, targetIndex, originalEvent, raw = true) { - return this.dnd.onDragOver(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent); - } - drop(data, targetNode, targetIndex, originalEvent) { - this.dnd.drop(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent); - } - onDragEnd(originalEvent) { - if (this.dnd.onDragEnd) { - this.dnd.onDragEnd(originalEvent); - } - } - } - function asObjectTreeOptions(options) { - return options && Object.assign(Object.assign({}, options), { collapseByDefault: true, identityProvider: options.identityProvider && { - getId(el) { - return options.identityProvider.getId(el.element); - } - }, dnd: options.dnd && new AsyncDataTreeNodeListDragAndDrop(options.dnd), multipleSelectionController: options.multipleSelectionController && { - isSelectionSingleChangeEvent(e) { - return options.multipleSelectionController.isSelectionSingleChangeEvent(Object.assign(Object.assign({}, e), { element: e.element })); - }, - isSelectionRangeChangeEvent(e) { - return options.multipleSelectionController.isSelectionRangeChangeEvent(Object.assign(Object.assign({}, e), { element: e.element })); - } - }, accessibilityProvider: options.accessibilityProvider && Object.assign(Object.assign({}, options.accessibilityProvider), { getPosInSet: undefined, getSetSize: undefined, getRole: options.accessibilityProvider.getRole ? (el) => { - return options.accessibilityProvider.getRole(el.element); - } : () => 'treeitem', isChecked: options.accessibilityProvider.isChecked ? (e) => { - var _a; - return !!((_a = options.accessibilityProvider) === null || _a === void 0 ? void 0 : _a.isChecked(e.element)); - } : undefined, getAriaLabel(e) { - return options.accessibilityProvider.getAriaLabel(e.element); - }, - getWidgetAriaLabel() { - return options.accessibilityProvider.getWidgetAriaLabel(); - }, getWidgetRole: options.accessibilityProvider.getWidgetRole ? () => options.accessibilityProvider.getWidgetRole() : () => 'tree', getAriaLevel: options.accessibilityProvider.getAriaLevel && (node => { - return options.accessibilityProvider.getAriaLevel(node.element); - }), getActiveDescendantId: options.accessibilityProvider.getActiveDescendantId && (node => { - return options.accessibilityProvider.getActiveDescendantId(node.element); - }) }), filter: options.filter && { - filter(e, parentVisibility) { - return options.filter.filter(e.element, parentVisibility); - } - }, keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && Object.assign(Object.assign({}, options.keyboardNavigationLabelProvider), { getKeyboardNavigationLabel(e) { - return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e.element); - } }), sorter: undefined, expandOnlyOnTwistieClick: typeof options.expandOnlyOnTwistieClick === 'undefined' ? undefined : (typeof options.expandOnlyOnTwistieClick !== 'function' ? options.expandOnlyOnTwistieClick : (e => options.expandOnlyOnTwistieClick(e.element))), additionalScrollHeight: options.additionalScrollHeight }); - } - function dfs(node, fn) { - fn(node); - node.children.forEach(child => dfs(child, fn)); - } - class AsyncDataTree { - constructor(user, container, delegate, renderers, dataSource, 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(node => 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 = Object.assign(Object.assign({}, this.root), { id: null }); - } - this.nodes.set(null, this.root); - this.tree.onDidChangeCollapseState(this._onDidChangeCollapseState, this, this.disposables); - } - get onDidChangeFocus() { return event_1.Event.map(this.tree.onDidChangeFocus, asTreeEvent); } - get onDidChangeSelection() { return event_1.Event.map(this.tree.onDidChangeSelection, asTreeEvent); } - get onMouseDblClick() { return event_1.Event.map(this.tree.onMouseDblClick, asTreeMouseEvent); } - get onPointer() { return event_1.Event.map(this.tree.onPointer, asTreeMouseEvent); } - get onDidFocus() { return this.tree.onDidFocus; } - get onDidDispose() { return this.tree.onDidDispose; } - createTree(user, container, delegate, renderers, options) { - const objectTreeDelegate = new abstractTree_1.ComposedTreeDelegate(delegate); - const objectTreeRenderers = renderers.map(r => new AsyncDataTreeRenderer(r, this.nodeMapper, this._onDidChangeNodeSlowState.event)); - const objectTreeOptions = asObjectTreeOptions(options) || {}; - return new objectTree_1.ObjectTree(user, container, objectTreeDelegate, objectTreeRenderers, objectTreeOptions); - } - updateOptions(options = {}) { - this.tree.updateOptions(options); - } - // Widget - getHTMLElement() { - return this.tree.getHTMLElement(); - } - get scrollTop() { - return this.tree.scrollTop; - } - set scrollTop(scrollTop) { - this.tree.scrollTop = scrollTop; - } - domFocus() { - this.tree.domFocus(); - } - layout(height, width) { - this.tree.layout(height, width); - } - style(styles) { - this.tree.style(styles); - } - // Model - getInput() { - return this.root.element; - } - setInput(input, viewState) { - return __awaiter(this, void 0, void 0, function* () { - this.refreshPromises.forEach(promise => promise.cancel()); - this.refreshPromises.clear(); - this.root.element = input; - const viewStateContext = viewState && { viewState, focus: [], selection: [] }; - yield this._updateChildren(input, true, false, viewStateContext); - if (viewStateContext) { - this.tree.setFocus(viewStateContext.focus); - this.tree.setSelection(viewStateContext.selection); - } - if (viewState && typeof viewState.scrollTop === 'number') { - this.scrollTop = viewState.scrollTop; - } - }); - } - _updateChildren(element = this.root.element, recursive = true, rerender = false, viewStateContext, options) { - return __awaiter(this, void 0, void 0, function* () { - if (typeof this.root.element === 'undefined') { - throw new tree_1.TreeError(this.user, 'Tree input not set'); - } - if (this.root.refreshPromise) { - yield this.root.refreshPromise; - yield event_1.Event.toPromise(this._onDidRender.event); - } - const node = this.getDataNode(element); - yield this.refreshAndRenderNode(node, recursive, viewStateContext, options); - if (rerender) { - try { - this.tree.rerender(node); - } - catch (_a) { - // missing nodes are fine, this could've resulted from - // parallel refresh calls, removing `node` altogether - } - } - }); - } - // View - rerender(element) { - if (element === undefined || element === this.root.element) { - this.tree.rerender(); - return; - } - const node = this.getDataNode(element); - this.tree.rerender(node); - } - collapse(element, recursive = false) { - const node = this.getDataNode(element); - return this.tree.collapse(node === this.root ? null : node, recursive); - } - expand(element, recursive = false) { - return __awaiter(this, void 0, void 0, function* () { - if (typeof this.root.element === 'undefined') { - throw new tree_1.TreeError(this.user, 'Tree input not set'); - } - if (this.root.refreshPromise) { - yield this.root.refreshPromise; - yield event_1.Event.toPromise(this._onDidRender.event); - } - const node = this.getDataNode(element); - if (this.tree.hasElement(node) && !this.tree.isCollapsible(node)) { - return false; - } - if (node.refreshPromise) { - yield this.root.refreshPromise; - yield event_1.Event.toPromise(this._onDidRender.event); - } - if (node !== this.root && !node.refreshPromise && !this.tree.isCollapsed(node)) { - return false; - } - const result = this.tree.expand(node === this.root ? null : node, recursive); - if (node.refreshPromise) { - yield this.root.refreshPromise; - yield event_1.Event.toPromise(this._onDidRender.event); - } - return result; - }); - } - setSelection(elements, browserEvent) { - const nodes = elements.map(e => this.getDataNode(e)); - this.tree.setSelection(nodes, browserEvent); - } - getSelection() { - const nodes = this.tree.getSelection(); - return nodes.map(n => n.element); - } - setFocus(elements, browserEvent) { - const nodes = elements.map(e => this.getDataNode(e)); - this.tree.setFocus(nodes, browserEvent); - } - getFocus() { - const nodes = this.tree.getFocus(); - return nodes.map(n => n.element); - } - reveal(element, relativeTop) { - this.tree.reveal(this.getDataNode(element), relativeTop); - } - // Implementation - getDataNode(element) { - const 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; - } - refreshAndRenderNode(node, recursive, viewStateContext, options) { - return __awaiter(this, void 0, void 0, function* () { - yield this.refreshNode(node, recursive, viewStateContext); - this.render(node, viewStateContext, options); - }); - } - refreshNode(node, recursive, viewStateContext) { - return __awaiter(this, void 0, void 0, function* () { - let result; - this.subTreeRefreshPromises.forEach((refreshPromise, refreshNode) => { - if (!result && intersects(refreshNode, node)) { - result = refreshPromise.then(() => this.refreshNode(node, recursive, viewStateContext)); - } - }); - if (result) { - return result; - } - return this.doRefreshSubTree(node, recursive, viewStateContext); - }); - } - doRefreshSubTree(node, recursive, viewStateContext) { - return __awaiter(this, void 0, void 0, function* () { - let done; - node.refreshPromise = new Promise(c => done = c); - this.subTreeRefreshPromises.set(node, node.refreshPromise); - node.refreshPromise.finally(() => { - node.refreshPromise = undefined; - this.subTreeRefreshPromises.delete(node); - }); - try { - const childrenToRefresh = yield this.doRefreshNode(node, recursive, viewStateContext); - node.stale = false; - yield async_1.Promises.settled(childrenToRefresh.map(child => this.doRefreshSubTree(child, recursive, viewStateContext))); - } - finally { - done(); - } - }); - } - doRefreshNode(node, recursive, viewStateContext) { - return __awaiter(this, void 0, void 0, function* () { - node.hasChildren = !!this.dataSource.hasChildren(node.element); - let childrenPromise; - if (!node.hasChildren) { - childrenPromise = Promise.resolve(iterator_1.Iterable.empty()); - } - else { - const slowTimeout = (0, async_1.timeout)(800); - slowTimeout.then(() => { - node.slow = true; - this._onDidChangeNodeSlowState.fire(node); - }, _ => null); - childrenPromise = this.doGetChildren(node) - .finally(() => slowTimeout.cancel()); - } - try { - const children = yield childrenPromise; - return this.setChildren(node, children, recursive, viewStateContext); - } - catch (err) { - if (node !== this.root && this.tree.hasElement(node)) { - this.tree.collapse(node); - } - if ((0, errors_1.isPromiseCanceledError)(err)) { - return []; - } - throw err; - } - finally { - if (node.slow) { - node.slow = false; - this._onDidChangeNodeSlowState.fire(node); - } - } - }); - } - doGetChildren(node) { - let result = this.refreshPromises.get(node); - if (result) { - return result; - } - result = (0, async_1.createCancelablePromise)(() => __awaiter(this, void 0, void 0, function* () { - const children = yield this.dataSource.getChildren(node.element); - return this.processChildren(children); - })); - this.refreshPromises.set(node, result); - return result.finally(() => { this.refreshPromises.delete(node); }); - } - _onDidChangeCollapseState({ node, deep }) { - if (node.element === null) { - return; - } - if (!node.collapsed && node.element.stale) { - if (deep) { - this.collapse(node.element.element); - } - else { - this.refreshAndRenderNode(node.element, false) - .catch(errors_1.onUnexpectedError); - } - } - } - setChildren(node, childrenElementsIterable, recursive, viewStateContext) { - const childrenElements = [...childrenElementsIterable]; - // perf: if the node was and still is a leaf, avoid all this hassle - if (node.children.length === 0 && childrenElements.length === 0) { - return []; - } - const nodesToForget = new Map(); - const childrenTreeNodesById = new Map(); - for (const child of node.children) { - nodesToForget.set(child.element, child); - if (this.identityProvider) { - const collapsed = this.tree.isCollapsed(child); - childrenTreeNodesById.set(child.id, { node: child, collapsed }); - } - } - const childrenToRefresh = []; - const children = childrenElements.map(element => { - const hasChildren = !!this.dataSource.hasChildren(element); - if (!this.identityProvider) { - const asyncDataTreeNode = createAsyncDataTreeNode({ element, parent: node, hasChildren }); - if (hasChildren && this.collapseByDefault && !this.collapseByDefault(element)) { - asyncDataTreeNode.collapsedByDefault = false; - childrenToRefresh.push(asyncDataTreeNode); - } - return asyncDataTreeNode; - } - const id = this.identityProvider.getId(element).toString(); - const result = childrenTreeNodesById.get(id); - if (result) { - const 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(node => dfs(node, node => 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; - } - const childAsyncDataTreeNode = createAsyncDataTreeNode({ element, parent: node, id, 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 (const node of nodesToForget.values()) { - dfs(node, node => this.nodes.delete(node.element)); - } - for (const child of children) { - this.nodes.set(child.element, child); - } - node.children.splice(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; - } - render(node, viewStateContext, options) { - const children = node.children.map(node => this.asTreeElement(node, viewStateContext)); - const objectTreeOptions = options && Object.assign(Object.assign({}, options), { diffIdentityProvider: options.diffIdentityProvider && { - getId(node) { - return options.diffIdentityProvider.getId(node.element); - } - } }); - this.tree.setChildren(node === this.root ? null : node, children, objectTreeOptions); - if (node !== this.root) { - this.tree.setCollapsible(node, node.hasChildren); - } - this._onDidRender.fire(); - } - asTreeElement(node, viewStateContext) { - if (node.stale) { - return { - element: node, - collapsible: node.hasChildren, - collapsed: true - }; - } - let 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.Iterable.map(node.children, child => this.asTreeElement(child, viewStateContext)) : [], - collapsible: node.hasChildren, - collapsed - }; - } - processChildren(children) { - if (this.sorter) { - children = [...children].sort(this.sorter.compare.bind(this.sorter)); - } - return children; - } - dispose() { - this.disposables.dispose(); - } - } - exports.AsyncDataTree = AsyncDataTree; - class CompressibleAsyncDataTreeNodeWrapper { - constructor(node) { - this.node = node; - } - get element() { - return { - elements: this.node.element.elements.map(e => e.element), - incompressible: this.node.element.incompressible - }; - } - get children() { return this.node.children.map(node => new CompressibleAsyncDataTreeNodeWrapper(node)); } - get depth() { return this.node.depth; } - get visibleChildrenCount() { return this.node.visibleChildrenCount; } - get visibleChildIndex() { return this.node.visibleChildIndex; } - get collapsible() { return this.node.collapsible; } - get collapsed() { return this.node.collapsed; } - get visible() { return this.node.visible; } - get filterData() { return this.node.filterData; } - } - class CompressibleAsyncDataTreeRenderer { - constructor(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; - } - renderTemplate(container) { - const templateData = this.renderer.renderTemplate(container); - return { templateData }; - } - renderElement(node, index, templateData, height) { - this.renderer.renderElement(this.nodeMapper.map(node), index, templateData.templateData, height); - } - renderCompressedElements(node, index, templateData, height) { - this.renderer.renderCompressedElements(this.compressibleNodeMapperProvider().map(node), index, templateData.templateData, height); - } - renderTwistie(element, twistieElement) { - if (element.slow) { - twistieElement.classList.add(...treeIcons_1.treeItemLoadingIcon.classNamesArray); - return true; - } - else { - twistieElement.classList.remove(...treeIcons_1.treeItemLoadingIcon.classNamesArray); - return false; - } - } - disposeElement(node, index, templateData, height) { - if (this.renderer.disposeElement) { - this.renderer.disposeElement(this.nodeMapper.map(node), index, templateData.templateData, height); - } - } - disposeCompressedElements(node, index, templateData, height) { - if (this.renderer.disposeCompressedElements) { - this.renderer.disposeCompressedElements(this.compressibleNodeMapperProvider().map(node), index, templateData.templateData, height); - } - } - disposeTemplate(templateData) { - this.renderer.disposeTemplate(templateData.templateData); - } - dispose() { - this.renderedNodes.clear(); - this.disposables = (0, lifecycle_1.dispose)(this.disposables); - } - } - function asCompressibleObjectTreeOptions(options) { - const objectTreeOptions = options && asObjectTreeOptions(options); - return objectTreeOptions && Object.assign(Object.assign({}, objectTreeOptions), { keyboardNavigationLabelProvider: objectTreeOptions.keyboardNavigationLabelProvider && Object.assign(Object.assign({}, objectTreeOptions.keyboardNavigationLabelProvider), { getCompressedNodeKeyboardNavigationLabel(els) { - return options.keyboardNavigationLabelProvider.getCompressedNodeKeyboardNavigationLabel(els.map(e => e.element)); - } }) }); - } - class CompressibleAsyncDataTree extends AsyncDataTree { - constructor(user, container, virtualDelegate, compressionDelegate, renderers, dataSource, options = {}) { - super(user, container, virtualDelegate, renderers, dataSource, options); - this.compressionDelegate = compressionDelegate; - this.compressibleNodeMapper = new tree_1.WeakMapper(node => new CompressibleAsyncDataTreeNodeWrapper(node)); - this.filter = options.filter; - } - createTree(user, container, delegate, renderers, options) { - const objectTreeDelegate = new abstractTree_1.ComposedTreeDelegate(delegate); - const objectTreeRenderers = renderers.map(r => new CompressibleAsyncDataTreeRenderer(r, this.nodeMapper, () => this.compressibleNodeMapper, this._onDidChangeNodeSlowState.event)); - const objectTreeOptions = asCompressibleObjectTreeOptions(options) || {}; - return new objectTree_1.CompressibleObjectTree(user, container, objectTreeDelegate, objectTreeRenderers, objectTreeOptions); - } - asTreeElement(node, viewStateContext) { - return Object.assign({ incompressible: this.compressionDelegate.isIncompressible(node.element) }, super.asTreeElement(node, viewStateContext)); - } - updateOptions(options = {}) { - this.tree.updateOptions(options); - } - render(node, viewStateContext) { - if (!this.identityProvider) { - return super.render(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. - const getId = (element) => this.identityProvider.getId(element).toString(); - const getUncompressedIds = (nodes) => { - const result = new Set(); - for (const node of nodes) { - const compressedNode = this.tree.getCompressedTreeNode(node === this.root ? null : node); - if (!compressedNode.element) { - continue; - } - for (const node of compressedNode.element.elements) { - result.add(getId(node.element)); - } - } - return result; - }; - const oldSelection = getUncompressedIds(this.tree.getSelection()); - const oldFocus = getUncompressedIds(this.tree.getFocus()); - super.render(node, viewStateContext); - const selection = this.getSelection(); - let didChangeSelection = false; - const focus = this.getFocus(); - let didChangeFocus = false; - const visit = (node) => { - const compressedNode = node.element; - if (compressedNode) { - for (let i = 0; i < compressedNode.elements.length; i++) { - const id = getId(compressedNode.elements[i].element); - const 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 - processChildren(children) { - if (this.filter) { - children = iterator_1.Iterable.filter(children, e => { - const result = this.filter.filter(e, 1 /* Visible */); - const 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.processChildren(children); - } - } - exports.CompressibleAsyncDataTree = CompressibleAsyncDataTree; - function getVisibility(filterResult) { - if (typeof filterResult === 'boolean') { - return filterResult ? 1 /* Visible */ : 0 /* Hidden */; - } - else if ((0, indexTreeModel_1.isFilterResult)(filterResult)) { - return (0, indexTreeModel_1.getVisibleState)(filterResult.visibility); - } - else { - return (0, indexTreeModel_1.getVisibleState)(filterResult); - } - } -}); - -define(__m[439/*vs/nls!vs/base/common/actions*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/common/actions", 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/common/actions*/], __M([0/*require*/,1/*exports*/,439/*vs/nls!vs/base/common/actions*/,2/*vs/base/common/lifecycle*/,6/*vs/base/common/event*/]), function (require, exports, nls, lifecycle_1, event_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.EmptySubmenuAction = exports.SubmenuAction = exports.Separator = exports.ActionRunner = exports.Action = void 0; - class Action extends lifecycle_1.Disposable { - constructor(id, label = '', cssClass = '', enabled = true, actionCallback) { - super(); - this._onDidChange = this._register(new event_1.Emitter()); - this.onDidChange = this._onDidChange.event; - this._enabled = true; - this._checked = false; - this._id = id; - this._label = label; - this._cssClass = cssClass; - this._enabled = enabled; - this._actionCallback = actionCallback; - } - get id() { - return this._id; - } - get label() { - return this._label; - } - set label(value) { - this._setLabel(value); - } - _setLabel(value) { - if (this._label !== value) { - this._label = value; - this._onDidChange.fire({ label: value }); - } - } - get tooltip() { - return this._tooltip || ''; - } - set tooltip(value) { - this._setTooltip(value); - } - _setTooltip(value) { - if (this._tooltip !== value) { - this._tooltip = value; - this._onDidChange.fire({ tooltip: value }); - } - } - get class() { - return this._cssClass; - } - set class(value) { - this._setClass(value); - } - _setClass(value) { - if (this._cssClass !== value) { - this._cssClass = value; - this._onDidChange.fire({ class: value }); - } - } - get enabled() { - return this._enabled; - } - set enabled(value) { - this._setEnabled(value); - } - _setEnabled(value) { - if (this._enabled !== value) { - this._enabled = value; - this._onDidChange.fire({ enabled: value }); - } - } - get checked() { - return this._checked; - } - set checked(value) { - this._setChecked(value); - } - _setChecked(value) { - if (this._checked !== value) { - this._checked = value; - this._onDidChange.fire({ checked: value }); - } - } - run(event, data) { - return __awaiter(this, void 0, void 0, function* () { - if (this._actionCallback) { - yield this._actionCallback(event); - } - }); - } - } - exports.Action = Action; - class ActionRunner extends lifecycle_1.Disposable { - constructor() { - super(...arguments); - this._onBeforeRun = this._register(new event_1.Emitter()); - this.onBeforeRun = this._onBeforeRun.event; - this._onDidRun = this._register(new event_1.Emitter()); - this.onDidRun = this._onDidRun.event; - } - run(action, context) { - return __awaiter(this, void 0, void 0, function* () { - if (!action.enabled) { - return; - } - this._onBeforeRun.fire({ action }); - let error = undefined; - try { - yield this.runAction(action, context); - } - catch (e) { - error = e; - } - this._onDidRun.fire({ action, error }); - }); - } - runAction(action, context) { - return __awaiter(this, void 0, void 0, function* () { - yield action.run(context); - }); - } - } - exports.ActionRunner = ActionRunner; - class Separator extends Action { - constructor(label) { - super(Separator.ID, label, label ? 'separator text' : 'separator'); - this.checked = false; - this.enabled = false; - } - } - exports.Separator = Separator; - Separator.ID = 'vs.actions.separator'; - class SubmenuAction { - constructor(id, label, actions, cssClass) { - this.tooltip = ''; - this.enabled = true; - this.checked = false; - this.id = id; - this.label = label; - this.class = cssClass; - this._actions = actions; - } - get actions() { return this._actions; } - dispose() { - // there is NOTHING to dispose and the SubmenuAction should - // never have anything to dispose as it is a convenience type - // to bridge into the rendering world. - } - run() { - return __awaiter(this, void 0, void 0, function* () { }); - } - } - exports.SubmenuAction = SubmenuAction; - class EmptySubmenuAction extends Action { - constructor() { - super(EmptySubmenuAction.ID, nls.localize(0, null), undefined, false); - } - } - exports.EmptySubmenuAction = EmptySubmenuAction; - EmptySubmenuAction.ID = 'vs.actions.empty'; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/browser/ui/actionbar/actionViewItems*/], __M([0/*require*/,1/*exports*/,17/*vs/base/common/platform*/,427/*vs/nls!vs/base/browser/ui/actionbar/actionViewItems*/,2/*vs/base/common/lifecycle*/,50/*vs/base/common/actions*/,20/*vs/base/common/types*/,60/*vs/base/browser/touch*/,164/*vs/base/browser/dnd*/,39/*vs/base/browser/browser*/,7/*vs/base/browser/dom*/,206/*vs/css!vs/base/browser/ui/actionbar/actionbar*/]), function (require, exports, platform, nls, lifecycle_1, actions_1, types, touch_1, dnd_1, browser_1, dom_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ActionViewItem = exports.BaseActionViewItem = void 0; - class BaseActionViewItem extends lifecycle_1.Disposable { - constructor(context, action, options = {}) { - super(); - this.options = options; - this._context = context || this; - this._action = action; - if (action instanceof actions_1.Action) { - this._register(action.onDidChange(event => { - if (!this.element) { - // we have not been rendered yet, so there - // is no point in updating the UI - return; - } - this.handleActionChangeEvent(event); - })); - } - } - handleActionChangeEvent(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(); - } - } - get actionRunner() { - if (!this._actionRunner) { - this._actionRunner = this._register(new actions_1.ActionRunner()); - } - return this._actionRunner; - } - set actionRunner(actionRunner) { - this._actionRunner = actionRunner; - } - getAction() { - return this._action; - } - isEnabled() { - return this._action.enabled; - } - setActionContext(newContext) { - this._context = newContext; - } - render(container) { - const element = this.element = container; - this._register(touch_1.Gesture.addTarget(container)); - const 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((0, dom_1.addDisposableListener)(container, dom_1.EventType.DRAG_START, e => { var _a; return (_a = e.dataTransfer) === null || _a === void 0 ? void 0 : _a.setData(dnd_1.DataTransfers.TEXT, this._action.label); })); - } - } - this._register((0, dom_1.addDisposableListener)(element, touch_1.EventType.Tap, e => this.onClick(e, true))); // Preserve focus on tap #125470 - this._register((0, dom_1.addDisposableListener)(element, dom_1.EventType.MOUSE_DOWN, e => { - if (!enableDragging) { - dom_1.EventHelper.stop(e, true); // do not run when dragging is on because that would disable it - } - if (this._action.enabled && e.button === 0) { - element.classList.add('active'); - } - })); - if (platform.isMacintosh) { - // macOS: allow to trigger the button when holding Ctrl+key and pressing the - // main mouse button. This is for scenarios where e.g. some interaction forces - // the Ctrl+key to be pressed and hold but the user still wants to interact - // with the actions (for example quick access in quick navigation mode). - this._register((0, dom_1.addDisposableListener)(element, dom_1.EventType.CONTEXT_MENU, e => { - if (e.button === 0 && e.ctrlKey === true) { - this.onClick(e); - } - })); - } - this._register((0, dom_1.addDisposableListener)(element, dom_1.EventType.CLICK, e => { - dom_1.EventHelper.stop(e, true); - // menus do not use the click event - if (!(this.options && this.options.isMenu)) { - platform.setImmediate(() => this.onClick(e)); - } - })); - this._register((0, dom_1.addDisposableListener)(element, dom_1.EventType.DBLCLICK, e => { - dom_1.EventHelper.stop(e, true); - })); - [dom_1.EventType.MOUSE_UP, dom_1.EventType.MOUSE_OUT].forEach(event => { - this._register((0, dom_1.addDisposableListener)(element, event, e => { - dom_1.EventHelper.stop(e); - element.classList.remove('active'); - })); - }); - } - onClick(event, preserveFocus = false) { - var _a; - dom_1.EventHelper.stop(event, true); - const context = types.isUndefinedOrNull(this._context) ? ((_a = this.options) === null || _a === void 0 ? void 0 : _a.useEventAsContext) ? event : { preserveFocus } : this._context; - this.actionRunner.run(this._action, context); - } - // Only set the tabIndex on the element once it is about to get focused - // That way this element wont be a tab stop when it is not needed #106441 - focus() { - if (this.element) { - this.element.tabIndex = 0; - this.element.focus(); - this.element.classList.add('focused'); - } - } - blur() { - if (this.element) { - this.element.blur(); - this.element.tabIndex = -1; - this.element.classList.remove('focused'); - } - } - setFocusable(focusable) { - if (this.element) { - this.element.tabIndex = focusable ? 0 : -1; - } - } - get trapsArrowNavigation() { - return false; - } - updateEnabled() { - // implement in subclass - } - updateLabel() { - // implement in subclass - } - updateTooltip() { - // implement in subclass - } - updateClass() { - // implement in subclass - } - updateChecked() { - // implement in subclass - } - dispose() { - if (this.element) { - this.element.remove(); - this.element = undefined; - } - super.dispose(); - } - } - exports.BaseActionViewItem = BaseActionViewItem; - class ActionViewItem extends BaseActionViewItem { - constructor(context, action, options = {}) { - super(context, action, options); - this.options = options; - this.options.icon = options.icon !== undefined ? options.icon : false; - this.options.label = options.label !== undefined ? options.label : true; - this.cssClass = ''; - } - render(container) { - super.render(container); - if (this.element) { - this.label = (0, dom_1.append)(this.element, (0, dom_1.$)('a.action-label')); - } - if (this.label) { - if (this._action.id === actions_1.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) { - (0, dom_1.append)(this.element, (0, dom_1.$)('span.keybinding')).textContent = this.options.keybinding; - } - this.updateClass(); - this.updateLabel(); - this.updateTooltip(); - this.updateEnabled(); - this.updateChecked(); - } - // Only set the tabIndex on the element once it is about to get focused - // That way this element wont be a tab stop when it is not needed #106441 - focus() { - if (this.label) { - this.label.tabIndex = 0; - this.label.focus(); - } - } - blur() { - if (this.label) { - this.label.tabIndex = -1; - } - } - setFocusable(focusable) { - if (this.label) { - this.label.tabIndex = focusable ? 0 : -1; - } - } - updateLabel() { - if (this.options.label && this.label) { - this.label.textContent = this.getAction().label; - } - } - updateTooltip() { - let 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; - } - } - updateClass() { - if (this.cssClass && this.label) { - this.label.classList.remove(...this.cssClass.split(' ')); - } - if (this.options.icon) { - this.cssClass = this.getAction().class; - if (this.label) { - this.label.classList.add('codicon'); - if (this.cssClass) { - this.label.classList.add(...this.cssClass.split(' ')); - } - } - this.updateEnabled(); - } - else { - if (this.label) { - this.label.classList.remove('codicon'); - } - } - } - updateEnabled() { - if (this.getAction().enabled) { - if (this.label) { - this.label.removeAttribute('aria-disabled'); - this.label.classList.remove('disabled'); - } - if (this.element) { - this.element.classList.remove('disabled'); - } - } - else { - if (this.label) { - this.label.setAttribute('aria-disabled', 'true'); - this.label.classList.add('disabled'); - } - if (this.element) { - this.element.classList.add('disabled'); - } - } - } - updateChecked() { - if (this.label) { - if (this.getAction().checked) { - this.label.classList.add('checked'); - } - else { - this.label.classList.remove('checked'); - } - } - } - } - exports.ActionViewItem = ActionViewItem; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/base/browser/ui/actionbar/actionbar*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,50/*vs/base/common/actions*/,7/*vs/base/browser/dom*/,20/*vs/base/common/types*/,51/*vs/base/browser/keyboardEvent*/,6/*vs/base/common/event*/,117/*vs/base/browser/ui/actionbar/actionViewItems*/,206/*vs/css!vs/base/browser/ui/actionbar/actionbar*/]), function (require, exports, lifecycle_1, actions_1, DOM, types, keyboardEvent_1, event_1, actionViewItems_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ActionBar = void 0; - class ActionBar extends lifecycle_1.Disposable { - constructor(container, options = {}) { - var _a, _b, _c, _d, _e, _f; - super(); - // Trigger Key Tracking - this.triggerKeyDown = false; - this.focusable = true; - this._onDidBlur = this._register(new event_1.Emitter()); - this.onDidBlur = this._onDidBlur.event; - this._onDidCancel = this._register(new event_1.Emitter({ onFirstListenerAdd: () => this.cancelHasListener = true })); - this.onDidCancel = this._onDidCancel.event; - this.cancelHasListener = false; - this._onDidRun = this._register(new event_1.Emitter()); - this.onDidRun = this._onDidRun.event; - this._onBeforeRun = this._register(new event_1.Emitter()); - this.onBeforeRun = this._onBeforeRun.event; - this.options = options; - this._context = (_a = options.context) !== null && _a !== void 0 ? _a : null; - this._orientation = (_b = this.options.orientation) !== null && _b !== void 0 ? _b : 0 /* HORIZONTAL */; - this._triggerKeys = { - keyDown: (_d = (_c = this.options.triggerKeys) === null || _c === void 0 ? void 0 : _c.keyDown) !== null && _d !== void 0 ? _d : false, - keys: (_f = (_e = this.options.triggerKeys) === null || _e === void 0 ? void 0 : _e.keys) !== null && _f !== void 0 ? _f : [3 /* Enter */, 10 /* Space */] - }; - 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(e => this._onDidRun.fire(e))); - this._register(this._actionRunner.onBeforeRun(e => this._onBeforeRun.fire(e))); - this._actionIds = []; - this.viewItems = []; - this.focusedItem = undefined; - this.domNode = document.createElement('div'); - this.domNode.className = 'monaco-action-bar'; - if (options.animated !== false) { - this.domNode.classList.add('animated'); - } - let previousKeys; - let nextKeys; - switch (this._orientation) { - case 0 /* HORIZONTAL */: - previousKeys = [15 /* LeftArrow */]; - nextKeys = [17 /* RightArrow */]; - break; - case 1 /* VERTICAL */: - previousKeys = [16 /* UpArrow */]; - nextKeys = [18 /* DownArrow */]; - this.domNode.className += ' vertical'; - break; - } - this._register(DOM.addDisposableListener(this.domNode, DOM.EventType.KEY_DOWN, e => { - const event = new keyboardEvent_1.StandardKeyboardEvent(e); - let eventHandled = true; - const focusedItem = typeof this.focusedItem === 'number' ? this.viewItems[this.focusedItem] : undefined; - if (previousKeys && (event.equals(previousKeys[0]) || event.equals(previousKeys[1]))) { - eventHandled = this.focusPrevious(); - } - else if (nextKeys && (event.equals(nextKeys[0]) || event.equals(nextKeys[1]))) { - eventHandled = this.focusNext(); - } - else if (event.equals(9 /* Escape */) && this.cancelHasListener) { - this._onDidCancel.fire(); - } - else if (event.equals(14 /* Home */)) { - eventHandled = this.focusFirst(); - } - else if (event.equals(13 /* End */)) { - eventHandled = this.focusLast(); - } - else if (event.equals(2 /* Tab */) && focusedItem instanceof actionViewItems_1.BaseActionViewItem && focusedItem.trapsArrowNavigation) { - eventHandled = this.focusNext(); - } - else if (this.isTriggerKeyEvent(event)) { - // Staying out of the else branch even if not triggered - if (this._triggerKeys.keyDown) { - this.doTrigger(event); - } - else { - this.triggerKeyDown = true; - } - } - else { - eventHandled = false; - } - if (eventHandled) { - event.preventDefault(); - event.stopPropagation(); - } - })); - this._register(DOM.addDisposableListener(this.domNode, DOM.EventType.KEY_UP, e => { - const event = new keyboardEvent_1.StandardKeyboardEvent(e); - // Run action on Enter/Space - if (this.isTriggerKeyEvent(event)) { - if (!this._triggerKeys.keyDown && this.triggerKeyDown) { - this.triggerKeyDown = false; - 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(() => { - if (DOM.getActiveElement() === this.domNode || !DOM.isAncestor(DOM.getActiveElement(), this.domNode)) { - this._onDidBlur.fire(); - this.focusedItem = undefined; - this.triggerKeyDown = false; - } - })); - this._register(this.focusTracker.onDidFocus(() => 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); - } - isTriggerKeyEvent(event) { - let ret = false; - this._triggerKeys.keys.forEach(keyCode => { - ret = ret || event.equals(keyCode); - }); - return ret; - } - updateFocusedItem() { - for (let i = 0; i < this.actionsList.children.length; i++) { - const elem = this.actionsList.children[i]; - if (DOM.isAncestor(DOM.getActiveElement(), elem)) { - this.focusedItem = i; - break; - } - } - } - get context() { - return this._context; - } - set context(context) { - this._context = context; - this.viewItems.forEach(i => i.setActionContext(context)); - } - get actionRunner() { - return this._actionRunner; - } - set actionRunner(actionRunner) { - if (actionRunner) { - this._actionRunner = actionRunner; - this.viewItems.forEach(item => item.actionRunner = actionRunner); - } - } - getContainer() { - return this.domNode; - } - push(arg, options = {}) { - const actions = Array.isArray(arg) ? arg : [arg]; - let index = types.isNumber(options.index) ? options.index : null; - actions.forEach((action) => { - const actionViewItemElement = document.createElement('li'); - actionViewItemElement.className = 'action-item'; - actionViewItemElement.setAttribute('role', 'presentation'); - // Prevent native context menu on actions - if (!this.options.allowContextMenu) { - this._register(DOM.addDisposableListener(actionViewItemElement, DOM.EventType.CONTEXT_MENU, (e) => { - DOM.EventHelper.stop(e, true); - })); - } - let item; - if (this.options.actionViewItemProvider) { - item = this.options.actionViewItemProvider(action); - } - if (!item) { - item = new actionViewItems_1.ActionViewItem(this.context, action, options); - } - item.actionRunner = this._actionRunner; - item.setActionContext(this.context); - item.render(actionViewItemElement); - if (this.focusable && item instanceof actionViewItems_1.BaseActionViewItem && this.viewItems.length === 0) { - // We need to allow for the first enabled item to be focused on using tab navigation #106441 - item.setFocusable(true); - } - if (index === null || index < 0 || index >= this.actionsList.children.length) { - this.actionsList.appendChild(actionViewItemElement); - this.viewItems.push(item); - this._actionIds.push(action.id); - } - else { - this.actionsList.insertBefore(actionViewItemElement, this.actionsList.children[index]); - this.viewItems.splice(index, 0, item); - this._actionIds.splice(index, 0, action.id); - index++; - } - }); - if (typeof this.focusedItem === 'number') { - // After a clear actions might be re-added to simply toggle some actions. We should preserve focus #97128 - this.focus(this.focusedItem); - } - } - clear() { - (0, lifecycle_1.dispose)(this.viewItems); - this.viewItems = []; - this._actionIds = []; - DOM.clearNode(this.actionsList); - } - length() { - return this.viewItems.length; - } - focus(arg) { - let selectFirst = false; - let 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') { - const firstEnabled = this.viewItems.findIndex(item => item.isEnabled()); - // Focus the first enabled item - this.focusedItem = firstEnabled === -1 ? undefined : firstEnabled; - this.updateFocus(); - } - else { - if (index !== undefined) { - this.focusedItem = index; - } - this.updateFocus(); - } - } - focusFirst() { - this.focusedItem = this.length() > 1 ? 1 : 0; - return this.focusPrevious(); - } - focusLast() { - this.focusedItem = this.length() < 2 ? 0 : this.length() - 2; - return this.focusNext(); - } - focusNext() { - if (typeof this.focusedItem === 'undefined') { - this.focusedItem = this.viewItems.length - 1; - } - else if (this.viewItems.length <= 1) { - return false; - } - const startIndex = this.focusedItem; - let item; - do { - if (this.options.preventLoopNavigation && this.focusedItem + 1 >= this.viewItems.length) { - this.focusedItem = startIndex; - return false; - } - this.focusedItem = (this.focusedItem + 1) % this.viewItems.length; - item = this.viewItems[this.focusedItem]; - } while (this.focusedItem !== startIndex && this.options.focusOnlyEnabledItems && !item.isEnabled()); - this.updateFocus(); - return true; - } - focusPrevious() { - if (typeof this.focusedItem === 'undefined') { - this.focusedItem = 0; - } - else if (this.viewItems.length <= 1) { - return false; - } - const startIndex = this.focusedItem; - let item; - do { - this.focusedItem = this.focusedItem - 1; - if (this.focusedItem < 0) { - if (this.options.preventLoopNavigation) { - this.focusedItem = startIndex; - return false; - } - this.focusedItem = this.viewItems.length - 1; - } - item = this.viewItems[this.focusedItem]; - } while (this.focusedItem !== startIndex && this.options.focusOnlyEnabledItems && !item.isEnabled()); - this.updateFocus(true); - return true; - } - updateFocus(fromRight, preventScroll) { - if (typeof this.focusedItem === 'undefined') { - this.actionsList.focus({ preventScroll }); - } - for (let i = 0; i < this.viewItems.length; i++) { - const item = this.viewItems[i]; - const actionViewItem = item; - if (i === this.focusedItem) { - let focusItem = true; - if (!types.isFunction(actionViewItem.focus)) { - focusItem = false; - } - if (this.options.focusOnlyEnabledItems && types.isFunction(item.isEnabled) && !item.isEnabled()) { - focusItem = false; - } - if (focusItem) { - actionViewItem.focus(fromRight); - } - else { - this.actionsList.focus({ preventScroll }); - } - } - else { - if (types.isFunction(actionViewItem.blur)) { - actionViewItem.blur(); - } - } - } - } - doTrigger(event) { - if (typeof this.focusedItem === 'undefined') { - return; //nothing to focus - } - // trigger action - const actionViewItem = this.viewItems[this.focusedItem]; - if (actionViewItem instanceof actionViewItems_1.BaseActionViewItem) { - const context = (actionViewItem._context === null || actionViewItem._context === undefined) ? event : actionViewItem._context; - this.run(actionViewItem._action, context); - } - } - run(action, context) { - return __awaiter(this, void 0, void 0, function* () { - yield this._actionRunner.run(action, context); - }); - } - dispose() { - (0, lifecycle_1.dispose)(this.viewItems); - this.viewItems = []; - this._actionIds = []; - this.getContainer().remove(); - super.dispose(); - } - } - exports.ActionBar = ActionBar; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[440/*vs/base/browser/ui/dropdown/dropdown*/], __M([0/*require*/,1/*exports*/,60/*vs/base/browser/touch*/,50/*vs/base/common/actions*/,7/*vs/base/browser/dom*/,51/*vs/base/browser/keyboardEvent*/,6/*vs/base/common/event*/,209/*vs/css!vs/base/browser/ui/dropdown/dropdown*/]), function (require, exports, touch_1, actions_1, dom_1, keyboardEvent_1, event_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DropdownMenu = exports.BaseDropdown = void 0; - class BaseDropdown extends actions_1.ActionRunner { - constructor(container, options) { - super(); - this._onDidChangeVisibility = new event_1.Emitter(); - this.onDidChangeVisibility = this._onDidChangeVisibility.event; - this._element = (0, dom_1.append)(container, (0, dom_1.$)('.monaco-dropdown')); - this._label = (0, dom_1.append)(this._element, (0, dom_1.$)('.dropdown-label')); - let labelRenderer = options.labelRenderer; - if (!labelRenderer) { - labelRenderer = (container) => { - container.textContent = options.label || ''; - return null; - }; - } - for (const event of [dom_1.EventType.CLICK, dom_1.EventType.MOUSE_DOWN, touch_1.EventType.Tap]) { - this._register((0, dom_1.addDisposableListener)(this.element, event, e => dom_1.EventHelper.stop(e, true))); // prevent default click behaviour to trigger - } - for (const event of [dom_1.EventType.MOUSE_DOWN, touch_1.EventType.Tap]) { - this._register((0, dom_1.addDisposableListener)(this._label, event, e => { - if (e instanceof MouseEvent && e.detail > 1) { - return; // prevent multiple clicks to open multiple context menus (https://github.com/microsoft/vscode/issues/41363) - } - if (this.visible) { - this.hide(); - } - else { - this.show(); - } - })); - } - this._register((0, dom_1.addDisposableListener)(this._label, dom_1.EventType.KEY_UP, e => { - const event = new keyboardEvent_1.StandardKeyboardEvent(e); - if (event.equals(3 /* Enter */) || event.equals(10 /* Space */)) { - dom_1.EventHelper.stop(e, true); // https://github.com/microsoft/vscode/issues/57997 - if (this.visible) { - this.hide(); - } - else { - this.show(); - } - } - })); - const cleanupFn = labelRenderer(this._label); - if (cleanupFn) { - this._register(cleanupFn); - } - this._register(touch_1.Gesture.addTarget(this._label)); - } - get element() { - return this._element; - } - show() { - if (!this.visible) { - this.visible = true; - this._onDidChangeVisibility.fire(true); - } - } - hide() { - if (this.visible) { - this.visible = false; - this._onDidChangeVisibility.fire(false); - } - } - dispose() { - super.dispose(); - this.hide(); - if (this.boxContainer) { - this.boxContainer.remove(); - this.boxContainer = undefined; - } - if (this.contents) { - this.contents.remove(); - this.contents = undefined; - } - if (this._label) { - this._label.remove(); - this._label = undefined; - } - } - } - exports.BaseDropdown = BaseDropdown; - class DropdownMenu extends BaseDropdown { - constructor(container, options) { - super(container, options); - this._actions = []; - this._contextMenuProvider = options.contextMenuProvider; - this.actions = options.actions || []; - this.actionProvider = options.actionProvider; - this.menuClassName = options.menuClassName || ''; - this.menuAsChild = !!options.menuAsChild; - } - set menuOptions(options) { - this._menuOptions = options; - } - get menuOptions() { - return this._menuOptions; - } - get actions() { - if (this.actionProvider) { - return this.actionProvider.getActions(); - } - return this._actions; - } - set actions(actions) { - this._actions = actions; - } - show() { - super.show(); - this.element.classList.add('active'); - this._contextMenuProvider.showContextMenu({ - getAnchor: () => this.element, - getActions: () => this.actions, - getActionsContext: () => this.menuOptions ? this.menuOptions.context : null, - getActionViewItem: action => this.menuOptions && this.menuOptions.actionViewItemProvider ? this.menuOptions.actionViewItemProvider(action) : undefined, - getKeyBinding: action => this.menuOptions && this.menuOptions.getKeyBinding ? this.menuOptions.getKeyBinding(action) : undefined, - getMenuClassName: () => this.menuClassName, - onHide: () => this.onHide(), - actionRunner: this.menuOptions ? this.menuOptions.actionRunner : undefined, - anchorAlignment: this.menuOptions ? this.menuOptions.anchorAlignment : 0 /* LEFT */, - domForShadowRoot: this.menuAsChild ? this.element : undefined - }); - } - hide() { - super.hide(); - } - onHide() { - this.hide(); - this.element.classList.remove('active'); - } - } - exports.DropdownMenu = DropdownMenu; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[441/*vs/base/browser/ui/dropdown/dropdownActionViewItem*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,6/*vs/base/common/event*/,117/*vs/base/browser/ui/actionbar/actionViewItems*/,440/*vs/base/browser/ui/dropdown/dropdown*/,209/*vs/css!vs/base/browser/ui/dropdown/dropdown*/]), function (require, exports, dom_1, event_1, actionViewItems_1, dropdown_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DropdownMenuActionViewItem = void 0; - class DropdownMenuActionViewItem extends actionViewItems_1.BaseActionViewItem { - constructor(action, menuActionsOrProvider, contextMenuProvider, options = Object.create(null)) { - super(null, action, options); - this.actionItem = null; - this._onDidChangeVisibility = this._register(new event_1.Emitter()); - this.menuActionsOrProvider = menuActionsOrProvider; - this.contextMenuProvider = contextMenuProvider; - this.options = options; - if (this.options.actionRunner) { - this.actionRunner = this.options.actionRunner; - } - } - render(container) { - this.actionItem = container; - const labelRenderer = (el) => { - this.element = (0, dom_1.append)(el, (0, dom_1.$)('a.action-label')); - let classNames = []; - if (typeof this.options.classNames === 'string') { - classNames = this.options.classNames.split(/\s+/g).filter(s => !!s); - } - else if (this.options.classNames) { - classNames = this.options.classNames; - } - // todo@aeschli: remove codicon, should come through `this.options.classNames` - if (!classNames.find(c => c === 'icon')) { - classNames.push('codicon'); - } - this.element.classList.add(...classNames); - this.element.setAttribute('role', 'button'); - this.element.setAttribute('aria-haspopup', 'true'); - this.element.setAttribute('aria-expanded', 'false'); - this.element.title = this._action.label || ''; - return null; - }; - const isActionsArray = Array.isArray(this.menuActionsOrProvider); - const options = { - contextMenuProvider: this.contextMenuProvider, - labelRenderer: labelRenderer, - menuAsChild: this.options.menuAsChild, - actions: isActionsArray ? this.menuActionsOrProvider : undefined, - actionProvider: isActionsArray ? undefined : this.menuActionsOrProvider - }; - this.dropdownMenu = this._register(new dropdown_1.DropdownMenu(container, options)); - this._register(this.dropdownMenu.onDidChangeVisibility(visible => { - var _a; - (_a = this.element) === null || _a === void 0 ? void 0 : _a.setAttribute('aria-expanded', `${visible}`); - this._onDidChangeVisibility.fire(visible); - })); - this.dropdownMenu.menuOptions = { - actionViewItemProvider: this.options.actionViewItemProvider, - actionRunner: this.actionRunner, - getKeyBinding: this.options.keybindingProvider, - context: this._context - }; - if (this.options.anchorAlignmentProvider) { - const that = this; - this.dropdownMenu.menuOptions = Object.assign(Object.assign({}, this.dropdownMenu.menuOptions), { get anchorAlignment() { - return that.options.anchorAlignmentProvider(); - } }); - } - this.updateEnabled(); - } - setActionContext(newContext) { - super.setActionContext(newContext); - if (this.dropdownMenu) { - if (this.dropdownMenu.menuOptions) { - this.dropdownMenu.menuOptions.context = newContext; - } - else { - this.dropdownMenu.menuOptions = { context: newContext }; - } - } - } - updateEnabled() { - var _a, _b; - const disabled = !this.getAction().enabled; - (_a = this.actionItem) === null || _a === void 0 ? void 0 : _a.classList.toggle('disabled', disabled); - (_b = this.element) === null || _b === void 0 ? void 0 : _b.classList.toggle('disabled', disabled); - } - } - exports.DropdownMenuActionViewItem = DropdownMenuActionViewItem; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/inputbox/inputBox*/], __M([0/*require*/,1/*exports*/,433/*vs/nls!vs/base/browser/ui/inputbox/inputBox*/,7/*vs/base/browser/dom*/,160/*vs/base/browser/formattedTextRenderer*/,44/*vs/base/browser/ui/aria/aria*/,84/*vs/base/browser/ui/actionbar/actionbar*/,6/*vs/base/common/event*/,52/*vs/base/browser/ui/widget*/,29/*vs/base/common/color*/,42/*vs/base/common/objects*/,287/*vs/base/common/history*/,61/*vs/base/browser/ui/scrollbar/scrollableElement*/,91/*vs/base/browser/event*/,312/*vs/css!vs/base/browser/ui/inputbox/inputBox*/]), function (require, exports, nls, 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 }); - exports.HistoryInputBox = exports.InputBox = void 0; - const $ = dom.$; - const 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') - }; - class InputBox extends widget_1.Widget { - constructor(container, contextViewProvider, options) { - var _a; - super(); - 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); - (0, objects_1.mixin)(this.options, defaultOpts, false); - this.message = null; - this.placeholder = this.options.placeholder || ''; - this.tooltip = (_a = this.options.tooltip) !== null && _a !== void 0 ? _a : (this.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')); - let tagName = this.options.flexibleHeight ? 'textarea' : 'input'; - let wrapper = dom.append(this.element, $('.ibwrapper')); - 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, () => this.element.classList.add('synthetic-focus')); - this.onblur(this.input, () => this.element.classList.remove('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.innerText = '\u00a0'; - 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(e => this.input.scrollTop = e.scrollTop)); - const onSelectionChange = this._register(new event_2.DomEmitter(document, 'selectionchange')); - const onAnchoredSelectionChange = event_1.Event.filter(onSelectionChange.event, () => { - const selection = document.getSelection(); - return (selection === null || selection === void 0 ? void 0 : selection.anchorNode) === wrapper; - }); - // from DOM to ScrollableElement - this._register(onAnchoredSelectionChange(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.options.showPlaceholderOnFocus) { - this.setPlaceHolder(this.placeholder); - } - if (this.tooltip) { - this.setTooltip(this.tooltip); - } - this.oninput(this.input, () => this.onValueChange()); - this.onblur(this.input, () => this.onBlur()); - this.onfocus(this.input, () => this.onFocus()); - this.ignoreGesture(this.input); - setTimeout(() => 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(); - } - onBlur() { - this._hideMessage(); - if (this.options.showPlaceholderOnFocus) { - this.input.setAttribute('placeholder', ''); - } - } - onFocus() { - this._showMessage(); - if (this.options.showPlaceholderOnFocus) { - this.input.setAttribute('placeholder', this.placeholder || ''); - } - } - setPlaceHolder(placeHolder) { - this.placeholder = placeHolder; - this.input.setAttribute('placeholder', placeHolder); - } - setTooltip(tooltip) { - this.tooltip = tooltip; - this.input.title = tooltip; - } - setAriaLabel(label) { - this.ariaLabel = label; - if (label) { - this.input.setAttribute('aria-label', this.ariaLabel); - } - else { - this.input.removeAttribute('aria-label'); - } - } - getAriaLabel() { - return this.ariaLabel; - } - get inputElement() { - return this.input; - } - get value() { - return this.input.value; - } - set value(newValue) { - if (this.input.value !== newValue) { - this.input.value = newValue; - this.onValueChange(); - } - } - get height() { - return typeof this.cachedHeight === 'number' ? this.cachedHeight : dom.getTotalHeight(this.element); - } - focus() { - this.input.focus(); - } - blur() { - this.input.blur(); - } - hasFocus() { - return document.activeElement === this.input; - } - select(range = null) { - this.input.select(); - if (range) { - this.input.setSelectionRange(range.start, range.end); - if (range.end === this.input.value.length) { - this.input.scrollLeft = this.input.scrollWidth; - } - } - } - isSelectionAtEnd() { - return this.input.selectionEnd === this.input.value.length && this.input.selectionStart === this.input.selectionEnd; - } - enable() { - this.input.removeAttribute('disabled'); - } - disable() { - this.blur(); - this.input.disabled = true; - this._hideMessage(); - } - get width() { - return dom.getTotalWidth(this.input); - } - set width(width) { - if (this.options.flexibleHeight && this.options.flexibleWidth) { - // textarea with horizontal scrolling - let horizontalPadding = 0; - if (this.mirror) { - const paddingLeft = parseFloat(this.mirror.style.paddingLeft || '') || 0; - const 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'; - } - } - set paddingRight(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'; - } - } - updateScrollDimensions() { - if (typeof this.cachedContentHeight !== 'number' || typeof this.cachedHeight !== 'number' || !this.scrollableElement) { - return; - } - const scrollHeight = this.cachedContentHeight; - const height = this.cachedHeight; - const scrollTop = this.input.scrollTop; - this.scrollableElement.setScrollDimensions({ scrollHeight, height }); - this.scrollableElement.setScrollPosition({ scrollTop }); - } - showMessage(message, force) { - this.message = message; - this.element.classList.remove('idle'); - this.element.classList.remove('info'); - this.element.classList.remove('warning'); - this.element.classList.remove('error'); - this.element.classList.add(this.classForType(message.type)); - const styles = this.stylesForType(this.message.type); - this.element.style.border = styles.border ? `1px solid ${styles.border}` : ''; - if (this.hasFocus() || force) { - this._showMessage(); - } - } - hideMessage() { - this.message = null; - this.element.classList.remove('info'); - this.element.classList.remove('warning'); - this.element.classList.remove('error'); - this.element.classList.add('idle'); - this._hideMessage(); - this.applyStyles(); - } - validate() { - let 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 === null || errorMsg === void 0 ? void 0 : errorMsg.type; - } - stylesForType(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 }; - } - } - classForType(type) { - switch (type) { - case 1 /* INFO */: return 'info'; - case 2 /* WARNING */: return 'warning'; - default: return 'error'; - } - } - _showMessage() { - if (!this.contextViewProvider || !this.message) { - return; - } - let div; - let layout = () => div.style.width = dom.getTotalWidth(this.element) + 'px'; - this.contextViewProvider.showContextView({ - getAnchor: () => this.element, - anchorAlignment: 1 /* RIGHT */, - render: (container) => { - if (!this.message) { - return null; - } - div = dom.append(container, $('.monaco-inputbox-container')); - layout(); - const renderOptions = { - inline: true, - className: 'monaco-inputbox-message' - }; - const spanElement = (this.message.formatContent - ? (0, formattedTextRenderer_1.renderFormattedText)(this.message.content, renderOptions) - : (0, formattedTextRenderer_1.renderText)(this.message.content, renderOptions)); - spanElement.classList.add(this.classForType(this.message.type)); - const 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: () => { - this.state = 'closed'; - }, - layout: layout - }); - // ARIA Support - let alertText; - if (this.message.type === 3 /* ERROR */) { - alertText = nls.localize(0, null, this.message.content); - } - else if (this.message.type === 2 /* WARNING */) { - alertText = nls.localize(1, null, this.message.content); - } - else { - alertText = nls.localize(2, null, this.message.content); - } - aria.alert(alertText); - this.state = 'open'; - } - _hideMessage() { - if (!this.contextViewProvider) { - return; - } - if (this.state === 'open') { - this.contextViewProvider.hideContextView(); - } - this.state = 'idle'; - } - onValueChange() { - this._onDidChange.fire(this.value); - this.validate(); - this.updateMirror(); - this.input.classList.toggle('empty', !this.value); - if (this.state === 'open' && this.contextViewProvider) { - this.contextViewProvider.layout(); - } - } - updateMirror() { - if (!this.mirror) { - return; - } - const value = this.value; - const lastCharCode = value.charCodeAt(value.length - 1); - const suffix = lastCharCode === 10 ? ' ' : ''; - const mirrorTextContent = (value + suffix) - .replace(/\u000c/g, ''); // Don't measure with the form feed character, which messes up sizing - if (mirrorTextContent) { - this.mirror.textContent = value + suffix; - } - else { - this.mirror.innerText = '\u00a0'; - } - this.layout(); - } - style(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(); - } - applyStyles() { - const background = this.inputBackground ? this.inputBackground.toString() : ''; - const foreground = this.inputForeground ? this.inputForeground.toString() : ''; - const border = this.inputBorder ? this.inputBorder.toString() : ''; - this.element.style.backgroundColor = background; - this.element.style.color = foreground; - this.input.style.backgroundColor = 'inherit'; - this.input.style.color = foreground; - this.element.style.borderWidth = border ? '1px' : ''; - this.element.style.borderStyle = border ? 'solid' : ''; - this.element.style.borderColor = border; - } - layout() { - if (!this.mirror) { - return; - } - const 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); - } - } - insertAtCursor(text) { - const inputElement = this.inputElement; - const start = inputElement.selectionStart; - const end = inputElement.selectionEnd; - const 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(); - } - } - dispose() { - this._hideMessage(); - this.message = null; - if (this.actionbar) { - this.actionbar.dispose(); - } - super.dispose(); - } - } - exports.InputBox = InputBox; - class HistoryInputBox extends InputBox { - constructor(container, contextViewProvider, options) { - super(container, contextViewProvider, options); - this.history = new history_1.HistoryNavigator(options.history, 100); - } - addToHistory() { - if (this.value && this.value !== this.getCurrentValue()) { - this.history.add(this.value); - } - } - showNextValue() { - if (!this.history.has(this.value)) { - this.addToHistory(); - } - let next = this.getNextValue(); - if (next) { - next = next === this.value ? this.getNextValue() : next; - } - if (next) { - this.value = next; - aria.status(this.value); - } - } - showPreviousValue() { - if (!this.history.has(this.value)) { - this.addToHistory(); - } - let previous = this.getPreviousValue(); - if (previous) { - previous = previous === this.value ? this.getPreviousValue() : previous; - } - if (previous) { - this.value = previous; - aria.status(this.value); - } - } - getCurrentValue() { - let currentValue = this.history.current(); - if (!currentValue) { - currentValue = this.history.last(); - this.history.next(); - } - return currentValue; - } - getPreviousValue() { - return this.history.previous() || this.history.first(); - } - getNextValue() { - return this.history.next() || this.history.last(); - } - } - 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[442/*vs/base/browser/ui/findinput/findInput*/], __M([0/*require*/,1/*exports*/,428/*vs/nls!vs/base/browser/ui/findinput/findInput*/,7/*vs/base/browser/dom*/,181/*vs/base/browser/ui/inputbox/inputBox*/,52/*vs/base/browser/ui/widget*/,6/*vs/base/common/event*/,237/*vs/base/browser/ui/findinput/findInputCheckboxes*/,210/*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 }); - exports.FindInput = void 0; - const NLS_DEFAULT_LABEL = nls.localize(0, null); - class FindInput extends widget_1.Widget { - constructor(parent, contextViewProvider, _showOptionButtons, options) { - super(); - this._showOptionButtons = _showOptionButtons; - this.fixFocusOnOptionClickEnabled = true; - this.imeSessionInProgress = false; - 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.inputActiveOptionForeground = options.inputActiveOptionForeground; - 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; - const appendCaseSensitiveLabel = options.appendCaseSensitiveLabel || ''; - const appendWholeWordsLabel = options.appendWholeWordsLabel || ''; - const appendRegexLabel = options.appendRegexLabel || ''; - const history = options.history || []; - const flexibleHeight = !!options.flexibleHeight; - const flexibleWidth = !!options.flexibleWidth; - const flexibleMaxHeight = options.flexibleMaxHeight; - this.domNode = document.createElement('div'); - this.domNode.classList.add('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, - flexibleHeight, - flexibleWidth, - flexibleMaxHeight - })); - this.regex = this._register(new findInputCheckboxes_1.RegexCheckbox({ - appendTitle: appendRegexLabel, - isChecked: false, - inputActiveOptionBorder: this.inputActiveOptionBorder, - inputActiveOptionForeground: this.inputActiveOptionForeground, - inputActiveOptionBackground: this.inputActiveOptionBackground - })); - this._register(this.regex.onChange(viaKeyboard => { - this._onDidOptionChange.fire(viaKeyboard); - if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) { - this.inputBox.focus(); - } - this.validate(); - })); - this._register(this.regex.onKeyDown(e => { - this._onRegexKeyDown.fire(e); - })); - this.wholeWords = this._register(new findInputCheckboxes_1.WholeWordsCheckbox({ - appendTitle: appendWholeWordsLabel, - isChecked: false, - inputActiveOptionBorder: this.inputActiveOptionBorder, - inputActiveOptionForeground: this.inputActiveOptionForeground, - inputActiveOptionBackground: this.inputActiveOptionBackground - })); - this._register(this.wholeWords.onChange(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, - inputActiveOptionForeground: this.inputActiveOptionForeground, - inputActiveOptionBackground: this.inputActiveOptionBackground - })); - this._register(this.caseSensitive.onChange(viaKeyboard => { - this._onDidOptionChange.fire(viaKeyboard); - if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) { - this.inputBox.focus(); - } - this.validate(); - })); - this._register(this.caseSensitive.onKeyDown(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 - let indexes = [this.caseSensitive.domNode, this.wholeWords.domNode, this.regex.domNode]; - this.onkeydown(this.domNode, (event) => { - if (event.equals(15 /* LeftArrow */) || event.equals(17 /* RightArrow */) || event.equals(9 /* Escape */)) { - let index = indexes.indexOf(document.activeElement); - if (index >= 0) { - let 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(); - this.inputBox.focus(); - } - else if (newIndex >= 0) { - indexes[newIndex].focus(); - } - dom.EventHelper.stop(event, true); - } - } - }); - let 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._register(dom.addDisposableListener(this.inputBox.inputElement, 'compositionstart', (e) => { - this.imeSessionInProgress = true; - })); - this._register(dom.addDisposableListener(this.inputBox.inputElement, 'compositionend', (e) => { - this.imeSessionInProgress = false; - this._onInput.fire(); - })); - this.onkeydown(this.inputBox.inputElement, (e) => this._onKeyDown.fire(e)); - this.onkeyup(this.inputBox.inputElement, (e) => this._onKeyUp.fire(e)); - this.oninput(this.inputBox.inputElement, (e) => this._onInput.fire()); - this.onmousedown(this.inputBox.inputElement, (e) => this._onMouseDown.fire(e)); - } - enable() { - this.domNode.classList.remove('disabled'); - this.inputBox.enable(); - this.regex.enable(); - this.wholeWords.enable(); - this.caseSensitive.enable(); - } - disable() { - this.domNode.classList.add('disabled'); - this.inputBox.disable(); - this.regex.disable(); - this.wholeWords.disable(); - this.caseSensitive.disable(); - } - setFocusInputOnOptionClick(value) { - this.fixFocusOnOptionClickEnabled = value; - } - setEnabled(enabled) { - if (enabled) { - this.enable(); - } - else { - this.disable(); - } - } - getValue() { - return this.inputBox.value; - } - setValue(value) { - if (this.inputBox.value !== value) { - this.inputBox.value = value; - } - } - style(styles) { - this.inputActiveOptionBorder = styles.inputActiveOptionBorder; - this.inputActiveOptionForeground = styles.inputActiveOptionForeground; - 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(); - } - applyStyles() { - if (this.domNode) { - const checkBoxStyles = { - inputActiveOptionBorder: this.inputActiveOptionBorder, - inputActiveOptionForeground: this.inputActiveOptionForeground, - inputActiveOptionBackground: this.inputActiveOptionBackground, - }; - this.regex.style(checkBoxStyles); - this.wholeWords.style(checkBoxStyles); - this.caseSensitive.style(checkBoxStyles); - const 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); - } - } - select() { - this.inputBox.select(); - } - focus() { - this.inputBox.focus(); - } - getCaseSensitive() { - return this.caseSensitive.checked; - } - setCaseSensitive(value) { - this.caseSensitive.checked = value; - } - getWholeWords() { - return this.wholeWords.checked; - } - setWholeWords(value) { - this.wholeWords.checked = value; - } - getRegex() { - return this.regex.checked; - } - setRegex(value) { - this.regex.checked = value; - this.validate(); - } - focusOnCaseSensitive() { - this.caseSensitive.focus(); - } - highlightFindOptions() { - this.domNode.classList.remove('highlight-' + (this._lastHighlightFindOptions)); - this._lastHighlightFindOptions = 1 - this._lastHighlightFindOptions; - this.domNode.classList.add('highlight-' + (this._lastHighlightFindOptions)); - } - validate() { - this.inputBox.validate(); - } - clearMessage() { - this.inputBox.hideMessage(); - } - } - 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[443/*vs/base/browser/ui/findinput/replaceInput*/], __M([0/*require*/,1/*exports*/,430/*vs/nls!vs/base/browser/ui/findinput/replaceInput*/,7/*vs/base/browser/dom*/,181/*vs/base/browser/ui/inputbox/inputBox*/,52/*vs/base/browser/ui/widget*/,6/*vs/base/common/event*/,165/*vs/base/browser/ui/checkbox/checkbox*/,27/*vs/base/common/codicons*/,210/*vs/css!vs/base/browser/ui/findinput/findInput*/]), function (require, exports, nls, dom, inputBox_1, widget_1, event_1, checkbox_1, codicons_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ReplaceInput = exports.PreserveCaseCheckbox = void 0; - const NLS_DEFAULT_LABEL = nls.localize(0, null); - const NLS_PRESERVE_CASE_LABEL = nls.localize(1, null); - class PreserveCaseCheckbox extends checkbox_1.Checkbox { - constructor(opts) { - super({ - // TODO: does this need its own icon? - icon: codicons_1.Codicon.preserveCase, - title: NLS_PRESERVE_CASE_LABEL + opts.appendTitle, - isChecked: opts.isChecked, - inputActiveOptionBorder: opts.inputActiveOptionBorder, - inputActiveOptionForeground: opts.inputActiveOptionForeground, - inputActiveOptionBackground: opts.inputActiveOptionBackground - }); - } - } - exports.PreserveCaseCheckbox = PreserveCaseCheckbox; - class ReplaceInput extends widget_1.Widget { - constructor(parent, contextViewProvider, _showOptionButtons, options) { - super(); - 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.inputActiveOptionForeground = options.inputActiveOptionForeground; - 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; - const appendPreserveCaseLabel = options.appendPreserveCaseLabel || ''; - const history = options.history || []; - const flexibleHeight = !!options.flexibleHeight; - const flexibleWidth = !!options.flexibleWidth; - const flexibleMaxHeight = options.flexibleMaxHeight; - this.domNode = document.createElement('div'); - this.domNode.classList.add('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, - flexibleHeight, - flexibleWidth, - flexibleMaxHeight - })); - this.preserveCase = this._register(new PreserveCaseCheckbox({ - appendTitle: appendPreserveCaseLabel, - isChecked: false, - inputActiveOptionBorder: this.inputActiveOptionBorder, - inputActiveOptionForeground: this.inputActiveOptionForeground, - inputActiveOptionBackground: this.inputActiveOptionBackground, - })); - this._register(this.preserveCase.onChange(viaKeyboard => { - this._onDidOptionChange.fire(viaKeyboard); - if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) { - this.inputBox.focus(); - } - this.validate(); - })); - this._register(this.preserveCase.onKeyDown(e => { - this._onPreserveCaseKeyDown.fire(e); - })); - if (this._showOptionButtons) { - this.cachedOptionsWidth = this.preserveCase.width(); - } - else { - this.cachedOptionsWidth = 0; - } - // Arrow-Key support to navigate between options - let indexes = [this.preserveCase.domNode]; - this.onkeydown(this.domNode, (event) => { - if (event.equals(15 /* LeftArrow */) || event.equals(17 /* RightArrow */) || event.equals(9 /* Escape */)) { - let index = indexes.indexOf(document.activeElement); - if (index >= 0) { - let 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(); - this.inputBox.focus(); - } - else if (newIndex >= 0) { - indexes[newIndex].focus(); - } - dom.EventHelper.stop(event, true); - } - } - }); - let 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, (e) => this._onKeyDown.fire(e)); - this.onkeyup(this.inputBox.inputElement, (e) => this._onKeyUp.fire(e)); - this.oninput(this.inputBox.inputElement, (e) => this._onInput.fire()); - this.onmousedown(this.inputBox.inputElement, (e) => this._onMouseDown.fire(e)); - } - enable() { - this.domNode.classList.remove('disabled'); - this.inputBox.enable(); - this.preserveCase.enable(); - } - disable() { - this.domNode.classList.add('disabled'); - this.inputBox.disable(); - this.preserveCase.disable(); - } - setEnabled(enabled) { - if (enabled) { - this.enable(); - } - else { - this.disable(); - } - } - style(styles) { - this.inputActiveOptionBorder = styles.inputActiveOptionBorder; - this.inputActiveOptionForeground = styles.inputActiveOptionForeground; - 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(); - } - applyStyles() { - if (this.domNode) { - const checkBoxStyles = { - inputActiveOptionBorder: this.inputActiveOptionBorder, - inputActiveOptionForeground: this.inputActiveOptionForeground, - inputActiveOptionBackground: this.inputActiveOptionBackground, - }; - this.preserveCase.style(checkBoxStyles); - const 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); - } - } - select() { - this.inputBox.select(); - } - focus() { - this.inputBox.focus(); - } - getPreserveCase() { - return this.preserveCase.checked; - } - setPreserveCase(value) { - this.preserveCase.checked = value; - } - focusOnPreserve() { - this.preserveCase.focus(); - } - validate() { - if (this.inputBox) { - this.inputBox.validate(); - } - } - set width(newWidth) { - this.inputBox.paddingRight = this.cachedOptionsWidth; - this.inputBox.width = newWidth; - this.domNode.style.width = newWidth + 'px'; - } - dispose() { - super.dispose(); - } - } - exports.ReplaceInput = ReplaceInput; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[444/*vs/base/browser/ui/menu/menu*/], __M([0/*require*/,1/*exports*/,435/*vs/nls!vs/base/browser/ui/menu/menu*/,8/*vs/base/common/strings*/,50/*vs/base/common/actions*/,84/*vs/base/browser/ui/actionbar/actionbar*/,7/*vs/base/browser/dom*/,51/*vs/base/browser/keyboardEvent*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,61/*vs/base/browser/ui/scrollbar/scrollableElement*/,207/*vs/base/browser/ui/contextview/contextview*/,17/*vs/base/common/platform*/,27/*vs/base/common/codicons*/,117/*vs/base/browser/ui/actionbar/actionViewItems*/,130/*vs/base/browser/ui/codicons/codiconStyles*/,39/*vs/base/browser/browser*/,55/*vs/base/browser/mouseEvent*/,104/*vs/base/common/iconLabels*/]), function (require, exports, nls, strings, actions_1, actionbar_1, dom_1, keyboardEvent_1, async_1, lifecycle_1, scrollableElement_1, contextview_1, platform_1, codicons_1, actionViewItems_1, codiconStyles_1, browser_1, mouseEvent_1, iconLabels_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.cleanMnemonic = exports.Menu = exports.Direction = exports.MENU_ESCAPED_MNEMONIC_REGEX = exports.MENU_MNEMONIC_REGEX = void 0; - exports.MENU_MNEMONIC_REGEX = /\(&([^\s&])\)|(^|[^&])&([^\s&])/; - exports.MENU_ESCAPED_MNEMONIC_REGEX = /(&)?(&)([^\s&])/g; - const menuSelectionIcon = (0, codicons_1.registerCodicon)('menu-selection', codicons_1.Codicon.check); - const menuSubmenuIcon = (0, codicons_1.registerCodicon)('menu-submenu', codicons_1.Codicon.chevronRight); - var Direction; - (function (Direction) { - Direction[Direction["Right"] = 0] = "Right"; - Direction[Direction["Left"] = 1] = "Left"; - })(Direction = exports.Direction || (exports.Direction = {})); - class Menu extends actionbar_1.ActionBar { - constructor(container, actions, options = {}) { - container.classList.add('monaco-menu-container'); - container.setAttribute('role', 'presentation'); - const menuElement = document.createElement('div'); - menuElement.classList.add('monaco-menu'); - menuElement.setAttribute('role', 'presentation'); - super(menuElement, { - orientation: 1 /* VERTICAL */, - actionViewItemProvider: action => this.doGetActionViewItem(action, options, parentData), - context: options.context, - actionRunner: options.actionRunner, - ariaLabel: options.ariaLabel, - focusOnlyEnabledItems: true, - triggerKeys: { keys: [3 /* Enter */, ...(platform_1.isMacintosh || platform_1.isLinux ? [10 /* Space */] : [])], keyDown: true } - }); - this.menuElement = menuElement; - this.actionsList.setAttribute('role', 'menu'); - this.actionsList.tabIndex = 0; - this.menuDisposables = this._register(new lifecycle_1.DisposableStore()); - this.initializeStyleSheet(container); - (0, dom_1.addDisposableListener)(menuElement, dom_1.EventType.KEY_DOWN, (e) => { - const event = new keyboardEvent_1.StandardKeyboardEvent(e); - // Stop tab navigation of menus - if (event.equals(2 /* Tab */)) { - e.preventDefault(); - } - }); - if (options.enableMnemonics) { - this.menuDisposables.add((0, dom_1.addDisposableListener)(menuElement, dom_1.EventType.KEY_DOWN, (e) => { - const key = e.key.toLocaleLowerCase(); - if (this.mnemonics.has(key)) { - dom_1.EventHelper.stop(e, true); - const actions = this.mnemonics.get(key); - if (actions.length === 1) { - if (actions[0] instanceof SubmenuMenuActionViewItem && actions[0].container) { - this.focusItemByElement(actions[0].container); - } - actions[0].onClick(e); - } - if (actions.length > 1) { - const action = actions.shift(); - if (action && action.container) { - this.focusItemByElement(action.container); - actions.push(action); - } - this.mnemonics.set(key, actions); - } - } - })); - } - if (platform_1.isLinux) { - this._register((0, dom_1.addDisposableListener)(menuElement, dom_1.EventType.KEY_DOWN, e => { - const 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((0, dom_1.addDisposableListener)(this.domNode, dom_1.EventType.MOUSE_OUT, e => { - let relatedTarget = e.relatedTarget; - if (!(0, dom_1.isAncestor)(relatedTarget, this.domNode)) { - this.focusedItem = undefined; - this.updateFocus(); - e.stopPropagation(); - } - })); - this._register((0, dom_1.addDisposableListener)(this.actionsList, dom_1.EventType.MOUSE_OVER, e => { - let target = e.target; - if (!target || !(0, dom_1.isAncestor)(target, this.actionsList) || target === this.actionsList) { - return; - } - while (target.parentElement !== this.actionsList && target.parentElement !== null) { - target = target.parentElement; - } - if (target.classList.contains('action-item')) { - const lastFocusedItem = this.focusedItem; - this.setFocusedItem(target); - if (lastFocusedItem !== this.focusedItem) { - this.updateFocus(); - } - } - })); - let 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 - })); - const scrollElement = this.scrollableElement.getDomNode(); - scrollElement.style.position = ''; - this._register((0, dom_1.addDisposableListener)(scrollElement, dom_1.EventType.MOUSE_UP, 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 - 35)}px`; - actions = actions.filter(a => { - var _a; - if ((_a = options.submenuIds) === null || _a === void 0 ? void 0 : _a.has(a.id)) { - console.warn(`Found submenu cycle: ${a.id}`); - return false; - } - return true; - }); - this.push(actions, { icon: true, label: true, isMenu: true }); - container.appendChild(this.scrollableElement.getDomNode()); - this.scrollableElement.scanDomNode(); - this.viewItems.filter(item => !(item instanceof MenuSeparatorActionViewItem)).forEach((item, index, array) => { - item.updatePositionInSet(index + 1, array.length); - }); - } - initializeStyleSheet(container) { - if ((0, dom_1.isInShadowDOM)(container)) { - this.styleSheet = (0, dom_1.createStyleSheet)(container); - this.styleSheet.textContent = MENU_WIDGET_CSS; - } - else { - if (!Menu.globalStyleSheet) { - Menu.globalStyleSheet = (0, dom_1.createStyleSheet)(); - Menu.globalStyleSheet.textContent = MENU_WIDGET_CSS; - } - this.styleSheet = Menu.globalStyleSheet; - } - } - style(style) { - const container = this.getContainer(); - const fgColor = style.foregroundColor ? `${style.foregroundColor}` : ''; - const bgColor = style.backgroundColor ? `${style.backgroundColor}` : ''; - const border = style.borderColor ? `1px solid ${style.borderColor}` : ''; - const 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(item => { - if (item instanceof BaseMenuActionViewItem || item instanceof MenuSeparatorActionViewItem) { - item.style(style); - } - }); - } - } - getContainer() { - return this.scrollableElement.getDomNode(); - } - get onScroll() { - return this.scrollableElement.onScroll; - } - focusItemByElement(element) { - const lastFocusedItem = this.focusedItem; - this.setFocusedItem(element); - if (lastFocusedItem !== this.focusedItem) { - this.updateFocus(); - } - } - setFocusedItem(element) { - for (let i = 0; i < this.actionsList.children.length; i++) { - let elem = this.actionsList.children[i]; - if (element === elem) { - this.focusedItem = i; - break; - } - } - } - updateFocus(fromRight) { - super.updateFocus(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) - }); - } - } - doGetActionViewItem(action, options, parentData) { - if (action instanceof actions_1.Separator) { - return new MenuSeparatorActionViewItem(options.context, action, { icon: true }); - } - else if (action instanceof actions_1.SubmenuAction) { - const menuActionViewItem = new SubmenuMenuActionViewItem(action, action.actions, parentData, Object.assign(Object.assign({}, options), { submenuIds: new Set([...(options.submenuIds || []), action.id]) })); - if (options.enableMnemonics) { - const mnemonic = menuActionViewItem.getMnemonic(); - if (mnemonic && menuActionViewItem.isEnabled()) { - let actionViewItems = []; - if (this.mnemonics.has(mnemonic)) { - actionViewItems = this.mnemonics.get(mnemonic); - } - actionViewItems.push(menuActionViewItem); - this.mnemonics.set(mnemonic, actionViewItems); - } - } - return menuActionViewItem; - } - else { - const menuItemOptions = { enableMnemonics: options.enableMnemonics, useEventAsContext: options.useEventAsContext }; - if (options.getKeyBinding) { - const keybinding = options.getKeyBinding(action); - if (keybinding) { - const keybindingLabel = keybinding.getLabel(); - if (keybindingLabel) { - menuItemOptions.keybinding = keybindingLabel; - } - } - } - const menuActionViewItem = new BaseMenuActionViewItem(options.context, action, menuItemOptions); - if (options.enableMnemonics) { - const mnemonic = menuActionViewItem.getMnemonic(); - if (mnemonic && menuActionViewItem.isEnabled()) { - let actionViewItems = []; - if (this.mnemonics.has(mnemonic)) { - actionViewItems = this.mnemonics.get(mnemonic); - } - actionViewItems.push(menuActionViewItem); - this.mnemonics.set(mnemonic, actionViewItems); - } - } - return menuActionViewItem; - } - } - } - exports.Menu = Menu; - class BaseMenuActionViewItem extends actionViewItems_1.BaseActionViewItem { - constructor(ctx, action, options = {}) { - options.isMenu = true; - super(action, action, options); - 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) { - let label = this.getAction().label; - if (label) { - let 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(() => { - if (!this.element) { - return; - } - this._register((0, dom_1.addDisposableListener)(this.element, dom_1.EventType.MOUSE_UP, e => { - // removed default prevention as it conflicts - // with BaseActionViewItem #101537 - // add back if issues arise and link new issue - dom_1.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 (browser_1.isFirefox) { - const mouseEvent = new mouseEvent_1.StandardMouseEvent(e); - // Allowing right click to trigger the event causes the issue described below, - // but since the solution below does not work in FF, we must disable right click - if (mouseEvent.rightButton) { - return; - } - this.onClick(e); - } - // In all other cases, set timout to allow context menu cancellation to trigger - // otherwise the action will destroy the menu and a second context menu - // will still trigger for right click. - else { - setTimeout(() => { - this.onClick(e); - }, 0); - } - })); - this._register((0, dom_1.addDisposableListener)(this.element, dom_1.EventType.CONTEXT_MENU, e => { - dom_1.EventHelper.stop(e, true); - })); - }, 100); - this._register(this.runOnceToEnableMouseUp); - } - render(container) { - super.render(container); - if (!this.element) { - return; - } - this.container = container; - this.item = (0, dom_1.append)(this.element, (0, dom_1.$)('a.action-menu-item')); - if (this._action.id === actions_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 = (0, dom_1.append)(this.item, (0, dom_1.$)('span.menu-item-check' + menuSelectionIcon.cssSelector)); - this.check.setAttribute('role', 'none'); - this.label = (0, dom_1.append)(this.item, (0, dom_1.$)('span.action-label')); - if (this.options.label && this.options.keybinding) { - (0, dom_1.append)(this.item, (0, 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(); - } - blur() { - super.blur(); - this.applyStyle(); - } - focus() { - super.focus(); - if (this.item) { - this.item.focus(); - } - this.applyStyle(); - } - updatePositionInSet(pos, setSize) { - if (this.item) { - this.item.setAttribute('aria-posinset', `${pos}`); - this.item.setAttribute('aria-setsize', `${setSize}`); - } - } - updateLabel() { - if (!this.label) { - return; - } - if (this.options.label) { - (0, dom_1.clearNode)(this.label); - let label = (0, iconLabels_1.stripIcons)(this.getAction().label); - if (label) { - const cleanLabel = cleanMnemonic(label); - if (!this.options.enableMnemonics) { - label = cleanLabel; - } - this.label.setAttribute('aria-label', cleanLabel.replace(/&&/g, '&')); - const 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; - let 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); - } - const replaceDoubleEscapes = (str) => str.replace(/&&/g, '&'); - if (escMatch) { - this.label.append(strings.ltrim(replaceDoubleEscapes(label.substr(0, escMatch.index)), ' '), (0, dom_1.$)('u', { 'aria-hidden': 'true' }, escMatch[3]), strings.rtrim(replaceDoubleEscapes(label.substr(escMatch.index + escMatch[0].length)), ' ')); - } - else { - this.label.innerText = replaceDoubleEscapes(label).trim(); - } - if (this.item) { - this.item.setAttribute('aria-keyshortcuts', (!!matches[1] ? matches[1] : matches[3]).toLocaleLowerCase()); - } - } - else { - this.label.innerText = label.replace(/&&/g, '&').trim(); - } - } - } - } - updateTooltip() { - let 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; - } - } - updateClass() { - if (this.cssClass && this.item) { - this.item.classList.remove(...this.cssClass.split(' ')); - } - if (this.options.icon && this.label) { - this.cssClass = this.getAction().class || ''; - this.label.classList.add('icon'); - if (this.cssClass) { - this.label.classList.add(...this.cssClass.split(' ')); - } - this.updateEnabled(); - } - else if (this.label) { - this.label.classList.remove('icon'); - } - } - updateEnabled() { - if (this.getAction().enabled) { - if (this.element) { - this.element.classList.remove('disabled'); - this.element.removeAttribute('aria-disabled'); - } - if (this.item) { - this.item.classList.remove('disabled'); - this.item.removeAttribute('aria-disabled'); - this.item.tabIndex = 0; - } - } - else { - if (this.element) { - this.element.classList.add('disabled'); - this.element.setAttribute('aria-disabled', 'true'); - } - if (this.item) { - this.item.classList.add('disabled'); - this.item.setAttribute('aria-disabled', 'true'); - } - } - } - updateChecked() { - if (!this.item) { - return; - } - if (this.getAction().checked) { - this.item.classList.add('checked'); - this.item.setAttribute('role', 'menuitemcheckbox'); - this.item.setAttribute('aria-checked', 'true'); - } - else { - this.item.classList.remove('checked'); - this.item.setAttribute('role', 'menuitem'); - this.item.setAttribute('aria-checked', 'false'); - } - } - getMnemonic() { - return this.mnemonic; - } - applyStyle() { - if (!this.menuStyle) { - return; - } - const isSelected = this.element && this.element.classList.contains('focused'); - const fgColor = isSelected && this.menuStyle.selectionForegroundColor ? this.menuStyle.selectionForegroundColor : this.menuStyle.foregroundColor; - const bgColor = isSelected && this.menuStyle.selectionBackgroundColor ? this.menuStyle.selectionBackgroundColor : undefined; - const 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; - } - } - style(style) { - this.menuStyle = style; - this.applyStyle(); - } - } - class SubmenuMenuActionViewItem extends BaseMenuActionViewItem { - constructor(action, submenuActions, parentData, submenuOptions) { - super(action, action, submenuOptions); - 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(() => { - if (this.mouseOver) { - this.cleanupExistingSubmenu(false); - this.createSubmenu(false); - } - }, 250); - this.hideScheduler = new async_1.RunOnceScheduler(() => { - if (this.element && (!(0, dom_1.isAncestor)((0, dom_1.getActiveElement)(), this.element) && this.parentData.submenu === this.mysubmenu)) { - this.parentData.parent.focus(false); - this.cleanupExistingSubmenu(true); - } - }, 750); - } - render(container) { - super.render(container); - if (!this.element) { - return; - } - if (this.item) { - this.item.classList.add('monaco-submenu-item'); - this.item.tabIndex = 0; - this.item.setAttribute('aria-haspopup', 'true'); - this.updateAriaExpanded('false'); - this.submenuIndicator = (0, dom_1.append)(this.item, (0, dom_1.$)('span.submenu-indicator' + menuSubmenuIcon.cssSelector)); - this.submenuIndicator.setAttribute('aria-hidden', 'true'); - } - this._register((0, dom_1.addDisposableListener)(this.element, dom_1.EventType.KEY_UP, e => { - let 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((0, dom_1.addDisposableListener)(this.element, dom_1.EventType.KEY_DOWN, e => { - let event = new keyboardEvent_1.StandardKeyboardEvent(e); - if ((0, dom_1.getActiveElement)() === this.item) { - if (event.equals(17 /* RightArrow */) || event.equals(3 /* Enter */)) { - dom_1.EventHelper.stop(e, true); - } - } - })); - this._register((0, dom_1.addDisposableListener)(this.element, dom_1.EventType.MOUSE_OVER, e => { - if (!this.mouseOver) { - this.mouseOver = true; - this.showScheduler.schedule(); - } - })); - this._register((0, dom_1.addDisposableListener)(this.element, dom_1.EventType.MOUSE_LEAVE, e => { - this.mouseOver = false; - })); - this._register((0, dom_1.addDisposableListener)(this.element, dom_1.EventType.FOCUS_OUT, e => { - if (this.element && !(0, dom_1.isAncestor)((0, dom_1.getActiveElement)(), this.element)) { - this.hideScheduler.schedule(); - } - })); - this._register(this.parentData.parent.onScroll(() => { - this.parentData.parent.focus(false); - this.cleanupExistingSubmenu(false); - })); - } - updateEnabled() { - // override on submenu entry - // native menus do not observe enablement on sumbenus - // we mimic that behavior - } - onClick(e) { - // stop clicking from trying to run an action - dom_1.EventHelper.stop(e, true); - this.cleanupExistingSubmenu(false); - this.createSubmenu(true); - } - cleanupExistingSubmenu(force) { - if (this.parentData.submenu && (force || (this.parentData.submenu !== this.mysubmenu))) { - // disposal may throw if the submenu has already been removed - try { - this.parentData.submenu.dispose(); - } - catch (_a) { } - this.parentData.submenu = undefined; - this.updateAriaExpanded('false'); - if (this.submenuContainer) { - this.submenuDisposables.clear(); - this.submenuContainer = undefined; - } - } - } - calculateSubmenuMenuLayout(windowDimensions, submenu, entry, expandDirection) { - const ret = { top: 0, left: 0 }; - // Start with horizontal - ret.left = (0, contextview_1.layout)(windowDimensions.width, submenu.width, { position: expandDirection === Direction.Right ? 0 /* Before */ : 1 /* After */, offset: entry.left, size: entry.width }); - // We don't have enough room to layout the menu fully, so we are overlapping the menu - if (ret.left >= entry.left && ret.left < entry.left + entry.width) { - if (entry.left + 10 + submenu.width <= windowDimensions.width) { - ret.left = entry.left + 10; - } - entry.top += 10; - entry.height = 0; - } - // Now that we have a horizontal position, try layout vertically - ret.top = (0, contextview_1.layout)(windowDimensions.height, submenu.height, { position: 0 /* Before */, offset: entry.top, size: 0 }); - // We didn't have enough room below, but we did above, so we shift down to align the menu - if (ret.top + submenu.height === entry.top && ret.top + entry.height + submenu.height <= windowDimensions.height) { - ret.top += entry.height; - } - return ret; - } - createSubmenu(selectFirstItem = true) { - if (!this.element) { - return; - } - if (!this.parentData.submenu) { - this.updateAriaExpanded('true'); - this.submenuContainer = (0, dom_1.append)(this.element, (0, dom_1.$)('div.monaco-submenu')); - this.submenuContainer.classList.add('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 - const computedStyles = getComputedStyle(this.parentData.parent.domNode); - const paddingTop = parseFloat(computedStyles.paddingTop || '0') || 0; - // this.submenuContainer.style.top = `${this.element.offsetTop - this.parentData.parent.scrollOffset - paddingTop}px`; - this.submenuContainer.style.zIndex = '1'; - this.submenuContainer.style.position = 'fixed'; - this.submenuContainer.style.top = '0'; - this.submenuContainer.style.left = '0'; - this.parentData.submenu = new Menu(this.submenuContainer, this.submenuActions.length ? this.submenuActions : [new actions_1.EmptySubmenuAction()], this.submenuOptions); - if (this.menuStyle) { - this.parentData.submenu.style(this.menuStyle); - } - // layout submenu - const entryBox = this.element.getBoundingClientRect(); - const entryBoxUpdated = { - top: entryBox.top - paddingTop, - left: entryBox.left, - height: entryBox.height + 2 * paddingTop, - width: entryBox.width - }; - const viewBox = this.submenuContainer.getBoundingClientRect(); - const { top, left } = this.calculateSubmenuMenuLayout(new dom_1.Dimension(window.innerWidth, window.innerHeight), dom_1.Dimension.lift(viewBox), entryBoxUpdated, this.expandDirection); - this.submenuContainer.style.left = `${left}px`; - this.submenuContainer.style.top = `${top}px`; - this.submenuDisposables.add((0, dom_1.addDisposableListener)(this.submenuContainer, dom_1.EventType.KEY_UP, e => { - let 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((0, dom_1.addDisposableListener)(this.submenuContainer, dom_1.EventType.KEY_DOWN, e => { - let event = new keyboardEvent_1.StandardKeyboardEvent(e); - if (event.equals(15 /* LeftArrow */)) { - dom_1.EventHelper.stop(e, true); - } - })); - this.submenuDisposables.add(this.parentData.submenu.onDidCancel(() => { - this.parentData.parent.focus(); - this.cleanupExistingSubmenu(true); - })); - this.parentData.submenu.focus(selectFirstItem); - this.mysubmenu = this.parentData.submenu; - } - else { - this.parentData.submenu.focus(false); - } - } - updateAriaExpanded(value) { - var _a; - if (this.item) { - (_a = this.item) === null || _a === void 0 ? void 0 : _a.setAttribute('aria-expanded', value); - } - } - applyStyle() { - super.applyStyle(); - if (!this.menuStyle) { - return; - } - const isSelected = this.element && this.element.classList.contains('focused'); - const 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); - } - } - dispose() { - super.dispose(); - this.hideScheduler.dispose(); - if (this.mysubmenu) { - this.mysubmenu.dispose(); - this.mysubmenu = null; - } - if (this.submenuContainer) { - this.submenuContainer = undefined; - } - } - } - class MenuSeparatorActionViewItem extends actionViewItems_1.ActionViewItem { - style(style) { - if (this.label) { - this.label.style.borderBottomColor = style.separatorColor ? `${style.separatorColor}` : ''; - } - } - } - function cleanMnemonic(label) { - const regex = exports.MENU_MNEMONIC_REGEX; - const matches = regex.exec(label); - if (!matches) { - return label; - } - const mnemonicInText = !matches[1]; - return label.replace(regex, mnemonicInText ? '$2$3' : '').trim(); - } - exports.cleanMnemonic = cleanMnemonic; - let MENU_WIDGET_CSS = ` -.monaco-menu { - font-size: 13px; - -} - -${(0, codiconStyles_1.formatRule)(menuSelectionIcon)} -${(0, codiconStyles_1.formatRule)(menuSubmenuIcon)} - -.monaco-menu .monaco-action-bar { - text-align: right; - overflow: hidden; - white-space: nowrap; -} - -.monaco-menu .monaco-action-bar .actions-container { - display: flex; - margin: 0 auto; - padding: 0; - width: 100%; - justify-content: flex-end; -} - -.monaco-menu .monaco-action-bar.vertical .actions-container { - display: inline-block; -} - -.monaco-menu .monaco-action-bar.reverse .actions-container { - flex-direction: row-reverse; -} - -.monaco-menu .monaco-action-bar .action-item { - cursor: pointer; - display: inline-block; - transition: transform 50ms ease; - position: relative; /* DO NOT REMOVE - this is the key to preventing the ghosting icon bug in Chrome 42 */ -} - -.monaco-menu .monaco-action-bar .action-item.disabled { - cursor: default; -} - -.monaco-menu .monaco-action-bar.animated .action-item.active { - transform: scale(1.272019649, 1.272019649); /* 1.272019649 = √φ */ -} - -.monaco-menu .monaco-action-bar .action-item .icon, -.monaco-menu .monaco-action-bar .action-item .codicon { - display: inline-block; -} - -.monaco-menu .monaco-action-bar .action-item .codicon { - display: flex; - align-items: center; -} - -.monaco-menu .monaco-action-bar .action-label { - font-size: 11px; - margin-right: 4px; -} - -.monaco-menu .monaco-action-bar .action-item.disabled .action-label, -.monaco-menu .monaco-action-bar .action-item.disabled .action-label:hover { - opacity: 0.4; -} - -/* Vertical actions */ - -.monaco-menu .monaco-action-bar.vertical { - text-align: left; -} - -.monaco-menu .monaco-action-bar.vertical .action-item { - display: block; -} - -.monaco-menu .monaco-action-bar.vertical .action-label.separator { - display: block; - border-bottom: 1px solid #bbb; - padding-top: 1px; - margin-left: .8em; - margin-right: .8em; -} - -.monaco-menu .secondary-actions .monaco-action-bar .action-label { - margin-left: 6px; -} - -/* Action Items */ -.monaco-menu .monaco-action-bar .action-item.select-container { - overflow: hidden; /* somehow the dropdown overflows its container, we prevent it here to not push */ - flex: 1; - max-width: 170px; - min-width: 60px; - display: flex; - align-items: center; - justify-content: center; - margin-right: 10px; -} - -.monaco-menu .monaco-action-bar.vertical { - margin-left: 0; - overflow: visible; -} - -.monaco-menu .monaco-action-bar.vertical .actions-container { - display: block; -} - -.monaco-menu .monaco-action-bar.vertical .action-item { - padding: 0; - transform: none; - display: flex; -} - -.monaco-menu .monaco-action-bar.vertical .action-item.active { - transform: none; -} - -.monaco-menu .monaco-action-bar.vertical .action-menu-item { - flex: 1 1 auto; - display: flex; - height: 2em; - align-items: center; - position: relative; -} - -.monaco-menu .monaco-action-bar.vertical .action-label { - flex: 1 1 auto; - text-decoration: none; - padding: 0 1em; - background: none; - font-size: 12px; - line-height: 1; -} - -.monaco-menu .monaco-action-bar.vertical .keybinding, -.monaco-menu .monaco-action-bar.vertical .submenu-indicator { - display: inline-block; - flex: 2 1 auto; - padding: 0 1em; - text-align: right; - font-size: 12px; - line-height: 1; -} - -.monaco-menu .monaco-action-bar.vertical .submenu-indicator { - height: 100%; -} - -.monaco-menu .monaco-action-bar.vertical .submenu-indicator.codicon { - font-size: 16px !important; - display: flex; - align-items: center; -} - -.monaco-menu .monaco-action-bar.vertical .submenu-indicator.codicon::before { - margin-left: auto; - margin-right: -20px; -} - -.monaco-menu .monaco-action-bar.vertical .action-item.disabled .keybinding, -.monaco-menu .monaco-action-bar.vertical .action-item.disabled .submenu-indicator { - opacity: 0.4; -} - -.monaco-menu .monaco-action-bar.vertical .action-label:not(.separator) { - display: inline-block; - box-sizing: border-box; - margin: 0; -} - -.monaco-menu .monaco-action-bar.vertical .action-item { - position: static; - overflow: visible; -} - -.monaco-menu .monaco-action-bar.vertical .action-item .monaco-submenu { - position: absolute; -} - -.monaco-menu .monaco-action-bar.vertical .action-label.separator { - padding: 0.5em 0 0 0; - margin-bottom: 0.5em; - width: 100%; - height: 0px !important; - margin-left: .8em !important; - margin-right: .8em !important; -} - -.monaco-menu .monaco-action-bar.vertical .action-label.separator.text { - padding: 0.7em 1em 0.1em 1em; - font-weight: bold; - opacity: 1; -} - -.monaco-menu .monaco-action-bar.vertical .action-label:hover { - color: inherit; -} - -.monaco-menu .monaco-action-bar.vertical .menu-item-check { - position: absolute; - visibility: hidden; - width: 1em; - height: 100%; -} - -.monaco-menu .monaco-action-bar.vertical .action-menu-item.checked .menu-item-check { - visibility: visible; - display: flex; - align-items: center; - justify-content: center; -} - -/* Context Menu */ - -.context-view.monaco-menu-container { - outline: 0; - border: none; - animation: fadeIn 0.083s linear; - -webkit-app-region: no-drag; -} - -.context-view.monaco-menu-container :focus, -.context-view.monaco-menu-container .monaco-action-bar.vertical:focus, -.context-view.monaco-menu-container .monaco-action-bar.vertical :focus { - outline: 0; -} - -.monaco-menu .monaco-action-bar.vertical .action-item { - border: thin solid transparent; /* prevents jumping behaviour on hover or focus */ -} - - -/* High Contrast Theming */ -:host-context(.hc-black) .context-view.monaco-menu-container { - box-shadow: none; -} - -:host-context(.hc-black) .monaco-menu .monaco-action-bar.vertical .action-item.focused { - background: none; -} - -/* Vertical Action Bar Styles */ - -.monaco-menu .monaco-action-bar.vertical { - padding: .5em 0; -} - -.monaco-menu .monaco-action-bar.vertical .action-menu-item { - height: 1.8em; -} - -.monaco-menu .monaco-action-bar.vertical .action-label:not(.separator), -.monaco-menu .monaco-action-bar.vertical .keybinding { - font-size: inherit; - padding: 0 2em; -} - -.monaco-menu .monaco-action-bar.vertical .menu-item-check { - font-size: inherit; - width: 2em; -} - -.monaco-menu .monaco-action-bar.vertical .action-label.separator { - font-size: inherit; - padding: 0.2em 0 0 0; - margin-bottom: 0.2em; -} - -:host-context(.linux) .monaco-menu .monaco-action-bar.vertical .action-label.separator { - margin-left: 0; - margin-right: 0; -} - -.monaco-menu .monaco-action-bar.vertical .submenu-indicator { - font-size: 60%; - padding: 0 1.8em; -} - -:host-context(.linux) .monaco-menu .monaco-action-bar.vertical .submenu-indicator { - height: 100%; - mask-size: 10px 10px; - -webkit-mask-size: 10px 10px; -} - -.monaco-menu .action-item { - cursor: default; -} - -/* Arrows */ -.monaco-scrollable-element > .scrollbar > .scra { - cursor: pointer; - font-size: 11px !important; -} - -.monaco-scrollable-element > .visible { - opacity: 1; - - /* Background rule added for IE9 - to allow clicks on dom node */ - background:rgba(0,0,0,0); - - transition: opacity 100ms linear; -} -.monaco-scrollable-element > .invisible { - opacity: 0; - pointer-events: none; -} -.monaco-scrollable-element > .invisible.fade { - transition: opacity 800ms linear; -} - -/* Scrollable Content Inset Shadow */ -.monaco-scrollable-element > .shadow { - position: absolute; - display: none; -} -.monaco-scrollable-element > .shadow.top { - display: block; - top: 0; - left: 3px; - height: 3px; - width: 100%; - box-shadow: #DDD 0 6px 6px -6px inset; -} -.monaco-scrollable-element > .shadow.left { - display: block; - top: 3px; - left: 0; - height: 100%; - width: 3px; - box-shadow: #DDD 6px 0 6px -6px inset; -} -.monaco-scrollable-element > .shadow.top-left-corner { - display: block; - top: 0; - left: 0; - height: 3px; - width: 3px; -} -.monaco-scrollable-element > .shadow.top.left { - box-shadow: #DDD 6px 6px 6px -6px inset; -} - -/* ---------- Default Style ---------- */ - -:host-context(.vs) .monaco-scrollable-element > .scrollbar > .slider { - background: rgba(100, 100, 100, .4); -} -:host-context(.vs-dark) .monaco-scrollable-element > .scrollbar > .slider { - background: rgba(121, 121, 121, .4); -} -:host-context(.hc-black) .monaco-scrollable-element > .scrollbar > .slider { - background: rgba(111, 195, 223, .6); -} - -.monaco-scrollable-element > .scrollbar > .slider:hover { - background: rgba(100, 100, 100, .7); -} -:host-context(.hc-black) .monaco-scrollable-element > .scrollbar > .slider:hover { - background: rgba(111, 195, 223, .8); -} - -.monaco-scrollable-element > .scrollbar > .slider.active { - background: rgba(0, 0, 0, .6); -} -:host-context(.vs-dark) .monaco-scrollable-element > .scrollbar > .slider.active { - background: rgba(191, 191, 191, .4); -} -:host-context(.hc-black) .monaco-scrollable-element > .scrollbar > .slider.active { - background: rgba(111, 195, 223, 1); -} - -:host-context(.vs-dark) .monaco-scrollable-element .shadow.top { - box-shadow: none; -} - -:host-context(.vs-dark) .monaco-scrollable-element .shadow.left { - box-shadow: #000 6px 0 6px -6px inset; -} - -:host-context(.vs-dark) .monaco-scrollable-element .shadow.top.left { - box-shadow: #000 6px 6px 6px -6px inset; -} - -:host-context(.hc-black) .monaco-scrollable-element .shadow.top { - box-shadow: none; -} - -:host-context(.hc-black) .monaco-scrollable-element .shadow.left { - box-shadow: none; -} - -:host-context(.hc-black) .monaco-scrollable-element .shadow.top.left { - box-shadow: none; -} -`; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[445/*vs/base/parts/quickinput/browser/quickInputBox*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,181/*vs/base/browser/ui/inputbox/inputBox*/,2/*vs/base/common/lifecycle*/,51/*vs/base/browser/keyboardEvent*/,74/*vs/base/common/severity*/,55/*vs/base/browser/mouseEvent*/,132/*vs/css!vs/base/parts/quickinput/browser/media/quickInput*/]), function (require, exports, dom, inputBox_1, lifecycle_1, keyboardEvent_1, severity_1, mouseEvent_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.QuickInputBox = void 0; - const $ = dom.$; - class QuickInputBox extends lifecycle_1.Disposable { - constructor(parent) { - super(); - this.parent = parent; - this.onKeyDown = (handler) => { - return dom.addDisposableListener(this.inputBox.inputElement, dom.EventType.KEY_DOWN, (e) => { - handler(new keyboardEvent_1.StandardKeyboardEvent(e)); - }); - }; - this.onMouseDown = (handler) => { - return dom.addDisposableListener(this.inputBox.inputElement, dom.EventType.MOUSE_DOWN, (e) => { - handler(new mouseEvent_1.StandardMouseEvent(e)); - }); - }; - this.onDidChange = (handler) => { - return this.inputBox.onDidChange(handler); - }; - this.container = dom.append(this.parent, $('.quick-input-box')); - this.inputBox = this._register(new inputBox_1.InputBox(this.container, undefined)); - } - get value() { - return this.inputBox.value; - } - set value(value) { - this.inputBox.value = value; - } - select(range = null) { - this.inputBox.select(range); - } - isSelectionAtEnd() { - return this.inputBox.isSelectionAtEnd(); - } - get placeholder() { - return this.inputBox.inputElement.getAttribute('placeholder') || ''; - } - set placeholder(placeholder) { - this.inputBox.setPlaceHolder(placeholder); - } - get ariaLabel() { - return this.inputBox.getAriaLabel(); - } - set ariaLabel(ariaLabel) { - this.inputBox.setAriaLabel(ariaLabel); - } - get password() { - return this.inputBox.inputElement.type === 'password'; - } - set password(password) { - this.inputBox.inputElement.type = password ? 'password' : 'text'; - } - setAttribute(name, value) { - this.inputBox.inputElement.setAttribute(name, value); - } - removeAttribute(name) { - this.inputBox.inputElement.removeAttribute(name); - } - showDecoration(decoration) { - if (decoration === severity_1.default.Ignore) { - this.inputBox.hideMessage(); - } - else { - this.inputBox.showMessage({ type: decoration === severity_1.default.Info ? 1 /* INFO */ : decoration === severity_1.default.Warning ? 2 /* WARNING */ : 3 /* ERROR */, content: '' }); - } - } - stylesForType(decoration) { - return this.inputBox.stylesForType(decoration === severity_1.default.Info ? 1 /* INFO */ : decoration === severity_1.default.Warning ? 2 /* WARNING */ : 3 /* ERROR */); - } - setFocus() { - this.inputBox.focus(); - } - layout() { - this.inputBox.layout(); - } - style(styles) { - this.inputBox.style(styles); - } - } - exports.QuickInputBox = QuickInputBox; -}); - -define(__m[446/*vs/nls!vs/base/common/errorMessage*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/common/errorMessage", 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[447/*vs/base/common/errorMessage*/], __M([0/*require*/,1/*exports*/,446/*vs/nls!vs/base/common/errorMessage*/,20/*vs/base/common/types*/,19/*vs/base/common/arrays*/]), function (require, exports, nls, types, arrays) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.toErrorMessage = void 0; - function exceptionToErrorMessage(exception, verbose) { - if (verbose && (exception.stack || exception.stacktrace)) { - return nls.localize(0, null, detectSystemErrorMessage(exception), stackToString(exception.stack) || stackToString(exception.stacktrace)); - } - return detectSystemErrorMessage(exception); - } - function stackToString(stack) { - if (Array.isArray(stack)) { - return stack.join('\n'); - } - return stack; - } - function detectSystemErrorMessage(exception) { - // See https://nodejs.org/api/errors.html#errors_class_system_error - if (typeof exception.code === 'string' && typeof exception.errno === 'number' && typeof exception.syscall === 'string') { - return nls.localize(1, null, exception.message); - } - return exception.message || nls.localize(2, null); - } - /** - * Tries to generate a human readable error message out of the error. If the verbose parameter - * is set to true, the error message will include stacktrace details if provided. - * - * @returns A string containing the error message. - */ - function toErrorMessage(error = null, verbose = false) { - if (!error) { - return nls.localize(3, null); - } - if (Array.isArray(error)) { - const errors = arrays.coalesce(error); - const msg = toErrorMessage(errors[0], verbose); - if (errors.length > 1) { - return nls.localize(4, null, msg, errors.length); - } - return msg; - } - if (types.isString(error)) { - return error; - } - if (error.detail) { - const detail = error.detail; - if (detail.error) { - return exceptionToErrorMessage(detail.error, verbose); - } - if (detail.exception) { - return exceptionToErrorMessage(detail.exception, verbose); - } - } - if (error.stack) { - return exceptionToErrorMessage(error, verbose); - } - if (error.message) { - return error.message; - } - return nls.localize(5, null); - } - exports.toErrorMessage = toErrorMessage; -}); - -define(__m[448/*vs/nls!vs/base/common/keybindingLabels*/], __M([4/*vs/nls*/,5/*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[182/*vs/base/common/keybindingLabels*/], __M([0/*require*/,1/*exports*/,448/*vs/nls!vs/base/common/keybindingLabels*/]), function (require, exports, nls) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.AriaLabelProvider = exports.UILabelProvider = exports.ModifierLabelProvider = void 0; - class ModifierLabelProvider { - constructor(mac, windows, 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; - } - toLabel(OS, parts, keyLabelProvider) { - if (parts.length === 0) { - return null; - } - const result = []; - for (let i = 0, len = parts.length; i < len; i++) { - const part = parts[i]; - const keyLabel = keyLabelProvider(part); - if (keyLabel === null) { - // this keybinding cannot be expressed... - return null; - } - result[i] = _simpleAsString(part, keyLabel, this.modifierLabels[OS]); - } - return result.join(' '); - } - } - 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 ''; - } - const 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 - if (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[449/*vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([0/*require*/,1/*exports*/,42/*vs/base/common/objects*/,182/*vs/base/common/keybindingLabels*/,7/*vs/base/browser/dom*/,434/*vs/nls!vs/base/browser/ui/keybindingLabel/keybindingLabel*/,313/*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 }); - exports.KeybindingLabel = void 0; - const $ = dom.$; - class KeybindingLabel { - constructor(container, os, options) { - this.os = os; - this.keyElements = new Set(); - this.options = options || Object.create(null); - this.labelBackground = this.options.keybindingLabelBackground; - this.labelForeground = this.options.keybindingLabelForeground; - this.labelBorder = this.options.keybindingLabelBorder; - this.labelBottomBorder = this.options.keybindingLabelBottomBorder; - this.labelShadow = this.options.keybindingLabelShadow; - this.domNode = dom.append(container, $('.monaco-keybinding')); - this.didEverRender = false; - container.appendChild(this.domNode); - } - get element() { - return this.domNode; - } - set(keybinding, matches) { - if (this.didEverRender && this.keybinding === keybinding && KeybindingLabel.areSame(this.matches, matches)) { - return; - } - this.keybinding = keybinding; - this.matches = matches; - this.render(); - } - render() { - this.clear(); - if (this.keybinding) { - let [firstPart, chordPart] = this.keybinding.getParts(); - 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.applyStyles(); - this.didEverRender = true; - } - clear() { - dom.clearNode(this.domNode); - this.keyElements.clear(); - } - renderPart(parent, part, match) { - const 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); - } - const keyLabel = part.keyLabel; - if (keyLabel) { - this.renderKey(parent, keyLabel, Boolean(match === null || match === void 0 ? void 0 : match.keyCode), ''); - } - } - renderKey(parent, label, highlight, separator) { - dom.append(parent, this.createKeyElement(label, highlight ? '.highlight' : '')); - if (separator) { - dom.append(parent, $('span.monaco-keybinding-key-separator', undefined, separator)); - } - } - renderUnbound(parent) { - dom.append(parent, this.createKeyElement((0, nls_1.localize)(0, null))); - } - createKeyElement(label, extraClass = '') { - const keyElement = $('span.monaco-keybinding-key' + extraClass, undefined, label); - this.keyElements.add(keyElement); - return keyElement; - } - style(styles) { - this.labelBackground = styles.keybindingLabelBackground; - this.labelForeground = styles.keybindingLabelForeground; - this.labelBorder = styles.keybindingLabelBorder; - this.labelBottomBorder = styles.keybindingLabelBottomBorder; - this.labelShadow = styles.keybindingLabelShadow; - this.applyStyles(); - } - applyStyles() { - var _a; - if (this.element) { - for (const keyElement of this.keyElements) { - if (this.labelBackground) { - keyElement.style.backgroundColor = (_a = this.labelBackground) === null || _a === void 0 ? void 0 : _a.toString(); - } - if (this.labelBorder) { - keyElement.style.borderColor = this.labelBorder.toString(); - } - if (this.labelBottomBorder) { - keyElement.style.borderBottomColor = this.labelBottomBorder.toString(); - } - if (this.labelShadow) { - keyElement.style.boxShadow = `inset 0 -1px 0 ${this.labelShadow}`; - } - } - if (this.labelForeground) { - this.element.style.color = this.labelForeground.toString(); - } - } - } - static areSame(a, b) { - if (a === b || (!a && !b)) { - return true; - } - return !!a && !!b && (0, objects_1.equals)(a.firstPart, b.firstPart) && (0, objects_1.equals)(a.chordPart, b.chordPart); - } - } - exports.KeybindingLabel = KeybindingLabel; -}); - -define(__m[450/*vs/nls!vs/base/parts/quickinput/browser/quickInput*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/parts/quickinput/browser/quickInput", data); }); -define(__m[451/*vs/nls!vs/base/parts/quickinput/browser/quickInputList*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/parts/quickinput/browser/quickInputList", 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[452/*vs/base/parts/quickinput/browser/quickInputList*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,104/*vs/base/common/iconLabels*/,291/*vs/base/common/comparers*/,6/*vs/base/common/event*/,51/*vs/base/browser/keyboardEvent*/,179/*vs/base/browser/ui/iconLabel/iconLabel*/,161/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/,90/*vs/base/common/decorators*/,19/*vs/base/common/arrays*/,17/*vs/base/common/platform*/,84/*vs/base/browser/ui/actionbar/actionbar*/,50/*vs/base/common/actions*/,213/*vs/base/parts/quickinput/browser/quickInputUtils*/,20/*vs/base/common/types*/,449/*vs/base/browser/ui/keybindingLabel/keybindingLabel*/,451/*vs/nls!vs/base/parts/quickinput/browser/quickInputList*/,27/*vs/base/common/codicons*/,132/*vs/css!vs/base/parts/quickinput/browser/media/quickInput*/]), function (require, exports, dom, lifecycle_1, iconLabels_1, comparers_1, event_1, keyboardEvent_1, iconLabel_1, highlightedLabel_1, decorators_1, arrays_1, platform, actionbar_1, actions_1, quickInputUtils_1, types_1, keybindingLabel_1, nls_1, codicons_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.QuickInputList = exports.QuickInputListFocus = void 0; - const $ = dom.$; - class ListElement { - constructor(init) { - this.hidden = false; - this._onChecked = new event_1.Emitter(); - this.onChecked = this._onChecked.event; - Object.assign(this, init); - } - get checked() { - return !!this._checked; - } - set checked(value) { - if (value !== this._checked) { - this._checked = value; - this._onChecked.fire(value); - } - } - dispose() { - this._onChecked.dispose(); - } - } - class ListElementRenderer { - get templateId() { - return ListElementRenderer.ID; - } - renderTemplate(container) { - const data = Object.create(null); - data.toDisposeElement = []; - data.toDisposeTemplate = []; - data.entry = dom.append(container, $('.quick-input-list-entry')); - // Checkbox - const label = dom.append(data.entry, $('label.quick-input-list-label')); - data.toDisposeTemplate.push(dom.addStandardDisposableListener(label, dom.EventType.CLICK, e => { - if (!data.checkbox.offsetParent) { // If checkbox not visible: - e.preventDefault(); // Prevent toggle of checkbox when it is immediately shown afterwards. #91740 - } - })); - data.checkbox = dom.append(label, $('input.quick-input-list-checkbox')); - data.checkbox.type = 'checkbox'; - data.toDisposeTemplate.push(dom.addStandardDisposableListener(data.checkbox, dom.EventType.CHANGE, e => { - data.element.checked = data.checkbox.checked; - })); - // Rows - const rows = dom.append(label, $('.quick-input-list-rows')); - const row1 = dom.append(rows, $('.quick-input-list-row')); - const row2 = dom.append(rows, $('.quick-input-list-row')); - // Label - data.label = new iconLabel_1.IconLabel(row1, { supportHighlights: true, supportDescriptionHighlights: true, supportIcons: true }); - // Keybinding - const keybindingContainer = dom.append(row1, $('.quick-input-list-entry-keybinding')); - data.keybinding = new keybindingLabel_1.KeybindingLabel(keybindingContainer, platform.OS); - // Detail - const detailContainer = dom.append(row2, $('.quick-input-list-label-meta')); - data.detail = new highlightedLabel_1.HighlightedLabel(detailContainer, true); - // Separator - data.separator = dom.append(data.entry, $('.quick-input-list-separator')); - // Actions - data.actionBar = new actionbar_1.ActionBar(data.entry); - data.actionBar.domNode.classList.add('quick-input-list-entry-action-bar'); - data.toDisposeTemplate.push(data.actionBar); - return data; - } - renderElement(element, index, data) { - data.toDisposeElement = (0, lifecycle_1.dispose)(data.toDisposeElement); - data.element = element; - data.checkbox.checked = element.checked; - data.toDisposeElement.push(element.onChecked(checked => data.checkbox.checked = checked)); - const { labelHighlights, descriptionHighlights, detailHighlights } = element; - // Label - const options = Object.create(null); - options.matches = labelHighlights || []; - options.descriptionTitle = element.saneDescription; - options.descriptionMatches = descriptionHighlights || []; - options.extraClasses = element.item.iconClasses; - options.italic = element.item.italic; - options.strikethrough = element.item.strikethrough; - data.label.setLabel(element.saneLabel, element.saneDescription, options); - // Keybinding - data.keybinding.set(element.item.keybinding); - // Meta - data.detail.set(element.saneDetail, detailHighlights); - // Separator - if (element.separator && element.separator.label) { - data.separator.textContent = element.separator.label; - data.separator.style.display = ''; - } - else { - data.separator.style.display = 'none'; - } - data.entry.classList.toggle('quick-input-list-separator-border', !!element.separator); - // Actions - data.actionBar.clear(); - const buttons = element.item.buttons; - if (buttons && buttons.length) { - data.actionBar.push(buttons.map((button, index) => { - let cssClasses = button.iconClass || (button.iconPath ? (0, quickInputUtils_1.getIconClass)(button.iconPath) : undefined); - if (button.alwaysVisible) { - cssClasses = cssClasses ? `${cssClasses} always-visible` : 'always-visible'; - } - const action = new actions_1.Action(`id-${index}`, '', cssClasses, true, () => __awaiter(this, void 0, void 0, function* () { - element.fireButtonTriggered({ - button, - item: element.item - }); - })); - action.tooltip = button.tooltip || ''; - return action; - }), { icon: true, label: false }); - data.entry.classList.add('has-actions'); - } - else { - data.entry.classList.remove('has-actions'); - } - } - disposeElement(element, index, data) { - data.toDisposeElement = (0, lifecycle_1.dispose)(data.toDisposeElement); - } - disposeTemplate(data) { - data.toDisposeElement = (0, lifecycle_1.dispose)(data.toDisposeElement); - data.toDisposeTemplate = (0, lifecycle_1.dispose)(data.toDisposeTemplate); - } - } - ListElementRenderer.ID = 'listelement'; - class ListElementDelegate { - getHeight(element) { - return element.saneDetail ? 44 : 22; - } - getTemplateId(element) { - return ListElementRenderer.ID; - } - } - var QuickInputListFocus; - (function (QuickInputListFocus) { - QuickInputListFocus[QuickInputListFocus["First"] = 1] = "First"; - QuickInputListFocus[QuickInputListFocus["Second"] = 2] = "Second"; - QuickInputListFocus[QuickInputListFocus["Last"] = 3] = "Last"; - QuickInputListFocus[QuickInputListFocus["Next"] = 4] = "Next"; - QuickInputListFocus[QuickInputListFocus["Previous"] = 5] = "Previous"; - QuickInputListFocus[QuickInputListFocus["NextPage"] = 6] = "NextPage"; - QuickInputListFocus[QuickInputListFocus["PreviousPage"] = 7] = "PreviousPage"; - })(QuickInputListFocus = exports.QuickInputListFocus || (exports.QuickInputListFocus = {})); - class QuickInputList { - constructor(parent, id, options) { - this.parent = parent; - this.inputElements = []; - this.elements = []; - this.elementsToIndexes = new Map(); - this.matchOnDescription = false; - this.matchOnDetail = false; - this.matchOnLabel = true; - this.matchOnMeta = true; - this.sortByLabel = true; - this._onChangedAllVisibleChecked = new event_1.Emitter(); - this.onChangedAllVisibleChecked = this._onChangedAllVisibleChecked.event; - this._onChangedCheckedCount = new event_1.Emitter(); - this.onChangedCheckedCount = this._onChangedCheckedCount.event; - this._onChangedVisibleCount = new event_1.Emitter(); - this.onChangedVisibleCount = this._onChangedVisibleCount.event; - this._onChangedCheckedElements = new event_1.Emitter(); - this.onChangedCheckedElements = this._onChangedCheckedElements.event; - this._onButtonTriggered = new event_1.Emitter(); - this.onButtonTriggered = this._onButtonTriggered.event; - this._onKeyDown = new event_1.Emitter(); - this.onKeyDown = this._onKeyDown.event; - this._onLeave = new event_1.Emitter(); - this.onLeave = this._onLeave.event; - this._fireCheckedEvents = true; - this.elementDisposables = []; - this.disposables = []; - this.id = id; - this.container = dom.append(this.parent, $('.quick-input-list')); - const delegate = new ListElementDelegate(); - const accessibilityProvider = new QuickInputAccessibilityProvider(); - this.list = options.createList('QuickInput', this.container, delegate, [new ListElementRenderer()], { - identityProvider: { getId: element => element.saneLabel }, - setRowLineHeight: false, - multipleSelectionSupport: false, - horizontalScrolling: false, - accessibilityProvider - }); - this.list.getHTMLElement().id = id; - this.disposables.push(this.list); - this.disposables.push(this.list.onKeyDown(e => { - const event = new keyboardEvent_1.StandardKeyboardEvent(e); - switch (event.keyCode) { - case 10 /* Space */: - this.toggleCheckbox(); - break; - case 31 /* KEY_A */: - if (platform.isMacintosh ? e.metaKey : e.ctrlKey) { - this.list.setFocus((0, arrays_1.range)(this.list.length)); - } - break; - case 16 /* UpArrow */: - const focus1 = this.list.getFocus(); - if (focus1.length === 1 && focus1[0] === 0) { - this._onLeave.fire(); - } - break; - case 18 /* DownArrow */: - const focus2 = this.list.getFocus(); - if (focus2.length === 1 && focus2[0] === this.list.length - 1) { - this._onLeave.fire(); - } - break; - } - this._onKeyDown.fire(event); - })); - this.disposables.push(this.list.onMouseDown(e => { - if (e.browserEvent.button !== 2) { - // Works around / fixes #64350. - e.browserEvent.preventDefault(); - } - })); - this.disposables.push(dom.addDisposableListener(this.container, dom.EventType.CLICK, e => { - if (e.x || e.y) { // Avoid 'click' triggered by 'space' on checkbox. - this._onLeave.fire(); - } - })); - this.disposables.push(this.list.onMouseMiddleClick(e => { - this._onLeave.fire(); - })); - this.disposables.push(this.list.onContextMenu(e => { - if (typeof e.index === 'number') { - e.browserEvent.preventDefault(); - // we want to treat a context menu event as - // a gesture to open the item at the index - // since we do not have any context menu - // this enables for example macOS to Ctrl- - // click on an item to open it. - this.list.setSelection([e.index]); - } - })); - this.disposables.push(this._onChangedAllVisibleChecked, this._onChangedCheckedCount, this._onChangedVisibleCount, this._onChangedCheckedElements, this._onButtonTriggered, this._onLeave, this._onKeyDown); - } - get onDidChangeFocus() { - return event_1.Event.map(this.list.onDidChangeFocus, e => e.elements.map(e => e.item)); - } - get onDidChangeSelection() { - return event_1.Event.map(this.list.onDidChangeSelection, e => ({ items: e.elements.map(e => e.item), event: e.browserEvent })); - } - getAllVisibleChecked() { - return this.allVisibleChecked(this.elements, false); - } - allVisibleChecked(elements, whenNoneVisible = true) { - for (let i = 0, n = elements.length; i < n; i++) { - const element = elements[i]; - if (!element.hidden) { - if (!element.checked) { - return false; - } - else { - whenNoneVisible = true; - } - } - } - return whenNoneVisible; - } - getCheckedCount() { - let count = 0; - const elements = this.elements; - for (let i = 0, n = elements.length; i < n; i++) { - if (elements[i].checked) { - count++; - } - } - return count; - } - getVisibleCount() { - let count = 0; - const elements = this.elements; - for (let i = 0, n = elements.length; i < n; i++) { - if (!elements[i].hidden) { - count++; - } - } - return count; - } - setAllVisibleChecked(checked) { - try { - this._fireCheckedEvents = false; - this.elements.forEach(element => { - if (!element.hidden) { - element.checked = checked; - } - }); - } - finally { - this._fireCheckedEvents = true; - this.fireCheckedEvents(); - } - } - setElements(inputElements) { - this.elementDisposables = (0, lifecycle_1.dispose)(this.elementDisposables); - const fireButtonTriggered = (event) => this.fireButtonTriggered(event); - this.inputElements = inputElements; - this.elements = inputElements.reduce((result, item, index) => { - var _a, _b, _c; - if (item.type !== 'separator') { - const previous = index && inputElements[index - 1]; - const saneLabel = item.label && item.label.replace(/\r?\n/g, ' '); - const saneMeta = item.meta && item.meta.replace(/\r?\n/g, ' '); - const saneDescription = item.description && item.description.replace(/\r?\n/g, ' '); - const saneDetail = item.detail && item.detail.replace(/\r?\n/g, ' '); - const saneAriaLabel = item.ariaLabel || [saneLabel, saneDescription, saneDetail] - .map(s => (0, codicons_1.getCodiconAriaLabel)(s)) - .filter(s => !!s) - .join(', '); - result.push(new ListElement({ - index, - item, - saneLabel, - saneMeta, - saneAriaLabel, - saneDescription, - saneDetail, - labelHighlights: (_a = item.highlights) === null || _a === void 0 ? void 0 : _a.label, - descriptionHighlights: (_b = item.highlights) === null || _b === void 0 ? void 0 : _b.description, - detailHighlights: (_c = item.highlights) === null || _c === void 0 ? void 0 : _c.detail, - checked: false, - separator: previous && previous.type === 'separator' ? previous : undefined, - fireButtonTriggered - })); - } - return result; - }, []); - this.elementDisposables.push(...this.elements); - this.elementDisposables.push(...this.elements.map(element => element.onChecked(() => this.fireCheckedEvents()))); - this.elementsToIndexes = this.elements.reduce((map, element, index) => { - map.set(element.item, index); - return map; - }, new Map()); - this.list.splice(0, this.list.length); // Clear focus and selection first, sending the events when the list is empty. - this.list.splice(0, this.list.length, this.elements); - this._onChangedVisibleCount.fire(this.elements.length); - } - getFocusedElements() { - return this.list.getFocusedElements() - .map(e => e.item); - } - setFocusedElements(items) { - this.list.setFocus(items - .filter(item => this.elementsToIndexes.has(item)) - .map(item => this.elementsToIndexes.get(item))); - if (items.length > 0) { - const focused = this.list.getFocus()[0]; - if (typeof focused === 'number') { - this.list.reveal(focused); - } - } - } - getActiveDescendant() { - return this.list.getHTMLElement().getAttribute('aria-activedescendant'); - } - setSelectedElements(items) { - this.list.setSelection(items - .filter(item => this.elementsToIndexes.has(item)) - .map(item => this.elementsToIndexes.get(item))); - } - getCheckedElements() { - return this.elements.filter(e => e.checked) - .map(e => e.item); - } - setCheckedElements(items) { - try { - this._fireCheckedEvents = false; - const checked = new Set(); - for (const item of items) { - checked.add(item); - } - for (const element of this.elements) { - element.checked = checked.has(element.item); - } - } - finally { - this._fireCheckedEvents = true; - this.fireCheckedEvents(); - } - } - set enabled(value) { - this.list.getHTMLElement().style.pointerEvents = value ? '' : 'none'; - } - focus(what) { - if (!this.list.length) { - return; - } - if (what === QuickInputListFocus.Next && this.list.getFocus()[0] === this.list.length - 1) { - what = QuickInputListFocus.First; - } - if (what === QuickInputListFocus.Previous && this.list.getFocus()[0] === 0) { - what = QuickInputListFocus.Last; - } - if (what === QuickInputListFocus.Second && this.list.length < 2) { - what = QuickInputListFocus.First; - } - switch (what) { - case QuickInputListFocus.First: - this.list.focusFirst(); - break; - case QuickInputListFocus.Second: - this.list.focusNth(1); - break; - case QuickInputListFocus.Last: - this.list.focusLast(); - break; - case QuickInputListFocus.Next: - this.list.focusNext(); - break; - case QuickInputListFocus.Previous: - this.list.focusPrevious(); - break; - case QuickInputListFocus.NextPage: - this.list.focusNextPage(); - break; - case QuickInputListFocus.PreviousPage: - this.list.focusPreviousPage(); - break; - } - const focused = this.list.getFocus()[0]; - if (typeof focused === 'number') { - this.list.reveal(focused); - } - } - clearFocus() { - this.list.setFocus([]); - } - domFocus() { - this.list.domFocus(); - } - layout(maxHeight) { - this.list.getHTMLElement().style.maxHeight = maxHeight ? `calc(${Math.floor(maxHeight / 44) * 44}px)` : ''; - this.list.layout(); - } - filter(query) { - if (!(this.sortByLabel || this.matchOnLabel || this.matchOnDescription || this.matchOnDetail)) { - this.list.layout(); - return false; - } - query = query.trim(); - // Reset filtering - if (!query || !(this.matchOnLabel || this.matchOnDescription || this.matchOnDetail)) { - this.elements.forEach(element => { - element.labelHighlights = undefined; - element.descriptionHighlights = undefined; - element.detailHighlights = undefined; - element.hidden = false; - const previous = element.index && this.inputElements[element.index - 1]; - element.separator = previous && previous.type === 'separator' ? previous : undefined; - }); - } - // Filter by value (since we support icons in labels, use $(..) aware fuzzy matching) - else { - let currentSeparator; - this.elements.forEach(element => { - const labelHighlights = this.matchOnLabel ? (0, types_1.withNullAsUndefined)((0, iconLabels_1.matchesFuzzyIconAware)(query, (0, iconLabels_1.parseLabelWithIcons)(element.saneLabel))) : undefined; - const descriptionHighlights = this.matchOnDescription ? (0, types_1.withNullAsUndefined)((0, iconLabels_1.matchesFuzzyIconAware)(query, (0, iconLabels_1.parseLabelWithIcons)(element.saneDescription || ''))) : undefined; - const detailHighlights = this.matchOnDetail ? (0, types_1.withNullAsUndefined)((0, iconLabels_1.matchesFuzzyIconAware)(query, (0, iconLabels_1.parseLabelWithIcons)(element.saneDetail || ''))) : undefined; - const metaHighlights = this.matchOnMeta ? (0, types_1.withNullAsUndefined)((0, iconLabels_1.matchesFuzzyIconAware)(query, (0, iconLabels_1.parseLabelWithIcons)(element.saneMeta || ''))) : undefined; - if (labelHighlights || descriptionHighlights || detailHighlights || metaHighlights) { - element.labelHighlights = labelHighlights; - element.descriptionHighlights = descriptionHighlights; - element.detailHighlights = detailHighlights; - element.hidden = false; - } - else { - element.labelHighlights = undefined; - element.descriptionHighlights = undefined; - element.detailHighlights = undefined; - element.hidden = !element.item.alwaysShow; - } - element.separator = undefined; - // we can show the separator unless the list gets sorted by match - if (!this.sortByLabel) { - const previous = element.index && this.inputElements[element.index - 1]; - currentSeparator = previous && previous.type === 'separator' ? previous : currentSeparator; - if (currentSeparator && !element.hidden) { - element.separator = currentSeparator; - currentSeparator = undefined; - } - } - }); - } - const shownElements = this.elements.filter(element => !element.hidden); - // Sort by value - if (this.sortByLabel && query) { - const normalizedSearchValue = query.toLowerCase(); - shownElements.sort((a, b) => { - return compareEntries(a, b, normalizedSearchValue); - }); - } - this.elementsToIndexes = shownElements.reduce((map, element, index) => { - map.set(element.item, index); - return map; - }, new Map()); - this.list.splice(0, this.list.length, shownElements); - this.list.setFocus([]); - this.list.layout(); - this._onChangedAllVisibleChecked.fire(this.getAllVisibleChecked()); - this._onChangedVisibleCount.fire(shownElements.length); - return true; - } - toggleCheckbox() { - try { - this._fireCheckedEvents = false; - const elements = this.list.getFocusedElements(); - const allChecked = this.allVisibleChecked(elements); - for (const element of elements) { - element.checked = !allChecked; - } - } - finally { - this._fireCheckedEvents = true; - this.fireCheckedEvents(); - } - } - display(display) { - this.container.style.display = display ? '' : 'none'; - } - isDisplayed() { - return this.container.style.display !== 'none'; - } - dispose() { - this.elementDisposables = (0, lifecycle_1.dispose)(this.elementDisposables); - this.disposables = (0, lifecycle_1.dispose)(this.disposables); - } - fireCheckedEvents() { - if (this._fireCheckedEvents) { - this._onChangedAllVisibleChecked.fire(this.getAllVisibleChecked()); - this._onChangedCheckedCount.fire(this.getCheckedCount()); - this._onChangedCheckedElements.fire(this.getCheckedElements()); - } - } - fireButtonTriggered(event) { - this._onButtonTriggered.fire(event); - } - style(styles) { - this.list.style(styles); - } - } - __decorate([ - decorators_1.memoize - ], QuickInputList.prototype, "onDidChangeFocus", null); - __decorate([ - decorators_1.memoize - ], QuickInputList.prototype, "onDidChangeSelection", null); - exports.QuickInputList = QuickInputList; - function compareEntries(elementA, elementB, lookFor) { - const labelHighlightsA = elementA.labelHighlights || []; - const labelHighlightsB = elementB.labelHighlights || []; - if (labelHighlightsA.length && !labelHighlightsB.length) { - return -1; - } - if (!labelHighlightsA.length && labelHighlightsB.length) { - return 1; - } - if (labelHighlightsA.length === 0 && labelHighlightsB.length === 0) { - return 0; - } - return (0, comparers_1.compareAnything)(elementA.saneLabel, elementB.saneLabel, lookFor); - } - class QuickInputAccessibilityProvider { - getWidgetAriaLabel() { - return (0, nls_1.localize)(0, null); - } - getAriaLabel(element) { - return element.saneAriaLabel; - } - getWidgetRole() { - return 'listbox'; - } - getRole() { - return 'option'; - } - } -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - - - - - - - - - -define(__m[453/*vs/base/parts/quickinput/browser/quickInput*/], __M([0/*require*/,1/*exports*/,205/*vs/base/parts/quickinput/common/quickInput*/,7/*vs/base/browser/dom*/,23/*vs/base/common/cancellation*/,452/*vs/base/parts/quickinput/browser/quickInputList*/,445/*vs/base/parts/quickinput/browser/quickInputBox*/,51/*vs/base/browser/keyboardEvent*/,450/*vs/nls!vs/base/parts/quickinput/browser/quickInput*/,208/*vs/base/browser/ui/countBadge/countBadge*/,316/*vs/base/browser/ui/progressbar/progressbar*/,6/*vs/base/common/event*/,304/*vs/base/browser/ui/button/button*/,2/*vs/base/common/lifecycle*/,74/*vs/base/common/severity*/,84/*vs/base/browser/ui/actionbar/actionbar*/,50/*vs/base/common/actions*/,19/*vs/base/common/arrays*/,15/*vs/base/common/async*/,213/*vs/base/parts/quickinput/browser/quickInputUtils*/,27/*vs/base/common/codicons*/,105/*vs/base/browser/ui/iconLabel/iconLabels*/,17/*vs/base/common/platform*/,132/*vs/css!vs/base/parts/quickinput/browser/media/quickInput*/]), function (require, exports, quickInput_1, dom, cancellation_1, quickInputList_1, quickInputBox_1, keyboardEvent_1, nls_1, countBadge_1, progressbar_1, event_1, button_1, lifecycle_1, severity_1, actionbar_1, actions_1, arrays_1, async_1, quickInputUtils_1, codicons_1, iconLabels_1, platform_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.QuickInputController = void 0; - const $ = dom.$; - const backButtonIcon = (0, codicons_1.registerCodicon)('quick-input-back', codicons_1.Codicon.arrowLeft); - const backButton = { - iconClass: backButtonIcon.classNames, - tooltip: (0, nls_1.localize)(0, null), - handle: -1 // TODO - }; - class QuickInput extends lifecycle_1.Disposable { - constructor(ui) { - super(); - this.ui = ui; - this.visible = false; - this._enabled = true; - this._busy = false; - this._ignoreFocusOut = false; - this._buttons = []; - this.noValidationMessage = QuickInput.noPromptMessage; - this._severity = severity_1.default.Ignore; - this.buttonsUpdated = false; - this.onDidTriggerButtonEmitter = this._register(new event_1.Emitter()); - this.onDidHideEmitter = this._register(new event_1.Emitter()); - this.onDisposeEmitter = this._register(new event_1.Emitter()); - this.visibleDisposables = this._register(new lifecycle_1.DisposableStore()); - this.onDidHide = this.onDidHideEmitter.event; - } - get title() { - return this._title; - } - set title(title) { - this._title = title; - this.update(); - } - get description() { - return this._description; - } - set description(description) { - this._description = description; - this.update(); - } - get step() { - return this._steps; - } - set step(step) { - this._steps = step; - this.update(); - } - get totalSteps() { - return this._totalSteps; - } - set totalSteps(totalSteps) { - this._totalSteps = totalSteps; - this.update(); - } - get enabled() { - return this._enabled; - } - set enabled(enabled) { - this._enabled = enabled; - this.update(); - } - get contextKey() { - return this._contextKey; - } - set contextKey(contextKey) { - this._contextKey = contextKey; - this.update(); - } - get busy() { - return this._busy; - } - set busy(busy) { - this._busy = busy; - this.update(); - } - get ignoreFocusOut() { - return this._ignoreFocusOut; - } - set ignoreFocusOut(ignoreFocusOut) { - const shouldUpdate = this._ignoreFocusOut !== ignoreFocusOut && !platform_1.isIOS; - this._ignoreFocusOut = ignoreFocusOut && !platform_1.isIOS; - if (shouldUpdate) { - this.update(); - } - } - get buttons() { - return this._buttons; - } - set buttons(buttons) { - this._buttons = buttons; - this.buttonsUpdated = true; - this.update(); - } - get validationMessage() { - return this._validationMessage; - } - set validationMessage(validationMessage) { - this._validationMessage = validationMessage; - this.update(); - } - get severity() { - return this._severity; - } - set severity(severity) { - this._severity = severity; - this.update(); - } - show() { - if (this.visible) { - return; - } - this.visibleDisposables.add(this.ui.onDidTriggerButton(button => { - if (this.buttons.indexOf(button) !== -1) { - this.onDidTriggerButtonEmitter.fire(button); - } - })); - this.ui.show(this); - this.visible = true; - this.update(); - } - hide() { - if (!this.visible) { - return; - } - this.ui.hide(); - } - didHide(reason = quickInput_1.QuickInputHideReason.Other) { - this.visible = false; - this.visibleDisposables.clear(); - this.onDidHideEmitter.fire({ reason }); - } - update() { - if (!this.visible) { - return; - } - const title = this.getTitle(); - if (title && this.ui.title.textContent !== title) { - this.ui.title.textContent = title; - } - else if (!title && this.ui.title.innerHTML !== ' ') { - this.ui.title.innerText = '\u00a0;'; - } - const description = this.getDescription(); - if (this.ui.description1.textContent !== description) { - this.ui.description1.textContent = description; - } - if (this.ui.description2.textContent !== description) { - this.ui.description2.textContent = description; - } - if (this.busy && !this.busyDelay) { - this.busyDelay = new async_1.TimeoutTimer(); - this.busyDelay.setIfNotSet(() => { - if (this.visible) { - this.ui.progressBar.infinite(); - } - }, 800); - } - if (!this.busy && this.busyDelay) { - this.ui.progressBar.stop(); - this.busyDelay.cancel(); - this.busyDelay = undefined; - } - if (this.buttonsUpdated) { - this.buttonsUpdated = false; - this.ui.leftActionBar.clear(); - const leftButtons = this.buttons.filter(button => button === backButton); - this.ui.leftActionBar.push(leftButtons.map((button, index) => { - const action = new actions_1.Action(`id-${index}`, '', button.iconClass || (0, quickInputUtils_1.getIconClass)(button.iconPath), true, () => __awaiter(this, void 0, void 0, function* () { - this.onDidTriggerButtonEmitter.fire(button); - })); - action.tooltip = button.tooltip || ''; - return action; - }), { icon: true, label: false }); - this.ui.rightActionBar.clear(); - const rightButtons = this.buttons.filter(button => button !== backButton); - this.ui.rightActionBar.push(rightButtons.map((button, index) => { - const action = new actions_1.Action(`id-${index}`, '', button.iconClass || (0, quickInputUtils_1.getIconClass)(button.iconPath), true, () => __awaiter(this, void 0, void 0, function* () { - this.onDidTriggerButtonEmitter.fire(button); - })); - action.tooltip = button.tooltip || ''; - return action; - }), { icon: true, label: false }); - } - this.ui.ignoreFocusOut = this.ignoreFocusOut; - this.ui.setEnabled(this.enabled); - this.ui.setContextKey(this.contextKey); - const validationMessage = this.validationMessage || this.noValidationMessage; - if (this._lastValidationMessage !== validationMessage) { - this._lastValidationMessage = validationMessage; - dom.reset(this.ui.message, ...(0, iconLabels_1.renderLabelWithIcons)(validationMessage)); - } - if (this._lastSeverity !== this.severity) { - this._lastSeverity = this.severity; - this.showMessageDecoration(this.severity); - } - } - getTitle() { - if (this.title && this.step) { - return `${this.title} (${this.getSteps()})`; - } - if (this.title) { - return this.title; - } - if (this.step) { - return this.getSteps(); - } - return ''; - } - getDescription() { - return this.description || ''; - } - getSteps() { - if (this.step && this.totalSteps) { - return (0, nls_1.localize)(2, null, this.step, this.totalSteps); - } - if (this.step) { - return String(this.step); - } - return ''; - } - showMessageDecoration(severity) { - this.ui.inputBox.showDecoration(severity); - if (severity !== severity_1.default.Ignore) { - const styles = this.ui.inputBox.stylesForType(severity); - this.ui.message.style.color = styles.foreground ? `${styles.foreground}` : ''; - this.ui.message.style.backgroundColor = styles.background ? `${styles.background}` : ''; - this.ui.message.style.border = styles.border ? `1px solid ${styles.border}` : ''; - this.ui.message.style.paddingBottom = '4px'; - } - else { - this.ui.message.style.color = ''; - this.ui.message.style.backgroundColor = ''; - this.ui.message.style.border = ''; - this.ui.message.style.paddingBottom = ''; - } - } - dispose() { - this.hide(); - this.onDisposeEmitter.fire(); - super.dispose(); - } - } - QuickInput.noPromptMessage = (0, nls_1.localize)(1, null); - class QuickPick extends QuickInput { - constructor() { - super(...arguments); - this._value = ''; - this.onDidChangeValueEmitter = this._register(new event_1.Emitter()); - this.onWillAcceptEmitter = this._register(new event_1.Emitter()); - this.onDidAcceptEmitter = this._register(new event_1.Emitter()); - this.onDidCustomEmitter = this._register(new event_1.Emitter()); - this._items = []; - this.itemsUpdated = false; - this._canSelectMany = false; - this._canAcceptInBackground = false; - this._matchOnDescription = false; - this._matchOnDetail = false; - this._matchOnLabel = true; - this._sortByLabel = true; - this._autoFocusOnList = true; - this._itemActivation = this.ui.isScreenReaderOptimized() ? quickInput_1.ItemActivation.NONE /* https://github.com/microsoft/vscode/issues/57501 */ : quickInput_1.ItemActivation.FIRST; - this._activeItems = []; - this.activeItemsUpdated = false; - this.activeItemsToConfirm = []; - this.onDidChangeActiveEmitter = this._register(new event_1.Emitter()); - this._selectedItems = []; - this.selectedItemsUpdated = false; - this.selectedItemsToConfirm = []; - this.onDidChangeSelectionEmitter = this._register(new event_1.Emitter()); - this.onDidTriggerItemButtonEmitter = this._register(new event_1.Emitter()); - this.valueSelectionUpdated = true; - this._ok = 'default'; - this._customButton = false; - this.filterValue = (value) => value; - this.onDidChangeValue = this.onDidChangeValueEmitter.event; - this.onWillAccept = this.onWillAcceptEmitter.event; - this.onDidAccept = this.onDidAcceptEmitter.event; - this.onDidChangeActive = this.onDidChangeActiveEmitter.event; - this.onDidChangeSelection = this.onDidChangeSelectionEmitter.event; - this.onDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event; - } - get quickNavigate() { - return this._quickNavigate; - } - set quickNavigate(quickNavigate) { - this._quickNavigate = quickNavigate; - this.update(); - } - get value() { - return this._value; - } - set value(value) { - if (this._value !== value) { - this._value = value || ''; - this.update(); - this.onDidChangeValueEmitter.fire(this._value); - } - } - set ariaLabel(ariaLabel) { - this._ariaLabel = ariaLabel; - this.update(); - } - get ariaLabel() { - return this._ariaLabel; - } - get placeholder() { - return this._placeholder; - } - set placeholder(placeholder) { - this._placeholder = placeholder; - this.update(); - } - get items() { - return this._items; - } - set items(items) { - this._items = items; - this.itemsUpdated = true; - this.update(); - } - get canSelectMany() { - return this._canSelectMany; - } - set canSelectMany(canSelectMany) { - this._canSelectMany = canSelectMany; - this.update(); - } - get canAcceptInBackground() { - return this._canAcceptInBackground; - } - set canAcceptInBackground(canAcceptInBackground) { - this._canAcceptInBackground = canAcceptInBackground; - } - get matchOnDescription() { - return this._matchOnDescription; - } - set matchOnDescription(matchOnDescription) { - this._matchOnDescription = matchOnDescription; - this.update(); - } - get matchOnDetail() { - return this._matchOnDetail; - } - set matchOnDetail(matchOnDetail) { - this._matchOnDetail = matchOnDetail; - this.update(); - } - get matchOnLabel() { - return this._matchOnLabel; - } - set matchOnLabel(matchOnLabel) { - this._matchOnLabel = matchOnLabel; - this.update(); - } - get sortByLabel() { - return this._sortByLabel; - } - set sortByLabel(sortByLabel) { - this._sortByLabel = sortByLabel; - this.update(); - } - get autoFocusOnList() { - return this._autoFocusOnList; - } - set autoFocusOnList(autoFocusOnList) { - this._autoFocusOnList = autoFocusOnList; - this.update(); - } - get itemActivation() { - return this._itemActivation; - } - set itemActivation(itemActivation) { - this._itemActivation = itemActivation; - } - get activeItems() { - return this._activeItems; - } - set activeItems(activeItems) { - this._activeItems = activeItems; - this.activeItemsUpdated = true; - this.update(); - } - get selectedItems() { - return this._selectedItems; - } - set selectedItems(selectedItems) { - this._selectedItems = selectedItems; - this.selectedItemsUpdated = true; - this.update(); - } - get keyMods() { - if (this._quickNavigate) { - // Disable keyMods when quick navigate is enabled - // because in this model the interaction is purely - // keyboard driven and Ctrl/Alt are typically - // pressed and hold during this interaction. - return quickInput_1.NO_KEY_MODS; - } - return this.ui.keyMods; - } - set valueSelection(valueSelection) { - this._valueSelection = valueSelection; - this.valueSelectionUpdated = true; - this.update(); - } - get customButton() { - return this._customButton; - } - set customButton(showCustomButton) { - this._customButton = showCustomButton; - this.update(); - } - get customLabel() { - return this._customButtonLabel; - } - set customLabel(label) { - this._customButtonLabel = label; - this.update(); - } - get customHover() { - return this._customButtonHover; - } - set customHover(hover) { - this._customButtonHover = hover; - this.update(); - } - get ok() { - return this._ok; - } - set ok(showOkButton) { - this._ok = showOkButton; - this.update(); - } - get hideInput() { - return !!this._hideInput; - } - set hideInput(hideInput) { - this._hideInput = hideInput; - this.update(); - } - trySelectFirst() { - if (this.autoFocusOnList) { - if (!this.canSelectMany) { - this.ui.list.focus(quickInputList_1.QuickInputListFocus.First); - } - } - } - show() { - if (!this.visible) { - this.visibleDisposables.add(this.ui.inputBox.onDidChange(value => { - if (value === this.value) { - return; - } - this._value = value; - const didFilter = this.ui.list.filter(this.filterValue(this.ui.inputBox.value)); - if (didFilter) { - this.trySelectFirst(); - } - this.onDidChangeValueEmitter.fire(value); - })); - this.visibleDisposables.add(this.ui.inputBox.onMouseDown(event => { - if (!this.autoFocusOnList) { - this.ui.list.clearFocus(); - } - })); - this.visibleDisposables.add((this._hideInput ? this.ui.list : this.ui.inputBox).onKeyDown((event) => { - switch (event.keyCode) { - case 18 /* DownArrow */: - this.ui.list.focus(quickInputList_1.QuickInputListFocus.Next); - if (this.canSelectMany) { - this.ui.list.domFocus(); - } - dom.EventHelper.stop(event, true); - break; - case 16 /* UpArrow */: - if (this.ui.list.getFocusedElements().length) { - this.ui.list.focus(quickInputList_1.QuickInputListFocus.Previous); - } - else { - this.ui.list.focus(quickInputList_1.QuickInputListFocus.Last); - } - if (this.canSelectMany) { - this.ui.list.domFocus(); - } - dom.EventHelper.stop(event, true); - break; - case 12 /* PageDown */: - this.ui.list.focus(quickInputList_1.QuickInputListFocus.NextPage); - if (this.canSelectMany) { - this.ui.list.domFocus(); - } - dom.EventHelper.stop(event, true); - break; - case 11 /* PageUp */: - this.ui.list.focus(quickInputList_1.QuickInputListFocus.PreviousPage); - if (this.canSelectMany) { - this.ui.list.domFocus(); - } - dom.EventHelper.stop(event, true); - break; - case 17 /* RightArrow */: - if (!this._canAcceptInBackground) { - return; // needs to be enabled - } - if (!this.ui.inputBox.isSelectionAtEnd()) { - return; // ensure input box selection at end - } - if (this.activeItems[0]) { - this._selectedItems = [this.activeItems[0]]; - this.onDidChangeSelectionEmitter.fire(this.selectedItems); - this.handleAccept(true); - } - break; - case 14 /* Home */: - if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey) { - this.ui.list.focus(quickInputList_1.QuickInputListFocus.First); - dom.EventHelper.stop(event, true); - } - break; - case 13 /* End */: - if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey) { - this.ui.list.focus(quickInputList_1.QuickInputListFocus.Last); - dom.EventHelper.stop(event, true); - } - break; - } - })); - this.visibleDisposables.add(this.ui.onDidAccept(() => { - if (!this.canSelectMany && this.activeItems[0]) { - this._selectedItems = [this.activeItems[0]]; - this.onDidChangeSelectionEmitter.fire(this.selectedItems); - } - this.handleAccept(false); - })); - this.visibleDisposables.add(this.ui.onDidCustom(() => { - this.onDidCustomEmitter.fire(); - })); - this.visibleDisposables.add(this.ui.list.onDidChangeFocus(focusedItems => { - if (this.activeItemsUpdated) { - return; // Expect another event. - } - if (this.activeItemsToConfirm !== this._activeItems && (0, arrays_1.equals)(focusedItems, this._activeItems, (a, b) => a === b)) { - return; - } - this._activeItems = focusedItems; - this.onDidChangeActiveEmitter.fire(focusedItems); - })); - this.visibleDisposables.add(this.ui.list.onDidChangeSelection(({ items: selectedItems, event }) => { - if (this.canSelectMany) { - if (selectedItems.length) { - this.ui.list.setSelectedElements([]); - } - return; - } - if (this.selectedItemsToConfirm !== this._selectedItems && (0, arrays_1.equals)(selectedItems, this._selectedItems, (a, b) => a === b)) { - return; - } - this._selectedItems = selectedItems; - this.onDidChangeSelectionEmitter.fire(selectedItems); - if (selectedItems.length) { - this.handleAccept(event instanceof MouseEvent && event.button === 1 /* mouse middle click */); - } - })); - this.visibleDisposables.add(this.ui.list.onChangedCheckedElements(checkedItems => { - if (!this.canSelectMany) { - return; - } - if (this.selectedItemsToConfirm !== this._selectedItems && (0, arrays_1.equals)(checkedItems, this._selectedItems, (a, b) => a === b)) { - return; - } - this._selectedItems = checkedItems; - this.onDidChangeSelectionEmitter.fire(checkedItems); - })); - this.visibleDisposables.add(this.ui.list.onButtonTriggered(event => this.onDidTriggerItemButtonEmitter.fire(event))); - this.visibleDisposables.add(this.registerQuickNavigation()); - this.valueSelectionUpdated = true; - } - super.show(); // TODO: Why have show() bubble up while update() trickles down? (Could move setComboboxAccessibility() here.) - } - handleAccept(inBackground) { - // Figure out veto via `onWillAccept` event - let veto = false; - this.onWillAcceptEmitter.fire({ veto: () => veto = true }); - // Continue with `onDidAccpet` if no veto - if (!veto) { - this.onDidAcceptEmitter.fire({ inBackground }); - } - } - registerQuickNavigation() { - return dom.addDisposableListener(this.ui.container, dom.EventType.KEY_UP, e => { - if (this.canSelectMany || !this._quickNavigate) { - return; - } - const keyboardEvent = new keyboardEvent_1.StandardKeyboardEvent(e); - const keyCode = keyboardEvent.keyCode; - // Select element when keys are pressed that signal it - const quickNavKeys = this._quickNavigate.keybindings; - const wasTriggerKeyPressed = quickNavKeys.some(k => { - const [firstPart, chordPart] = k.getParts(); - 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 input - } - 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) { - if (this.activeItems[0]) { - this._selectedItems = [this.activeItems[0]]; - this.onDidChangeSelectionEmitter.fire(this.selectedItems); - this.handleAccept(false); - } - // Unset quick navigate after press. It is only valid once - // and should not result in any behaviour change afterwards - // if the picker remains open because there was no active item - this._quickNavigate = undefined; - } - }); - } - update() { - if (!this.visible) { - return; - } - const hideInput = !!this._hideInput && this._items.length > 0; - this.ui.container.classList.toggle('hidden-input', hideInput && !this.description); - const visibilities = { - title: !!this.title || !!this.step || !!this.buttons.length, - description: !!this.description, - checkAll: this.canSelectMany && !this._hideCheckAll, - checkBox: this.canSelectMany, - inputBox: !hideInput, - progressBar: !hideInput, - visibleCount: true, - count: this.canSelectMany, - ok: this.ok === 'default' ? this.canSelectMany : this.ok, - list: true, - message: !!this.validationMessage, - customButton: this.customButton - }; - this.ui.setVisibilities(visibilities); - super.update(); - if (this.ui.inputBox.value !== this.value) { - this.ui.inputBox.value = this.value; - } - if (this.valueSelectionUpdated) { - this.valueSelectionUpdated = false; - this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); - } - if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { - this.ui.inputBox.placeholder = (this.placeholder || ''); - } - const ariaLabel = this.ariaLabel || this.placeholder || QuickPick.DEFAULT_ARIA_LABEL; - if (this.ui.inputBox.ariaLabel !== ariaLabel) { - this.ui.inputBox.ariaLabel = ariaLabel; - } - this.ui.list.matchOnDescription = this.matchOnDescription; - this.ui.list.matchOnDetail = this.matchOnDetail; - this.ui.list.matchOnLabel = this.matchOnLabel; - this.ui.list.sortByLabel = this.sortByLabel; - if (this.itemsUpdated) { - this.itemsUpdated = false; - this.ui.list.setElements(this.items); - this.ui.list.filter(this.filterValue(this.ui.inputBox.value)); - this.ui.checkAll.checked = this.ui.list.getAllVisibleChecked(); - this.ui.visibleCount.setCount(this.ui.list.getVisibleCount()); - this.ui.count.setCount(this.ui.list.getCheckedCount()); - switch (this._itemActivation) { - case quickInput_1.ItemActivation.NONE: - this._itemActivation = quickInput_1.ItemActivation.FIRST; // only valid once, then unset - break; - case quickInput_1.ItemActivation.SECOND: - this.ui.list.focus(quickInputList_1.QuickInputListFocus.Second); - this._itemActivation = quickInput_1.ItemActivation.FIRST; // only valid once, then unset - break; - case quickInput_1.ItemActivation.LAST: - this.ui.list.focus(quickInputList_1.QuickInputListFocus.Last); - this._itemActivation = quickInput_1.ItemActivation.FIRST; // only valid once, then unset - break; - default: - this.trySelectFirst(); - break; - } - } - if (this.ui.container.classList.contains('show-checkboxes') !== !!this.canSelectMany) { - if (this.canSelectMany) { - this.ui.list.clearFocus(); - } - else { - this.trySelectFirst(); - } - } - if (this.activeItemsUpdated) { - this.activeItemsUpdated = false; - this.activeItemsToConfirm = this._activeItems; - this.ui.list.setFocusedElements(this.activeItems); - if (this.activeItemsToConfirm === this._activeItems) { - this.activeItemsToConfirm = null; - } - } - if (this.selectedItemsUpdated) { - this.selectedItemsUpdated = false; - this.selectedItemsToConfirm = this._selectedItems; - if (this.canSelectMany) { - this.ui.list.setCheckedElements(this.selectedItems); - } - else { - this.ui.list.setSelectedElements(this.selectedItems); - } - if (this.selectedItemsToConfirm === this._selectedItems) { - this.selectedItemsToConfirm = null; - } - } - this.ui.customButton.label = this.customLabel || ''; - this.ui.customButton.element.title = this.customHover || ''; - this.ui.setComboboxAccessibility(true); - if (!visibilities.inputBox) { - // we need to move focus into the tree to detect keybindings - // properly when the input box is not visible (quick nav) - this.ui.list.domFocus(); - // Focus the first element in the list if multiselect is enabled - if (this.canSelectMany) { - this.ui.list.focus(quickInputList_1.QuickInputListFocus.First); - } - } - } - } - QuickPick.DEFAULT_ARIA_LABEL = (0, nls_1.localize)(3, null); - class QuickInputController extends lifecycle_1.Disposable { - constructor(options) { - super(); - this.options = options; - this.comboboxAccessibility = false; - this.enabled = true; - this.onDidAcceptEmitter = this._register(new event_1.Emitter()); - this.onDidCustomEmitter = this._register(new event_1.Emitter()); - this.onDidTriggerButtonEmitter = this._register(new event_1.Emitter()); - this.keyMods = { ctrlCmd: false, alt: false }; - this.controller = null; - this.onShowEmitter = this._register(new event_1.Emitter()); - this.onShow = this.onShowEmitter.event; - this.onHideEmitter = this._register(new event_1.Emitter()); - this.onHide = this.onHideEmitter.event; - this.idPrefix = options.idPrefix; - this.parentElement = options.container; - this.styles = options.styles; - this.registerKeyModsListeners(); - } - registerKeyModsListeners() { - const listener = (e) => { - this.keyMods.ctrlCmd = e.ctrlKey || e.metaKey; - this.keyMods.alt = e.altKey; - }; - this._register(dom.addDisposableListener(window, dom.EventType.KEY_DOWN, listener, true)); - this._register(dom.addDisposableListener(window, dom.EventType.KEY_UP, listener, true)); - this._register(dom.addDisposableListener(window, dom.EventType.MOUSE_DOWN, listener, true)); - } - getUI() { - if (this.ui) { - return this.ui; - } - const container = dom.append(this.parentElement, $('.quick-input-widget.show-file-icons')); - container.tabIndex = -1; - container.style.display = 'none'; - const styleSheet = dom.createStyleSheet(container); - const titleBar = dom.append(container, $('.quick-input-titlebar')); - const leftActionBar = this._register(new actionbar_1.ActionBar(titleBar)); - leftActionBar.domNode.classList.add('quick-input-left-action-bar'); - const title = dom.append(titleBar, $('.quick-input-title')); - const rightActionBar = this._register(new actionbar_1.ActionBar(titleBar)); - rightActionBar.domNode.classList.add('quick-input-right-action-bar'); - const description1 = dom.append(container, $('.quick-input-description')); - const headerContainer = dom.append(container, $('.quick-input-header')); - const checkAll = dom.append(headerContainer, $('input.quick-input-check-all')); - checkAll.type = 'checkbox'; - this._register(dom.addStandardDisposableListener(checkAll, dom.EventType.CHANGE, e => { - const checked = checkAll.checked; - list.setAllVisibleChecked(checked); - })); - this._register(dom.addDisposableListener(checkAll, dom.EventType.CLICK, e => { - if (e.x || e.y) { // Avoid 'click' triggered by 'space'... - inputBox.setFocus(); - } - })); - const description2 = dom.append(headerContainer, $('.quick-input-description')); - const extraContainer = dom.append(headerContainer, $('.quick-input-and-message')); - const filterContainer = dom.append(extraContainer, $('.quick-input-filter')); - const inputBox = this._register(new quickInputBox_1.QuickInputBox(filterContainer)); - inputBox.setAttribute('aria-describedby', `${this.idPrefix}message`); - const visibleCountContainer = dom.append(filterContainer, $('.quick-input-visible-count')); - visibleCountContainer.setAttribute('aria-live', 'polite'); - visibleCountContainer.setAttribute('aria-atomic', 'true'); - const visibleCount = new countBadge_1.CountBadge(visibleCountContainer, { countFormat: (0, nls_1.localize)(4, null) }); - const countContainer = dom.append(filterContainer, $('.quick-input-count')); - countContainer.setAttribute('aria-live', 'polite'); - const count = new countBadge_1.CountBadge(countContainer, { countFormat: (0, nls_1.localize)(5, null) }); - const okContainer = dom.append(headerContainer, $('.quick-input-action')); - const ok = new button_1.Button(okContainer); - ok.label = (0, nls_1.localize)(6, null); - this._register(ok.onDidClick(e => { - this.onDidAcceptEmitter.fire(); - })); - const customButtonContainer = dom.append(headerContainer, $('.quick-input-action')); - const customButton = new button_1.Button(customButtonContainer); - customButton.label = (0, nls_1.localize)(7, null); - this._register(customButton.onDidClick(e => { - this.onDidCustomEmitter.fire(); - })); - const message = dom.append(extraContainer, $(`#${this.idPrefix}message.quick-input-message`)); - const list = this._register(new quickInputList_1.QuickInputList(container, this.idPrefix + 'list', this.options)); - this._register(list.onChangedAllVisibleChecked(checked => { - checkAll.checked = checked; - })); - this._register(list.onChangedVisibleCount(c => { - visibleCount.setCount(c); - })); - this._register(list.onChangedCheckedCount(c => { - count.setCount(c); - })); - this._register(list.onLeave(() => { - // Defer to avoid the input field reacting to the triggering key. - setTimeout(() => { - inputBox.setFocus(); - if (this.controller instanceof QuickPick && this.controller.canSelectMany) { - list.clearFocus(); - } - }, 0); - })); - this._register(list.onDidChangeFocus(() => { - if (this.comboboxAccessibility) { - this.getUI().inputBox.setAttribute('aria-activedescendant', this.getUI().list.getActiveDescendant() || ''); - } - })); - const progressBar = new progressbar_1.ProgressBar(container); - progressBar.getContainer().classList.add('quick-input-progress'); - const focusTracker = dom.trackFocus(container); - this._register(focusTracker); - this._register(dom.addDisposableListener(container, dom.EventType.FOCUS, e => { - this.previousFocusElement = e.relatedTarget instanceof HTMLElement ? e.relatedTarget : undefined; - }, true)); - this._register(focusTracker.onDidBlur(() => { - if (!this.getUI().ignoreFocusOut && !this.options.ignoreFocusOut()) { - this.hide(quickInput_1.QuickInputHideReason.Blur); - } - this.previousFocusElement = undefined; - })); - this._register(dom.addDisposableListener(container, dom.EventType.FOCUS, (e) => { - inputBox.setFocus(); - })); - this._register(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, (e) => { - const event = new keyboardEvent_1.StandardKeyboardEvent(e); - switch (event.keyCode) { - case 3 /* Enter */: - dom.EventHelper.stop(e, true); - this.onDidAcceptEmitter.fire(); - break; - case 9 /* Escape */: - dom.EventHelper.stop(e, true); - this.hide(quickInput_1.QuickInputHideReason.Gesture); - break; - case 2 /* Tab */: - if (!event.altKey && !event.ctrlKey && !event.metaKey) { - const selectors = ['.action-label.codicon']; - if (container.classList.contains('show-checkboxes')) { - selectors.push('input'); - } - else { - selectors.push('input[type=text]'); - } - if (this.getUI().list.isDisplayed()) { - selectors.push('.monaco-list'); - } - const stops = container.querySelectorAll(selectors.join(', ')); - if (event.shiftKey && event.target === stops[0]) { - dom.EventHelper.stop(e, true); - stops[stops.length - 1].focus(); - } - else if (!event.shiftKey && event.target === stops[stops.length - 1]) { - dom.EventHelper.stop(e, true); - stops[0].focus(); - } - } - break; - } - })); - this.ui = { - container, - styleSheet, - leftActionBar, - titleBar, - title, - description1, - description2, - rightActionBar, - checkAll, - filterContainer, - inputBox, - visibleCountContainer, - visibleCount, - countContainer, - count, - okContainer, - ok, - message, - customButtonContainer, - customButton, - list, - progressBar, - onDidAccept: this.onDidAcceptEmitter.event, - onDidCustom: this.onDidCustomEmitter.event, - onDidTriggerButton: this.onDidTriggerButtonEmitter.event, - ignoreFocusOut: false, - keyMods: this.keyMods, - isScreenReaderOptimized: () => this.options.isScreenReaderOptimized(), - show: controller => this.show(controller), - hide: () => this.hide(), - setVisibilities: visibilities => this.setVisibilities(visibilities), - setComboboxAccessibility: enabled => this.setComboboxAccessibility(enabled), - setEnabled: enabled => this.setEnabled(enabled), - setContextKey: contextKey => this.options.setContextKey(contextKey), - }; - this.updateStyles(); - return this.ui; - } - pick(picks, options = {}, token = cancellation_1.CancellationToken.None) { - return new Promise((doResolve, reject) => { - let resolve = (result) => { - resolve = doResolve; - if (options.onKeyMods) { - options.onKeyMods(input.keyMods); - } - doResolve(result); - }; - if (token.isCancellationRequested) { - resolve(undefined); - return; - } - const input = this.createQuickPick(); - let activeItem; - const disposables = [ - input, - input.onDidAccept(() => { - if (input.canSelectMany) { - resolve(input.selectedItems.slice()); - input.hide(); - } - else { - const result = input.activeItems[0]; - if (result) { - resolve(result); - input.hide(); - } - } - }), - input.onDidChangeActive(items => { - const focused = items[0]; - if (focused && options.onDidFocus) { - options.onDidFocus(focused); - } - }), - input.onDidChangeSelection(items => { - if (!input.canSelectMany) { - const result = items[0]; - if (result) { - resolve(result); - input.hide(); - } - } - }), - input.onDidTriggerItemButton(event => options.onDidTriggerItemButton && options.onDidTriggerItemButton(Object.assign(Object.assign({}, event), { removeItem: () => { - const index = input.items.indexOf(event.item); - if (index !== -1) { - const items = input.items.slice(); - const removed = items.splice(index, 1); - const activeItems = input.activeItems.filter((ai) => ai !== removed[0]); - input.items = items; - if (activeItems) { - input.activeItems = activeItems; - } - } - } }))), - input.onDidChangeValue(value => { - if (activeItem && !value && (input.activeItems.length !== 1 || input.activeItems[0] !== activeItem)) { - input.activeItems = [activeItem]; - } - }), - token.onCancellationRequested(() => { - input.hide(); - }), - input.onDidHide(() => { - (0, lifecycle_1.dispose)(disposables); - resolve(undefined); - }), - ]; - input.title = options.title; - input.canSelectMany = !!options.canPickMany; - input.placeholder = options.placeHolder; - input.ignoreFocusOut = !!options.ignoreFocusLost; - input.matchOnDescription = !!options.matchOnDescription; - input.matchOnDetail = !!options.matchOnDetail; - input.matchOnLabel = (options.matchOnLabel === undefined) || options.matchOnLabel; // default to true - input.autoFocusOnList = (options.autoFocusOnList === undefined) || options.autoFocusOnList; // default to true - input.quickNavigate = options.quickNavigate; - input.contextKey = options.contextKey; - input.busy = true; - Promise.all([picks, options.activeItem]) - .then(([items, _activeItem]) => { - activeItem = _activeItem; - input.busy = false; - input.items = items; - if (input.canSelectMany) { - input.selectedItems = items.filter(item => item.type !== 'separator' && item.picked); - } - if (activeItem) { - input.activeItems = [activeItem]; - } - }); - input.show(); - Promise.resolve(picks).then(undefined, err => { - reject(err); - input.hide(); - }); - }); - } - createQuickPick() { - const ui = this.getUI(); - return new QuickPick(ui); - } - show(controller) { - const ui = this.getUI(); - this.onShowEmitter.fire(); - const oldController = this.controller; - this.controller = controller; - if (oldController) { - oldController.didHide(); - } - this.setEnabled(true); - ui.leftActionBar.clear(); - ui.title.textContent = ''; - ui.description1.textContent = ''; - ui.description2.textContent = ''; - ui.rightActionBar.clear(); - ui.checkAll.checked = false; - // ui.inputBox.value = ''; Avoid triggering an event. - ui.inputBox.placeholder = ''; - ui.inputBox.password = false; - ui.inputBox.showDecoration(severity_1.default.Ignore); - ui.visibleCount.setCount(0); - ui.count.setCount(0); - dom.reset(ui.message); - ui.progressBar.stop(); - ui.list.setElements([]); - ui.list.matchOnDescription = false; - ui.list.matchOnDetail = false; - ui.list.matchOnLabel = true; - ui.list.sortByLabel = true; - ui.ignoreFocusOut = false; - this.setComboboxAccessibility(false); - ui.inputBox.ariaLabel = ''; - const backKeybindingLabel = this.options.backKeybindingLabel(); - backButton.tooltip = backKeybindingLabel ? (0, nls_1.localize)(8, null, backKeybindingLabel) : (0, nls_1.localize)(9, null); - ui.container.style.display = ''; - this.updateLayout(); - ui.inputBox.setFocus(); - } - setVisibilities(visibilities) { - const ui = this.getUI(); - ui.title.style.display = visibilities.title ? '' : 'none'; - ui.description1.style.display = visibilities.description && (visibilities.inputBox || visibilities.checkAll) ? '' : 'none'; - ui.description2.style.display = visibilities.description && !(visibilities.inputBox || visibilities.checkAll) ? '' : 'none'; - ui.checkAll.style.display = visibilities.checkAll ? '' : 'none'; - ui.filterContainer.style.display = visibilities.inputBox ? '' : 'none'; - ui.visibleCountContainer.style.display = visibilities.visibleCount ? '' : 'none'; - ui.countContainer.style.display = visibilities.count ? '' : 'none'; - ui.okContainer.style.display = visibilities.ok ? '' : 'none'; - ui.customButtonContainer.style.display = visibilities.customButton ? '' : 'none'; - ui.message.style.display = visibilities.message ? '' : 'none'; - ui.progressBar.getContainer().style.display = visibilities.progressBar ? '' : 'none'; - ui.list.display(!!visibilities.list); - ui.container.classList[visibilities.checkBox ? 'add' : 'remove']('show-checkboxes'); - this.updateLayout(); // TODO - } - setComboboxAccessibility(enabled) { - if (enabled !== this.comboboxAccessibility) { - const ui = this.getUI(); - this.comboboxAccessibility = enabled; - if (this.comboboxAccessibility) { - ui.inputBox.setAttribute('role', 'combobox'); - ui.inputBox.setAttribute('aria-haspopup', 'true'); - ui.inputBox.setAttribute('aria-autocomplete', 'list'); - ui.inputBox.setAttribute('aria-activedescendant', ui.list.getActiveDescendant() || ''); - } - else { - ui.inputBox.removeAttribute('role'); - ui.inputBox.removeAttribute('aria-haspopup'); - ui.inputBox.removeAttribute('aria-autocomplete'); - ui.inputBox.removeAttribute('aria-activedescendant'); - } - } - } - setEnabled(enabled) { - if (enabled !== this.enabled) { - this.enabled = enabled; - for (const item of this.getUI().leftActionBar.viewItems) { - item.getAction().enabled = enabled; - } - for (const item of this.getUI().rightActionBar.viewItems) { - item.getAction().enabled = enabled; - } - this.getUI().checkAll.disabled = !enabled; - // this.getUI().inputBox.enabled = enabled; Avoid loosing focus. - this.getUI().ok.enabled = enabled; - this.getUI().list.enabled = enabled; - } - } - hide(reason) { - var _a; - const controller = this.controller; - if (controller) { - const focusChanged = !((_a = this.ui) === null || _a === void 0 ? void 0 : _a.container.contains(document.activeElement)); - this.controller = null; - this.onHideEmitter.fire(); - this.getUI().container.style.display = 'none'; - if (!focusChanged) { - if (this.previousFocusElement && this.previousFocusElement.offsetParent) { - this.previousFocusElement.focus(); - this.previousFocusElement = undefined; - } - else { - this.options.returnFocus(); - } - } - controller.didHide(reason); - } - } - layout(dimension, titleBarOffset) { - this.dimension = dimension; - this.titleBarOffset = titleBarOffset; - this.updateLayout(); - } - updateLayout() { - if (this.ui) { - this.ui.container.style.top = `${this.titleBarOffset}px`; - const style = this.ui.container.style; - const width = Math.min(this.dimension.width * 0.62 /* golden cut */, QuickInputController.MAX_WIDTH); - style.width = width + 'px'; - style.marginLeft = '-' + (width / 2) + 'px'; - this.ui.inputBox.layout(); - this.ui.list.layout(this.dimension && this.dimension.height * 0.4); - } - } - applyStyles(styles) { - this.styles = styles; - this.updateStyles(); - } - updateStyles() { - if (this.ui) { - const { quickInputTitleBackground, quickInputBackground, quickInputForeground, contrastBorder, widgetShadow, } = this.styles.widget; - this.ui.titleBar.style.backgroundColor = quickInputTitleBackground ? quickInputTitleBackground.toString() : ''; - this.ui.container.style.backgroundColor = quickInputBackground ? quickInputBackground.toString() : ''; - this.ui.container.style.color = quickInputForeground ? quickInputForeground.toString() : ''; - this.ui.container.style.border = contrastBorder ? `1px solid ${contrastBorder}` : ''; - this.ui.container.style.boxShadow = widgetShadow ? `0 0 8px 2px ${widgetShadow}` : ''; - this.ui.inputBox.style(this.styles.inputBox); - this.ui.count.style(this.styles.countBadge); - this.ui.ok.style(this.styles.button); - this.ui.customButton.style(this.styles.button); - this.ui.progressBar.style(this.styles.progressBar); - this.ui.list.style(this.styles.list); - const content = []; - if (this.styles.list.pickerGroupBorder) { - content.push(`.quick-input-list .quick-input-list-entry { border-top-color: ${this.styles.list.pickerGroupBorder}; }`); - } - if (this.styles.list.pickerGroupForeground) { - content.push(`.quick-input-list .quick-input-list-separator { color: ${this.styles.list.pickerGroupForeground}; }`); - } - if (this.styles.keybindingLabel.keybindingLabelBackground || - this.styles.keybindingLabel.keybindingLabelBorder || - this.styles.keybindingLabel.keybindingLabelBottomBorder || - this.styles.keybindingLabel.keybindingLabelShadow || - this.styles.keybindingLabel.keybindingLabelForeground) { - content.push('.quick-input-list .monaco-keybinding > .monaco-keybinding-key {'); - if (this.styles.keybindingLabel.keybindingLabelBackground) { - content.push(`background-color: ${this.styles.keybindingLabel.keybindingLabelBackground};`); - } - if (this.styles.keybindingLabel.keybindingLabelBorder) { - // Order matters here. `border-color` must come before `border-bottom-color`. - content.push(`border-color: ${this.styles.keybindingLabel.keybindingLabelBorder};`); - } - if (this.styles.keybindingLabel.keybindingLabelBottomBorder) { - content.push(`border-bottom-color: ${this.styles.keybindingLabel.keybindingLabelBottomBorder};`); - } - if (this.styles.keybindingLabel.keybindingLabelShadow) { - content.push(`box-shadow: inset 0 -1px 0 ${this.styles.keybindingLabel.keybindingLabelShadow};`); - } - if (this.styles.keybindingLabel.keybindingLabelForeground) { - content.push(`color: ${this.styles.keybindingLabel.keybindingLabelForeground};`); - } - content.push('}'); - } - const newStyles = content.join('\n'); - if (newStyles !== this.ui.styleSheet.textContent) { - this.ui.styleSheet.textContent = newStyles; - } - } - } - } - exports.QuickInputController = QuickInputController; - QuickInputController.MAX_WIDTH = 600; // Max total width of quick input widget -}); - -define(__m[454/*vs/nls!vs/editor/browser/controller/coreCommands*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/controller/coreCommands", data); }); -define(__m[455/*vs/nls!vs/editor/browser/controller/textAreaHandler*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/controller/textAreaHandler", data); }); -define(__m[456/*vs/nls!vs/editor/browser/core/keybindingCancellation*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/core/keybindingCancellation", data); }); -define(__m[457/*vs/nls!vs/editor/browser/editorExtensions*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/editorExtensions", data); }); -define(__m[458/*vs/nls!vs/editor/browser/widget/codeEditorWidget*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/widget/codeEditorWidget", data); }); -define(__m[459/*vs/nls!vs/editor/browser/widget/diffEditorWidget*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/widget/diffEditorWidget", data); }); -define(__m[460/*vs/nls!vs/editor/browser/widget/diffReview*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/widget/diffReview", data); }); -define(__m[461/*vs/nls!vs/editor/browser/widget/inlineDiffMargin*/], __M([4/*vs/nls*/,5/*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[462/*vs/editor/browser/widget/inlineDiffMargin*/], __M([0/*require*/,1/*exports*/,461/*vs/nls!vs/editor/browser/widget/inlineDiffMargin*/,7/*vs/base/browser/dom*/,50/*vs/base/common/actions*/,2/*vs/base/common/lifecycle*/,3/*vs/editor/common/core/range*/,27/*vs/base/common/codicons*/]), function (require, exports, nls, dom, actions_1, lifecycle_1, range_1, codicons_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.InlineDiffMargin = void 0; - class InlineDiffMargin extends lifecycle_1.Disposable { - constructor(_viewZoneId, _marginDomNode, editor, diff, _contextMenuService, _clipboardService) { - super(); - 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 = codicons_1.Codicon.lightBulb.classNames + ' lightbulb-glyph'; - this._diffActions.style.position = 'absolute'; - const lineHeight = editor.getOption(57 /* lineHeight */); - const 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); - const 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, () => __awaiter(this, void 0, void 0, function* () { - const range = new range_1.Range(diff.originalStartLineNumber, 1, diff.originalEndLineNumber + 1, 1); - const deletedText = diff.originalModel.getValueInRange(range); - yield this._clipboardService.writeText(deletedText); - }))); - let currentLineNumberOffset = 0; - let copyLineAction = undefined; - if (diff.originalEndLineNumber > diff.modifiedStartLineNumber) { - copyLineAction = new actions_1.Action('diff.clipboard.copyDeletedLineContent', nls.localize(2, null, diff.originalStartLineNumber), undefined, true, () => __awaiter(this, void 0, void 0, function* () { - const lineContent = diff.originalModel.getLineContent(diff.originalStartLineNumber + currentLineNumberOffset); - yield this._clipboardService.writeText(lineContent); - })); - actions.push(copyLineAction); - } - const readOnly = editor.getOption(79 /* readOnly */); - if (!readOnly) { - actions.push(new actions_1.Action('diff.inline.revertChange', nls.localize(3, null), undefined, true, () => __awaiter(this, void 0, void 0, function* () { - const range = new range_1.Range(diff.originalStartLineNumber, 1, diff.originalEndLineNumber, diff.originalModel.getLineMaxColumn(diff.originalEndLineNumber)); - const deletedText = diff.originalModel.getValueInRange(range); - if (diff.modifiedEndLineNumber === 0) { - // deletion only - const column = editor.getModel().getLineMaxColumn(diff.modifiedStartLineNumber); - editor.executeEdits('diffEditor', [ - { - range: new range_1.Range(diff.modifiedStartLineNumber, column, diff.modifiedStartLineNumber, column), - text: lineFeed + deletedText - } - ]); - } - else { - const column = editor.getModel().getLineMaxColumn(diff.modifiedEndLineNumber); - editor.executeEdits('diffEditor', [ - { - range: new range_1.Range(diff.modifiedStartLineNumber, 1, diff.modifiedEndLineNumber, column), - text: deletedText - } - ]); - } - }))); - } - const showContextMenu = (x, y) => { - this._contextMenuService.showContextMenu({ - getAnchor: () => { - return { - x, - y - }; - }, - getActions: () => { - if (copyLineAction) { - copyLineAction.label = nls.localize(4, null, diff.originalStartLineNumber + currentLineNumberOffset); - } - return actions; - }, - autoSelectFirstItem: true - }); - }; - this._register(dom.addStandardDisposableListener(this._diffActions, 'mousedown', e => { - const { top, height } = dom.getDomNodePagePosition(this._diffActions); - let pad = Math.floor(lineHeight / 3); - e.preventDefault(); - showContextMenu(e.posx, top + height + pad); - })); - this._register(editor.onMouseMove((e) => { - if (e.target.type === 8 /* CONTENT_VIEW_ZONE */ || e.target.type === 5 /* GUTTER_VIEW_ZONE */) { - const 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((e) => { - if (!e.event.rightButton) { - return; - } - if (e.target.type === 8 /* CONTENT_VIEW_ZONE */ || e.target.type === 5 /* GUTTER_VIEW_ZONE */) { - const 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); - } - } - })); - } - get visibility() { - return this._visibility; - } - set visibility(_visibility) { - if (this._visibility !== _visibility) { - this._visibility = _visibility; - if (_visibility) { - this._diffActions.style.visibility = 'visible'; - } - else { - this._diffActions.style.visibility = 'hidden'; - } - } - } - _updateLightBulbPosition(marginDomNode, y, lineHeight) { - const { top } = dom.getDomNodePagePosition(marginDomNode); - const offset = y - top; - const lineNumberOffset = Math.floor(offset / lineHeight); - const newTop = lineNumberOffset * lineHeight; - this._diffActions.style.top = `${newTop}px`; - if (this.diff.viewLineCounts) { - let acc = 0; - for (let i = 0; i < this.diff.viewLineCounts.length; i++) { - acc += this.diff.viewLineCounts[i]; - if (lineNumberOffset < acc) { - return i; - } - } - } - return lineNumberOffset; - } - } - exports.InlineDiffMargin = InlineDiffMargin; -}); - -define(__m[463/*vs/nls!vs/editor/common/config/commonEditorConfig*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/config/commonEditorConfig", data); }); -define(__m[464/*vs/nls!vs/editor/common/config/editorOptions*/], __M([4/*vs/nls*/,5/*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[35/*vs/editor/common/config/editorOptions*/], __M([0/*require*/,1/*exports*/,464/*vs/nls!vs/editor/common/config/editorOptions*/,17/*vs/base/common/platform*/,135/*vs/editor/common/model/wordHelper*/]), function (require, exports, nls, platform, wordHelper_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.EditorOptions = exports.editorOptionsRegistry = exports.EDITOR_MODEL_DEFAULTS = exports.EDITOR_FONT_DEFAULTS = exports.filterValidationDecorations = exports.EditorLayoutInfoComputer = exports.EditorFontLigatures = exports.TextEditorCursorStyle = exports.stringSet = exports.boolean = exports.ComputeOptionsMemory = exports.ValidatedEditorOptions = exports.ConfigurationChangedEvent = exports.MINIMAP_GUTTER_WIDTH = void 0; - /** - * @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. - */ - class ConfigurationChangedEvent { - /** - * @internal - */ - constructor(values) { - this._values = values; - } - hasChanged(id) { - return this._values[id]; - } - } - exports.ConfigurationChangedEvent = ConfigurationChangedEvent; - /** - * @internal - */ - class ValidatedEditorOptions { - constructor() { - this._values = []; - } - _read(option) { - return this._values[option]; - } - get(id) { - return this._values[id]; - } - _write(option, value) { - this._values[option] = value; - } - } - exports.ValidatedEditorOptions = ValidatedEditorOptions; - /** - * @internal - */ - class ComputeOptionsMemory { - constructor() { - this.stableMinimapLayoutInput = null; - this.stableFitMaxMinimapScale = 0; - this.stableFitRemainingWidth = 0; - } - } - exports.ComputeOptionsMemory = ComputeOptionsMemory; - /** - * @internal - */ - class BaseEditorOption { - constructor(id, name, defaultValue, schema) { - this.id = id; - this.name = name; - this.defaultValue = defaultValue; - this.schema = schema; - } - compute(env, options, value) { - return value; - } - } - /** - * @internal - */ - class ComputedEditorOption { - constructor(id, deps = null) { - this.schema = undefined; - this.id = id; - this.name = '_never_'; - this.defaultValue = undefined; - this.deps = deps; - } - validate(input) { - return this.defaultValue; - } - } - class SimpleEditorOption { - constructor(id, name, defaultValue, schema) { - this.id = id; - this.name = name; - this.defaultValue = defaultValue; - this.schema = schema; - } - validate(input) { - if (typeof input === 'undefined') { - return this.defaultValue; - } - return input; - } - compute(env, options, value) { - return value; - } - } - /** - * @internal - */ - function boolean(value, defaultValue) { - if (typeof value === 'undefined') { - return defaultValue; - } - if (value === 'false') { - // treat the string 'false' as false - return false; - } - return Boolean(value); - } - exports.boolean = boolean; - class EditorBooleanOption extends SimpleEditorOption { - constructor(id, name, defaultValue, schema = undefined) { - if (typeof schema !== 'undefined') { - schema.type = 'boolean'; - schema.default = defaultValue; - } - super(id, name, defaultValue, schema); - } - validate(input) { - return boolean(input, this.defaultValue); - } - } - class EditorIntOption extends SimpleEditorOption { - constructor(id, name, defaultValue, minimum, maximum, schema = undefined) { - if (typeof schema !== 'undefined') { - schema.type = 'integer'; - schema.default = defaultValue; - schema.minimum = minimum; - schema.maximum = maximum; - } - super(id, name, defaultValue, schema); - this.minimum = minimum; - this.maximum = maximum; - } - static clampedInt(value, defaultValue, minimum, maximum) { - if (typeof value === 'undefined') { - return defaultValue; - } - let r = parseInt(value, 10); - if (isNaN(r)) { - return defaultValue; - } - r = Math.max(minimum, r); - r = Math.min(maximum, r); - return r | 0; - } - validate(input) { - return EditorIntOption.clampedInt(input, this.defaultValue, this.minimum, this.maximum); - } - } - class EditorFloatOption extends SimpleEditorOption { - constructor(id, name, defaultValue, validationFn, schema) { - if (typeof schema !== 'undefined') { - schema.type = 'number'; - schema.default = defaultValue; - } - super(id, name, defaultValue, schema); - this.validationFn = validationFn; - } - static clamp(n, min, max) { - if (n < min) { - return min; - } - if (n > max) { - return max; - } - return n; - } - static float(value, defaultValue) { - if (typeof value === 'number') { - return value; - } - if (typeof value === 'undefined') { - return defaultValue; - } - const r = parseFloat(value); - return (isNaN(r) ? defaultValue : r); - } - validate(input) { - return this.validationFn(EditorFloatOption.float(input, this.defaultValue)); - } - } - class EditorStringOption extends SimpleEditorOption { - static string(value, defaultValue) { - if (typeof value !== 'string') { - return defaultValue; - } - return value; - } - constructor(id, name, defaultValue, schema = undefined) { - if (typeof schema !== 'undefined') { - schema.type = 'string'; - schema.default = defaultValue; - } - super(id, name, defaultValue, schema); - } - validate(input) { - return EditorStringOption.string(input, this.defaultValue); - } - } - /** - * @internal - */ - function stringSet(value, defaultValue, allowedValues) { - if (typeof value !== 'string') { - return defaultValue; - } - if (allowedValues.indexOf(value) === -1) { - return defaultValue; - } - return value; - } - exports.stringSet = stringSet; - class EditorStringEnumOption extends SimpleEditorOption { - constructor(id, name, defaultValue, allowedValues, schema = undefined) { - if (typeof schema !== 'undefined') { - schema.type = 'string'; - schema.enum = allowedValues; - schema.default = defaultValue; - } - super(id, name, defaultValue, schema); - this._allowedValues = allowedValues; - } - validate(input) { - return stringSet(input, this.defaultValue, this._allowedValues); - } - } - class EditorEnumOption extends BaseEditorOption { - constructor(id, name, defaultValue, defaultStringValue, allowedValues, convert, schema = undefined) { - if (typeof schema !== 'undefined') { - schema.type = 'string'; - schema.enum = allowedValues; - schema.default = defaultStringValue; - } - super(id, name, defaultValue, schema); - this._allowedValues = allowedValues; - this._convert = convert; - } - validate(input) { - if (typeof input !== 'string') { - return this.defaultValue; - } - if (this._allowedValues.indexOf(input) === -1) { - return this.defaultValue; - } - return this._convert(input); - } - } - //#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 - class EditorAccessibilitySupport extends BaseEditorOption { - constructor() { - super(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) - }); - } - validate(input) { - switch (input) { - case 'auto': return 0 /* Unknown */; - case 'off': return 1 /* Disabled */; - case 'on': return 2 /* Enabled */; - } - return this.defaultValue; - } - compute(env, options, value) { - if (value === 0 /* Unknown */) { - // The editor reads the `accessibilitySupport` from the environment - return env.accessibilitySupport; - } - return value; - } - } - class EditorComments extends BaseEditorOption { - constructor() { - const defaults = { - insertSpace: true, - ignoreEmptyLines: true, - }; - super(17 /* comments */, 'comments', defaults, { - 'editor.comments.insertSpace': { - type: 'boolean', - default: defaults.insertSpace, - description: nls.localize(4, null) - }, - 'editor.comments.ignoreEmptyLines': { - type: 'boolean', - default: defaults.ignoreEmptyLines, - description: nls.localize(5, null) - }, - }); - } - validate(_input) { - if (!_input || typeof _input !== 'object') { - return this.defaultValue; - } - const input = _input; - return { - insertSpace: boolean(input.insertSpace, this.defaultValue.insertSpace), - ignoreEmptyLines: boolean(input.ignoreEmptyLines, this.defaultValue.ignoreEmptyLines), - }; - } - } - 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 - class EditorClassName extends ComputedEditorOption { - constructor() { - super(126 /* editorClassName */, [64 /* mouseStyle */, 31 /* extraEditorClassName */]); - } - compute(env, options, _) { - const classNames = ['monaco-editor']; - if (options.get(31 /* extraEditorClassName */)) { - classNames.push(options.get(31 /* extraEditorClassName */)); - } - if (env.extraEditorClassName) { - classNames.push(env.extraEditorClassName); - } - if (options.get(64 /* mouseStyle */) === 'default') { - classNames.push('mouse-default'); - } - else if (options.get(64 /* mouseStyle */) === 'copy') { - classNames.push('mouse-copy'); - } - if (options.get(99 /* showUnused */)) { - classNames.push('showUnused'); - } - if (options.get(124 /* showDeprecated */)) { - classNames.push('showDeprecated'); - } - return classNames.join(' '); - } - } - //#endregion - //#region emptySelectionClipboard - class EditorEmptySelectionClipboard extends EditorBooleanOption { - constructor() { - super(30 /* emptySelectionClipboard */, 'emptySelectionClipboard', true, { description: nls.localize(6, null) }); - } - compute(env, options, value) { - return value && env.emptySelectionClipboard; - } - } - class EditorFind extends BaseEditorOption { - constructor() { - const defaults = { - cursorMoveOnType: true, - seedSearchStringFromSelection: 'always', - autoFindInSelection: 'never', - globalFindClipboard: false, - addExtraSpaceOnTop: true, - loop: true - }; - super(33 /* find */, 'find', defaults, { - 'editor.find.cursorMoveOnType': { - type: 'boolean', - default: defaults.cursorMoveOnType, - description: nls.localize(7, null) - }, - 'editor.find.seedSearchStringFromSelection': { - type: 'string', - enum: ['never', 'always', 'selection'], - default: defaults.seedSearchStringFromSelection, - enumDescriptions: [ - nls.localize(8, null), - nls.localize(9, null), - nls.localize(10, null) - ], - description: nls.localize(11, null) - }, - 'editor.find.autoFindInSelection': { - type: 'string', - enum: ['never', 'always', 'multiline'], - default: defaults.autoFindInSelection, - enumDescriptions: [ - nls.localize(12, null), - nls.localize(13, null), - nls.localize(14, null) - ], - description: nls.localize(15, null) - }, - 'editor.find.globalFindClipboard': { - type: 'boolean', - default: defaults.globalFindClipboard, - description: nls.localize(16, null), - included: platform.isMacintosh - }, - 'editor.find.addExtraSpaceOnTop': { - type: 'boolean', - default: defaults.addExtraSpaceOnTop, - description: nls.localize(17, null) - }, - 'editor.find.loop': { - type: 'boolean', - default: defaults.loop, - description: nls.localize(18, null) - }, - }); - } - validate(_input) { - if (!_input || typeof _input !== 'object') { - return this.defaultValue; - } - const input = _input; - return { - cursorMoveOnType: boolean(input.cursorMoveOnType, this.defaultValue.cursorMoveOnType), - seedSearchStringFromSelection: typeof _input.seedSearchStringFromSelection === 'boolean' - ? (_input.seedSearchStringFromSelection ? 'always' : 'never') - : stringSet(input.seedSearchStringFromSelection, this.defaultValue.seedSearchStringFromSelection, ['never', 'always', 'selection']), - autoFindInSelection: typeof _input.autoFindInSelection === 'boolean' - ? (_input.autoFindInSelection ? 'always' : 'never') - : stringSet(input.autoFindInSelection, this.defaultValue.autoFindInSelection, ['never', 'always', 'multiline']), - globalFindClipboard: boolean(input.globalFindClipboard, this.defaultValue.globalFindClipboard), - addExtraSpaceOnTop: boolean(input.addExtraSpaceOnTop, this.defaultValue.addExtraSpaceOnTop), - loop: boolean(input.loop, this.defaultValue.loop), - }; - } - } - //#endregion - //#region fontLigatures - /** - * @internal - */ - class EditorFontLigatures extends BaseEditorOption { - constructor() { - super(42 /* fontLigatures */, 'fontLigatures', EditorFontLigatures.OFF, { - anyOf: [ - { - type: 'boolean', - description: nls.localize(19, null), - }, - { - type: 'string', - description: nls.localize(20, null) - } - ], - description: nls.localize(21, null), - default: false - }); - } - validate(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; - } - } - exports.EditorFontLigatures = EditorFontLigatures; - EditorFontLigatures.OFF = '"liga" off, "calt" off'; - EditorFontLigatures.ON = '"liga" on, "calt" on'; - //#endregion - //#region fontInfo - class EditorFontInfo extends ComputedEditorOption { - constructor() { - super(41 /* fontInfo */); - } - compute(env, options, _) { - return env.fontInfo; - } - } - //#endregion - //#region fontSize - class EditorFontSize extends SimpleEditorOption { - constructor() { - super(43 /* fontSize */, 'fontSize', exports.EDITOR_FONT_DEFAULTS.fontSize, { - type: 'number', - minimum: 6, - maximum: 100, - default: exports.EDITOR_FONT_DEFAULTS.fontSize, - description: nls.localize(22, null) - }); - } - validate(input) { - let r = EditorFloatOption.float(input, this.defaultValue); - if (r === 0) { - return exports.EDITOR_FONT_DEFAULTS.fontSize; - } - return EditorFloatOption.clamp(r, 6, 100); - } - compute(env, options, value) { - // The final fontSize respects the editor zoom level. - // So take the result from env.fontInfo - return env.fontInfo.fontSize; - } - } - //#endregion - //#region fontWeight - class EditorFontWeight extends BaseEditorOption { - constructor() { - super(44 /* fontWeight */, 'fontWeight', exports.EDITOR_FONT_DEFAULTS.fontWeight, { - anyOf: [ - { - type: 'number', - minimum: EditorFontWeight.MINIMUM_VALUE, - maximum: EditorFontWeight.MAXIMUM_VALUE, - errorMessage: nls.localize(23, null) - }, - { - type: 'string', - pattern: '^(normal|bold|1000|[1-9][0-9]{0,2})$' - }, - { - enum: EditorFontWeight.SUGGESTION_VALUES - } - ], - default: exports.EDITOR_FONT_DEFAULTS.fontWeight, - description: nls.localize(24, null) - }); - } - validate(input) { - if (input === 'normal' || input === 'bold') { - return input; - } - return String(EditorIntOption.clampedInt(input, exports.EDITOR_FONT_DEFAULTS.fontWeight, EditorFontWeight.MINIMUM_VALUE, EditorFontWeight.MAXIMUM_VALUE)); - } - } - EditorFontWeight.SUGGESTION_VALUES = ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900']; - EditorFontWeight.MINIMUM_VALUE = 1; - EditorFontWeight.MAXIMUM_VALUE = 1000; - class EditorGoToLocation extends BaseEditorOption { - constructor() { - const 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: '', - }; - const jsonSubset = { - type: 'string', - enum: ['peek', 'gotoAndPeek', 'goto'], - default: defaults.multiple, - enumDescriptions: [ - nls.localize(25, null), - nls.localize(26, null), - nls.localize(27, null) - ] - }; - const alternativeCommandOptions = ['', 'editor.action.referenceSearch.trigger', 'editor.action.goToReferences', 'editor.action.peekImplementation', 'editor.action.goToImplementation', 'editor.action.peekTypeDefinition', 'editor.action.goToTypeDefinition', 'editor.action.peekDeclaration', 'editor.action.revealDeclaration', 'editor.action.peekDefinition', 'editor.action.revealDefinitionAside', 'editor.action.revealDefinition']; - super(48 /* gotoLocation */, 'gotoLocation', defaults, { - 'editor.gotoLocation.multiple': { - deprecationMessage: nls.localize(28, null), - }, - 'editor.gotoLocation.multipleDefinitions': Object.assign({ description: nls.localize(29, null) }, jsonSubset), - 'editor.gotoLocation.multipleTypeDefinitions': Object.assign({ description: nls.localize(30, null) }, jsonSubset), - 'editor.gotoLocation.multipleDeclarations': Object.assign({ description: nls.localize(31, null) }, jsonSubset), - 'editor.gotoLocation.multipleImplementations': Object.assign({ description: nls.localize(32, null) }, jsonSubset), - 'editor.gotoLocation.multipleReferences': Object.assign({ description: nls.localize(33, null) }, jsonSubset), - 'editor.gotoLocation.alternativeDefinitionCommand': { - type: 'string', - default: defaults.alternativeDefinitionCommand, - enum: alternativeCommandOptions, - description: nls.localize(34, null) - }, - 'editor.gotoLocation.alternativeTypeDefinitionCommand': { - type: 'string', - default: defaults.alternativeTypeDefinitionCommand, - enum: alternativeCommandOptions, - description: nls.localize(35, null) - }, - 'editor.gotoLocation.alternativeDeclarationCommand': { - type: 'string', - default: defaults.alternativeDeclarationCommand, - enum: alternativeCommandOptions, - description: nls.localize(36, null) - }, - 'editor.gotoLocation.alternativeImplementationCommand': { - type: 'string', - default: defaults.alternativeImplementationCommand, - enum: alternativeCommandOptions, - description: nls.localize(37, null) - }, - 'editor.gotoLocation.alternativeReferenceCommand': { - type: 'string', - default: defaults.alternativeReferenceCommand, - enum: alternativeCommandOptions, - description: nls.localize(38, null) - }, - }); - } - validate(_input) { - var _a, _b, _c, _d, _e; - if (!_input || typeof _input !== 'object') { - return this.defaultValue; - } - const input = _input; - return { - multiple: stringSet(input.multiple, this.defaultValue.multiple, ['peek', 'gotoAndPeek', 'goto']), - multipleDefinitions: (_a = input.multipleDefinitions) !== null && _a !== void 0 ? _a : stringSet(input.multipleDefinitions, 'peek', ['peek', 'gotoAndPeek', 'goto']), - multipleTypeDefinitions: (_b = input.multipleTypeDefinitions) !== null && _b !== void 0 ? _b : stringSet(input.multipleTypeDefinitions, 'peek', ['peek', 'gotoAndPeek', 'goto']), - multipleDeclarations: (_c = input.multipleDeclarations) !== null && _c !== void 0 ? _c : stringSet(input.multipleDeclarations, 'peek', ['peek', 'gotoAndPeek', 'goto']), - multipleImplementations: (_d = input.multipleImplementations) !== null && _d !== void 0 ? _d : stringSet(input.multipleImplementations, 'peek', ['peek', 'gotoAndPeek', 'goto']), - multipleReferences: (_e = input.multipleReferences) !== null && _e !== void 0 ? _e : 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), - }; - } - } - class EditorHover extends BaseEditorOption { - constructor() { - const defaults = { - enabled: true, - delay: 300, - sticky: true - }; - super(51 /* hover */, 'hover', defaults, { - 'editor.hover.enabled': { - type: 'boolean', - default: defaults.enabled, - description: nls.localize(39, null) - }, - 'editor.hover.delay': { - type: 'number', - default: defaults.delay, - description: nls.localize(40, null) - }, - 'editor.hover.sticky': { - type: 'boolean', - default: defaults.sticky, - description: nls.localize(41, null) - }, - }); - } - validate(_input) { - if (!_input || typeof _input !== 'object') { - return this.defaultValue; - } - const input = _input; - return { - enabled: boolean(input.enabled, this.defaultValue.enabled), - delay: EditorIntOption.clampedInt(input.delay, this.defaultValue.delay, 0, 10000), - sticky: boolean(input.sticky, this.defaultValue.sticky) - }; - } - } - /** - * @internal - */ - class EditorLayoutInfoComputer extends ComputedEditorOption { - constructor() { - super(129 /* layoutInfo */, [ - 47 /* glyphMargin */, 56 /* lineDecorationsWidth */, 35 /* folding */, - 63 /* minimap */, 91 /* scrollbar */, 58 /* lineNumbers */, - 59 /* lineNumbersMinChars */, 93 /* scrollBeyondLastLine */, - 116 /* wordWrap */, 119 /* wordWrapColumn */, 120 /* wordWrapOverride1 */, 121 /* wordWrapOverride2 */, - 2 /* accessibilitySupport */ - ]); - } - compute(env, options, _) { - return EditorLayoutInfoComputer.computeLayout(options, { - memory: env.memory, - outerWidth: env.outerWidth, - outerHeight: env.outerHeight, - isDominatedByLongLines: env.isDominatedByLongLines, - lineHeight: env.fontInfo.lineHeight, - viewLineCount: env.viewLineCount, - lineNumbersDigitCount: env.lineNumbersDigitCount, - typicalHalfwidthCharacterWidth: env.fontInfo.typicalHalfwidthCharacterWidth, - maxDigitWidth: env.fontInfo.maxDigitWidth, - pixelRatio: env.pixelRatio - }); - } - static computeContainedMinimapLineCount(input) { - const typicalViewportLineCount = input.height / input.lineHeight; - const extraLinesBeyondLastLine = input.scrollBeyondLastLine ? (typicalViewportLineCount - 1) : 0; - const desiredRatio = (input.viewLineCount + extraLinesBeyondLastLine) / (input.pixelRatio * input.height); - const minimapLineCount = Math.floor(input.viewLineCount / desiredRatio); - return { typicalViewportLineCount, extraLinesBeyondLastLine, desiredRatio, minimapLineCount }; - } - static _computeMinimapLayout(input, memory) { - const outerWidth = input.outerWidth; - const outerHeight = input.outerHeight; - const pixelRatio = input.pixelRatio; - if (!input.minimap.enabled) { - return { - renderMinimap: 0 /* None */, - minimapLeft: 0, - minimapWidth: 0, - minimapHeightIsEditorHeight: false, - minimapIsSampling: false, - minimapScale: 1, - minimapLineHeight: 1, - minimapCanvasInnerWidth: 0, - minimapCanvasInnerHeight: Math.floor(pixelRatio * outerHeight), - minimapCanvasOuterWidth: 0, - minimapCanvasOuterHeight: outerHeight, - }; - } - // Can use memory if only the `viewLineCount` and `remainingWidth` have changed - const stableMinimapLayoutInput = memory.stableMinimapLayoutInput; - const couldUseMemory = (stableMinimapLayoutInput - // && input.outerWidth === lastMinimapLayoutInput.outerWidth !!! INTENTIONAL OMITTED - && input.outerHeight === stableMinimapLayoutInput.outerHeight - && input.lineHeight === stableMinimapLayoutInput.lineHeight - && input.typicalHalfwidthCharacterWidth === stableMinimapLayoutInput.typicalHalfwidthCharacterWidth - && input.pixelRatio === stableMinimapLayoutInput.pixelRatio - && input.scrollBeyondLastLine === stableMinimapLayoutInput.scrollBeyondLastLine - && input.minimap.enabled === stableMinimapLayoutInput.minimap.enabled - && input.minimap.side === stableMinimapLayoutInput.minimap.side - && input.minimap.size === stableMinimapLayoutInput.minimap.size - && input.minimap.showSlider === stableMinimapLayoutInput.minimap.showSlider - && input.minimap.renderCharacters === stableMinimapLayoutInput.minimap.renderCharacters - && input.minimap.maxColumn === stableMinimapLayoutInput.minimap.maxColumn - && input.minimap.scale === stableMinimapLayoutInput.minimap.scale - && input.verticalScrollbarWidth === stableMinimapLayoutInput.verticalScrollbarWidth - // && input.viewLineCount === lastMinimapLayoutInput.viewLineCount !!! INTENTIONAL OMITTED - // && input.remainingWidth === lastMinimapLayoutInput.remainingWidth !!! INTENTIONAL OMITTED - && input.isViewportWrapping === stableMinimapLayoutInput.isViewportWrapping); - const lineHeight = input.lineHeight; - const typicalHalfwidthCharacterWidth = input.typicalHalfwidthCharacterWidth; - const scrollBeyondLastLine = input.scrollBeyondLastLine; - const minimapRenderCharacters = input.minimap.renderCharacters; - let minimapScale = (pixelRatio >= 2 ? Math.round(input.minimap.scale * 2) : input.minimap.scale); - const minimapMaxColumn = input.minimap.maxColumn; - const minimapSize = input.minimap.size; - const minimapSide = input.minimap.side; - const verticalScrollbarWidth = input.verticalScrollbarWidth; - const viewLineCount = input.viewLineCount; - const remainingWidth = input.remainingWidth; - const isViewportWrapping = input.isViewportWrapping; - const baseCharHeight = minimapRenderCharacters ? 2 : 3; - let minimapCanvasInnerHeight = Math.floor(pixelRatio * outerHeight); - const minimapCanvasOuterHeight = minimapCanvasInnerHeight / pixelRatio; - let minimapHeightIsEditorHeight = false; - let minimapIsSampling = false; - let minimapLineHeight = baseCharHeight * minimapScale; - let minimapCharWidth = minimapScale / pixelRatio; - let minimapWidthMultiplier = 1; - if (minimapSize === 'fill' || minimapSize === 'fit') { - const { typicalViewportLineCount, extraLinesBeyondLastLine, desiredRatio, minimapLineCount } = EditorLayoutInfoComputer.computeContainedMinimapLineCount({ - viewLineCount: viewLineCount, - scrollBeyondLastLine: scrollBeyondLastLine, - height: outerHeight, - lineHeight: lineHeight, - pixelRatio: pixelRatio - }); - // ratio is intentionally not part of the layout to avoid the layout changing all the time - // when doing sampling - const ratio = viewLineCount / minimapLineCount; - if (ratio > 1) { - minimapHeightIsEditorHeight = true; - minimapIsSampling = true; - minimapScale = 1; - minimapLineHeight = 1; - minimapCharWidth = minimapScale / pixelRatio; - } - else { - let fitBecomesFill = false; - let maxMinimapScale = minimapScale + 1; - if (minimapSize === 'fit') { - const effectiveMinimapHeight = Math.ceil((viewLineCount + extraLinesBeyondLastLine) * minimapLineHeight); - if (isViewportWrapping && couldUseMemory && remainingWidth <= memory.stableFitRemainingWidth) { - // There is a loop when using `fit` and viewport wrapping: - // - view line count impacts minimap layout - // - minimap layout impacts viewport width - // - viewport width impacts view line count - // To break the loop, once we go to a smaller minimap scale, we try to stick with it. - fitBecomesFill = true; - maxMinimapScale = memory.stableFitMaxMinimapScale; - } - else { - fitBecomesFill = (effectiveMinimapHeight > minimapCanvasInnerHeight); - } - } - if (minimapSize === 'fill' || fitBecomesFill) { - minimapHeightIsEditorHeight = true; - const configuredMinimapScale = minimapScale; - minimapLineHeight = Math.min(lineHeight * pixelRatio, Math.max(1, Math.floor(1 / desiredRatio))); - if (isViewportWrapping && couldUseMemory && remainingWidth <= memory.stableFitRemainingWidth) { - // There is a loop when using `fill` and viewport wrapping: - // - view line count impacts minimap layout - // - minimap layout impacts viewport width - // - viewport width impacts view line count - // To break the loop, once we go to a smaller minimap scale, we try to stick with it. - maxMinimapScale = memory.stableFitMaxMinimapScale; - } - minimapScale = Math.min(maxMinimapScale, Math.max(1, Math.floor(minimapLineHeight / baseCharHeight))); - if (minimapScale > configuredMinimapScale) { - minimapWidthMultiplier = Math.min(2, minimapScale / configuredMinimapScale); - } - minimapCharWidth = minimapScale / pixelRatio / minimapWidthMultiplier; - minimapCanvasInnerHeight = Math.ceil((Math.max(typicalViewportLineCount, viewLineCount + extraLinesBeyondLastLine)) * minimapLineHeight); - if (isViewportWrapping) { - // remember for next time - memory.stableMinimapLayoutInput = input; - memory.stableFitRemainingWidth = remainingWidth; - memory.stableFitMaxMinimapScale = minimapScale; - } - else { - memory.stableMinimapLayoutInput = null; - memory.stableFitRemainingWidth = 0; - } - } - } - } - // 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) - const minimapMaxWidth = Math.floor(minimapMaxColumn * minimapCharWidth); - const minimapWidth = Math.min(minimapMaxWidth, Math.max(0, Math.floor(((remainingWidth - verticalScrollbarWidth - 2) * minimapCharWidth) / (typicalHalfwidthCharacterWidth + minimapCharWidth))) + exports.MINIMAP_GUTTER_WIDTH); - let minimapCanvasInnerWidth = Math.floor(pixelRatio * minimapWidth); - const minimapCanvasOuterWidth = minimapCanvasInnerWidth / pixelRatio; - minimapCanvasInnerWidth = Math.floor(minimapCanvasInnerWidth * minimapWidthMultiplier); - const renderMinimap = (minimapRenderCharacters ? 1 /* Text */ : 2 /* Blocks */); - const minimapLeft = (minimapSide === 'left' ? 0 : (outerWidth - minimapWidth - verticalScrollbarWidth)); - return { - renderMinimap, - minimapLeft, - minimapWidth, - minimapHeightIsEditorHeight, - minimapIsSampling, - minimapScale, - minimapLineHeight, - minimapCanvasInnerWidth, - minimapCanvasInnerHeight, - minimapCanvasOuterWidth, - minimapCanvasOuterHeight, - }; - } - static computeLayout(options, env) { - const outerWidth = env.outerWidth | 0; - const outerHeight = env.outerHeight | 0; - const lineHeight = env.lineHeight | 0; - const lineNumbersDigitCount = env.lineNumbersDigitCount | 0; - const typicalHalfwidthCharacterWidth = env.typicalHalfwidthCharacterWidth; - const maxDigitWidth = env.maxDigitWidth; - const pixelRatio = env.pixelRatio; - const viewLineCount = env.viewLineCount; - const wordWrapOverride2 = options.get(121 /* wordWrapOverride2 */); - const wordWrapOverride1 = (wordWrapOverride2 === 'inherit' ? options.get(120 /* wordWrapOverride1 */) : wordWrapOverride2); - const wordWrap = (wordWrapOverride1 === 'inherit' ? options.get(116 /* wordWrap */) : wordWrapOverride1); - const wordWrapColumn = options.get(119 /* wordWrapColumn */); - const accessibilitySupport = options.get(2 /* accessibilitySupport */); - const isDominatedByLongLines = env.isDominatedByLongLines; - const showGlyphMargin = options.get(47 /* glyphMargin */); - const showLineNumbers = (options.get(58 /* lineNumbers */).renderType !== 0 /* Off */); - const lineNumbersMinChars = options.get(59 /* lineNumbersMinChars */); - const scrollBeyondLastLine = options.get(93 /* scrollBeyondLastLine */); - const minimap = options.get(63 /* minimap */); - const scrollbar = options.get(91 /* scrollbar */); - const verticalScrollbarWidth = scrollbar.verticalScrollbarSize; - const verticalScrollbarHasArrows = scrollbar.verticalHasArrows; - const scrollbarArrowSize = scrollbar.arrowSize; - const horizontalScrollbarHeight = scrollbar.horizontalScrollbarSize; - const rawLineDecorationsWidth = options.get(56 /* lineDecorationsWidth */); - const folding = options.get(35 /* folding */); - let lineDecorationsWidth; - if (typeof rawLineDecorationsWidth === 'string' && /^\d+(\.\d+)?ch$/.test(rawLineDecorationsWidth)) { - const 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; - } - let lineNumbersWidth = 0; - if (showLineNumbers) { - const digitCount = Math.max(lineNumbersDigitCount, lineNumbersMinChars); - lineNumbersWidth = Math.round(digitCount * maxDigitWidth); - } - let glyphMarginWidth = 0; - if (showGlyphMargin) { - glyphMarginWidth = lineHeight; - } - let glyphMarginLeft = 0; - let lineNumbersLeft = glyphMarginLeft + glyphMarginWidth; - let decorationsLeft = lineNumbersLeft + lineNumbersWidth; - let contentLeft = decorationsLeft + lineDecorationsWidth; - const remainingWidth = outerWidth - glyphMarginWidth - lineNumbersWidth - lineDecorationsWidth; - let isWordWrapMinified = false; - let isViewportWrapping = false; - let wrappingColumn = -1; - 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. - if (wordWrapOverride1 === 'inherit' && isDominatedByLongLines) { - // Force viewport width wrapping if model is dominated by long lines - isWordWrapMinified = true; - isViewportWrapping = true; - } - else if (wordWrap === 'on' || wordWrap === 'bounded') { - isViewportWrapping = true; - } - else if (wordWrap === 'wordWrapColumn') { - wrappingColumn = wordWrapColumn; - } - } - const minimapLayout = EditorLayoutInfoComputer._computeMinimapLayout({ - outerWidth: outerWidth, - outerHeight: outerHeight, - lineHeight: lineHeight, - typicalHalfwidthCharacterWidth: typicalHalfwidthCharacterWidth, - pixelRatio: pixelRatio, - scrollBeyondLastLine: scrollBeyondLastLine, - minimap: minimap, - verticalScrollbarWidth: verticalScrollbarWidth, - viewLineCount: viewLineCount, - remainingWidth: remainingWidth, - isViewportWrapping: isViewportWrapping, - }, env.memory || new ComputeOptionsMemory()); - if (minimapLayout.renderMinimap !== 0 /* None */ && minimapLayout.minimapLeft === 0) { - // the minimap is rendered to the left, so move everything to the right - glyphMarginLeft += minimapLayout.minimapWidth; - lineNumbersLeft += minimapLayout.minimapWidth; - decorationsLeft += minimapLayout.minimapWidth; - contentLeft += minimapLayout.minimapWidth; - } - const contentWidth = remainingWidth - minimapLayout.minimapWidth; - // (leaving 2px for the cursor to have space after the last character) - const viewportColumn = Math.max(1, Math.floor((contentWidth - verticalScrollbarWidth - 2) / typicalHalfwidthCharacterWidth)); - const verticalArrowSize = (verticalScrollbarHasArrows ? scrollbarArrowSize : 0); - if (isViewportWrapping) { - // compute the actual wrappingColumn - wrappingColumn = Math.max(1, viewportColumn); - if (wordWrap === 'bounded') { - wrappingColumn = Math.min(wrappingColumn, wordWrapColumn); - } - } - return { - width: outerWidth, - height: outerHeight, - glyphMarginLeft: glyphMarginLeft, - glyphMarginWidth: glyphMarginWidth, - lineNumbersLeft: lineNumbersLeft, - lineNumbersWidth: lineNumbersWidth, - decorationsLeft: decorationsLeft, - decorationsWidth: lineDecorationsWidth, - contentLeft: contentLeft, - contentWidth: contentWidth, - minimap: minimapLayout, - viewportColumn: viewportColumn, - isWordWrapMinified: isWordWrapMinified, - isViewportWrapping: isViewportWrapping, - wrappingColumn: wrappingColumn, - verticalScrollbarWidth: verticalScrollbarWidth, - horizontalScrollbarHeight: horizontalScrollbarHeight, - overviewRuler: { - top: verticalArrowSize, - width: verticalScrollbarWidth, - height: (outerHeight - 2 * verticalArrowSize), - right: 0 - } - }; - } - } - exports.EditorLayoutInfoComputer = EditorLayoutInfoComputer; - class EditorLightbulb extends BaseEditorOption { - constructor() { - const defaults = { enabled: true }; - super(55 /* lightbulb */, 'lightbulb', defaults, { - 'editor.lightbulb.enabled': { - type: 'boolean', - default: defaults.enabled, - description: nls.localize(42, null) - }, - }); - } - validate(_input) { - if (!_input || typeof _input !== 'object') { - return this.defaultValue; - } - const input = _input; - return { - enabled: boolean(input.enabled, this.defaultValue.enabled) - }; - } - } - class EditorInlayHints extends BaseEditorOption { - constructor() { - const defaults = { enabled: true, fontSize: 0, fontFamily: '' }; - super(125 /* inlayHints */, 'inlayHints', defaults, { - 'editor.inlayHints.enabled': { - type: 'boolean', - default: defaults.enabled, - description: nls.localize(43, null) - }, - 'editor.inlayHints.fontSize': { - type: 'number', - default: defaults.fontSize, - markdownDescription: nls.localize(44, null) - }, - 'editor.inlayHints.fontFamily': { - type: 'string', - default: defaults.fontFamily, - description: nls.localize(45, null) - }, - }); - } - validate(_input) { - if (!_input || typeof _input !== 'object') { - return this.defaultValue; - } - const input = _input; - return { - enabled: boolean(input.enabled, this.defaultValue.enabled), - fontSize: EditorIntOption.clampedInt(input.fontSize, this.defaultValue.fontSize, 0, 100), - fontFamily: EditorStringOption.string(input.fontFamily, this.defaultValue.fontFamily) - }; - } - } - //#endregion - //#region lineHeight - class EditorLineHeight extends EditorFloatOption { - constructor() { - super(57 /* lineHeight */, 'lineHeight', exports.EDITOR_FONT_DEFAULTS.lineHeight, x => EditorFloatOption.clamp(x, 0, 150), { markdownDescription: nls.localize(46, null) }); - } - compute(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; - } - } - class EditorMinimap extends BaseEditorOption { - constructor() { - const defaults = { - enabled: true, - size: 'proportional', - side: 'right', - showSlider: 'mouseover', - renderCharacters: true, - maxColumn: 120, - scale: 1, - }; - super(63 /* minimap */, 'minimap', defaults, { - 'editor.minimap.enabled': { - type: 'boolean', - default: defaults.enabled, - description: nls.localize(47, null) - }, - 'editor.minimap.size': { - type: 'string', - enum: ['proportional', 'fill', 'fit'], - enumDescriptions: [ - nls.localize(48, null), - nls.localize(49, null), - nls.localize(50, null), - ], - default: defaults.size, - description: nls.localize(51, null) - }, - 'editor.minimap.side': { - type: 'string', - enum: ['left', 'right'], - default: defaults.side, - description: nls.localize(52, null) - }, - 'editor.minimap.showSlider': { - type: 'string', - enum: ['always', 'mouseover'], - default: defaults.showSlider, - description: nls.localize(53, null) - }, - 'editor.minimap.scale': { - type: 'number', - default: defaults.scale, - minimum: 1, - maximum: 3, - enum: [1, 2, 3], - description: nls.localize(54, null) - }, - 'editor.minimap.renderCharacters': { - type: 'boolean', - default: defaults.renderCharacters, - description: nls.localize(55, null) - }, - 'editor.minimap.maxColumn': { - type: 'number', - default: defaults.maxColumn, - description: nls.localize(56, null) - } - }); - } - validate(_input) { - if (!_input || typeof _input !== 'object') { - return this.defaultValue; - } - const input = _input; - return { - enabled: boolean(input.enabled, this.defaultValue.enabled), - size: stringSet(input.size, this.defaultValue.size, ['proportional', 'fill', 'fit']), - side: stringSet(input.side, this.defaultValue.side, ['right', 'left']), - showSlider: stringSet(input.showSlider, this.defaultValue.showSlider, ['always', 'mouseover']), - renderCharacters: boolean(input.renderCharacters, this.defaultValue.renderCharacters), - scale: EditorIntOption.clampedInt(input.scale, 1, 1, 3), - maxColumn: EditorIntOption.clampedInt(input.maxColumn, this.defaultValue.maxColumn, 1, 10000), - }; - } - } - //#endregion - //#region multiCursorModifier - function _multiCursorModifierFromString(multiCursorModifier) { - if (multiCursorModifier === 'ctrlCmd') { - return (platform.isMacintosh ? 'metaKey' : 'ctrlKey'); - } - return 'altKey'; - } - class EditorPadding extends BaseEditorOption { - constructor() { - super(73 /* padding */, 'padding', { top: 0, bottom: 0 }, { - 'editor.padding.top': { - type: 'number', - default: 0, - minimum: 0, - maximum: 1000, - description: nls.localize(57, null) - }, - 'editor.padding.bottom': { - type: 'number', - default: 0, - minimum: 0, - maximum: 1000, - description: nls.localize(58, null) - } - }); - } - validate(_input) { - if (!_input || typeof _input !== 'object') { - return this.defaultValue; - } - const input = _input; - return { - top: EditorIntOption.clampedInt(input.top, 0, 0, 1000), - bottom: EditorIntOption.clampedInt(input.bottom, 0, 0, 1000) - }; - } - } - class EditorParameterHints extends BaseEditorOption { - constructor() { - const defaults = { - enabled: true, - cycle: false - }; - super(74 /* parameterHints */, 'parameterHints', defaults, { - 'editor.parameterHints.enabled': { - type: 'boolean', - default: defaults.enabled, - description: nls.localize(59, null) - }, - 'editor.parameterHints.cycle': { - type: 'boolean', - default: defaults.cycle, - description: nls.localize(60, null) - }, - }); - } - validate(_input) { - if (!_input || typeof _input !== 'object') { - return this.defaultValue; - } - const input = _input; - return { - enabled: boolean(input.enabled, this.defaultValue.enabled), - cycle: boolean(input.cycle, this.defaultValue.cycle) - }; - } - } - //#endregion - //#region pixelRatio - class EditorPixelRatio extends ComputedEditorOption { - constructor() { - super(127 /* pixelRatio */); - } - compute(env, options, _) { - return env.pixelRatio; - } - } - class EditorQuickSuggestions extends BaseEditorOption { - constructor() { - const defaults = { - other: true, - comments: false, - strings: false - }; - super(77 /* quickSuggestions */, 'quickSuggestions', defaults, { - anyOf: [ - { - type: 'boolean', - }, - { - type: 'object', - properties: { - strings: { - type: 'boolean', - default: defaults.strings, - description: nls.localize(61, null) - }, - comments: { - type: 'boolean', - default: defaults.comments, - description: nls.localize(62, null) - }, - other: { - type: 'boolean', - default: defaults.other, - description: nls.localize(63, null) - }, - } - } - ], - default: defaults, - description: nls.localize(64, null) - }); - this.defaultValue = defaults; - } - validate(_input) { - if (typeof _input === 'boolean') { - return _input; - } - if (_input && typeof _input === 'object') { - const input = _input; - const opts = { - other: boolean(input.other, this.defaultValue.other), - comments: boolean(input.comments, this.defaultValue.comments), - strings: 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; - } - } - class EditorRenderLineNumbersOption extends BaseEditorOption { - constructor() { - super(58 /* lineNumbers */, 'lineNumbers', { renderType: 1 /* On */, renderFn: null }, { - type: 'string', - enum: ['off', 'on', 'relative', 'interval'], - enumDescriptions: [ - nls.localize(65, null), - nls.localize(66, null), - nls.localize(67, null), - nls.localize(68, null) - ], - default: 'on', - description: nls.localize(69, null) - }); - } - validate(lineNumbers) { - let renderType = this.defaultValue.renderType; - let 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, - renderFn - }; - } - } - //#endregion - //#region renderValidationDecorations - /** - * @internal - */ - function filterValidationDecorations(options) { - const renderValidationDecorations = options.get(86 /* renderValidationDecorations */); - if (renderValidationDecorations === 'editable') { - return options.get(79 /* readOnly */); - } - return renderValidationDecorations === 'on' ? false : true; - } - exports.filterValidationDecorations = filterValidationDecorations; - class EditorRulers extends BaseEditorOption { - constructor() { - const defaults = []; - const columnSchema = { type: 'number', description: nls.localize(70, null) }; - super(90 /* rulers */, 'rulers', defaults, { - type: 'array', - items: { - anyOf: [ - columnSchema, - { - type: [ - 'object' - ], - properties: { - column: columnSchema, - color: { - type: 'string', - description: nls.localize(71, null), - format: 'color-hex' - } - } - } - ] - }, - default: defaults, - description: nls.localize(72, null) - }); - } - validate(input) { - if (Array.isArray(input)) { - let rulers = []; - for (let _element of input) { - if (typeof _element === 'number') { - rulers.push({ - column: EditorIntOption.clampedInt(_element, 0, 0, 10000), - color: null - }); - } - else if (_element && typeof _element === 'object') { - const element = _element; - rulers.push({ - column: EditorIntOption.clampedInt(element.column, 0, 0, 10000), - color: element.color - }); - } - } - rulers.sort((a, b) => a.column - b.column); - return rulers; - } - return this.defaultValue; - } - } - 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 */; - } - } - class EditorScrollbar extends BaseEditorOption { - constructor() { - const defaults = { - vertical: 1 /* Auto */, - horizontal: 1 /* Auto */, - arrowSize: 11, - useShadows: true, - verticalHasArrows: false, - horizontalHasArrows: false, - horizontalScrollbarSize: 12, - horizontalSliderSize: 12, - verticalScrollbarSize: 14, - verticalSliderSize: 14, - handleMouseWheel: true, - alwaysConsumeMouseWheel: true, - scrollByPage: false - }; - super(91 /* scrollbar */, 'scrollbar', defaults, { - 'editor.scrollbar.vertical': { - type: 'string', - enum: ['auto', 'visible', 'hidden'], - enumDescriptions: [ - nls.localize(73, null), - nls.localize(74, null), - nls.localize(75, null), - ], - default: 'auto', - description: nls.localize(76, null) - }, - 'editor.scrollbar.horizontal': { - type: 'string', - enum: ['auto', 'visible', 'hidden'], - enumDescriptions: [ - nls.localize(77, null), - nls.localize(78, null), - nls.localize(79, null), - ], - default: 'auto', - description: nls.localize(80, null) - }, - 'editor.scrollbar.verticalScrollbarSize': { - type: 'number', - default: defaults.verticalScrollbarSize, - description: nls.localize(81, null) - }, - 'editor.scrollbar.horizontalScrollbarSize': { - type: 'number', - default: defaults.horizontalScrollbarSize, - description: nls.localize(82, null) - }, - 'editor.scrollbar.scrollByPage': { - type: 'boolean', - default: defaults.scrollByPage, - description: nls.localize(83, null) - } - }); - } - validate(_input) { - if (!_input || typeof _input !== 'object') { - return this.defaultValue; - } - const input = _input; - const horizontalScrollbarSize = EditorIntOption.clampedInt(input.horizontalScrollbarSize, this.defaultValue.horizontalScrollbarSize, 0, 1000); - const 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: boolean(input.useShadows, this.defaultValue.useShadows), - verticalHasArrows: boolean(input.verticalHasArrows, this.defaultValue.verticalHasArrows), - horizontalHasArrows: boolean(input.horizontalHasArrows, this.defaultValue.horizontalHasArrows), - handleMouseWheel: boolean(input.handleMouseWheel, this.defaultValue.handleMouseWheel), - alwaysConsumeMouseWheel: 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), - scrollByPage: boolean(input.scrollByPage, this.defaultValue.scrollByPage), - }; - } - } - /** - * Configuration options for inline suggestions - */ - class InlineEditorSuggest extends BaseEditorOption { - constructor() { - const defaults = { - enabled: false, - mode: 'subwordSmart' - }; - super(53 /* inlineSuggest */, 'inlineSuggest', defaults, { - 'editor.inlineSuggest.enabled': { - type: 'boolean', - default: defaults.enabled, - description: nls.localize(84, null) - }, - 'editor.inlineSuggest.mode': { - type: 'string', - enum: ['prefix', 'subword', 'subwordSmart'], - enumDescriptions: [ - nls.localize(85, null), - nls.localize(86, null), - nls.localize(87, null), - ], - default: defaults.mode, - description: nls.localize(88, null) - }, - }); - } - validate(_input) { - if (!_input || typeof _input !== 'object') { - return this.defaultValue; - } - const input = _input; - return { - enabled: boolean(input.enabled, this.defaultValue.enabled), - mode: stringSet(input.mode, this.defaultValue.mode, ['prefix', 'subword', 'subwordSmart']), - }; - } - } - class EditorSuggest extends BaseEditorOption { - constructor() { - const defaults = { - insertMode: 'insert', - filterGraceful: true, - snippetsPreventQuickSuggestions: true, - localityBonus: false, - shareSuggestSelections: false, - showIcons: true, - showStatusBar: false, - preview: false, - previewMode: 'subwordSmart', - showInlineDetails: true, - showMethods: true, - showFunctions: true, - showConstructors: true, - showDeprecated: 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, - showUsers: true, - showIssues: true, - }; - super(105 /* suggest */, 'suggest', defaults, { - 'editor.suggest.insertMode': { - type: 'string', - enum: ['insert', 'replace'], - enumDescriptions: [ - nls.localize(89, null), - nls.localize(90, null), - ], - default: defaults.insertMode, - description: nls.localize(91, null) - }, - 'editor.suggest.filterGraceful': { - type: 'boolean', - default: defaults.filterGraceful, - description: nls.localize(92, null) - }, - 'editor.suggest.localityBonus': { - type: 'boolean', - default: defaults.localityBonus, - description: nls.localize(93, null) - }, - 'editor.suggest.shareSuggestSelections': { - type: 'boolean', - default: defaults.shareSuggestSelections, - markdownDescription: nls.localize(94, null) - }, - 'editor.suggest.snippetsPreventQuickSuggestions': { - type: 'boolean', - default: defaults.snippetsPreventQuickSuggestions, - description: nls.localize(95, null) - }, - 'editor.suggest.showIcons': { - type: 'boolean', - default: defaults.showIcons, - description: nls.localize(96, null) - }, - 'editor.suggest.showStatusBar': { - type: 'boolean', - default: defaults.showStatusBar, - description: nls.localize(97, null) - }, - 'editor.suggest.preview': { - type: 'boolean', - default: defaults.preview, - description: nls.localize(98, null) - }, - 'editor.suggest.previewMode': { - type: 'string', - enum: ['prefix', 'subword', 'subwordSmart'], - enumDescriptions: [ - nls.localize(99, null), - nls.localize(100, null), - nls.localize(101, null), - ], - default: defaults.previewMode, - description: nls.localize(102, null) - }, - 'editor.suggest.showInlineDetails': { - type: 'boolean', - default: defaults.showInlineDetails, - description: nls.localize(103, null) - }, - 'editor.suggest.maxVisibleSuggestions': { - type: 'number', - deprecationMessage: nls.localize(104, null), - }, - 'editor.suggest.filteredTypes': { - type: 'object', - deprecationMessage: nls.localize(105, null) - }, - 'editor.suggest.showMethods': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(106, null) - }, - 'editor.suggest.showFunctions': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(107, null) - }, - 'editor.suggest.showConstructors': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(108, null) - }, - 'editor.suggest.showDeprecated': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(109, null) - }, - 'editor.suggest.showFields': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(110, null) - }, - 'editor.suggest.showVariables': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(111, null) - }, - 'editor.suggest.showClasses': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(112, null) - }, - 'editor.suggest.showStructs': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(113, null) - }, - 'editor.suggest.showInterfaces': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(114, null) - }, - 'editor.suggest.showModules': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(115, null) - }, - 'editor.suggest.showProperties': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(116, null) - }, - 'editor.suggest.showEvents': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(117, null) - }, - 'editor.suggest.showOperators': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(118, null) - }, - 'editor.suggest.showUnits': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(119, null) - }, - 'editor.suggest.showValues': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(120, null) - }, - 'editor.suggest.showConstants': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(121, null) - }, - 'editor.suggest.showEnums': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(122, null) - }, - 'editor.suggest.showEnumMembers': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(123, null) - }, - 'editor.suggest.showKeywords': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(124, null) - }, - 'editor.suggest.showWords': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(125, null) - }, - 'editor.suggest.showColors': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(126, null) - }, - 'editor.suggest.showFiles': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(127, null) - }, - 'editor.suggest.showReferences': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(128, null) - }, - 'editor.suggest.showCustomcolors': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(129, null) - }, - 'editor.suggest.showFolders': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(130, null) - }, - 'editor.suggest.showTypeParameters': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(131, null) - }, - 'editor.suggest.showSnippets': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(132, null) - }, - 'editor.suggest.showUsers': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(133, null) - }, - 'editor.suggest.showIssues': { - type: 'boolean', - default: true, - markdownDescription: nls.localize(134, null) - } - }); - } - validate(_input) { - if (!_input || typeof _input !== 'object') { - return this.defaultValue; - } - const input = _input; - return { - insertMode: stringSet(input.insertMode, this.defaultValue.insertMode, ['insert', 'replace']), - filterGraceful: boolean(input.filterGraceful, this.defaultValue.filterGraceful), - snippetsPreventQuickSuggestions: boolean(input.snippetsPreventQuickSuggestions, this.defaultValue.filterGraceful), - localityBonus: boolean(input.localityBonus, this.defaultValue.localityBonus), - shareSuggestSelections: boolean(input.shareSuggestSelections, this.defaultValue.shareSuggestSelections), - showIcons: boolean(input.showIcons, this.defaultValue.showIcons), - showStatusBar: boolean(input.showStatusBar, this.defaultValue.showStatusBar), - preview: boolean(input.preview, this.defaultValue.preview), - previewMode: stringSet(input.previewMode, this.defaultValue.previewMode, ['prefix', 'subword', 'subwordSmart']), - showInlineDetails: boolean(input.showInlineDetails, this.defaultValue.showInlineDetails), - showMethods: boolean(input.showMethods, this.defaultValue.showMethods), - showFunctions: boolean(input.showFunctions, this.defaultValue.showFunctions), - showConstructors: boolean(input.showConstructors, this.defaultValue.showConstructors), - showDeprecated: boolean(input.showDeprecated, this.defaultValue.showDeprecated), - showFields: boolean(input.showFields, this.defaultValue.showFields), - showVariables: boolean(input.showVariables, this.defaultValue.showVariables), - showClasses: boolean(input.showClasses, this.defaultValue.showClasses), - showStructs: boolean(input.showStructs, this.defaultValue.showStructs), - showInterfaces: boolean(input.showInterfaces, this.defaultValue.showInterfaces), - showModules: boolean(input.showModules, this.defaultValue.showModules), - showProperties: boolean(input.showProperties, this.defaultValue.showProperties), - showEvents: boolean(input.showEvents, this.defaultValue.showEvents), - showOperators: boolean(input.showOperators, this.defaultValue.showOperators), - showUnits: boolean(input.showUnits, this.defaultValue.showUnits), - showValues: boolean(input.showValues, this.defaultValue.showValues), - showConstants: boolean(input.showConstants, this.defaultValue.showConstants), - showEnums: boolean(input.showEnums, this.defaultValue.showEnums), - showEnumMembers: boolean(input.showEnumMembers, this.defaultValue.showEnumMembers), - showKeywords: boolean(input.showKeywords, this.defaultValue.showKeywords), - showWords: boolean(input.showWords, this.defaultValue.showWords), - showColors: boolean(input.showColors, this.defaultValue.showColors), - showFiles: boolean(input.showFiles, this.defaultValue.showFiles), - showReferences: boolean(input.showReferences, this.defaultValue.showReferences), - showFolders: boolean(input.showFolders, this.defaultValue.showFolders), - showTypeParameters: boolean(input.showTypeParameters, this.defaultValue.showTypeParameters), - showSnippets: boolean(input.showSnippets, this.defaultValue.showSnippets), - showUsers: boolean(input.showUsers, this.defaultValue.showUsers), - showIssues: boolean(input.showIssues, this.defaultValue.showIssues), - }; - } - } - class SmartSelect extends BaseEditorOption { - constructor() { - super(101 /* smartSelect */, 'smartSelect', { - selectLeadingAndTrailingWhitespace: true - }, { - 'editor.smartSelect.selectLeadingAndTrailingWhitespace': { - description: nls.localize(135, null), - default: true, - type: 'boolean' - } - }); - } - validate(input) { - if (!input || typeof input !== 'object') { - return this.defaultValue; - } - return { - selectLeadingAndTrailingWhitespace: boolean(input.selectLeadingAndTrailingWhitespace, this.defaultValue.selectLeadingAndTrailingWhitespace) - }; - } - } - //#endregion - //#region tabFocusMode - class EditorTabFocusMode extends ComputedEditorOption { - constructor() { - super(128 /* tabFocusMode */, [79 /* readOnly */]); - } - compute(env, options, _) { - const readOnly = options.get(79 /* readOnly */); - return (readOnly ? true : env.tabFocusMode); - } - } - 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 */; - } - } - class EditorWrappingInfoComputer extends ComputedEditorOption { - constructor() { - super(130 /* wrappingInfo */, [129 /* layoutInfo */]); - } - compute(env, options, _) { - const layoutInfo = options.get(129 /* layoutInfo */); - return { - isDominatedByLongLines: env.isDominatedByLongLines, - isWordWrapMinified: layoutInfo.isWordWrapMinified, - isViewportWrapping: layoutInfo.isViewportWrapping, - wrappingColumn: layoutInfo.wrappingColumn, - }; - } - } - //#endregion - const DEFAULT_WINDOWS_FONT_FAMILY = 'Consolas, \'Courier New\', monospace'; - const DEFAULT_MAC_FONT_FAMILY = 'Menlo, Monaco, \'Courier New\', monospace'; - const 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(136, null) })), - acceptSuggestionOnEnter: register(new EditorStringEnumOption(1 /* acceptSuggestionOnEnter */, 'acceptSuggestionOnEnter', 'on', ['on', 'smart', 'off'], { - markdownEnumDescriptions: [ - '', - nls.localize(137, null), - '' - ], - markdownDescription: nls.localize(138, null) - })), - accessibilitySupport: register(new EditorAccessibilitySupport()), - accessibilityPageSize: register(new EditorIntOption(3 /* accessibilityPageSize */, 'accessibilityPageSize', 10, 1, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { - description: nls.localize(139, null) - })), - ariaLabel: register(new EditorStringOption(4 /* ariaLabel */, 'ariaLabel', nls.localize(140, null))), - autoClosingBrackets: register(new EditorStringEnumOption(5 /* autoClosingBrackets */, 'autoClosingBrackets', 'languageDefined', ['always', 'languageDefined', 'beforeWhitespace', 'never'], { - enumDescriptions: [ - '', - nls.localize(141, null), - nls.localize(142, null), - '', - ], - description: nls.localize(143, null) - })), - autoClosingDelete: register(new EditorStringEnumOption(6 /* autoClosingDelete */, 'autoClosingDelete', 'auto', ['always', 'auto', 'never'], { - enumDescriptions: [ - '', - nls.localize(144, null), - '', - ], - description: nls.localize(145, null) - })), - autoClosingOvertype: register(new EditorStringEnumOption(7 /* autoClosingOvertype */, 'autoClosingOvertype', 'auto', ['always', 'auto', 'never'], { - enumDescriptions: [ - '', - nls.localize(146, null), - '', - ], - description: nls.localize(147, null) - })), - autoClosingQuotes: register(new EditorStringEnumOption(8 /* autoClosingQuotes */, 'autoClosingQuotes', 'languageDefined', ['always', 'languageDefined', 'beforeWhitespace', 'never'], { - enumDescriptions: [ - '', - nls.localize(148, null), - nls.localize(149, null), - '', - ], - description: nls.localize(150, null) - })), - autoIndent: register(new EditorEnumOption(9 /* autoIndent */, 'autoIndent', 4 /* Full */, 'full', ['none', 'keep', 'brackets', 'advanced', 'full'], _autoIndentFromString, { - enumDescriptions: [ - nls.localize(151, null), - nls.localize(152, null), - nls.localize(153, null), - nls.localize(154, null), - nls.localize(155, null), - ], - description: nls.localize(156, null) - })), - automaticLayout: register(new EditorBooleanOption(10 /* automaticLayout */, 'automaticLayout', false)), - autoSurround: register(new EditorStringEnumOption(11 /* autoSurround */, 'autoSurround', 'languageDefined', ['languageDefined', 'quotes', 'brackets', 'never'], { - enumDescriptions: [ - nls.localize(157, null), - nls.localize(158, null), - nls.localize(159, null), - '' - ], - description: nls.localize(160, null) - })), - stickyTabStops: register(new EditorBooleanOption(103 /* stickyTabStops */, 'stickyTabStops', false, { description: nls.localize(161, null) })), - codeLens: register(new EditorBooleanOption(12 /* codeLens */, 'codeLens', true, { description: nls.localize(162, null) })), - codeLensFontFamily: register(new EditorStringOption(13 /* codeLensFontFamily */, 'codeLensFontFamily', '', { description: nls.localize(163, null) })), - codeLensFontSize: register(new EditorIntOption(14 /* codeLensFontSize */, 'codeLensFontSize', 0, 0, 100, { - type: 'number', - default: 0, - minimum: 0, - maximum: 100, - markdownDescription: nls.localize(164, null) - })), - colorDecorators: register(new EditorBooleanOption(15 /* colorDecorators */, 'colorDecorators', true, { description: nls.localize(165, null) })), - columnSelection: register(new EditorBooleanOption(16 /* columnSelection */, 'columnSelection', false, { description: nls.localize(166, null) })), - comments: register(new EditorComments()), - contextmenu: register(new EditorBooleanOption(18 /* contextmenu */, 'contextmenu', true)), - copyWithSyntaxHighlighting: register(new EditorBooleanOption(19 /* copyWithSyntaxHighlighting */, 'copyWithSyntaxHighlighting', true, { description: nls.localize(167, null) })), - cursorBlinking: register(new EditorEnumOption(20 /* cursorBlinking */, 'cursorBlinking', 1 /* Blink */, 'blink', ['blink', 'smooth', 'phase', 'expand', 'solid'], _cursorBlinkingStyleFromString, { description: nls.localize(168, null) })), - cursorSmoothCaretAnimation: register(new EditorBooleanOption(21 /* cursorSmoothCaretAnimation */, 'cursorSmoothCaretAnimation', false, { description: nls.localize(169, null) })), - cursorStyle: register(new EditorEnumOption(22 /* cursorStyle */, 'cursorStyle', TextEditorCursorStyle.Line, 'line', ['line', 'block', 'underline', 'line-thin', 'block-outline', 'underline-thin'], _cursorStyleFromString, { description: nls.localize(170, null) })), - cursorSurroundingLines: register(new EditorIntOption(23 /* cursorSurroundingLines */, 'cursorSurroundingLines', 0, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(171, null) })), - cursorSurroundingLinesStyle: register(new EditorStringEnumOption(24 /* cursorSurroundingLinesStyle */, 'cursorSurroundingLinesStyle', 'default', ['default', 'all'], { - enumDescriptions: [ - nls.localize(172, null), - nls.localize(173, null) - ], - description: nls.localize(174, null) - })), - cursorWidth: register(new EditorIntOption(25 /* cursorWidth */, 'cursorWidth', 0, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { markdownDescription: nls.localize(175, null) })), - disableLayerHinting: register(new EditorBooleanOption(26 /* disableLayerHinting */, 'disableLayerHinting', false)), - disableMonospaceOptimizations: register(new EditorBooleanOption(27 /* disableMonospaceOptimizations */, 'disableMonospaceOptimizations', false)), - domReadOnly: register(new EditorBooleanOption(28 /* domReadOnly */, 'domReadOnly', false)), - dragAndDrop: register(new EditorBooleanOption(29 /* dragAndDrop */, 'dragAndDrop', true, { description: nls.localize(176, null) })), - emptySelectionClipboard: register(new EditorEmptySelectionClipboard()), - extraEditorClassName: register(new EditorStringOption(31 /* extraEditorClassName */, 'extraEditorClassName', '')), - fastScrollSensitivity: register(new EditorFloatOption(32 /* fastScrollSensitivity */, 'fastScrollSensitivity', 5, x => (x <= 0 ? 5 : x), { markdownDescription: nls.localize(177, null) })), - find: register(new EditorFind()), - fixedOverflowWidgets: register(new EditorBooleanOption(34 /* fixedOverflowWidgets */, 'fixedOverflowWidgets', false)), - folding: register(new EditorBooleanOption(35 /* folding */, 'folding', true, { description: nls.localize(178, null) })), - foldingStrategy: register(new EditorStringEnumOption(36 /* foldingStrategy */, 'foldingStrategy', 'auto', ['auto', 'indentation'], { - enumDescriptions: [ - nls.localize(179, null), - nls.localize(180, null), - ], - description: nls.localize(181, null) - })), - foldingHighlight: register(new EditorBooleanOption(37 /* foldingHighlight */, 'foldingHighlight', true, { description: nls.localize(182, null) })), - foldingImportsByDefault: register(new EditorBooleanOption(38 /* foldingImportsByDefault */, 'foldingImportsByDefault', false, { description: nls.localize(183, null) })), - unfoldOnClickAfterEndOfLine: register(new EditorBooleanOption(39 /* unfoldOnClickAfterEndOfLine */, 'unfoldOnClickAfterEndOfLine', false, { description: nls.localize(184, null) })), - fontFamily: register(new EditorStringOption(40 /* fontFamily */, 'fontFamily', exports.EDITOR_FONT_DEFAULTS.fontFamily, { description: nls.localize(185, null) })), - fontInfo: register(new EditorFontInfo()), - fontLigatures2: register(new EditorFontLigatures()), - fontSize: register(new EditorFontSize()), - fontWeight: register(new EditorFontWeight()), - formatOnPaste: register(new EditorBooleanOption(45 /* formatOnPaste */, 'formatOnPaste', false, { description: nls.localize(186, null) })), - formatOnType: register(new EditorBooleanOption(46 /* formatOnType */, 'formatOnType', false, { description: nls.localize(187, null) })), - glyphMargin: register(new EditorBooleanOption(47 /* glyphMargin */, 'glyphMargin', true, { description: nls.localize(188, null) })), - gotoLocation: register(new EditorGoToLocation()), - hideCursorInOverviewRuler: register(new EditorBooleanOption(49 /* hideCursorInOverviewRuler */, 'hideCursorInOverviewRuler', false, { description: nls.localize(189, null) })), - highlightActiveIndentGuide: register(new EditorBooleanOption(50 /* highlightActiveIndentGuide */, 'highlightActiveIndentGuide', true, { description: nls.localize(190, null) })), - hover: register(new EditorHover()), - inDiffEditor: register(new EditorBooleanOption(52 /* inDiffEditor */, 'inDiffEditor', false)), - letterSpacing: register(new EditorFloatOption(54 /* letterSpacing */, 'letterSpacing', exports.EDITOR_FONT_DEFAULTS.letterSpacing, x => EditorFloatOption.clamp(x, -5, 20), { description: nls.localize(191, null) })), - lightbulb: register(new EditorLightbulb()), - lineDecorationsWidth: register(new SimpleEditorOption(56 /* lineDecorationsWidth */, 'lineDecorationsWidth', 10)), - lineHeight: register(new EditorLineHeight()), - lineNumbers: register(new EditorRenderLineNumbersOption()), - lineNumbersMinChars: register(new EditorIntOption(59 /* lineNumbersMinChars */, 'lineNumbersMinChars', 5, 1, 300)), - linkedEditing: register(new EditorBooleanOption(60 /* linkedEditing */, 'linkedEditing', false, { description: nls.localize(192, null) })), - links: register(new EditorBooleanOption(61 /* links */, 'links', true, { description: nls.localize(193, null) })), - matchBrackets: register(new EditorStringEnumOption(62 /* matchBrackets */, 'matchBrackets', 'always', ['always', 'near', 'never'], { description: nls.localize(194, null) })), - minimap: register(new EditorMinimap()), - mouseStyle: register(new EditorStringEnumOption(64 /* mouseStyle */, 'mouseStyle', 'text', ['text', 'default', 'copy'])), - mouseWheelScrollSensitivity: register(new EditorFloatOption(65 /* mouseWheelScrollSensitivity */, 'mouseWheelScrollSensitivity', 1, x => (x === 0 ? 1 : x), { markdownDescription: nls.localize(195, null) })), - mouseWheelZoom: register(new EditorBooleanOption(66 /* mouseWheelZoom */, 'mouseWheelZoom', false, { markdownDescription: nls.localize(196, null) })), - multiCursorMergeOverlapping: register(new EditorBooleanOption(67 /* multiCursorMergeOverlapping */, 'multiCursorMergeOverlapping', true, { description: nls.localize(197, null) })), - multiCursorModifier: register(new EditorEnumOption(68 /* multiCursorModifier */, 'multiCursorModifier', 'altKey', 'alt', ['ctrlCmd', 'alt'], _multiCursorModifierFromString, { - markdownEnumDescriptions: [ - nls.localize(198, null), - nls.localize(199, null) - ], - markdownDescription: nls.localize(200, null) - - - - - - - })), - multiCursorPaste: register(new EditorStringEnumOption(69 /* multiCursorPaste */, 'multiCursorPaste', 'spread', ['spread', 'full'], { - markdownEnumDescriptions: [ - nls.localize(201, null), - nls.localize(202, null) - ], - markdownDescription: nls.localize(203, null) - })), - occurrencesHighlight: register(new EditorBooleanOption(70 /* occurrencesHighlight */, 'occurrencesHighlight', true, { description: nls.localize(204, null) })), - overviewRulerBorder: register(new EditorBooleanOption(71 /* overviewRulerBorder */, 'overviewRulerBorder', true, { description: nls.localize(205, null) })), - overviewRulerLanes: register(new EditorIntOption(72 /* overviewRulerLanes */, 'overviewRulerLanes', 3, 0, 3)), - padding: register(new EditorPadding()), - parameterHints: register(new EditorParameterHints()), - peekWidgetDefaultFocus: register(new EditorStringEnumOption(75 /* peekWidgetDefaultFocus */, 'peekWidgetDefaultFocus', 'tree', ['tree', 'editor'], { - enumDescriptions: [ - nls.localize(206, null), - nls.localize(207, null) - ], - description: nls.localize(208, null) - })), - definitionLinkOpensInPeek: register(new EditorBooleanOption(76 /* definitionLinkOpensInPeek */, 'definitionLinkOpensInPeek', false, { description: nls.localize(209, null) })), - quickSuggestions: register(new EditorQuickSuggestions()), - quickSuggestionsDelay: register(new EditorIntOption(78 /* quickSuggestionsDelay */, 'quickSuggestionsDelay', 10, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(210, null) })), - readOnly: register(new EditorBooleanOption(79 /* readOnly */, 'readOnly', false)), - renameOnType: register(new EditorBooleanOption(80 /* renameOnType */, 'renameOnType', false, { description: nls.localize(211, null), markdownDeprecationMessage: nls.localize(212, null) })), - renderControlCharacters: register(new EditorBooleanOption(81 /* renderControlCharacters */, 'renderControlCharacters', false, { description: nls.localize(213, null) })), - renderIndentGuides: register(new EditorBooleanOption(82 /* renderIndentGuides */, 'renderIndentGuides', true, { description: nls.localize(214, null) })), - renderFinalNewline: register(new EditorBooleanOption(83 /* renderFinalNewline */, 'renderFinalNewline', true, { description: nls.localize(215, null) })), - renderLineHighlight: register(new EditorStringEnumOption(84 /* renderLineHighlight */, 'renderLineHighlight', 'line', ['none', 'gutter', 'line', 'all'], { - enumDescriptions: [ - '', - '', - '', - nls.localize(216, null), - ], - description: nls.localize(217, null) - })), - renderLineHighlightOnlyWhenFocus: register(new EditorBooleanOption(85 /* renderLineHighlightOnlyWhenFocus */, 'renderLineHighlightOnlyWhenFocus', false, { description: nls.localize(218, null) })), - renderValidationDecorations: register(new EditorStringEnumOption(86 /* renderValidationDecorations */, 'renderValidationDecorations', 'editable', ['editable', 'on', 'off'])), - renderWhitespace: register(new EditorStringEnumOption(87 /* renderWhitespace */, 'renderWhitespace', 'selection', ['none', 'boundary', 'selection', 'trailing', 'all'], { - enumDescriptions: [ - '', - nls.localize(219, null), - nls.localize(220, null), - nls.localize(221, null), - '' - ], - description: nls.localize(222, null) - })), - revealHorizontalRightPadding: register(new EditorIntOption(88 /* revealHorizontalRightPadding */, 'revealHorizontalRightPadding', 30, 0, 1000)), - roundedSelection: register(new EditorBooleanOption(89 /* roundedSelection */, 'roundedSelection', true, { description: nls.localize(223, null) })), - rulers: register(new EditorRulers()), - scrollbar: register(new EditorScrollbar()), - scrollBeyondLastColumn: register(new EditorIntOption(92 /* scrollBeyondLastColumn */, 'scrollBeyondLastColumn', 5, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(224, null) })), - scrollBeyondLastLine: register(new EditorBooleanOption(93 /* scrollBeyondLastLine */, 'scrollBeyondLastLine', true, { description: nls.localize(225, null) })), - scrollPredominantAxis: register(new EditorBooleanOption(94 /* scrollPredominantAxis */, 'scrollPredominantAxis', true, { description: nls.localize(226, null) })), - selectionClipboard: register(new EditorBooleanOption(95 /* selectionClipboard */, 'selectionClipboard', true, { - description: nls.localize(227, null), - included: platform.isLinux - })), - selectionHighlight: register(new EditorBooleanOption(96 /* selectionHighlight */, 'selectionHighlight', true, { description: nls.localize(228, null) })), - selectOnLineNumbers: register(new EditorBooleanOption(97 /* selectOnLineNumbers */, 'selectOnLineNumbers', true)), - showFoldingControls: register(new EditorStringEnumOption(98 /* showFoldingControls */, 'showFoldingControls', 'mouseover', ['always', 'mouseover'], { - enumDescriptions: [ - nls.localize(229, null), - nls.localize(230, null), - ], - description: nls.localize(231, null) - })), - showUnused: register(new EditorBooleanOption(99 /* showUnused */, 'showUnused', true, { description: nls.localize(232, null) })), - showDeprecated: register(new EditorBooleanOption(124 /* showDeprecated */, 'showDeprecated', true, { description: nls.localize(233, null) })), - inlayHints: register(new EditorInlayHints()), - snippetSuggestions: register(new EditorStringEnumOption(100 /* snippetSuggestions */, 'snippetSuggestions', 'inline', ['top', 'bottom', 'inline', 'none'], { - enumDescriptions: [ - nls.localize(234, null), - nls.localize(235, null), - nls.localize(236, null), - nls.localize(237, null), - ], - description: nls.localize(238, null) - })), - smartSelect: register(new SmartSelect()), - smoothScrolling: register(new EditorBooleanOption(102 /* smoothScrolling */, 'smoothScrolling', false, { description: nls.localize(239, null) })), - stopRenderingLineAfter: register(new EditorIntOption(104 /* stopRenderingLineAfter */, 'stopRenderingLineAfter', 10000, -1, 1073741824 /* MAX_SAFE_SMALL_INTEGER */)), - suggest: register(new EditorSuggest()), - inlineSuggest: register(new InlineEditorSuggest()), - suggestFontSize: register(new EditorIntOption(106 /* suggestFontSize */, 'suggestFontSize', 0, 0, 1000, { markdownDescription: nls.localize(240, null) })), - suggestLineHeight: register(new EditorIntOption(107 /* suggestLineHeight */, 'suggestLineHeight', 0, 0, 1000, { markdownDescription: nls.localize(241, null) })), - suggestOnTriggerCharacters: register(new EditorBooleanOption(108 /* suggestOnTriggerCharacters */, 'suggestOnTriggerCharacters', true, { description: nls.localize(242, null) })), - suggestSelection: register(new EditorStringEnumOption(109 /* suggestSelection */, 'suggestSelection', 'recentlyUsed', ['first', 'recentlyUsed', 'recentlyUsedByPrefix'], { - markdownEnumDescriptions: [ - nls.localize(243, null), - nls.localize(244, null), - nls.localize(245, null), - ], - description: nls.localize(246, null) - })), - tabCompletion: register(new EditorStringEnumOption(110 /* tabCompletion */, 'tabCompletion', 'off', ['on', 'off', 'onlySnippets'], { - enumDescriptions: [ - nls.localize(247, null), - nls.localize(248, null), - nls.localize(249, null), - ], - description: nls.localize(250, null) - })), - tabIndex: register(new EditorIntOption(111 /* tabIndex */, 'tabIndex', 0, -1, 1073741824 /* MAX_SAFE_SMALL_INTEGER */)), - unusualLineTerminators: register(new EditorStringEnumOption(112 /* unusualLineTerminators */, 'unusualLineTerminators', 'prompt', ['auto', 'off', 'prompt'], { - enumDescriptions: [ - nls.localize(251, null), - nls.localize(252, null), - nls.localize(253, null), - ], - description: nls.localize(254, null) - })), - useShadowDOM: register(new EditorBooleanOption(113 /* useShadowDOM */, 'useShadowDOM', true)), - useTabStops: register(new EditorBooleanOption(114 /* useTabStops */, 'useTabStops', true, { description: nls.localize(255, null) })), - wordSeparators: register(new EditorStringOption(115 /* wordSeparators */, 'wordSeparators', wordHelper_1.USUAL_WORD_SEPARATORS, { description: nls.localize(256, null) })), - wordWrap: register(new EditorStringEnumOption(116 /* wordWrap */, 'wordWrap', 'off', ['off', 'on', 'wordWrapColumn', 'bounded'], { - markdownEnumDescriptions: [ - nls.localize(257, null), - nls.localize(258, null), - nls.localize(259, null), - - - - - - nls.localize(260, null), - - - - - - - ], - description: nls.localize(261, null) - - - - - - - })), - wordWrapBreakAfterCharacters: register(new EditorStringOption(117 /* wordWrapBreakAfterCharacters */, 'wordWrapBreakAfterCharacters', ' \t})]?|/&.,;¢°′″‰℃、。。、¢,.:;?!%・・ゝゞヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻ァィゥェォャュョッー”〉》」』】〕)]}」')), - wordWrapBreakBeforeCharacters: register(new EditorStringOption(118 /* wordWrapBreakBeforeCharacters */, 'wordWrapBreakBeforeCharacters', '([{‘“〈《「『【〔([{「£¥$£¥++')), - wordWrapColumn: register(new EditorIntOption(119 /* wordWrapColumn */, 'wordWrapColumn', 80, 1, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { - markdownDescription: nls.localize(262, null) - - - - - - - })), - wordWrapOverride1: register(new EditorStringEnumOption(120 /* wordWrapOverride1 */, 'wordWrapOverride1', 'inherit', ['off', 'on', 'inherit'])), - wordWrapOverride2: register(new EditorStringEnumOption(121 /* wordWrapOverride2 */, 'wordWrapOverride2', 'inherit', ['off', 'on', 'inherit'])), - wrappingIndent: register(new EditorEnumOption(122 /* wrappingIndent */, 'wrappingIndent', 1 /* Same */, 'same', ['none', 'same', 'indent', 'deepIndent'], _wrappingIndentFromString, { - enumDescriptions: [ - nls.localize(263, null), - nls.localize(264, null), - nls.localize(265, null), - nls.localize(266, null), - ], - description: nls.localize(267, null), - })), - wrappingStrategy: register(new EditorStringEnumOption(123 /* wrappingStrategy */, 'wrappingStrategy', 'simple', ['simple', 'advanced'], { - enumDescriptions: [ - nls.localize(268, null), - nls.localize(269, null) - ], - description: nls.localize(270, 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[465/*vs/editor/common/viewModel/viewModelDecorations*/], __M([0/*require*/,1/*exports*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,62/*vs/editor/common/viewModel/viewModel*/,35/*vs/editor/common/config/editorOptions*/]), function (require, exports, position_1, range_1, viewModel_1, editorOptions_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ViewModelDecorations = void 0; - class ViewModelDecorations { - constructor(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; - } - _clearCachedModelDecorationsResolver() { - this._cachedModelDecorationsResolver = null; - this._cachedModelDecorationsResolverViewRange = null; - } - dispose() { - this._decorationsCache = Object.create(null); - this._clearCachedModelDecorationsResolver(); - } - reset() { - this._decorationsCache = Object.create(null); - this._clearCachedModelDecorationsResolver(); - } - onModelDecorationsChanged() { - this._decorationsCache = Object.create(null); - this._clearCachedModelDecorationsResolver(); - } - onLineMappingChanged() { - this._decorationsCache = Object.create(null); - this._clearCachedModelDecorationsResolver(); - } - _getOrCreateViewModelDecoration(modelDecoration) { - const id = modelDecoration.id; - let r = this._decorationsCache[id]; - if (!r) { - const modelRange = modelDecoration.range; - const options = modelDecoration.options; - let viewRange; - if (options.isWholeLine) { - const start = this._coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelRange.startLineNumber, 1), 0 /* Left */); - const end = this._coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelRange.endLineNumber, this.model.getLineMaxColumn(modelRange.endLineNumber)), 1 /* Right */); - viewRange = new range_1.Range(start.lineNumber, start.column, end.lineNumber, end.column); - } - else { - // For backwards compatibility reasons, we want injected text before any decoration. - // Thus, move decorations to the right. - viewRange = this._coordinatesConverter.convertModelRangeToViewRange(modelRange, 1 /* Right */); - } - r = new viewModel_1.ViewModelDecoration(viewRange, options); - this._decorationsCache[id] = r; - } - return r; - } - getDecorationsViewportData(viewRange) { - let cacheIsValid = (this._cachedModelDecorationsResolver !== null); - cacheIsValid = cacheIsValid && (viewRange.equalsRange(this._cachedModelDecorationsResolverViewRange)); - if (!cacheIsValid) { - this._cachedModelDecorationsResolver = this._getDecorationsViewportData(viewRange); - this._cachedModelDecorationsResolverViewRange = viewRange; - } - return this._cachedModelDecorationsResolver; - } - _getDecorationsViewportData(viewportRange) { - const modelDecorations = this._linesCollection.getDecorationsInRange(viewportRange, this.editorId, (0, editorOptions_1.filterValidationDecorations)(this.configuration.options)); - const startLineNumber = viewportRange.startLineNumber; - const endLineNumber = viewportRange.endLineNumber; - let decorationsInViewport = [], decorationsInViewportLen = 0; - let inlineDecorations = []; - for (let j = startLineNumber; j <= endLineNumber; j++) { - inlineDecorations[j - startLineNumber] = []; - } - for (let i = 0, len = modelDecorations.length; i < len; i++) { - let modelDecoration = modelDecorations[i]; - let decorationOptions = modelDecoration.options; - let viewModelDecoration = this._getOrCreateViewModelDecoration(modelDecoration); - let viewRange = viewModelDecoration.range; - decorationsInViewport[decorationsInViewportLen++] = viewModelDecoration; - if (decorationOptions.inlineClassName) { - let inlineDecoration = new viewModel_1.InlineDecoration(viewRange, decorationOptions.inlineClassName, decorationOptions.inlineClassNameAffectsLetterSpacing ? 3 /* RegularAffectingLetterSpacing */ : 0 /* Regular */); - let intersectedStartLineNumber = Math.max(startLineNumber, viewRange.startLineNumber); - let intersectedEndLineNumber = Math.min(endLineNumber, viewRange.endLineNumber); - for (let j = intersectedStartLineNumber; j <= intersectedEndLineNumber; j++) { - inlineDecorations[j - startLineNumber].push(inlineDecoration); - } - } - if (decorationOptions.beforeContentClassName) { - if (startLineNumber <= viewRange.startLineNumber && viewRange.startLineNumber <= endLineNumber) { - let 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) { - let 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 - }; - } - } - exports.ViewModelDecorations = ViewModelDecorations; -}); - -define(__m[466/*vs/nls!vs/editor/common/editorContextKeys*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/editorContextKeys", data); }); -define(__m[467/*vs/nls!vs/editor/common/model/editStack*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/model/editStack", 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[239/*vs/editor/common/model/editStack*/], __M([0/*require*/,1/*exports*/,467/*vs/nls!vs/editor/common/model/editStack*/,12/*vs/base/common/errors*/,21/*vs/editor/common/core/selection*/,24/*vs/base/common/uri*/,220/*vs/editor/common/model/textChange*/,103/*vs/base/common/buffer*/,43/*vs/base/common/resources*/]), function (require, exports, nls, errors_1, selection_1, uri_1, textChange_1, buffer, resources_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.EditStack = exports.isEditStackElement = exports.MultiModelEditStackElement = exports.SingleModelEditStackElement = exports.SingleModelEditStackData = void 0; - function uriGetComparisonKey(resource) { - return resource.toString(); - } - class SingleModelEditStackData { - constructor(beforeVersionId, afterVersionId, beforeEOL, afterEOL, beforeCursorState, afterCursorState, changes) { - this.beforeVersionId = beforeVersionId; - this.afterVersionId = afterVersionId; - this.beforeEOL = beforeEOL; - this.afterEOL = afterEOL; - this.beforeCursorState = beforeCursorState; - this.afterCursorState = afterCursorState; - this.changes = changes; - } - static create(model, beforeCursorState) { - const alternativeVersionId = model.getAlternativeVersionId(); - const eol = getModelEOL(model); - return new SingleModelEditStackData(alternativeVersionId, alternativeVersionId, eol, eol, beforeCursorState, beforeCursorState, []); - } - append(model, textChanges, afterEOL, afterVersionId, afterCursorState) { - if (textChanges.length > 0) { - this.changes = (0, textChange_1.compressConsecutiveTextChanges)(this.changes, textChanges); - } - this.afterEOL = afterEOL; - this.afterVersionId = afterVersionId; - this.afterCursorState = afterCursorState; - } - static _writeSelectionsSize(selections) { - return 4 + 4 * 4 * (selections ? selections.length : 0); - } - static _writeSelections(b, selections, offset) { - buffer.writeUInt32BE(b, (selections ? selections.length : 0), offset); - offset += 4; - if (selections) { - for (const selection of selections) { - buffer.writeUInt32BE(b, selection.selectionStartLineNumber, offset); - offset += 4; - buffer.writeUInt32BE(b, selection.selectionStartColumn, offset); - offset += 4; - buffer.writeUInt32BE(b, selection.positionLineNumber, offset); - offset += 4; - buffer.writeUInt32BE(b, selection.positionColumn, offset); - offset += 4; - } - } - return offset; - } - static _readSelections(b, offset, dest) { - const count = buffer.readUInt32BE(b, offset); - offset += 4; - for (let i = 0; i < count; i++) { - const selectionStartLineNumber = buffer.readUInt32BE(b, offset); - offset += 4; - const selectionStartColumn = buffer.readUInt32BE(b, offset); - offset += 4; - const positionLineNumber = buffer.readUInt32BE(b, offset); - offset += 4; - const positionColumn = buffer.readUInt32BE(b, offset); - offset += 4; - dest.push(new selection_1.Selection(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn)); - } - return offset; - } - serialize() { - let necessarySize = (+4 // beforeVersionId - + 4 // afterVersionId - + 1 // beforeEOL - + 1 // afterEOL - + SingleModelEditStackData._writeSelectionsSize(this.beforeCursorState) - + SingleModelEditStackData._writeSelectionsSize(this.afterCursorState) - + 4 // change count - ); - for (const change of this.changes) { - necessarySize += change.writeSize(); - } - const b = new Uint8Array(necessarySize); - let offset = 0; - buffer.writeUInt32BE(b, this.beforeVersionId, offset); - offset += 4; - buffer.writeUInt32BE(b, this.afterVersionId, offset); - offset += 4; - buffer.writeUInt8(b, this.beforeEOL, offset); - offset += 1; - buffer.writeUInt8(b, this.afterEOL, offset); - offset += 1; - offset = SingleModelEditStackData._writeSelections(b, this.beforeCursorState, offset); - offset = SingleModelEditStackData._writeSelections(b, this.afterCursorState, offset); - buffer.writeUInt32BE(b, this.changes.length, offset); - offset += 4; - for (const change of this.changes) { - offset = change.write(b, offset); - } - return b.buffer; - } - static deserialize(source) { - const b = new Uint8Array(source); - let offset = 0; - const beforeVersionId = buffer.readUInt32BE(b, offset); - offset += 4; - const afterVersionId = buffer.readUInt32BE(b, offset); - offset += 4; - const beforeEOL = buffer.readUInt8(b, offset); - offset += 1; - const afterEOL = buffer.readUInt8(b, offset); - offset += 1; - const beforeCursorState = []; - offset = SingleModelEditStackData._readSelections(b, offset, beforeCursorState); - const afterCursorState = []; - offset = SingleModelEditStackData._readSelections(b, offset, afterCursorState); - const changeCount = buffer.readUInt32BE(b, offset); - offset += 4; - const changes = []; - for (let i = 0; i < changeCount; i++) { - offset = textChange_1.TextChange.read(b, offset, changes); - } - return new SingleModelEditStackData(beforeVersionId, afterVersionId, beforeEOL, afterEOL, beforeCursorState, afterCursorState, changes); - } - } - exports.SingleModelEditStackData = SingleModelEditStackData; - class SingleModelEditStackElement { - constructor(model, beforeCursorState) { - this.model = model; - this._data = SingleModelEditStackData.create(model, beforeCursorState); - } - get type() { - return 0 /* Resource */; - } - get resource() { - if (uri_1.URI.isUri(this.model)) { - return this.model; - } - return this.model.uri; - } - get label() { - return nls.localize(0, null); - } - toString() { - const data = (this._data instanceof SingleModelEditStackData ? this._data : SingleModelEditStackData.deserialize(this._data)); - return data.changes.map(change => change.toString()).join(', '); - } - matchesResource(resource) { - const uri = (uri_1.URI.isUri(this.model) ? this.model : this.model.uri); - return (uri.toString() === resource.toString()); - } - setModel(model) { - this.model = model; - } - canAppend(model) { - return (this.model === model && this._data instanceof SingleModelEditStackData); - } - append(model, textChanges, afterEOL, afterVersionId, afterCursorState) { - if (this._data instanceof SingleModelEditStackData) { - this._data.append(model, textChanges, afterEOL, afterVersionId, afterCursorState); - } - } - close() { - if (this._data instanceof SingleModelEditStackData) { - this._data = this._data.serialize(); - } - } - open() { - if (!(this._data instanceof SingleModelEditStackData)) { - this._data = SingleModelEditStackData.deserialize(this._data); - } - } - undo() { - if (uri_1.URI.isUri(this.model)) { - // don't have a model - throw new Error(`Invalid SingleModelEditStackElement`); - } - if (this._data instanceof SingleModelEditStackData) { - this._data = this._data.serialize(); - } - const data = SingleModelEditStackData.deserialize(this._data); - this.model._applyUndo(data.changes, data.beforeEOL, data.beforeVersionId, data.beforeCursorState); - } - redo() { - if (uri_1.URI.isUri(this.model)) { - // don't have a model - throw new Error(`Invalid SingleModelEditStackElement`); - } - if (this._data instanceof SingleModelEditStackData) { - this._data = this._data.serialize(); - } - const data = SingleModelEditStackData.deserialize(this._data); - this.model._applyRedo(data.changes, data.afterEOL, data.afterVersionId, data.afterCursorState); - } - heapSize() { - if (this._data instanceof SingleModelEditStackData) { - this._data = this._data.serialize(); - } - return this._data.byteLength + 168 /*heap overhead*/; - } - } - exports.SingleModelEditStackElement = SingleModelEditStackElement; - class MultiModelEditStackElement { - constructor(label, editStackElements) { - this.type = 1 /* Workspace */; - this.label = label; - this._isOpen = true; - this._editStackElementsArr = editStackElements.slice(0); - this._editStackElementsMap = new Map(); - for (const editStackElement of this._editStackElementsArr) { - const key = uriGetComparisonKey(editStackElement.resource); - this._editStackElementsMap.set(key, editStackElement); - } - this._delegate = null; - } - get resources() { - return this._editStackElementsArr.map(editStackElement => editStackElement.resource); - } - prepareUndoRedo() { - if (this._delegate) { - return this._delegate.prepareUndoRedo(this); - } - } - matchesResource(resource) { - const key = uriGetComparisonKey(resource); - return (this._editStackElementsMap.has(key)); - } - setModel(model) { - const key = uriGetComparisonKey(uri_1.URI.isUri(model) ? model : model.uri); - if (this._editStackElementsMap.has(key)) { - this._editStackElementsMap.get(key).setModel(model); - } - } - canAppend(model) { - if (!this._isOpen) { - return false; - } - const key = uriGetComparisonKey(model.uri); - if (this._editStackElementsMap.has(key)) { - const editStackElement = this._editStackElementsMap.get(key); - return editStackElement.canAppend(model); - } - return false; - } - append(model, textChanges, afterEOL, afterVersionId, afterCursorState) { - const key = uriGetComparisonKey(model.uri); - const editStackElement = this._editStackElementsMap.get(key); - editStackElement.append(model, textChanges, afterEOL, afterVersionId, afterCursorState); - } - close() { - this._isOpen = false; - } - open() { - // cannot reopen - } - undo() { - this._isOpen = false; - for (const editStackElement of this._editStackElementsArr) { - editStackElement.undo(); - } - } - redo() { - for (const editStackElement of this._editStackElementsArr) { - editStackElement.redo(); - } - } - heapSize(resource) { - const key = uriGetComparisonKey(resource); - if (this._editStackElementsMap.has(key)) { - const editStackElement = this._editStackElementsMap.get(key); - return editStackElement.heapSize(); - } - return 0; - } - split() { - return this._editStackElementsArr; - } - toString() { - let result = []; - for (const editStackElement of this._editStackElementsArr) { - result.push(`${(0, resources_1.basename)(editStackElement.resource)}: ${editStackElement}`); - } - return `{${result.join(', ')}}`; - } - } - exports.MultiModelEditStackElement = MultiModelEditStackElement; - function getModelEOL(model) { - const eol = model.getEOL(); - if (eol === '\n') { - return 0 /* LF */; - } - else { - return 1 /* CRLF */; - } - } - function isEditStackElement(element) { - if (!element) { - return false; - } - return ((element instanceof SingleModelEditStackElement) || (element instanceof MultiModelEditStackElement)); - } - exports.isEditStackElement = isEditStackElement; - class EditStack { - constructor(model, undoRedoService) { - this._model = model; - this._undoRedoService = undoRedoService; - } - pushStackElement() { - const lastElement = this._undoRedoService.getLastElement(this._model.uri); - if (isEditStackElement(lastElement)) { - lastElement.close(); - } - } - popStackElement() { - const lastElement = this._undoRedoService.getLastElement(this._model.uri); - if (isEditStackElement(lastElement)) { - lastElement.open(); - } - } - clear() { - this._undoRedoService.removeElements(this._model.uri); - } - _getOrCreateEditStackElement(beforeCursorState) { - const lastElement = this._undoRedoService.getLastElement(this._model.uri); - if (isEditStackElement(lastElement) && lastElement.canAppend(this._model)) { - return lastElement; - } - const newElement = new SingleModelEditStackElement(this._model, beforeCursorState); - this._undoRedoService.pushElement(newElement); - return newElement; - } - pushEOL(eol) { - const editStackElement = this._getOrCreateEditStackElement(null); - this._model.setEOL(eol); - editStackElement.append(this._model, [], getModelEOL(this._model), this._model.getAlternativeVersionId(), null); - } - pushEditOperation(beforeCursorState, editOperations, cursorStateComputer) { - const editStackElement = this._getOrCreateEditStackElement(beforeCursorState); - const inverseEditOperations = this._model.applyEdits(editOperations, true); - const afterCursorState = EditStack._computeCursorState(cursorStateComputer, inverseEditOperations); - const textChanges = inverseEditOperations.map((op, index) => ({ index: index, textChange: op.textChange })); - textChanges.sort((a, b) => { - if (a.textChange.oldPosition === b.textChange.oldPosition) { - return a.index - b.index; - } - return a.textChange.oldPosition - b.textChange.oldPosition; - }); - editStackElement.append(this._model, textChanges.map(op => op.textChange), getModelEOL(this._model), this._model.getAlternativeVersionId(), afterCursorState); - return afterCursorState; - } - static _computeCursorState(cursorStateComputer, inverseEditOperations) { - try { - return cursorStateComputer ? cursorStateComputer(inverseEditOperations) : null; - } - catch (e) { - (0, errors_1.onUnexpectedError)(e); - return null; - } - } - } - exports.EditStack = EditStack; -}); - -define(__m[468/*vs/nls!vs/editor/common/modes/modesRegistry*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/modes/modesRegistry", data); }); -define(__m[469/*vs/nls!vs/editor/common/standaloneStrings*/], __M([4/*vs/nls*/,5/*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[63/*vs/editor/common/standaloneStrings*/], __M([0/*require*/,1/*exports*/,469/*vs/nls!vs/editor/common/standaloneStrings*/]), function (require, exports, nls) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.SimpleServicesNLS = exports.ToggleHighContrastNLS = exports.StandaloneCodeEditorNLS = exports.QuickOutlineNLS = exports.QuickCommandNLS = exports.QuickHelpNLS = exports.GoToLineNLS = exports.InspectTokensNLS = exports.AccessibilityHelpNLS = void 0; - 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.gotoLineActionLabel = nls.localize(24, null); - })(GoToLineNLS = exports.GoToLineNLS || (exports.GoToLineNLS = {})); - var QuickHelpNLS; - (function (QuickHelpNLS) { - QuickHelpNLS.helpQuickAccessActionLabel = nls.localize(25, null); - })(QuickHelpNLS = exports.QuickHelpNLS || (exports.QuickHelpNLS = {})); - var QuickCommandNLS; - (function (QuickCommandNLS) { - QuickCommandNLS.quickCommandActionLabel = nls.localize(26, null); - QuickCommandNLS.quickCommandHelp = nls.localize(27, null); - })(QuickCommandNLS = exports.QuickCommandNLS || (exports.QuickCommandNLS = {})); - var QuickOutlineNLS; - (function (QuickOutlineNLS) { - QuickOutlineNLS.quickOutlineActionLabel = nls.localize(28, null); - QuickOutlineNLS.quickOutlineByCategoryActionLabel = nls.localize(29, null); - })(QuickOutlineNLS = exports.QuickOutlineNLS || (exports.QuickOutlineNLS = {})); - var StandaloneCodeEditorNLS; - (function (StandaloneCodeEditorNLS) { - StandaloneCodeEditorNLS.editorViewAccessibleLabel = nls.localize(30, null); - StandaloneCodeEditorNLS.accessibilityHelpMessage = nls.localize(31, null); - })(StandaloneCodeEditorNLS = exports.StandaloneCodeEditorNLS || (exports.StandaloneCodeEditorNLS = {})); - var ToggleHighContrastNLS; - (function (ToggleHighContrastNLS) { - ToggleHighContrastNLS.toggleHighContrast = nls.localize(32, null); - })(ToggleHighContrastNLS = exports.ToggleHighContrastNLS || (exports.ToggleHighContrastNLS = {})); - var SimpleServicesNLS; - (function (SimpleServicesNLS) { - SimpleServicesNLS.bulkEditServiceSummary = nls.localize(33, null); - })(SimpleServicesNLS = exports.SimpleServicesNLS || (exports.SimpleServicesNLS = {})); -}); - -define(__m[470/*vs/nls!vs/editor/common/view/editorColorRegistry*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/view/editorColorRegistry", data); }); -define(__m[471/*vs/nls!vs/editor/contrib/anchorSelect/anchorSelect*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/anchorSelect/anchorSelect", data); }); -define(__m[472/*vs/nls!vs/editor/contrib/bracketMatching/bracketMatching*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/bracketMatching/bracketMatching", data); }); -define(__m[473/*vs/nls!vs/editor/contrib/caretOperations/caretOperations*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/caretOperations/caretOperations", data); }); -define(__m[474/*vs/nls!vs/editor/contrib/caretOperations/transpose*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/caretOperations/transpose", data); }); -define(__m[475/*vs/nls!vs/editor/contrib/clipboard/clipboard*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/clipboard/clipboard", data); }); -define(__m[476/*vs/nls!vs/editor/contrib/codeAction/codeActionCommands*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/codeAction/codeActionCommands", data); }); -define(__m[477/*vs/nls!vs/editor/contrib/codeAction/lightBulbWidget*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/codeAction/lightBulbWidget", data); }); -define(__m[478/*vs/nls!vs/editor/contrib/codelens/codelensController*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/codelens/codelensController", data); }); -define(__m[479/*vs/nls!vs/editor/contrib/comment/comment*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/comment/comment", data); }); -define(__m[480/*vs/nls!vs/editor/contrib/contextmenu/contextmenu*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/contextmenu/contextmenu", data); }); -define(__m[481/*vs/nls!vs/editor/contrib/cursorUndo/cursorUndo*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/cursorUndo/cursorUndo", data); }); -define(__m[482/*vs/nls!vs/editor/contrib/find/findController*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/find/findController", data); }); -define(__m[483/*vs/nls!vs/editor/contrib/find/findWidget*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/find/findWidget", data); }); -define(__m[484/*vs/nls!vs/editor/contrib/folding/folding*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/folding/folding", data); }); -define(__m[485/*vs/nls!vs/editor/contrib/folding/foldingDecorations*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/folding/foldingDecorations", data); }); -define(__m[486/*vs/nls!vs/editor/contrib/fontZoom/fontZoom*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/fontZoom/fontZoom", data); }); -define(__m[487/*vs/nls!vs/editor/contrib/format/format*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/format/format", data); }); -define(__m[488/*vs/nls!vs/editor/contrib/format/formatActions*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/format/formatActions", data); }); -define(__m[489/*vs/nls!vs/editor/contrib/gotoError/gotoError*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoError/gotoError", data); }); -define(__m[490/*vs/nls!vs/editor/contrib/gotoError/gotoErrorWidget*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoError/gotoErrorWidget", data); }); -define(__m[491/*vs/nls!vs/editor/contrib/gotoSymbol/goToCommands*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/goToCommands", data); }); -define(__m[492/*vs/nls!vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition", data); }); -define(__m[493/*vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesController*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/peek/referencesController", data); }); -define(__m[494/*vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesTree*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/peek/referencesTree", data); }); -define(__m[495/*vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesWidget*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/peek/referencesWidget", data); }); -define(__m[496/*vs/nls!vs/editor/contrib/gotoSymbol/referencesModel*/], __M([4/*vs/nls*/,5/*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[118/*vs/editor/contrib/gotoSymbol/referencesModel*/], __M([0/*require*/,1/*exports*/,496/*vs/nls!vs/editor/contrib/gotoSymbol/referencesModel*/,6/*vs/base/common/event*/,43/*vs/base/common/resources*/,2/*vs/base/common/lifecycle*/,8/*vs/base/common/strings*/,125/*vs/base/common/idGenerator*/,3/*vs/editor/common/core/range*/,49/*vs/base/common/map*/,12/*vs/base/common/errors*/]), function (require, exports, nls_1, event_1, resources_1, lifecycle_1, strings, idGenerator_1, range_1, map_1, errors_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ReferencesModel = exports.FileReferences = exports.FilePreview = exports.OneReference = void 0; - class OneReference { - constructor(isProviderFirst, parent, link, _rangeCallback) { - this.isProviderFirst = isProviderFirst; - this.parent = parent; - this.link = link; - this._rangeCallback = _rangeCallback; - this.id = idGenerator_1.defaultGenerator.nextId(); - } - get uri() { - return this.link.uri; - } - get range() { - var _a, _b; - return (_b = (_a = this._range) !== null && _a !== void 0 ? _a : this.link.targetSelectionRange) !== null && _b !== void 0 ? _b : this.link.range; - } - set range(value) { - this._range = value; - this._rangeCallback(this); - } - get ariaMessage() { - var _a; - const preview = (_a = this.parent.getPreview(this)) === null || _a === void 0 ? void 0 : _a.preview(this.range); - if (!preview) { - return (0, nls_1.localize)(0, null, (0, resources_1.basename)(this.uri), this.range.startLineNumber, this.range.startColumn); - } - else { - return (0, nls_1.localize)(1, null, (0, resources_1.basename)(this.uri), this.range.startLineNumber, this.range.startColumn, preview.value); - } - } - } - exports.OneReference = OneReference; - class FilePreview { - constructor(_modelReference) { - this._modelReference = _modelReference; - } - dispose() { - this._modelReference.dispose(); - } - preview(range, n = 8) { - const model = this._modelReference.object.textEditorModel; - if (!model) { - return undefined; - } - const { startLineNumber, startColumn, endLineNumber, endColumn } = range; - const word = model.getWordUntilPosition({ lineNumber: startLineNumber, column: startColumn - n }); - const beforeRange = new range_1.Range(startLineNumber, word.startColumn, startLineNumber, startColumn); - const afterRange = new range_1.Range(endLineNumber, endColumn, endLineNumber, 1073741824 /* MAX_SAFE_SMALL_INTEGER */); - const before = model.getValueInRange(beforeRange).replace(/^\s+/, ''); - const inside = model.getValueInRange(range); - const after = model.getValueInRange(afterRange).replace(/\s+$/, ''); - return { - value: before + inside + after, - highlight: { start: before.length, end: before.length + inside.length } - }; - } - } - exports.FilePreview = FilePreview; - class FileReferences { - constructor(parent, uri) { - this.parent = parent; - this.uri = uri; - this.children = []; - this._previews = new map_1.ResourceMap(); - } - dispose() { - (0, lifecycle_1.dispose)(this._previews.values()); - this._previews.clear(); - } - getPreview(child) { - return this._previews.get(child.uri); - } - get ariaMessage() { - const len = this.children.length; - if (len === 1) { - return (0, nls_1.localize)(2, null, (0, resources_1.basename)(this.uri), this.uri.fsPath); - } - else { - return (0, nls_1.localize)(3, null, len, (0, resources_1.basename)(this.uri), this.uri.fsPath); - } - } - resolve(textModelResolverService) { - return __awaiter(this, void 0, void 0, function* () { - if (this._previews.size !== 0) { - return this; - } - for (let child of this.children) { - if (this._previews.has(child.uri)) { - continue; - } - try { - const ref = yield textModelResolverService.createModelReference(child.uri); - this._previews.set(child.uri, new FilePreview(ref)); - } - catch (err) { - (0, errors_1.onUnexpectedError)(err); - } - } - return this; - }); - } - } - exports.FileReferences = FileReferences; - class ReferencesModel { - constructor(links, title) { - this.groups = []; - this.references = []; - this._onDidChangeReferenceRange = new event_1.Emitter(); - this.onDidChangeReferenceRange = this._onDidChangeReferenceRange.event; - this._links = links; - this._title = title; - // grouping and sorting - const [providersFirst] = links; - links.sort(ReferencesModel._compareReferences); - let current; - for (let link of links) { - if (!current || !resources_1.extUri.isEqual(current.uri, link.uri, true)) { - // new group - current = new FileReferences(this, link.uri); - this.groups.push(current); - } - // append, check for equality first! - if (current.children.length === 0 || ReferencesModel._compareReferences(link, current.children[current.children.length - 1]) !== 0) { - const oneRef = new OneReference(providersFirst === link, current, link, ref => this._onDidChangeReferenceRange.fire(ref)); - this.references.push(oneRef); - current.children.push(oneRef); - } - } - } - dispose() { - (0, lifecycle_1.dispose)(this.groups); - this._onDidChangeReferenceRange.dispose(); - this.groups.length = 0; - } - clone() { - return new ReferencesModel(this._links, this._title); - } - get title() { - return this._title; - } - get isEmpty() { - return this.groups.length === 0; - } - get ariaMessage() { - if (this.isEmpty) { - return (0, nls_1.localize)(4, null); - } - else if (this.references.length === 1) { - return (0, nls_1.localize)(5, null, this.references[0].uri.fsPath); - } - else if (this.groups.length === 1) { - return (0, nls_1.localize)(6, null, this.references.length, this.groups[0].uri.fsPath); - } - else { - return (0, nls_1.localize)(7, null, this.references.length, this.groups.length); - } - } - nextOrPreviousReference(reference, next) { - let { parent } = reference; - let idx = parent.children.indexOf(reference); - let childCount = parent.children.length; - let 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]; - } - } - nearestReference(resource, position) { - const nearest = this.references.map((ref, idx) => { - return { - 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((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; - } - referenceAt(resource, position) { - for (const ref of this.references) { - if (ref.uri.toString() === resource.toString()) { - if (range_1.Range.containsPosition(ref.range, position)) { - return ref; - } - } - } - return undefined; - } - firstReference() { - for (const ref of this.references) { - if (ref.isProviderFirst) { - return ref; - } - } - return this.references[0]; - } - static _compareReferences(a, b) { - return resources_1.extUri.compare(a.uri, b.uri) || range_1.Range.compareRangesUsingStarts(a.range, b.range); - } - } - exports.ReferencesModel = ReferencesModel; -}); - -define(__m[497/*vs/nls!vs/editor/contrib/gotoSymbol/symbolNavigation*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/symbolNavigation", data); }); -define(__m[498/*vs/nls!vs/editor/contrib/hover/hover*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/hover/hover", data); }); -define(__m[499/*vs/nls!vs/editor/contrib/hover/markdownHoverParticipant*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/hover/markdownHoverParticipant", data); }); -define(__m[500/*vs/nls!vs/editor/contrib/hover/markerHoverParticipant*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/hover/markerHoverParticipant", data); }); -define(__m[501/*vs/nls!vs/editor/contrib/inPlaceReplace/inPlaceReplace*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/inPlaceReplace/inPlaceReplace", data); }); -define(__m[502/*vs/nls!vs/editor/contrib/indentation/indentation*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/indentation/indentation", data); }); -define(__m[503/*vs/nls!vs/editor/contrib/inlineCompletions/ghostTextController*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/inlineCompletions/ghostTextController", data); }); -define(__m[504/*vs/nls!vs/editor/contrib/inlineCompletions/inlineCompletionsHoverParticipant*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/inlineCompletions/inlineCompletionsHoverParticipant", data); }); -define(__m[505/*vs/nls!vs/editor/contrib/linesOperations/linesOperations*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/linesOperations/linesOperations", data); }); -define(__m[506/*vs/nls!vs/editor/contrib/linkedEditing/linkedEditing*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/linkedEditing/linkedEditing", data); }); -define(__m[507/*vs/nls!vs/editor/contrib/links/links*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/links/links", data); }); -define(__m[508/*vs/nls!vs/editor/contrib/message/messageController*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/message/messageController", data); }); -define(__m[509/*vs/nls!vs/editor/contrib/multicursor/multicursor*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/multicursor/multicursor", data); }); -define(__m[510/*vs/nls!vs/editor/contrib/parameterHints/parameterHints*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/parameterHints/parameterHints", data); }); -define(__m[511/*vs/nls!vs/editor/contrib/parameterHints/parameterHintsWidget*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/parameterHints/parameterHintsWidget", data); }); -define(__m[512/*vs/nls!vs/editor/contrib/peekView/peekView*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/peekView/peekView", data); }); -define(__m[513/*vs/nls!vs/editor/contrib/quickAccess/gotoLineQuickAccess*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/quickAccess/gotoLineQuickAccess", data); }); -define(__m[514/*vs/nls!vs/editor/contrib/quickAccess/gotoSymbolQuickAccess*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/quickAccess/gotoSymbolQuickAccess", data); }); -define(__m[515/*vs/nls!vs/editor/contrib/rename/rename*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/rename/rename", data); }); -define(__m[516/*vs/nls!vs/editor/contrib/rename/renameInputField*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/rename/renameInputField", data); }); -define(__m[517/*vs/nls!vs/editor/contrib/smartSelect/smartSelect*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/smartSelect/smartSelect", data); }); -define(__m[518/*vs/nls!vs/editor/contrib/snippet/snippetController2*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/snippet/snippetController2", data); }); -define(__m[519/*vs/nls!vs/editor/contrib/snippet/snippetVariables*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/snippet/snippetVariables", data); }); -define(__m[520/*vs/nls!vs/editor/contrib/suggest/suggest*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/suggest", data); }); -define(__m[521/*vs/nls!vs/editor/contrib/suggest/suggestController*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/suggestController", data); }); -define(__m[522/*vs/nls!vs/editor/contrib/suggest/suggestWidget*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/suggestWidget", data); }); -define(__m[523/*vs/nls!vs/editor/contrib/suggest/suggestWidgetDetails*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/suggestWidgetDetails", data); }); -define(__m[524/*vs/nls!vs/editor/contrib/suggest/suggestWidgetRenderer*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/suggestWidgetRenderer", data); }); -define(__m[525/*vs/nls!vs/editor/contrib/suggest/suggestWidgetStatus*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/suggestWidgetStatus", data); }); -define(__m[526/*vs/nls!vs/editor/contrib/symbolIcons/symbolIcons*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/symbolIcons/symbolIcons", data); }); -define(__m[527/*vs/nls!vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode", data); }); -define(__m[528/*vs/nls!vs/editor/contrib/tokenization/tokenization*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/tokenization/tokenization", data); }); -define(__m[529/*vs/nls!vs/editor/contrib/unusualLineTerminators/unusualLineTerminators*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/unusualLineTerminators/unusualLineTerminators", data); }); -define(__m[530/*vs/nls!vs/editor/contrib/wordHighlighter/wordHighlighter*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/wordHighlighter/wordHighlighter", data); }); -define(__m[531/*vs/nls!vs/editor/contrib/wordOperations/wordOperations*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/wordOperations/wordOperations", data); }); -define(__m[532/*vs/nls!vs/platform/actions/browser/menuEntryActionViewItem*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/actions/browser/menuEntryActionViewItem", data); }); -define(__m[533/*vs/nls!vs/platform/configuration/common/configurationRegistry*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/configuration/common/configurationRegistry", data); }); -define(__m[534/*vs/nls!vs/platform/contextkey/browser/contextKeyService*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/contextkey/browser/contextKeyService", data); }); -define(__m[535/*vs/nls!vs/platform/contextkey/common/contextkeys*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/contextkey/common/contextkeys", data); }); -define(__m[536/*vs/nls!vs/platform/keybinding/common/abstractKeybindingService*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/keybinding/common/abstractKeybindingService", data); }); -define(__m[537/*vs/nls!vs/platform/list/browser/listService*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/list/browser/listService", data); }); -define(__m[538/*vs/nls!vs/platform/markers/common/markers*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/markers/common/markers", data); }); -define(__m[539/*vs/nls!vs/platform/quickinput/browser/commandsQuickAccess*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/quickinput/browser/commandsQuickAccess", data); }); -define(__m[540/*vs/nls!vs/platform/quickinput/browser/helpQuickAccess*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/quickinput/browser/helpQuickAccess", data); }); -define(__m[541/*vs/nls!vs/platform/theme/common/colorRegistry*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/theme/common/colorRegistry", data); }); -define(__m[542/*vs/nls!vs/platform/theme/common/iconRegistry*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/theme/common/iconRegistry", data); }); -define(__m[543/*vs/nls!vs/platform/undoRedo/common/undoRedoService*/], __M([4/*vs/nls*/,5/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/undoRedo/common/undoRedoService", 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[544/*vs/platform/clipboard/browser/clipboardService*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/]), function (require, exports, dom_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.BrowserClipboardService = void 0; - class BrowserClipboardService { - constructor() { - this.mapTextToType = new Map(); // unsupported in web (only in-memory) - this.findText = ''; // unsupported in web (only in-memory) - } - writeText(text, type) { - return __awaiter(this, void 0, void 0, function* () { - // With type: only in-memory is supported - if (type) { - this.mapTextToType.set(type, text); - return; - } - // Guard access to navigator.clipboard with try/catch - // as we have seen DOMExceptions in certain browsers - // due to security policies. - try { - return yield navigator.clipboard.writeText(text); - } - catch (error) { - console.error(error); - } - // Fallback to textarea and execCommand solution - const activeElement = document.activeElement; - const textArea = document.body.appendChild((0, dom_1.$)('textarea', { 'aria-hidden': true })); - textArea.style.height = '1px'; - textArea.style.width = '1px'; - textArea.style.position = 'absolute'; - textArea.value = text; - textArea.focus(); - textArea.select(); - document.execCommand('copy'); - if (activeElement instanceof HTMLElement) { - activeElement.focus(); - } - document.body.removeChild(textArea); - return; - }); - } - readText(type) { - return __awaiter(this, void 0, void 0, function* () { - // With type: only in-memory is supported - if (type) { - return this.mapTextToType.get(type) || ''; - } - // Guard access to navigator.clipboard with try/catch - // as we have seen DOMExceptions in certain browsers - // due to security policies. - try { - return yield navigator.clipboard.readText(); - } - catch (error) { - console.error(error); - return ''; - } - }); - } - readFindText() { - return __awaiter(this, void 0, void 0, function* () { - return this.findText; - }); - } - writeFindText(text) { - return __awaiter(this, void 0, void 0, function* () { - this.findText = text; - }); - } - } - exports.BrowserClipboardService = BrowserClipboardService; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[545/*vs/platform/editor/common/editor*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.EditorOpenContext = void 0; - 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[546/*vs/platform/extensions/common/extensions*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ExtensionIdentifier = void 0; - /** - * **!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. - */ - class ExtensionIdentifier { - constructor(value) { - this.value = value; - this._lower = value.toLowerCase(); - } - /** - * Gives the value by which to index (for equality). - */ - static toKey(id) { - if (typeof id === 'string') { - return id.toLowerCase(); - } - return id._lower; - } - } - exports.ExtensionIdentifier = ExtensionIdentifier; -}); - -//#endregion -define(__m[240/*vs/platform/files/common/files*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.FileKind = void 0; - //#region Utilities - 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 = {})); -}); -//#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[241/*vs/platform/instantiation/common/descriptors*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.SyncDescriptor = void 0; - class SyncDescriptor { - constructor(ctor, staticArguments = [], supportsDelayedInstantiation = false) { - this.ctor = ctor; - this.staticArguments = staticArguments; - this.supportsDelayedInstantiation = supportsDelayedInstantiation; - } - } - 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[75/*vs/platform/instantiation/common/extensions*/], __M([0/*require*/,1/*exports*/,241/*vs/platform/instantiation/common/descriptors*/]), function (require, exports, descriptors_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getSingletonServiceDescriptors = exports.registerSingleton = void 0; - const _registry = []; - function registerSingleton(id, ctorOrDescriptor, supportsDelayedInstantiation) { - if (!(ctorOrDescriptor instanceof descriptors_1.SyncDescriptor)) { - ctorOrDescriptor = new descriptors_1.SyncDescriptor(ctorOrDescriptor, [], supportsDelayedInstantiation); - } - _registry.push([id, ctorOrDescriptor]); - } - 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[547/*vs/platform/instantiation/common/graph*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Graph = exports.Node = void 0; - class Node { - constructor(data) { - this.incoming = new Map(); - this.outgoing = new Map(); - this.data = data; - } - } - exports.Node = Node; - class Graph { - constructor(_hashFn) { - this._hashFn = _hashFn; - this._nodes = new Map(); - // empty - } - roots() { - const ret = []; - for (let node of this._nodes.values()) { - if (node.outgoing.size === 0) { - ret.push(node); - } - } - return ret; - } - insertEdge(from, to) { - const fromNode = this.lookupOrInsertNode(from); - const toNode = this.lookupOrInsertNode(to); - fromNode.outgoing.set(this._hashFn(to), toNode); - toNode.incoming.set(this._hashFn(from), fromNode); - } - removeNode(data) { - const key = this._hashFn(data); - this._nodes.delete(key); - for (let node of this._nodes.values()) { - node.outgoing.delete(key); - node.incoming.delete(key); - } - } - lookupOrInsertNode(data) { - const key = this._hashFn(data); - let node = this._nodes.get(key); - if (!node) { - node = new Node(data); - this._nodes.set(key, node); - } - return node; - } - isEmpty() { - return this._nodes.size === 0; - } - toString() { - let data = []; - for (let [key, value] of this._nodes) { - data.push(`${key}, (incoming)[${[...value.incoming.keys()].join(', ')}], (outgoing)[${[...value.outgoing.keys()].join(',')}]`); - } - return data.join('\n'); - } - /** - * This is brute force and slow and **only** be used - * to trouble shoot. - */ - findCycleSlow() { - for (let [id, node] of this._nodes) { - const seen = new Set([id]); - const res = this._findCycle(node, seen); - if (res) { - return res; - } - } - return undefined; - } - _findCycle(node, seen) { - for (let [id, outgoing] of node.outgoing) { - if (seen.has(id)) { - return [...seen, id].join(' -> '); - } - seen.add(id); - const value = this._findCycle(outgoing, seen); - if (value) { - return value; - } - seen.delete(id); - } - return undefined; - } - } - 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[9/*vs/platform/instantiation/common/instantiation*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.optional = exports.createDecorator = exports.IInstantiationService = exports._util = void 0; - // ------ 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, index, optional }); - } - else { - target[_util.DI_DEPENDENCIES] = [{ id, index, optional }]; - target[_util.DI_TARGET] = target; - } - } - /** - * The *only* valid way to create a {{ServiceIdentifier}}. - */ - function createDecorator(serviceId) { - if (_util.serviceIds.has(serviceId)) { - return _util.serviceIds.get(serviceId); - } - const 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 = () => 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[138/*vs/editor/browser/services/bulkEditService*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/,24/*vs/base/common/uri*/,20/*vs/base/common/types*/]), function (require, exports, instantiation_1, uri_1, types_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ResourceFileEdit = exports.ResourceTextEdit = exports.ResourceEdit = exports.IBulkEditService = void 0; - exports.IBulkEditService = (0, instantiation_1.createDecorator)('IWorkspaceEditService'); - function isWorkspaceFileEdit(thing) { - return (0, types_1.isObject)(thing) && (Boolean(thing.newUri) || Boolean(thing.oldUri)); - } - function isWorkspaceTextEdit(thing) { - return (0, types_1.isObject)(thing) && uri_1.URI.isUri(thing.resource) && (0, types_1.isObject)(thing.edit); - } - class ResourceEdit { - constructor(metadata) { - this.metadata = metadata; - } - static convert(edit) { - return edit.edits.map(edit => { - if (isWorkspaceTextEdit(edit)) { - return new ResourceTextEdit(edit.resource, edit.edit, edit.modelVersionId, edit.metadata); - } - if (isWorkspaceFileEdit(edit)) { - return new ResourceFileEdit(edit.oldUri, edit.newUri, edit.options, edit.metadata); - } - throw new Error('Unsupported edit'); - }); - } - } - exports.ResourceEdit = ResourceEdit; - class ResourceTextEdit extends ResourceEdit { - constructor(resource, textEdit, versionId, metadata) { - super(metadata); - this.resource = resource; - this.textEdit = textEdit; - this.versionId = versionId; - } - } - exports.ResourceTextEdit = ResourceTextEdit; - class ResourceFileEdit extends ResourceEdit { - constructor(oldResource, newResource, options, metadata) { - super(metadata); - this.oldResource = oldResource; - this.newResource = newResource; - this.options = options; - } - } - exports.ResourceFileEdit = ResourceFileEdit; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[28/*vs/editor/browser/services/codeEditorService*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ICodeEditorService = void 0; - exports.ICodeEditorService = (0, 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[76/*vs/editor/common/services/editorWorkerService*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.IEditorWorkerService = exports.ID_EDITOR_WORKER_SERVICE = void 0; - exports.ID_EDITOR_WORKER_SERVICE = 'editorWorkerService'; - exports.IEditorWorkerService = (0, 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[183/*vs/editor/common/services/markersDecorationService*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.IMarkerDecorationsService = void 0; - exports.IMarkerDecorationsService = (0, 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[57/*vs/editor/common/services/modeService*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.IModeService = void 0; - exports.IModeService = (0, 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[36/*vs/editor/common/services/modelService*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.shouldSynchronizeModel = exports.IModelService = void 0; - exports.IModelService = (0, 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[139/*vs/editor/common/modes/languageFeatureRegistry*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,92/*vs/base/common/hash*/,2/*vs/base/common/lifecycle*/,49/*vs/base/common/map*/,102/*vs/base/common/numbers*/,382/*vs/editor/common/modes/languageSelector*/,36/*vs/editor/common/services/modelService*/]), function (require, exports, event_1, hash_1, lifecycle_1, map_1, numbers_1, languageSelector_1, modelService_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.LanguageFeatureRequestDelays = exports.LanguageFeatureRegistry = void 0; - function isExclusive(selector) { - if (typeof selector === 'string') { - return false; - } - else if (Array.isArray(selector)) { - return selector.every(isExclusive); - } - else { - return !!selector.exclusive; // TODO: microsoft/TypeScript#42768 - } - } - class LanguageFeatureRegistry { - constructor() { - this._clock = 0; - this._entries = []; - this._onDidChange = new event_1.Emitter(); - } - get onDidChange() { - return this._onDidChange.event; - } - register(selector, provider) { - let entry = { - selector, - provider, - _score: -1, - _time: this._clock++ - }; - this._entries.push(entry); - this._lastCandidate = undefined; - this._onDidChange.fire(this._entries.length); - return (0, lifecycle_1.toDisposable)(() => { - if (entry) { - let idx = this._entries.indexOf(entry); - if (idx >= 0) { - this._entries.splice(idx, 1); - this._lastCandidate = undefined; - this._onDidChange.fire(this._entries.length); - entry = undefined; - } - } - }); - } - has(model) { - return this.all(model).length > 0; - } - all(model) { - if (!model) { - return []; - } - this._updateScores(model); - const result = []; - // from registry - for (let entry of this._entries) { - if (entry._score > 0) { - result.push(entry.provider); - } - } - return result; - } - ordered(model) { - const result = []; - this._orderedForEach(model, entry => result.push(entry.provider)); - return result; - } - orderedGroups(model) { - const result = []; - let lastBucket; - let lastBucketScore; - this._orderedForEach(model, entry => { - if (lastBucket && lastBucketScore === entry._score) { - lastBucket.push(entry.provider); - } - else { - lastBucketScore = entry._score; - lastBucket = [entry.provider]; - result.push(lastBucket); - } - }); - return result; - } - _orderedForEach(model, callback) { - if (!model) { - return; - } - this._updateScores(model); - for (const entry of this._entries) { - if (entry._score > 0) { - callback(entry); - } - } - } - _updateScores(model) { - let 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 (let entry of this._entries) { - entry._score = (0, languageSelector_1.score)(entry.selector, model.uri, model.getLanguageIdentifier().language, (0, modelService_1.shouldSynchronizeModel)(model)); - if (isExclusive(entry.selector) && entry._score > 0) { - // support for one exclusive selector that overwrites - // any other selector - for (let entry of this._entries) { - entry._score = 0; - } - entry._score = 1000; - break; - } - } - // needs sorting - this._entries.sort(LanguageFeatureRegistry._compareByScoreAndTime); - } - static _compareByScoreAndTime(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; - } - } - } - exports.LanguageFeatureRegistry = LanguageFeatureRegistry; - /** - * Keeps moving average per model and set of providers so that requests - * can be debounce according to the provider performance - */ - class LanguageFeatureRequestDelays { - constructor(_registry, min, max = Number.MAX_SAFE_INTEGER) { - this._registry = _registry; - this.min = min; - this.max = max; - this._cache = new map_1.LRUCache(50, 0.7); - } - _key(model) { - return model.id + (0, hash_1.hash)(this._registry.all(model)); - } - _clamp(value) { - if (value === undefined) { - return this.min; - } - else { - return Math.min(this.max, Math.max(this.min, Math.floor(value * 1.3))); - } - } - get(model) { - const key = this._key(model); - const avg = this._cache.get(key); - return this._clamp(avg === null || avg === void 0 ? void 0 : avg.value); - } - update(model, value) { - const key = this._key(model); - let avg = this._cache.get(key); - if (!avg) { - avg = new numbers_1.MovingAverage(); - this._cache.set(key, avg); - } - avg.update(value); - return this.get(model); - } - } - exports.LanguageFeatureRequestDelays = LanguageFeatureRequestDelays; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/editor/common/modes*/], __M([0/*require*/,1/*exports*/,24/*vs/base/common/uri*/,3/*vs/editor/common/core/range*/,139/*vs/editor/common/modes/languageFeatureRegistry*/,390/*vs/editor/common/modes/tokenizationRegistry*/,27/*vs/base/common/codicons*/]), function (require, exports, uri_1, range_1, languageFeatureRegistry_1, tokenizationRegistry_1, codicons_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.TokenizationRegistry = exports.DocumentRangeSemanticTokensProviderRegistry = exports.DocumentSemanticTokensProviderRegistry = exports.FoldingRangeProviderRegistry = exports.SelectionRangeRegistry = exports.ColorProviderRegistry = exports.LinkProviderRegistry = exports.OnTypeFormattingEditProviderRegistry = exports.DocumentRangeFormattingEditProviderRegistry = exports.DocumentFormattingEditProviderRegistry = exports.CodeActionProviderRegistry = exports.InlayHintsProviderRegistry = exports.CodeLensProviderRegistry = exports.TypeDefinitionProviderRegistry = exports.ImplementationProviderRegistry = exports.DeclarationProviderRegistry = exports.DefinitionProviderRegistry = exports.LinkedEditingRangeProviderRegistry = exports.DocumentHighlightProviderRegistry = exports.DocumentSymbolProviderRegistry = exports.HoverProviderRegistry = exports.SignatureHelpProviderRegistry = exports.InlineCompletionsProviderRegistry = exports.CompletionProviderRegistry = exports.RenameProviderRegistry = exports.ReferenceProviderRegistry = exports.InlayHintKind = exports.FoldingRangeKind = exports.SymbolKinds = exports.isLocationLink = exports.DocumentHighlightKind = exports.SignatureHelpTriggerKind = exports.InlineCompletionTriggerKind = exports.completionKindFromString = exports.completionKindToCssClass = exports.TokenMetadata = exports.LanguageIdentifier = void 0; - /** - * @internal - */ - class LanguageIdentifier { - constructor(language, id) { - this.language = language; - this.id = id; - } - } - exports.LanguageIdentifier = LanguageIdentifier; - /** - * @internal - */ - class TokenMetadata { - static getLanguageId(metadata) { - return (metadata & 255 /* LANGUAGEID_MASK */) >>> 0 /* LANGUAGEID_OFFSET */; - } - static getTokenType(metadata) { - return (metadata & 1792 /* TOKEN_TYPE_MASK */) >>> 8 /* TOKEN_TYPE_OFFSET */; - } - static getFontStyle(metadata) { - return (metadata & 14336 /* FONT_STYLE_MASK */) >>> 11 /* FONT_STYLE_OFFSET */; - } - static getForeground(metadata) { - return (metadata & 8372224 /* FOREGROUND_MASK */) >>> 14 /* FOREGROUND_OFFSET */; - } - static getBackground(metadata) { - return (metadata & 4286578688 /* BACKGROUND_MASK */) >>> 23 /* BACKGROUND_OFFSET */; - } - static getClassNameFromMetadata(metadata) { - let foreground = this.getForeground(metadata); - let className = 'mtk' + foreground; - let fontStyle = this.getFontStyle(metadata); - if (fontStyle & 1 /* Italic */) { - className += ' mtki'; - } - if (fontStyle & 2 /* Bold */) { - className += ' mtkb'; - } - if (fontStyle & 4 /* Underline */) { - className += ' mtku'; - } - return className; - } - static getInlineStyleFromMetadata(metadata, colorMap) { - const foreground = this.getForeground(metadata); - const fontStyle = this.getFontStyle(metadata); - let 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; - } - } - exports.TokenMetadata = TokenMetadata; - /** - * @internal - */ - exports.completionKindToCssClass = (function () { - let data = Object.create(null); - data[0 /* Method */] = 'symbol-method'; - data[1 /* Function */] = 'symbol-function'; - data[2 /* Constructor */] = 'symbol-constructor'; - data[3 /* Field */] = 'symbol-field'; - data[4 /* Variable */] = 'symbol-variable'; - data[5 /* Class */] = 'symbol-class'; - data[6 /* Struct */] = 'symbol-struct'; - data[7 /* Interface */] = 'symbol-interface'; - data[8 /* Module */] = 'symbol-module'; - data[9 /* Property */] = 'symbol-property'; - data[10 /* Event */] = 'symbol-event'; - data[11 /* Operator */] = 'symbol-operator'; - data[12 /* Unit */] = 'symbol-unit'; - data[13 /* Value */] = 'symbol-value'; - data[14 /* Constant */] = 'symbol-constant'; - data[15 /* Enum */] = 'symbol-enum'; - data[16 /* EnumMember */] = 'symbol-enum-member'; - data[17 /* Keyword */] = 'symbol-keyword'; - data[27 /* Snippet */] = 'symbol-snippet'; - data[18 /* Text */] = 'symbol-text'; - data[19 /* Color */] = 'symbol-color'; - data[20 /* File */] = 'symbol-file'; - data[21 /* Reference */] = 'symbol-reference'; - data[22 /* Customcolor */] = 'symbol-customcolor'; - data[23 /* Folder */] = 'symbol-folder'; - data[24 /* TypeParameter */] = 'symbol-type-parameter'; - data[25 /* User */] = 'account'; - data[26 /* Issue */] = 'issues'; - return function (kind) { - const name = data[kind]; - let codicon = name && codicons_1.iconRegistry.get(name); - if (!codicon) { - console.info('No codicon found for CompletionItemKind ' + kind); - codicon = codicons_1.Codicon.symbolProperty; - } - return codicon.classNames; - }; - })(); - /** - * @internal - */ - exports.completionKindFromString = (function () { - let 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'] = 27 /* 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 */; - data['account'] = 25 /* User */; - data['issue'] = 26 /* Issue */; - return function (value, strict) { - let res = data[value]; - if (typeof res === 'undefined' && !strict) { - res = 9 /* Property */; - } - return res; - }; - })(); - /** - * How an {@link InlineCompletionsProvider inline completion provider} was triggered. - */ - var InlineCompletionTriggerKind; - (function (InlineCompletionTriggerKind) { - /** - * Completion was triggered automatically while editing. - * It is sufficient to return a single completion item in this case. - */ - InlineCompletionTriggerKind[InlineCompletionTriggerKind["Automatic"] = 0] = "Automatic"; - /** - * Completion was triggered explicitly by a user gesture. - * Return multiple completion items to enable cycling through them. - */ - InlineCompletionTriggerKind[InlineCompletionTriggerKind["Explicit"] = 1] = "Explicit"; - })(InlineCompletionTriggerKind = exports.InlineCompletionTriggerKind || (exports.InlineCompletionTriggerKind = {})); - 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) { - const 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 */); - const 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) { - const symbolName = byKind.get(kind); - let codicon = symbolName && codicons_1.iconRegistry.get('symbol-' + symbolName); - if (!codicon) { - console.info('No codicon found for SymbolKind ' + kind); - codicon = codicons_1.Codicon.symbolProperty; - } - return `${inline ? 'inline' : 'block'} ${codicon.classNames}`; - } - SymbolKinds.toCssClassName = toCssClassName; - })(SymbolKinds = exports.SymbolKinds || (exports.SymbolKinds = {})); - class FoldingRangeKind { - /** - * Creates a new {@link FoldingRangeKind}. - * - * @param value of the kind. - */ - constructor(value) { - this.value = value; - } - } - exports.FoldingRangeKind = FoldingRangeKind; - /** - * 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'); - var InlayHintKind; - (function (InlayHintKind) { - InlayHintKind[InlayHintKind["Other"] = 0] = "Other"; - InlayHintKind[InlayHintKind["Type"] = 1] = "Type"; - InlayHintKind[InlayHintKind["Parameter"] = 2] = "Parameter"; - })(InlayHintKind = exports.InlayHintKind || (exports.InlayHintKind = {})); - // --- 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.InlineCompletionsProviderRegistry = 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.LinkedEditingRangeProviderRegistry = 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.InlayHintsProviderRegistry = 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[85/*vs/editor/common/core/lineTokens*/], __M([0/*require*/,1/*exports*/,18/*vs/editor/common/modes*/]), function (require, exports, modes_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.SlicedLineTokens = exports.LineTokens = void 0; - class LineTokens { - constructor(tokens, text) { - this._lineTokensBrand = undefined; - this._tokens = tokens; - this._tokensCount = (this._tokens.length >>> 1); - this._text = text; - } - static createEmpty(lineContent) { - const defaultMetadata = LineTokens.defaultTokenMetadata; - const tokens = new Uint32Array(2); - tokens[0] = lineContent.length; - tokens[1] = defaultMetadata; - return new LineTokens(tokens, lineContent); - } - equals(other) { - if (other instanceof LineTokens) { - return this.slicedEquals(other, 0, this._tokensCount); - } - return false; - } - slicedEquals(other, sliceFromTokenIndex, sliceTokenCount) { - if (this._text !== other._text) { - return false; - } - if (this._tokensCount !== other._tokensCount) { - return false; - } - const from = (sliceFromTokenIndex << 1); - const to = from + (sliceTokenCount << 1); - for (let i = from; i < to; i++) { - if (this._tokens[i] !== other._tokens[i]) { - return false; - } - } - return true; - } - getLineContent() { - return this._text; - } - getCount() { - return this._tokensCount; - } - getStartOffset(tokenIndex) { - if (tokenIndex > 0) { - return this._tokens[(tokenIndex - 1) << 1]; - } - return 0; - } - getMetadata(tokenIndex) { - const metadata = this._tokens[(tokenIndex << 1) + 1]; - return metadata; - } - getLanguageId(tokenIndex) { - const metadata = this._tokens[(tokenIndex << 1) + 1]; - return modes_1.TokenMetadata.getLanguageId(metadata); - } - getStandardTokenType(tokenIndex) { - const metadata = this._tokens[(tokenIndex << 1) + 1]; - return modes_1.TokenMetadata.getTokenType(metadata); - } - getForeground(tokenIndex) { - const metadata = this._tokens[(tokenIndex << 1) + 1]; - return modes_1.TokenMetadata.getForeground(metadata); - } - getClassName(tokenIndex) { - const metadata = this._tokens[(tokenIndex << 1) + 1]; - return modes_1.TokenMetadata.getClassNameFromMetadata(metadata); - } - getInlineStyle(tokenIndex, colorMap) { - const metadata = this._tokens[(tokenIndex << 1) + 1]; - return modes_1.TokenMetadata.getInlineStyleFromMetadata(metadata, colorMap); - } - getEndOffset(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. - */ - findTokenIndexAtOffset(offset) { - return LineTokens.findIndexInTokensArray(this._tokens, offset); - } - inflate() { - return this; - } - sliceAndInflate(startOffset, endOffset, deltaOffset) { - return new SlicedLineTokens(this, startOffset, endOffset, deltaOffset); - } - static convertToEndOffset(tokens, lineTextLength) { - const tokenCount = (tokens.length >>> 1); - const lastTokenIndex = tokenCount - 1; - for (let tokenIndex = 0; tokenIndex < lastTokenIndex; tokenIndex++) { - tokens[tokenIndex << 1] = tokens[(tokenIndex + 1) << 1]; - } - tokens[lastTokenIndex << 1] = lineTextLength; - } - static findIndexInTokensArray(tokens, desiredIndex) { - if (tokens.length <= 2) { - return 0; - } - let low = 0; - let high = (tokens.length >>> 1) - 1; - while (low < high) { - const mid = low + Math.floor((high - low) / 2); - const 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; - } - /** - * @pure - * @param insertTokens Must be sorted by offset. - */ - withInserted(insertTokens) { - if (insertTokens.length === 0) { - return this; - } - let nextOriginalTokenIdx = 0; - let nextInsertTokenIdx = 0; - let text = ''; - const newTokens = new Array(); - let originalEndOffset = 0; - while (true) { - let nextOriginalTokenEndOffset = nextOriginalTokenIdx < this._tokensCount ? this._tokens[nextOriginalTokenIdx << 1] : -1; - let nextInsertToken = nextInsertTokenIdx < insertTokens.length ? insertTokens[nextInsertTokenIdx] : null; - if (nextOriginalTokenEndOffset !== -1 && (nextInsertToken === null || nextOriginalTokenEndOffset <= nextInsertToken.offset)) { - // original token ends before next insert token - text += this._text.substring(originalEndOffset, nextOriginalTokenEndOffset); - const metadata = this._tokens[(nextOriginalTokenIdx << 1) + 1]; - newTokens.push(text.length, metadata); - nextOriginalTokenIdx++; - originalEndOffset = nextOriginalTokenEndOffset; - } - else if (nextInsertToken) { - if (nextInsertToken.offset > originalEndOffset) { - // insert token is in the middle of the next token. - text += this._text.substring(originalEndOffset, nextInsertToken.offset); - const metadata = this._tokens[(nextOriginalTokenIdx << 1) + 1]; - newTokens.push(text.length, metadata); - originalEndOffset = nextInsertToken.offset; - } - text += nextInsertToken.text; - newTokens.push(text.length, nextInsertToken.tokenMetadata); - nextInsertTokenIdx++; - } - else { - break; - } - } - return new LineTokens(new Uint32Array(newTokens), text); - } - } - exports.LineTokens = LineTokens; - LineTokens.defaultTokenMetadata = ((0 /* None */ << 11 /* FONT_STYLE_OFFSET */) - | (1 /* DefaultForeground */ << 14 /* FOREGROUND_OFFSET */) - | (2 /* DefaultBackground */ << 23 /* BACKGROUND_OFFSET */)) >>> 0; - class SlicedLineTokens { - constructor(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 (let i = this._firstTokenIndex, len = source.getCount(); i < len; i++) { - const tokenStartOffset = source.getStartOffset(i); - if (tokenStartOffset >= endOffset) { - break; - } - this._tokensCount++; - } - } - equals(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; - } - getCount() { - return this._tokensCount; - } - getForeground(tokenIndex) { - return this._source.getForeground(this._firstTokenIndex + tokenIndex); - } - getEndOffset(tokenIndex) { - const tokenEndOffset = this._source.getEndOffset(this._firstTokenIndex + tokenIndex); - return Math.min(this._endOffset, tokenEndOffset) - this._startOffset + this._deltaOffset; - } - getClassName(tokenIndex) { - return this._source.getClassName(this._firstTokenIndex + tokenIndex); - } - getInlineStyle(tokenIndex, colorMap) { - return this._source.getInlineStyle(this._firstTokenIndex + tokenIndex, colorMap); - } - findTokenIndexAtOffset(offset) { - return this._source.findTokenIndexAtOffset(offset + this._startOffset - this._deltaOffset) - this._firstTokenIndex; - } - } - 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[140/*vs/editor/common/model/tokensStore*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,85/*vs/editor/common/core/lineTokens*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,18/*vs/editor/common/modes*/]), function (require, exports, arrays, lineTokens_1, position_1, range_1, modes_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.TokensStore = exports.TokensStore2 = exports.MultilineTokens = exports.MultilineTokens2 = exports.LineTokens2 = exports.SparseEncodedTokens = exports.MultilineTokensBuilder = exports.countEOL = void 0; - function countEOL(text) { - let eolCount = 0; - let firstLineLength = 0; - let lastLineStart = 0; - let eol = 0 /* Unknown */; - for (let i = 0, len = text.length; i < len; i++) { - const 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 - eol |= 2 /* CRLF */; - i++; // skip \n - } - else { - // \r... case - eol |= 3 /* Invalid */; - } - lastLineStart = i + 1; - } - else if (chr === 10 /* LineFeed */) { - // \n... case - eol |= 1 /* LF */; - if (eolCount === 0) { - firstLineLength = i; - } - eolCount++; - lastLineStart = i + 1; - } - } - if (eolCount === 0) { - firstLineLength = text.length; - } - return [eolCount, firstLineLength, text.length - lastLineStart, eol]; - } - 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; - } - const EMPTY_LINE_TOKENS = (new Uint32Array(0)).buffer; - class MultilineTokensBuilder { - constructor() { - this.tokens = []; - } - add(lineNumber, lineTokens) { - if (this.tokens.length > 0) { - const last = this.tokens[this.tokens.length - 1]; - const lastLineNumber = last.startLineNumber + last.tokens.length - 1; - if (lastLineNumber + 1 === lineNumber) { - // append - last.tokens.push(lineTokens); - return; - } - } - this.tokens.push(new MultilineTokens(lineNumber, [lineTokens])); - } - } - exports.MultilineTokensBuilder = MultilineTokensBuilder; - class SparseEncodedTokens { - constructor(tokens) { - this._tokens = tokens; - this._tokenCount = tokens.length / 4; - } - toString(startLineNumber) { - let pieces = []; - for (let i = 0; i < this._tokenCount; i++) { - pieces.push(`(${this._getDeltaLine(i) + startLineNumber},${this._getStartCharacter(i)}-${this._getEndCharacter(i)})`); - } - return `[${pieces.join(',')}]`; - } - getMaxDeltaLine() { - const tokenCount = this._getTokenCount(); - if (tokenCount === 0) { - return -1; - } - return this._getDeltaLine(tokenCount - 1); - } - getRange() { - const tokenCount = this._getTokenCount(); - if (tokenCount === 0) { - return null; - } - const startChar = this._getStartCharacter(0); - const maxDeltaLine = this._getDeltaLine(tokenCount - 1); - const endChar = this._getEndCharacter(tokenCount - 1); - return new range_1.Range(0, startChar + 1, maxDeltaLine, endChar + 1); - } - _getTokenCount() { - return this._tokenCount; - } - _getDeltaLine(tokenIndex) { - return this._tokens[4 * tokenIndex]; - } - _getStartCharacter(tokenIndex) { - return this._tokens[4 * tokenIndex + 1]; - } - _getEndCharacter(tokenIndex) { - return this._tokens[4 * tokenIndex + 2]; - } - isEmpty() { - return (this._getTokenCount() === 0); - } - getLineTokens(deltaLine) { - let low = 0; - let high = this._getTokenCount() - 1; - while (low < high) { - const mid = low + Math.floor((high - low) / 2); - const midDeltaLine = this._getDeltaLine(mid); - if (midDeltaLine < deltaLine) { - low = mid + 1; - } - else if (midDeltaLine > deltaLine) { - high = mid - 1; - } - else { - let min = mid; - while (min > low && this._getDeltaLine(min - 1) === deltaLine) { - min--; - } - let max = mid; - while (max < high && this._getDeltaLine(max + 1) === deltaLine) { - max++; - } - return new LineTokens2(this._tokens.subarray(4 * min, 4 * max + 4)); - } - } - if (this._getDeltaLine(low) === deltaLine) { - return new LineTokens2(this._tokens.subarray(4 * low, 4 * low + 4)); - } - return null; - } - clear() { - this._tokenCount = 0; - } - removeTokens(startDeltaLine, startChar, endDeltaLine, endChar) { - const tokens = this._tokens; - const tokenCount = this._tokenCount; - let newTokenCount = 0; - let hasDeletedTokens = false; - let firstDeltaLine = 0; - for (let i = 0; i < tokenCount; i++) { - const srcOffset = 4 * i; - const tokenDeltaLine = tokens[srcOffset]; - const tokenStartCharacter = tokens[srcOffset + 1]; - const tokenEndCharacter = tokens[srcOffset + 2]; - const tokenMetadata = tokens[srcOffset + 3]; - if ((tokenDeltaLine > startDeltaLine || (tokenDeltaLine === startDeltaLine && tokenEndCharacter >= startChar)) - && (tokenDeltaLine < endDeltaLine || (tokenDeltaLine === endDeltaLine && tokenStartCharacter <= endChar))) { - hasDeletedTokens = true; - } - else { - if (newTokenCount === 0) { - firstDeltaLine = tokenDeltaLine; - } - if (hasDeletedTokens) { - // must move the token to the left - const destOffset = 4 * newTokenCount; - tokens[destOffset] = tokenDeltaLine - firstDeltaLine; - tokens[destOffset + 1] = tokenStartCharacter; - tokens[destOffset + 2] = tokenEndCharacter; - tokens[destOffset + 3] = tokenMetadata; - } - newTokenCount++; - } - } - this._tokenCount = newTokenCount; - return firstDeltaLine; - } - split(startDeltaLine, startChar, endDeltaLine, endChar) { - const tokens = this._tokens; - const tokenCount = this._tokenCount; - let aTokens = []; - let bTokens = []; - let destTokens = aTokens; - let destOffset = 0; - let destFirstDeltaLine = 0; - for (let i = 0; i < tokenCount; i++) { - const srcOffset = 4 * i; - const tokenDeltaLine = tokens[srcOffset]; - const tokenStartCharacter = tokens[srcOffset + 1]; - const tokenEndCharacter = tokens[srcOffset + 2]; - const tokenMetadata = tokens[srcOffset + 3]; - if ((tokenDeltaLine > startDeltaLine || (tokenDeltaLine === startDeltaLine && tokenEndCharacter >= startChar))) { - if ((tokenDeltaLine < endDeltaLine || (tokenDeltaLine === endDeltaLine && tokenStartCharacter <= endChar))) { - // this token is touching the range - continue; - } - else { - // this token is after the range - if (destTokens !== bTokens) { - // this token is the first token after the range - destTokens = bTokens; - destOffset = 0; - destFirstDeltaLine = tokenDeltaLine; - } - } - } - destTokens[destOffset++] = tokenDeltaLine - destFirstDeltaLine; - destTokens[destOffset++] = tokenStartCharacter; - destTokens[destOffset++] = tokenEndCharacter; - destTokens[destOffset++] = tokenMetadata; - } - return [new SparseEncodedTokens(new Uint32Array(aTokens)), new SparseEncodedTokens(new Uint32Array(bTokens)), destFirstDeltaLine]; - } - acceptDeleteRange(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 - // - const tokens = this._tokens; - const tokenCount = this._tokenCount; - const deletedLineCount = (endDeltaLine - startDeltaLine); - let newTokenCount = 0; - let hasDeletedTokens = false; - for (let i = 0; i < tokenCount; i++) { - const srcOffset = 4 * i; - let tokenDeltaLine = tokens[srcOffset]; - let tokenStartCharacter = tokens[srcOffset + 1]; - let tokenEndCharacter = tokens[srcOffset + 2]; - const 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!`); - } - const destOffset = 4 * newTokenCount; - tokens[destOffset] = tokenDeltaLine; - tokens[destOffset + 1] = tokenStartCharacter; - tokens[destOffset + 2] = tokenEndCharacter; - tokens[destOffset + 3] = tokenMetadata; - newTokenCount++; - } - this._tokenCount = newTokenCount; - } - acceptInsertText(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 - // | ----------- - // - const isInsertingPreciselyOneWordCharacter = (eolCount === 0 - && firstLineLength === 1 - && ((firstCharCode >= 48 /* Digit0 */ && firstCharCode <= 57 /* Digit9 */) - || (firstCharCode >= 65 /* A */ && firstCharCode <= 90 /* Z */) - || (firstCharCode >= 97 /* a */ && firstCharCode <= 122 /* z */))); - const tokens = this._tokens; - const tokenCount = this._tokenCount; - for (let i = 0; i < tokenCount; i++) { - const offset = 4 * i; - let tokenDeltaLine = tokens[offset]; - let tokenStartCharacter = tokens[offset + 1]; - let 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 { - const tokenLength = tokenEndCharacter - tokenStartCharacter; - tokenStartCharacter = lastLineLength + (tokenStartCharacter - character); - tokenEndCharacter = tokenStartCharacter + tokenLength; - } - } - else { - tokenDeltaLine += eolCount; - } - } - tokens[offset] = tokenDeltaLine; - tokens[offset + 1] = tokenStartCharacter; - tokens[offset + 2] = tokenEndCharacter; - } - } - } - exports.SparseEncodedTokens = SparseEncodedTokens; - class LineTokens2 { - constructor(tokens) { - this._tokens = tokens; - } - getCount() { - return this._tokens.length / 4; - } - getStartCharacter(tokenIndex) { - return this._tokens[4 * tokenIndex + 1]; - } - getEndCharacter(tokenIndex) { - return this._tokens[4 * tokenIndex + 2]; - } - getMetadata(tokenIndex) { - return this._tokens[4 * tokenIndex + 3]; - } - } - exports.LineTokens2 = LineTokens2; - class MultilineTokens2 { - constructor(startLineNumber, tokens) { - this.startLineNumber = startLineNumber; - this.tokens = tokens; - this.endLineNumber = this.startLineNumber + this.tokens.getMaxDeltaLine(); - } - toString() { - return this.tokens.toString(this.startLineNumber); - } - _updateEndLineNumber() { - this.endLineNumber = this.startLineNumber + this.tokens.getMaxDeltaLine(); - } - isEmpty() { - return this.tokens.isEmpty(); - } - getLineTokens(lineNumber) { - if (this.startLineNumber <= lineNumber && lineNumber <= this.endLineNumber) { - return this.tokens.getLineTokens(lineNumber - this.startLineNumber); - } - return null; - } - getRange() { - const deltaRange = this.tokens.getRange(); - if (!deltaRange) { - return deltaRange; - } - return new range_1.Range(this.startLineNumber + deltaRange.startLineNumber, deltaRange.startColumn, this.startLineNumber + deltaRange.endLineNumber, deltaRange.endColumn); - } - removeTokens(range) { - const startLineIndex = range.startLineNumber - this.startLineNumber; - const endLineIndex = range.endLineNumber - this.startLineNumber; - this.startLineNumber += this.tokens.removeTokens(startLineIndex, range.startColumn - 1, endLineIndex, range.endColumn - 1); - this._updateEndLineNumber(); - } - split(range) { - // split tokens to two: - // a) all the tokens before `range` - // b) all the tokens after `range` - const startLineIndex = range.startLineNumber - this.startLineNumber; - const endLineIndex = range.endLineNumber - this.startLineNumber; - const [a, b, bDeltaLine] = this.tokens.split(startLineIndex, range.startColumn - 1, endLineIndex, range.endColumn - 1); - return [new MultilineTokens2(this.startLineNumber, a), new MultilineTokens2(this.startLineNumber + bDeltaLine, b)]; - } - applyEdit(range, text) { - const [eolCount, firstLineLength, lastLineLength] = countEOL(text); - this.acceptEdit(range, eolCount, firstLineLength, lastLineLength, text.length > 0 ? text.charCodeAt(0) : 0 /* Null */); - } - acceptEdit(range, eolCount, firstLineLength, lastLineLength, firstCharCode) { - this._acceptDeleteRange(range); - this._acceptInsertText(new position_1.Position(range.startLineNumber, range.startColumn), eolCount, firstLineLength, lastLineLength, firstCharCode); - this._updateEndLineNumber(); - } - _acceptDeleteRange(range) { - if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) { - // Nothing to delete - return; - } - const firstLineIndex = range.startLineNumber - this.startLineNumber; - const lastLineIndex = range.endLineNumber - this.startLineNumber; - if (lastLineIndex < 0) { - // this deletion occurs entirely before this block, so we only need to adjust line numbers - const deletedLinesCount = lastLineIndex - firstLineIndex; - this.startLineNumber -= deletedLinesCount; - return; - } - const 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) { - const 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); - } - } - _acceptInsertText(position, eolCount, firstLineLength, lastLineLength, firstCharCode) { - if (eolCount === 0 && firstLineLength === 0) { - // Nothing to insert - return; - } - const 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; - } - const 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); - } - } - exports.MultilineTokens2 = MultilineTokens2; - class MultilineTokens { - constructor(startLineNumber, tokens) { - this.startLineNumber = startLineNumber; - this.tokens = tokens; - } - } - exports.MultilineTokens = MultilineTokens; - function toUint32Array(arr) { - if (arr instanceof Uint32Array) { - return arr; - } - else { - return new Uint32Array(arr); - } - } - class TokensStore2 { - constructor() { - this._pieces = []; - this._isComplete = false; - } - flush() { - this._pieces = []; - this._isComplete = false; - } - isEmpty() { - return (this._pieces.length === 0); - } - set(pieces, isComplete) { - this._pieces = pieces || []; - this._isComplete = isComplete; - } - setPartial(_range, pieces) { - // console.log(`setPartial ${_range} ${pieces.map(p => p.toString()).join(', ')}`); - let range = _range; - if (pieces.length > 0) { - const _firstRange = pieces[0].getRange(); - const _lastRange = pieces[pieces.length - 1].getRange(); - if (!_firstRange || !_lastRange) { - return _range; - } - range = _range.plusRange(_firstRange).plusRange(_lastRange); - } - let insertPosition = null; - for (let i = 0, len = this._pieces.length; i < len; i++) { - const piece = this._pieces[i]; - if (piece.endLineNumber < range.startLineNumber) { - // this piece is before the range - continue; - } - if (piece.startLineNumber > range.endLineNumber) { - // this piece is after the range, so mark the spot before this piece - // as a good insertion position and stop looping - insertPosition = insertPosition || { index: i }; - break; - } - // this piece might intersect with the range - piece.removeTokens(range); - if (piece.isEmpty()) { - // remove the piece if it became empty - this._pieces.splice(i, 1); - i--; - len--; - continue; - } - if (piece.endLineNumber < range.startLineNumber) { - // after removal, this piece is before the range - continue; - } - if (piece.startLineNumber > range.endLineNumber) { - // after removal, this piece is after the range - insertPosition = insertPosition || { index: i }; - continue; - } - // after removal, this piece contains the range - const [a, b] = piece.split(range); - if (a.isEmpty()) { - // this piece is actually after the range - insertPosition = insertPosition || { index: i }; - continue; - } - if (b.isEmpty()) { - // this piece is actually before the range - continue; - } - this._pieces.splice(i, 1, a, b); - i++; - len++; - insertPosition = insertPosition || { index: i }; - } - insertPosition = insertPosition || { index: this._pieces.length }; - if (pieces.length > 0) { - this._pieces = arrays.arrayInsert(this._pieces, insertPosition.index, pieces); - } - // console.log(`I HAVE ${this._pieces.length} pieces`); - // console.log(`${this._pieces.map(p => p.toString()).join('\n')}`); - return range; - } - isComplete() { - return this._isComplete; - } - addSemanticTokens(lineNumber, aTokens) { - const pieces = this._pieces; - if (pieces.length === 0) { - return aTokens; - } - const pieceIndex = TokensStore2._findFirstPieceWithLine(pieces, lineNumber); - const bTokens = pieces[pieceIndex].getLineTokens(lineNumber); - if (!bTokens) { - return aTokens; - } - const aLen = aTokens.getCount(); - const bLen = bTokens.getCount(); - let aIndex = 0; - let result = [], resultLen = 0; - let lastEndOffset = 0; - const emitToken = (endOffset, metadata) => { - if (endOffset === lastEndOffset) { - return; - } - lastEndOffset = endOffset; - result[resultLen++] = endOffset; - result[resultLen++] = metadata; - }; - for (let bIndex = 0; bIndex < bLen; bIndex++) { - const bStartCharacter = bTokens.getStartCharacter(bIndex); - const bEndCharacter = bTokens.getEndCharacter(bIndex); - const bMetadata = bTokens.getMetadata(bIndex); - const 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; - const aMask = (~bMask) >>> 0; - // push any token from `a` that is before `b` - while (aIndex < aLen && aTokens.getEndOffset(aIndex) <= bStartCharacter) { - emitToken(aTokens.getEndOffset(aIndex), aTokens.getMetadata(aIndex)); - aIndex++; - } - // push the token from `a` if it intersects the token from `b` - if (aIndex < aLen && aTokens.getStartOffset(aIndex) < bStartCharacter) { - emitToken(bStartCharacter, aTokens.getMetadata(aIndex)); - } - // skip any tokens from `a` that are contained inside `b` - while (aIndex < aLen && aTokens.getEndOffset(aIndex) < bEndCharacter) { - emitToken(aTokens.getEndOffset(aIndex), (aTokens.getMetadata(aIndex) & aMask) | (bMetadata & bMask)); - aIndex++; - } - if (aIndex < aLen) { - emitToken(bEndCharacter, (aTokens.getMetadata(aIndex) & aMask) | (bMetadata & bMask)); - if (aTokens.getEndOffset(aIndex) === bEndCharacter) { - // `a` ends exactly at the same spot as `b`! - aIndex++; - } - } - else { - const aMergeIndex = Math.min(Math.max(0, aIndex - 1), aLen - 1); - // push the token from `b` - emitToken(bEndCharacter, (aTokens.getMetadata(aMergeIndex) & aMask) | (bMetadata & bMask)); - } - } - // push the remaining tokens from `a` - while (aIndex < aLen) { - emitToken(aTokens.getEndOffset(aIndex), aTokens.getMetadata(aIndex)); - aIndex++; - } - return new lineTokens_1.LineTokens(new Uint32Array(result), aTokens.getLineContent()); - } - static _findFirstPieceWithLine(pieces, lineNumber) { - let low = 0; - let high = pieces.length - 1; - while (low < high) { - let 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 - acceptEdit(range, eolCount, firstLineLength, lastLineLength, firstCharCode) { - for (const piece of this._pieces) { - piece.acceptEdit(range, eolCount, firstLineLength, lastLineLength, firstCharCode); - } - } - } - exports.TokensStore2 = TokensStore2; - class TokensStore { - constructor() { - this._lineTokens = []; - this._len = 0; - } - flush() { - this._lineTokens = []; - this._len = 0; - } - getTokens(topLevelLanguageId, lineIndex, lineText) { - let 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); - } - let lineTokens = new Uint32Array(2); - lineTokens[0] = lineText.length; - lineTokens[1] = getDefaultMetadata(topLevelLanguageId); - return new lineTokens_1.LineTokens(lineTokens, lineText); - } - static _massageTokens(topLevelLanguageId, lineTextLength, _tokens) { - const tokens = _tokens ? toUint32Array(_tokens) : null; - if (lineTextLength === 0) { - let 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) { - const tokens = new Uint32Array(2); - tokens[0] = lineTextLength; - tokens[1] = getDefaultMetadata(topLevelLanguageId); - return tokens.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; - } - _ensureLine(lineIndex) { - while (lineIndex >= this._len) { - this._lineTokens[this._len] = null; - this._len++; - } - } - _deleteLines(start, deleteCount) { - if (deleteCount === 0) { - return; - } - if (start + deleteCount > this._len) { - deleteCount = this._len - start; - } - this._lineTokens.splice(start, deleteCount); - this._len -= deleteCount; - } - _insertLines(insertIndex, insertCount) { - if (insertCount === 0) { - return; - } - let lineTokens = []; - for (let i = 0; i < insertCount; i++) { - lineTokens[i] = null; - } - this._lineTokens = arrays.arrayInsert(this._lineTokens, insertIndex, lineTokens); - this._len += insertCount; - } - setTokens(topLevelLanguageId, lineIndex, lineTextLength, _tokens, checkEquality) { - const tokens = TokensStore._massageTokens(topLevelLanguageId, lineTextLength, _tokens); - this._ensureLine(lineIndex); - const oldTokens = this._lineTokens[lineIndex]; - this._lineTokens[lineIndex] = tokens; - if (checkEquality) { - return !TokensStore._equals(oldTokens, tokens); - } - return false; - } - static _equals(_a, _b) { - if (!_a || !_b) { - return !_a && !_b; - } - const a = toUint32Array(_a); - const b = toUint32Array(_b); - if (a.length !== b.length) { - return false; - } - for (let i = 0, len = a.length; i < len; i++) { - if (a[i] !== b[i]) { - return false; - } - } - return true; - } - //#region Editing - acceptEdit(range, eolCount, firstLineLength) { - this._acceptDeleteRange(range); - this._acceptInsertText(new position_1.Position(range.startLineNumber, range.startColumn), eolCount, firstLineLength); - } - _acceptDeleteRange(range) { - const 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); - const lastLineIndex = range.endLineNumber - 1; - let 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); - } - _acceptInsertText(position, eolCount, firstLineLength) { - if (eolCount === 0 && firstLineLength === 0) { - // Nothing to insert - return; - } - const 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); - } - static _deleteBeginning(lineTokens, toChIndex) { - if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) { - return lineTokens; - } - return TokensStore._delete(lineTokens, 0, toChIndex); - } - static _deleteEnding(lineTokens, fromChIndex) { - if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) { - return lineTokens; - } - const tokens = toUint32Array(lineTokens); - const lineTextLength = tokens[tokens.length - 2]; - return TokensStore._delete(lineTokens, fromChIndex, lineTextLength); - } - static _delete(lineTokens, fromChIndex, toChIndex) { - if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS || fromChIndex === toChIndex) { - return lineTokens; - } - const tokens = toUint32Array(lineTokens); - const tokensCount = (tokens.length >>> 1); - // special case: deleting everything - if (fromChIndex === 0 && tokens[tokens.length - 2] === toChIndex) { - return EMPTY_LINE_TOKENS; - } - const fromTokenIndex = lineTokens_1.LineTokens.findIndexInTokensArray(tokens, fromChIndex); - const fromTokenStartOffset = (fromTokenIndex > 0 ? tokens[(fromTokenIndex - 1) << 1] : 0); - const fromTokenEndOffset = tokens[fromTokenIndex << 1]; - if (toChIndex < fromTokenEndOffset) { - // the delete range is inside a single token - const delta = (toChIndex - fromChIndex); - for (let i = fromTokenIndex; i < tokensCount; i++) { - tokens[i << 1] -= delta; - } - return lineTokens; - } - let dest; - let lastEnd; - if (fromTokenStartOffset !== fromChIndex) { - tokens[fromTokenIndex << 1] = fromChIndex; - dest = ((fromTokenIndex + 1) << 1); - lastEnd = fromChIndex; - } - else { - dest = (fromTokenIndex << 1); - lastEnd = fromTokenStartOffset; - } - const delta = (toChIndex - fromChIndex); - for (let tokenIndex = fromTokenIndex + 1; tokenIndex < tokensCount; tokenIndex++) { - const 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; - } - let tmp = new Uint32Array(dest); - tmp.set(tokens.subarray(0, dest), 0); - return tmp.buffer; - } - static _append(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; - } - const myTokens = toUint32Array(lineTokens); - const otherTokens = toUint32Array(_otherTokens); - const otherTokensCount = (otherTokens.length >>> 1); - let result = new Uint32Array(myTokens.length + otherTokens.length); - result.set(myTokens, 0); - let dest = myTokens.length; - const delta = myTokens[myTokens.length - 2]; - for (let i = 0; i < otherTokensCount; i++) { - result[dest++] = otherTokens[(i << 1)] + delta; - result[dest++] = otherTokens[(i << 1) + 1]; - } - return result.buffer; - } - static _insert(lineTokens, chIndex, textLength) { - if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) { - // nothing to do - return lineTokens; - } - const tokens = toUint32Array(lineTokens); - const tokensCount = (tokens.length >>> 1); - let fromTokenIndex = lineTokens_1.LineTokens.findIndexInTokensArray(tokens, chIndex); - if (fromTokenIndex > 0) { - const fromTokenStartOffset = tokens[(fromTokenIndex - 1) << 1]; - if (fromTokenStartOffset === chIndex) { - fromTokenIndex--; - } - } - for (let tokenIndex = fromTokenIndex; tokenIndex < tokensCount; tokenIndex++) { - tokens[tokenIndex << 1] += textLength; - } - return lineTokens; - } - } - 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[242/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,8/*vs/base/common/strings*/,3/*vs/editor/common/core/range*/,53/*vs/editor/common/model*/,221/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase*/,140/*vs/editor/common/model/tokensStore*/,220/*vs/editor/common/model/textChange*/,2/*vs/base/common/lifecycle*/]), function (require, exports, event_1, strings, range_1, model_1, pieceTreeBase_1, tokensStore_1, textChange_1, lifecycle_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.PieceTreeTextBuffer = void 0; - class PieceTreeTextBuffer extends lifecycle_1.Disposable { - constructor(chunks, BOM, eol, containsRTL, containsUnusualLineTerminators, isBasicASCII, eolNormalized) { - super(); - this._onDidChangeContent = this._register(new event_1.Emitter()); - this._BOM = BOM; - this._mightContainNonBasicASCII = !isBasicASCII; - this._mightContainRTL = containsRTL; - this._mightContainUnusualLineTerminators = containsUnusualLineTerminators; - this._pieceTree = new pieceTreeBase_1.PieceTreeBase(chunks, eol, eolNormalized); - } - mightContainRTL() { - return this._mightContainRTL; - } - mightContainUnusualLineTerminators() { - return this._mightContainUnusualLineTerminators; - } - resetMightContainUnusualLineTerminators() { - this._mightContainUnusualLineTerminators = false; - } - mightContainNonBasicASCII() { - return this._mightContainNonBasicASCII; - } - getBOM() { - return this._BOM; - } - getEOL() { - return this._pieceTree.getEOL(); - } - createSnapshot(preserveBOM) { - return this._pieceTree.createSnapshot(preserveBOM ? this._BOM : ''); - } - getOffsetAt(lineNumber, column) { - return this._pieceTree.getOffsetAt(lineNumber, column); - } - getPositionAt(offset) { - return this._pieceTree.getPositionAt(offset); - } - getRangeAt(start, length) { - let end = start + length; - const startPosition = this.getPositionAt(start); - const endPosition = this.getPositionAt(end); - return new range_1.Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column); - } - getValueInRange(range, eol = 0 /* TextDefined */) { - if (range.isEmpty()) { - return ''; - } - const lineEnding = this._getEndOfLine(eol); - return this._pieceTree.getValueInRange(range, lineEnding); - } - getValueLengthInRange(range, eol = 0 /* TextDefined */) { - if (range.isEmpty()) { - return 0; - } - if (range.startLineNumber === range.endLineNumber) { - return (range.endColumn - range.startColumn); - } - let startOffset = this.getOffsetAt(range.startLineNumber, range.startColumn); - let endOffset = this.getOffsetAt(range.endLineNumber, range.endColumn); - return endOffset - startOffset; - } - getCharacterCountInRange(range, eol = 0 /* TextDefined */) { - if (this._mightContainNonBasicASCII) { - // we must count by iterating - let result = 0; - const fromLineNumber = range.startLineNumber; - const toLineNumber = range.endLineNumber; - for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) { - const lineContent = this.getLineContent(lineNumber); - const fromOffset = (lineNumber === fromLineNumber ? range.startColumn - 1 : 0); - const toOffset = (lineNumber === toLineNumber ? range.endColumn - 1 : lineContent.length); - for (let 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); - } - getLength() { - return this._pieceTree.getLength(); - } - getLineCount() { - return this._pieceTree.getLineCount(); - } - getLinesContent() { - return this._pieceTree.getLinesContent(); - } - getLineContent(lineNumber) { - return this._pieceTree.getLineContent(lineNumber); - } - getLineCharCode(lineNumber, index) { - return this._pieceTree.getLineCharCode(lineNumber, index); - } - getLineLength(lineNumber) { - return this._pieceTree.getLineLength(lineNumber); - } - getLineFirstNonWhitespaceColumn(lineNumber) { - const result = strings.firstNonWhitespaceIndex(this.getLineContent(lineNumber)); - if (result === -1) { - return 0; - } - return result + 1; - } - getLineLastNonWhitespaceColumn(lineNumber) { - const result = strings.lastNonWhitespaceIndex(this.getLineContent(lineNumber)); - if (result === -1) { - return 0; - } - return result + 2; - } - _getEndOfLine(eol) { - switch (eol) { - case 1 /* LF */: - return '\n'; - case 2 /* CRLF */: - return '\r\n'; - case 0 /* TextDefined */: - return this.getEOL(); - default: - throw new Error('Unknown EOL preference'); - } - } - setEOL(newEOL) { - this._pieceTree.setEOL(newEOL); - } - applyEdits(rawOperations, recordTrimAutoWhitespace, computeUndoEdits) { - let mightContainRTL = this._mightContainRTL; - let mightContainUnusualLineTerminators = this._mightContainUnusualLineTerminators; - let mightContainNonBasicASCII = this._mightContainNonBasicASCII; - let canReduceOperations = true; - let operations = []; - for (let i = 0; i < rawOperations.length; i++) { - let op = rawOperations[i]; - if (canReduceOperations && op._isTracked) { - canReduceOperations = false; - } - let validatedRange = op.range; - if (op.text) { - let textMightContainNonBasicASCII = true; - if (!mightContainNonBasicASCII) { - textMightContainNonBasicASCII = !strings.isBasicASCII(op.text); - mightContainNonBasicASCII = textMightContainNonBasicASCII; - } - if (!mightContainRTL && textMightContainNonBasicASCII) { - // check if the new inserted text contains RTL - mightContainRTL = strings.containsRTL(op.text); - } - if (!mightContainUnusualLineTerminators && textMightContainNonBasicASCII) { - // check if the new inserted text contains unusual line terminators - mightContainUnusualLineTerminators = strings.containsUnusualLineTerminators(op.text); - } - } - let validText = ''; - let eolCount = 0; - let firstLineLength = 0; - let lastLineLength = 0; - if (op.text) { - let strEOL; - [eolCount, firstLineLength, lastLineLength, strEOL] = (0, tokensStore_1.countEOL)(op.text); - const bufferEOL = this.getEOL(); - const expectedStrEOL = (bufferEOL === '\r\n' ? 2 /* CRLF */ : 1 /* LF */); - if (strEOL === 0 /* Unknown */ || strEOL === expectedStrEOL) { - validText = op.text; - } - else { - validText = op.text.replace(/\r\n|\r|\n/g, bufferEOL); - } - } - operations[i] = { - sortIndex: i, - identifier: op.identifier || null, - range: validatedRange, - rangeOffset: this.getOffsetAt(validatedRange.startLineNumber, validatedRange.startColumn), - rangeLength: this.getValueLengthInRange(validatedRange), - text: validText, - eolCount: eolCount, - firstLineLength: firstLineLength, - lastLineLength: lastLineLength, - forceMoveMarkers: Boolean(op.forceMoveMarkers), - isAutoWhitespaceEdit: op.isAutoWhitespaceEdit || false - }; - } - // Sort operations ascending - operations.sort(PieceTreeTextBuffer._sortOpsAscending); - let hasTouchingRanges = false; - for (let i = 0, count = operations.length - 1; i < count; i++) { - let rangeEnd = operations[i].range.getEndPosition(); - let 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 - let reverseRanges = (computeUndoEdits || recordTrimAutoWhitespace ? PieceTreeTextBuffer._getInverseEditRanges(operations) : []); - let newTrimAutoWhitespaceCandidates = []; - if (recordTrimAutoWhitespace) { - for (let i = 0; i < operations.length; i++) { - let op = operations[i]; - let reverseRange = reverseRanges[i]; - if (op.isAutoWhitespaceEdit && op.range.isEmpty()) { - // Record already the future line numbers that might be auto whitespace removal candidates on next edit - for (let lineNumber = reverseRange.startLineNumber; lineNumber <= reverseRange.endLineNumber; lineNumber++) { - let currentLineContent = ''; - if (lineNumber === reverseRange.startLineNumber) { - currentLineContent = this.getLineContent(op.range.startLineNumber); - if (strings.firstNonWhitespaceIndex(currentLineContent) !== -1) { - continue; - } - } - newTrimAutoWhitespaceCandidates.push({ lineNumber: lineNumber, oldContent: currentLineContent }); - } - } - } - } - let reverseOperations = null; - if (computeUndoEdits) { - let reverseRangeDeltaOffset = 0; - reverseOperations = []; - for (let i = 0; i < operations.length; i++) { - const op = operations[i]; - const reverseRange = reverseRanges[i]; - const bufferText = this.getValueInRange(op.range); - const reverseRangeOffset = op.rangeOffset + reverseRangeDeltaOffset; - reverseRangeDeltaOffset += (op.text.length - bufferText.length); - reverseOperations[i] = { - sortIndex: op.sortIndex, - identifier: op.identifier, - range: reverseRange, - text: bufferText, - textChange: new textChange_1.TextChange(op.rangeOffset, bufferText, reverseRangeOffset, op.text) - }; - } - // Can only sort reverse operations when the order is not significant - if (!hasTouchingRanges) { - reverseOperations.sort((a, b) => a.sortIndex - b.sortIndex); - } - } - this._mightContainRTL = mightContainRTL; - this._mightContainUnusualLineTerminators = mightContainUnusualLineTerminators; - this._mightContainNonBasicASCII = mightContainNonBasicASCII; - const contentChanges = this._doApplyEdits(operations); - let trimAutoWhitespaceLineNumbers = null; - if (recordTrimAutoWhitespace && newTrimAutoWhitespaceCandidates.length > 0) { - // sort line numbers auto whitespace removal candidates for next edit descending - newTrimAutoWhitespaceCandidates.sort((a, b) => b.lineNumber - a.lineNumber); - trimAutoWhitespaceLineNumbers = []; - for (let i = 0, len = newTrimAutoWhitespaceCandidates.length; i < len; i++) { - let lineNumber = newTrimAutoWhitespaceCandidates[i].lineNumber; - if (i > 0 && newTrimAutoWhitespaceCandidates[i - 1].lineNumber === lineNumber) { - // Do not have the same line number twice - continue; - } - let prevContent = newTrimAutoWhitespaceCandidates[i].oldContent; - let lineContent = this.getLineContent(lineNumber); - if (lineContent.length === 0 || lineContent === prevContent || strings.firstNonWhitespaceIndex(lineContent) !== -1) { - continue; - } - trimAutoWhitespaceLineNumbers.push(lineNumber); - } - } - this._onDidChangeContent.fire(); - 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. - */ - _reduceOperations(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)]; - } - _toSingleEditOperation(operations) { - let forceMoveMarkers = false; - const firstEditRange = operations[0].range; - const lastEditRange = operations[operations.length - 1].range; - const entireEditRange = new range_1.Range(firstEditRange.startLineNumber, firstEditRange.startColumn, lastEditRange.endLineNumber, lastEditRange.endColumn); - let lastEndLineNumber = firstEditRange.startLineNumber; - let lastEndColumn = firstEditRange.startColumn; - const result = []; - for (let i = 0, len = operations.length; i < len; i++) { - const operation = operations[i]; - const range = operation.range; - forceMoveMarkers = forceMoveMarkers || operation.forceMoveMarkers; - // (1) -- Push old text - result.push(this.getValueInRange(new range_1.Range(lastEndLineNumber, lastEndColumn, range.startLineNumber, range.startColumn))); - // (2) -- Push new text - if (operation.text.length > 0) { - result.push(operation.text); - } - lastEndLineNumber = range.endLineNumber; - lastEndColumn = range.endColumn; - } - const text = result.join(''); - const [eolCount, firstLineLength, lastLineLength] = (0, tokensStore_1.countEOL)(text); - return { - sortIndex: 0, - identifier: operations[0].identifier, - range: entireEditRange, - rangeOffset: this.getOffsetAt(entireEditRange.startLineNumber, entireEditRange.startColumn), - rangeLength: this.getValueLengthInRange(entireEditRange, 0 /* TextDefined */), - text: text, - eolCount: eolCount, - firstLineLength: firstLineLength, - lastLineLength: lastLineLength, - forceMoveMarkers: forceMoveMarkers, - isAutoWhitespaceEdit: false - }; - } - _doApplyEdits(operations) { - operations.sort(PieceTreeTextBuffer._sortOpsDescending); - let contentChanges = []; - // operations are from bottom to top - for (let i = 0; i < operations.length; i++) { - let op = operations[i]; - const startLineNumber = op.range.startLineNumber; - const startColumn = op.range.startColumn; - const endLineNumber = op.range.endLineNumber; - const endColumn = op.range.endColumn; - if (startLineNumber === endLineNumber && startColumn === endColumn && op.text.length === 0) { - // no-op - continue; - } - if (op.text) { - // replacement - this._pieceTree.delete(op.rangeOffset, op.rangeLength); - this._pieceTree.insert(op.rangeOffset, op.text, true); - } - else { - // deletion - this._pieceTree.delete(op.rangeOffset, op.rangeLength); - } - const contentChangeRange = new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn); - contentChanges.push({ - range: contentChangeRange, - rangeLength: op.rangeLength, - text: op.text, - rangeOffset: op.rangeOffset, - forceMoveMarkers: op.forceMoveMarkers - }); - } - return contentChanges; - } - findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount) { - return this._pieceTree.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount); - } - /** - * Assumes `operations` are validated and sorted ascending - */ - static _getInverseEditRanges(operations) { - let result = []; - let prevOpEndLineNumber = 0; - let prevOpEndColumn = 0; - let prevOp = null; - for (let i = 0, len = operations.length; i < len; i++) { - let op = operations[i]; - let startLineNumber; - let startColumn; - 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; - } - let resultRange; - if (op.text.length > 0) { - // the operation inserts something - const lineCount = op.eolCount + 1; - if (lineCount === 1) { - // single line insert - resultRange = new range_1.Range(startLineNumber, startColumn, startLineNumber, startColumn + op.firstLineLength); - } - else { - // multi line insert - resultRange = new range_1.Range(startLineNumber, startColumn, startLineNumber + lineCount - 1, op.lastLineLength + 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; - } - static _sortOpsAscending(a, b) { - let r = range_1.Range.compareRangesUsingEnds(a.range, b.range); - if (r === 0) { - return a.sortIndex - b.sortIndex; - } - return r; - } - static _sortOpsDescending(a, b) { - let r = range_1.Range.compareRangesUsingEnds(a.range, b.range); - if (r === 0) { - return b.sortIndex - a.sortIndex; - } - return -r; - } - } - 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[548/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,221/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase*/,242/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer*/]), function (require, exports, strings, pieceTreeBase_1, pieceTreeTextBuffer_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.PieceTreeTextBufferBuilder = exports.PieceTreeTextBufferFactory = void 0; - class PieceTreeTextBufferFactory { - constructor(_chunks, _bom, _cr, _lf, _crlf, _containsRTL, _containsUnusualLineTerminators, _isBasicASCII, _normalizeEOL) { - this._chunks = _chunks; - this._bom = _bom; - this._cr = _cr; - this._lf = _lf; - this._crlf = _crlf; - this._containsRTL = _containsRTL; - this._containsUnusualLineTerminators = _containsUnusualLineTerminators; - this._isBasicASCII = _isBasicASCII; - this._normalizeEOL = _normalizeEOL; - } - _getEOL(defaultEOL) { - const totalEOLCount = this._cr + this._lf + this._crlf; - const 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'; - } - create(defaultEOL) { - const eol = this._getEOL(defaultEOL); - let 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 (let i = 0, len = chunks.length; i < len; i++) { - let str = chunks[i].buffer.replace(/\r\n|\r|\n/g, eol); - let newLineStart = (0, pieceTreeBase_1.createLineStartsFast)(str); - chunks[i] = new pieceTreeBase_1.StringBuffer(str, newLineStart); - } - } - const textBuffer = new pieceTreeTextBuffer_1.PieceTreeTextBuffer(chunks, this._bom, eol, this._containsRTL, this._containsUnusualLineTerminators, this._isBasicASCII, this._normalizeEOL); - return { textBuffer: textBuffer, disposable: textBuffer }; - } - } - exports.PieceTreeTextBufferFactory = PieceTreeTextBufferFactory; - class PieceTreeTextBufferBuilder { - constructor() { - 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.containsUnusualLineTerminators = false; - this.isBasicASCII = true; - } - acceptChunk(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); - } - } - const 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; - } - } - _acceptChunk1(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); - } - } - _acceptChunk2(chunk) { - const lineStarts = (0, 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 it is basic ASCII - this.containsRTL = strings.containsRTL(chunk); - } - if (!this.isBasicASCII && !this.containsUnusualLineTerminators) { - // No need to check if it is basic ASCII - this.containsUnusualLineTerminators = strings.containsUnusualLineTerminators(chunk); - } - } - finish(normalizeEOL = true) { - this._finish(); - return new PieceTreeTextBufferFactory(this.chunks, this.BOM, this.cr, this.lf, this.crlf, this.containsRTL, this.containsUnusualLineTerminators, this.isBasicASCII, normalizeEOL); - } - _finish() { - if (this.chunks.length === 0) { - this._acceptChunk1('', true); - } - if (this._hasPreviousChar) { - this._hasPreviousChar = false; - // recreate last chunk - let lastChunk = this.chunks[this.chunks.length - 1]; - lastChunk.buffer += String.fromCharCode(this._previousChar); - let newLineStarts = (0, pieceTreeBase_1.createLineStartsFast)(lastChunk.buffer); - lastChunk.lineStarts = newLineStarts; - if (this._previousChar === 13 /* CarriageReturn */) { - this.cr++; - } - } - } - } - 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[77/*vs/editor/common/modes/nullMode*/], __M([0/*require*/,1/*exports*/,134/*vs/editor/common/core/token*/,18/*vs/editor/common/modes*/]), function (require, exports, token_1, modes_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.nullTokenize2 = exports.nullTokenize = exports.NULL_LANGUAGE_IDENTIFIER = exports.NULL_MODE_ID = exports.NULL_STATE = void 0; - class NullStateImpl { - clone() { - return this; - } - equals(other) { - return (this === other); - } - } - 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) { - let 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[549/*vs/editor/common/model/textModelTokens*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,12/*vs/base/common/errors*/,85/*vs/editor/common/core/lineTokens*/,13/*vs/editor/common/core/position*/,18/*vs/editor/common/modes*/,77/*vs/editor/common/modes/nullMode*/,2/*vs/base/common/lifecycle*/,81/*vs/base/common/stopwatch*/,140/*vs/editor/common/model/tokensStore*/,17/*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 }); - exports.TextModelTokenization = exports.TokenizationStateStore = void 0; - class TokenizationStateStore { - constructor() { - this._beginState = []; - this._valid = []; - this._len = 0; - this._invalidLineStartIndex = 0; - } - _reset(initialState) { - this._beginState = []; - this._valid = []; - this._len = 0; - this._invalidLineStartIndex = 0; - if (initialState) { - this._setBeginState(0, initialState); - } - } - flush(initialState) { - this._reset(initialState); - } - get invalidLineStartIndex() { - return this._invalidLineStartIndex; - } - _invalidateLine(lineIndex) { - if (lineIndex < this._len) { - this._valid[lineIndex] = false; - } - if (lineIndex < this._invalidLineStartIndex) { - this._invalidLineStartIndex = lineIndex; - } - } - _isValid(lineIndex) { - if (lineIndex < this._len) { - return this._valid[lineIndex]; - } - return false; - } - getBeginState(lineIndex) { - if (lineIndex < this._len) { - return this._beginState[lineIndex]; - } - return null; - } - _ensureLine(lineIndex) { - while (lineIndex >= this._len) { - this._beginState[this._len] = null; - this._valid[this._len] = false; - this._len++; - } - } - _deleteLines(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; - } - _insertLines(insertIndex, insertCount) { - if (insertCount === 0) { - return; - } - let beginState = []; - let valid = []; - for (let 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; - } - _setValid(lineIndex, valid) { - this._ensureLine(lineIndex); - this._valid[lineIndex] = valid; - } - _setBeginState(lineIndex, beginState) { - this._ensureLine(lineIndex); - this._beginState[lineIndex] = beginState; - } - setEndState(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 - const 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... - let i = lineIndex + 1; - while (i < linesLength) { - if (!this._isValid(i)) { - break; - } - i++; - } - this._invalidLineStartIndex = i; - } - setFakeTokens(lineIndex) { - this._setValid(lineIndex, false); - } - //#region Editing - applyEdits(range, eolCount) { - const deletingLinesCnt = range.endLineNumber - range.startLineNumber; - const insertingLinesCnt = eolCount; - const editingLinesCnt = Math.min(deletingLinesCnt, insertingLinesCnt); - for (let 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); - } - _acceptDeleteRange(range) { - const firstLineIndex = range.startLineNumber - 1; - if (firstLineIndex >= this._len) { - return; - } - this._deleteLines(range.startLineNumber, range.endLineNumber - range.startLineNumber); - } - _acceptInsertText(position, eolCount) { - const lineIndex = position.lineNumber - 1; - if (lineIndex >= this._len) { - return; - } - this._insertLines(position.lineNumber, eolCount); - } - } - exports.TokenizationStateStore = TokenizationStateStore; - class TextModelTokenization extends lifecycle_1.Disposable { - constructor(textModel) { - super(); - this._isDisposed = false; - this._textModel = textModel; - this._tokenizationStateStore = new TokenizationStateStore(); - this._tokenizationSupport = null; - this._register(modes_1.TokenizationRegistry.onDidChange((e) => { - const languageIdentifier = this._textModel.getLanguageIdentifier(); - if (e.changedLanguages.indexOf(languageIdentifier.language) === -1) { - return; - } - this._resetTokenizationState(); - this._textModel.clearTokens(); - })); - this._register(this._textModel.onDidChangeContentFast((e) => { - if (e.isFlush) { - this._resetTokenizationState(); - return; - } - for (let i = 0, len = e.changes.length; i < len; i++) { - const change = e.changes[i]; - const [eolCount] = (0, tokensStore_1.countEOL)(change.text); - this._tokenizationStateStore.applyEdits(change.range, eolCount); - } - this._beginBackgroundTokenization(); - })); - this._register(this._textModel.onDidChangeAttached(() => { - this._beginBackgroundTokenization(); - })); - this._register(this._textModel.onDidChangeLanguage(() => { - this._resetTokenizationState(); - this._textModel.clearTokens(); - })); - this._resetTokenizationState(); - } - dispose() { - this._isDisposed = true; - super.dispose(); - } - _resetTokenizationState() { - const [tokenizationSupport, initialState] = initializeTokenization(this._textModel); - this._tokenizationSupport = tokenizationSupport; - this._tokenizationStateStore.flush(initialState); - this._beginBackgroundTokenization(); - } - _beginBackgroundTokenization() { - if (this._textModel.isAttachedToEditor() && this._hasLinesToTokenize()) { - platform.setImmediate(() => { - if (this._isDisposed) { - // disposed in the meantime - return; - } - this._revalidateTokensNow(); - }); - } - } - _revalidateTokensNow(toLineNumber = this._textModel.getLineCount()) { - const MAX_ALLOWED_TIME = 1; - const builder = new tokensStore_1.MultilineTokensBuilder(); - const sw = stopwatch_1.StopWatch.create(false); - while (this._hasLinesToTokenize()) { - if (sw.elapsed() > MAX_ALLOWED_TIME) { - // Stop if MAX_ALLOWED_TIME is reached - break; - } - const tokenizedLineNumber = this._tokenizeOneInvalidLine(builder); - if (tokenizedLineNumber >= toLineNumber) { - break; - } - } - this._beginBackgroundTokenization(); - this._textModel.setTokens(builder.tokens); - } - tokenizeViewport(startLineNumber, endLineNumber) { - const builder = new tokensStore_1.MultilineTokensBuilder(); - this._tokenizeViewport(builder, startLineNumber, endLineNumber); - this._textModel.setTokens(builder.tokens); - } - reset() { - this._resetTokenizationState(); - this._textModel.clearTokens(); - } - forceTokenization(lineNumber) { - const builder = new tokensStore_1.MultilineTokensBuilder(); - this._updateTokensUntilLine(builder, lineNumber); - this._textModel.setTokens(builder.tokens); - } - isCheapToTokenize(lineNumber) { - if (!this._tokenizationSupport) { - return true; - } - const 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; - } - _hasLinesToTokenize() { - if (!this._tokenizationSupport) { - return false; - } - return (this._tokenizationStateStore.invalidLineStartIndex < this._textModel.getLineCount()); - } - _tokenizeOneInvalidLine(builder) { - if (!this._hasLinesToTokenize()) { - return this._textModel.getLineCount() + 1; - } - const lineNumber = this._tokenizationStateStore.invalidLineStartIndex + 1; - this._updateTokensUntilLine(builder, lineNumber); - return lineNumber; - } - _updateTokensUntilLine(builder, lineNumber) { - if (!this._tokenizationSupport) { - return; - } - const languageIdentifier = this._textModel.getLanguageIdentifier(); - const linesLength = this._textModel.getLineCount(); - const endLineIndex = lineNumber - 1; - // Validate all states up to and including endLineIndex - for (let lineIndex = this._tokenizationStateStore.invalidLineStartIndex; lineIndex <= endLineIndex; lineIndex++) { - const text = this._textModel.getLineContent(lineIndex + 1); - const lineStartState = this._tokenizationStateStore.getBeginState(lineIndex); - const r = safeTokenize(languageIdentifier, this._tokenizationSupport, text, true, 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 - } - } - _tokenizeViewport(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; - } - let nonWhitespaceColumn = this._textModel.getLineFirstNonWhitespaceColumn(startLineNumber); - let fakeLines = []; - let initialState = null; - for (let i = startLineNumber - 1; nonWhitespaceColumn > 0 && i >= 1; i--) { - let 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(); - } - const languageIdentifier = this._textModel.getLanguageIdentifier(); - let state = initialState; - for (let i = fakeLines.length - 1; i >= 0; i--) { - let r = safeTokenize(languageIdentifier, this._tokenizationSupport, fakeLines[i], false, state); - state = r.endState; - } - for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { - let text = this._textModel.getLineContent(lineNumber); - let r = safeTokenize(languageIdentifier, this._tokenizationSupport, text, true, state); - builder.add(lineNumber, r.tokens); - this._tokenizationStateStore.setFakeTokens(lineNumber - 1); - state = r.endState; - } - } - } - exports.TextModelTokenization = TextModelTokenization; - function initializeTokenization(textModel) { - const languageIdentifier = textModel.getLanguageIdentifier(); - let tokenizationSupport = (textModel.isTooLargeForTokenization() - ? null - : modes_1.TokenizationRegistry.get(languageIdentifier.language)); - let initialState = null; - if (tokenizationSupport) { - try { - initialState = tokenizationSupport.getInitialState(); - } - catch (e) { - (0, errors_1.onUnexpectedError)(e); - tokenizationSupport = null; - } - } - return [tokenizationSupport, initialState]; - } - function safeTokenize(languageIdentifier, tokenizationSupport, text, hasEOL, state) { - let r = null; - if (tokenizationSupport) { - try { - r = tokenizationSupport.tokenize2(text, hasEOL, state.clone(), 0); - } - catch (e) { - (0, errors_1.onUnexpectedError)(e); - } - } - if (!r) { - r = (0, 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[31/*vs/editor/common/model/textModel*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,8/*vs/base/common/strings*/,24/*vs/base/common/uri*/,35/*vs/editor/common/config/editorOptions*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,53/*vs/editor/common/model*/,239/*vs/editor/common/model/editStack*/,378/*vs/editor/common/model/indentationGuesser*/,379/*vs/editor/common/model/intervalTree*/,548/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder*/,96/*vs/editor/common/model/textModelEvents*/,171/*vs/editor/common/model/textModelSearch*/,549/*vs/editor/common/model/textModelTokens*/,135/*vs/editor/common/model/wordHelper*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/,77/*vs/editor/common/modes/nullMode*/,172/*vs/editor/common/modes/supports*/,173/*vs/editor/common/modes/supports/richEditBrackets*/,140/*vs/editor/common/model/tokensStore*/,29/*vs/base/common/color*/,242/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer*/,19/*vs/base/common/arrays*/]), 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, tokensStore_1, color_1, pieceTreeTextBuffer_1, arrays_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DidChangeContentEmitter = exports.DidChangeDecorationsEmitter = exports.ModelDecorationOptions = exports.ModelDecorationInjectedTextOptions = exports.ModelDecorationMinimapOptions = exports.ModelDecorationOverviewRulerOptions = exports.TextModel = exports.LONG_LINE_BOUNDARY = exports.createTextBuffer = exports.createTextBufferFactory = void 0; - function createTextBufferBuilder() { - return new pieceTreeTextBufferBuilder_1.PieceTreeTextBufferBuilder(); - } - function createTextBufferFactory(text) { - const builder = createTextBufferBuilder(); - builder.acceptChunk(text); - return builder.finish(); - } - exports.createTextBufferFactory = createTextBufferFactory; - function createTextBuffer(value, defaultEOL) { - const factory = (typeof value === 'string' ? createTextBufferFactory(value) : value); - return factory.create(defaultEOL); - } - exports.createTextBuffer = createTextBuffer; - let MODEL_ID = 0; - const LIMIT_FIND_COUNT = 999; - exports.LONG_LINE_BOUNDARY = 10000; - class TextModelSnapshot { - constructor(source) { - this._source = source; - this._eos = false; - } - read() { - if (this._eos) { - return null; - } - let result = [], resultCnt = 0, resultLength = 0; - do { - let tmp = this._source.read(); - if (tmp === null) { - // end-of-stream - this._eos = true; - if (resultCnt === 0) { - return null; - } - else { - return result.join(''); - } - } - if (tmp.length > 0) { - result[resultCnt++] = tmp; - resultLength += tmp.length; - } - if (resultLength >= 64 * 1024) { - return result.join(''); - } - } while (true); - } - } - const invalidFunc = () => { throw new Error(`Invalid change accessor`); }; - class BracketSearchCanceled { - constructor() { - this._searchCanceledBrand = undefined; - } - } - BracketSearchCanceled.INSTANCE = new BracketSearchCanceled(); - function stripBracketSearchCanceled(result) { - if (result instanceof BracketSearchCanceled) { - return null; - } - return result; - } - class TextModel extends lifecycle_1.Disposable { - //#endregion - constructor(source, creationOptions, languageIdentifier, associatedResource = null, undoRedoService) { - super(); - //#region Events - this._onWillDispose = this._register(new event_1.Emitter()); - this.onWillDispose = this._onWillDispose.event; - this._onDidChangeDecorations = this._register(new DidChangeDecorationsEmitter(affectedInjectedTextLines => this.handleBeforeFireDecorationsChangedEvent(affectedInjectedTextLines))); - 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._onDidChangeContentOrInjectedText = this._register(new event_1.Emitter()); - this.onDidChangeContentOrInjectedText = this._onDidChangeContentOrInjectedText.event; - this._eventEmitter = this._register(new DidChangeContentEmitter()); - this._register(this._eventEmitter.fastEvent((e) => { - this._onDidChangeContentOrInjectedText.fire(e.rawContentChangedEvent); - })); - // 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._undoRedoService = undoRedoService; - this._attachedEditorCount = 0; - const { textBuffer, disposable } = createTextBuffer(source, creationOptions.defaultEOL); - this._buffer = textBuffer; - this._bufferDisposable = disposable; - this._options = TextModel.resolveOptions(this._buffer, creationOptions); - const bufferLineCount = this._buffer.getLineCount(); - const 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._initialUndoRedoSnapshot = null; - this._isDisposed = false; - this._isDisposing = false; - this._languageIdentifier = languageIdentifier || nullMode_1.NULL_LANGUAGE_IDENTIFIER; - this._languageRegistryListener = languageConfigurationRegistry_1.LanguageConfigurationRegistry.onDidChange((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, undoRedoService); - 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); - } - static resolveOptions(textBuffer, options) { - if (options.detectIndentation) { - const guessedIndentation = (0, 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 - }); - } - onDidChangeContentFast(listener) { - return this._eventEmitter.fastEvent((e) => listener(e.contentChangedEvent)); - } - onDidChangeContent(listener) { - return this._eventEmitter.slowEvent((e) => listener(e.contentChangedEvent)); - } - dispose() { - this._isDisposing = true; - this._onWillDispose.fire(); - this._languageRegistryListener.dispose(); - this._tokenization.dispose(); - this._isDisposed = true; - super.dispose(); - this._bufferDisposable.dispose(); - this._isDisposing = false; - // Manually release reference to previous text buffer to avoid large leaks - // in case someone leaks a TextModel reference - const emptyDisposedTextBuffer = new pieceTreeTextBuffer_1.PieceTreeTextBuffer([], '', '\n', false, false, true, true); - emptyDisposedTextBuffer.dispose(); - this._buffer = emptyDisposedTextBuffer; - } - _assertNotDisposed() { - if (this._isDisposed) { - throw new Error('Model is disposed!'); - } - } - _emitContentChangedEvent(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)); - } - setValue(value) { - this._assertNotDisposed(); - if (value === null) { - // There's nothing to do - return; - } - const { textBuffer, disposable } = createTextBuffer(value, this._options.defaultEOL); - this._setValueFromTextBuffer(textBuffer, disposable); - } - _createContentChanged2(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 - }; - } - _setValueFromTextBuffer(textBuffer, textBufferDisposable) { - this._assertNotDisposed(); - const oldFullModelRange = this.getFullModelRange(); - const oldModelValueLength = this.getValueLengthInRange(oldFullModelRange); - const endLineNumber = this.getLineCount(); - const endColumn = this.getLineMaxColumn(endLineNumber); - this._buffer = textBuffer; - this._bufferDisposable.dispose(); - this._bufferDisposable = textBufferDisposable; - 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.clear(); - 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)); - } - setEOL(eol) { - this._assertNotDisposed(); - const newEOL = (eol === 1 /* CRLF */ ? '\r\n' : '\n'); - if (this._buffer.getEOL() === newEOL) { - // Nothing to do - return; - } - const oldFullModelRange = this.getFullModelRange(); - const oldModelValueLength = this.getValueLengthInRange(oldFullModelRange); - const endLineNumber = this.getLineCount(); - const 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)); - } - _onBeforeEOLChange() { - // Ensure all decorations get their `range` set. - this._decorationsTree.ensureAllNodesHaveRanges(this); - } - _onAfterEOLChange() { - // Transform back `range` to offsets - const versionId = this.getVersionId(); - const allDecorations = this._decorationsTree.collectNodesPostOrder(); - for (let i = 0, len = allDecorations.length; i < len; i++) { - const node = allDecorations[i]; - const range = node.range; // the range is defined due to `_onBeforeEOLChange` - const delta = node.cachedAbsoluteStart - node.start; - const startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn); - const endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn); - node.cachedAbsoluteStart = startOffset; - node.cachedAbsoluteEnd = endOffset; - node.cachedVersionId = versionId; - node.start = startOffset - delta; - node.end = endOffset - delta; - (0, intervalTree_1.recomputeMaxEnd)(node); - } - } - onBeforeAttached() { - this._attachedEditorCount++; - if (this._attachedEditorCount === 1) { - this._onDidChangeAttached.fire(undefined); - } - } - onBeforeDetached() { - this._attachedEditorCount--; - if (this._attachedEditorCount === 0) { - this._onDidChangeAttached.fire(undefined); - } - } - isAttachedToEditor() { - return this._attachedEditorCount > 0; - } - getAttachedEditorCount() { - return this._attachedEditorCount; - } - isTooLargeForSyncing() { - return this._isTooLargeForSyncing; - } - isTooLargeForTokenization() { - return this._isTooLargeForTokenization; - } - isDisposed() { - return this._isDisposed; - } - isDominatedByLongLines() { - this._assertNotDisposed(); - if (this.isTooLargeForTokenization()) { - // Cannot word wrap huge files anyways, so it doesn't really matter - return false; - } - let smallLineCharCount = 0; - let longLineCharCount = 0; - const lineCount = this._buffer.getLineCount(); - for (let lineNumber = 1; lineNumber <= lineCount; lineNumber++) { - const lineLength = this._buffer.getLineLength(lineNumber); - if (lineLength >= exports.LONG_LINE_BOUNDARY) { - longLineCharCount += lineLength; - } - else { - smallLineCharCount += lineLength; - } - } - return (longLineCharCount > smallLineCharCount); - } - get uri() { - return this._associatedResource; - } - //#region Options - getOptions() { - this._assertNotDisposed(); - return this._options; - } - getFormattingOptions() { - return { - tabSize: this._options.indentSize, - insertSpaces: this._options.insertSpaces - }; - } - updateOptions(_newOpts) { - this._assertNotDisposed(); - let tabSize = (typeof _newOpts.tabSize !== 'undefined') ? _newOpts.tabSize : this._options.tabSize; - let indentSize = (typeof _newOpts.indentSize !== 'undefined') ? _newOpts.indentSize : this._options.indentSize; - let insertSpaces = (typeof _newOpts.insertSpaces !== 'undefined') ? _newOpts.insertSpaces : this._options.insertSpaces; - let trimAutoWhitespace = (typeof _newOpts.trimAutoWhitespace !== 'undefined') ? _newOpts.trimAutoWhitespace : this._options.trimAutoWhitespace; - let newOpts = new model.TextModelResolvedOptions({ - tabSize: tabSize, - indentSize: indentSize, - insertSpaces: insertSpaces, - defaultEOL: this._options.defaultEOL, - trimAutoWhitespace: trimAutoWhitespace - }); - if (this._options.equals(newOpts)) { - return; - } - let e = this._options.createChangeEvent(newOpts); - this._options = newOpts; - this._onDidChangeOptions.fire(e); - } - detectIndentation(defaultInsertSpaces, defaultTabSize) { - this._assertNotDisposed(); - let guessedIndentation = (0, indentationGuesser_1.guessIndentation)(this._buffer, defaultTabSize, defaultInsertSpaces); - this.updateOptions({ - insertSpaces: guessedIndentation.insertSpaces, - tabSize: guessedIndentation.tabSize, - indentSize: guessedIndentation.tabSize, // TODO@Alex: guess indentSize independent of tabSize - }); - } - static _normalizeIndentationFromWhitespace(str, indentSize, insertSpaces) { - let spacesCnt = 0; - for (let i = 0; i < str.length; i++) { - if (str.charAt(i) === '\t') { - spacesCnt += indentSize; - } - else { - spacesCnt++; - } - } - let result = ''; - if (!insertSpaces) { - let tabsCnt = Math.floor(spacesCnt / indentSize); - spacesCnt = spacesCnt % indentSize; - for (let i = 0; i < tabsCnt; i++) { - result += '\t'; - } - } - for (let i = 0; i < spacesCnt; i++) { - result += ' '; - } - return result; - } - static normalizeIndentation(str, indentSize, insertSpaces) { - let firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(str); - if (firstNonWhitespaceIndex === -1) { - firstNonWhitespaceIndex = str.length; - } - return TextModel._normalizeIndentationFromWhitespace(str.substring(0, firstNonWhitespaceIndex), indentSize, insertSpaces) + str.substring(firstNonWhitespaceIndex); - } - normalizeIndentation(str) { - this._assertNotDisposed(); - return TextModel.normalizeIndentation(str, this._options.indentSize, this._options.insertSpaces); - } - //#endregion - //#region Reading - getVersionId() { - this._assertNotDisposed(); - return this._versionId; - } - mightContainRTL() { - return this._buffer.mightContainRTL(); - } - mightContainUnusualLineTerminators() { - return this._buffer.mightContainUnusualLineTerminators(); - } - removeUnusualLineTerminators(selections = null) { - const matches = this.findMatches(strings.UNUSUAL_LINE_TERMINATORS.source, false, true, false, null, false, 1073741824 /* MAX_SAFE_SMALL_INTEGER */); - this._buffer.resetMightContainUnusualLineTerminators(); - this.pushEditOperations(selections, matches.map(m => ({ range: m.range, text: null })), () => null); - } - mightContainNonBasicASCII() { - return this._buffer.mightContainNonBasicASCII(); - } - getAlternativeVersionId() { - this._assertNotDisposed(); - return this._alternativeVersionId; - } - getInitialUndoRedoSnapshot() { - this._assertNotDisposed(); - return this._initialUndoRedoSnapshot; - } - getOffsetAt(rawPosition) { - this._assertNotDisposed(); - let position = this._validatePosition(rawPosition.lineNumber, rawPosition.column, 0 /* Relaxed */); - return this._buffer.getOffsetAt(position.lineNumber, position.column); - } - getPositionAt(rawOffset) { - this._assertNotDisposed(); - let offset = (Math.min(this._buffer.getLength(), Math.max(0, rawOffset))); - return this._buffer.getPositionAt(offset); - } - _increaseVersionId() { - this._versionId = this._versionId + 1; - this._alternativeVersionId = this._versionId; - } - _overwriteVersionId(versionId) { - this._versionId = versionId; - } - _overwriteAlternativeVersionId(newAlternativeVersionId) { - this._alternativeVersionId = newAlternativeVersionId; - } - _overwriteInitialUndoRedoSnapshot(newInitialUndoRedoSnapshot) { - this._initialUndoRedoSnapshot = newInitialUndoRedoSnapshot; - } - getValue(eol, preserveBOM = false) { - this._assertNotDisposed(); - const fullModelRange = this.getFullModelRange(); - const fullModelValue = this.getValueInRange(fullModelRange, eol); - if (preserveBOM) { - return this._buffer.getBOM() + fullModelValue; - } - return fullModelValue; - } - createSnapshot(preserveBOM = false) { - return new TextModelSnapshot(this._buffer.createSnapshot(preserveBOM)); - } - getValueLength(eol, preserveBOM = false) { - this._assertNotDisposed(); - const fullModelRange = this.getFullModelRange(); - const fullModelValue = this.getValueLengthInRange(fullModelRange, eol); - if (preserveBOM) { - return this._buffer.getBOM().length + fullModelValue; - } - return fullModelValue; - } - getValueInRange(rawRange, eol = 0 /* TextDefined */) { - this._assertNotDisposed(); - return this._buffer.getValueInRange(this.validateRange(rawRange), eol); - } - getValueLengthInRange(rawRange, eol = 0 /* TextDefined */) { - this._assertNotDisposed(); - return this._buffer.getValueLengthInRange(this.validateRange(rawRange), eol); - } - getCharacterCountInRange(rawRange, eol = 0 /* TextDefined */) { - this._assertNotDisposed(); - return this._buffer.getCharacterCountInRange(this.validateRange(rawRange), eol); - } - getLineCount() { - this._assertNotDisposed(); - return this._buffer.getLineCount(); - } - getLineContent(lineNumber) { - this._assertNotDisposed(); - if (lineNumber < 1 || lineNumber > this.getLineCount()) { - throw new Error('Illegal value for lineNumber'); - } - return this._buffer.getLineContent(lineNumber); - } - getLineLength(lineNumber) { - this._assertNotDisposed(); - if (lineNumber < 1 || lineNumber > this.getLineCount()) { - throw new Error('Illegal value for lineNumber'); - } - return this._buffer.getLineLength(lineNumber); - } - getLinesContent() { - this._assertNotDisposed(); - return this._buffer.getLinesContent(); - } - getEOL() { - this._assertNotDisposed(); - return this._buffer.getEOL(); - } - getEndOfLineSequence() { - this._assertNotDisposed(); - return (this._buffer.getEOL() === '\n' - ? 0 /* LF */ - : 1 /* CRLF */); - } - getLineMinColumn(lineNumber) { - this._assertNotDisposed(); - return 1; - } - getLineMaxColumn(lineNumber) { - this._assertNotDisposed(); - if (lineNumber < 1 || lineNumber > this.getLineCount()) { - throw new Error('Illegal value for lineNumber'); - } - return this._buffer.getLineLength(lineNumber) + 1; - } - getLineFirstNonWhitespaceColumn(lineNumber) { - this._assertNotDisposed(); - if (lineNumber < 1 || lineNumber > this.getLineCount()) { - throw new Error('Illegal value for lineNumber'); - } - return this._buffer.getLineFirstNonWhitespaceColumn(lineNumber); - } - getLineLastNonWhitespaceColumn(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. - */ - _validateRangeRelaxedNoAllocations(range) { - const linesCount = this._buffer.getLineCount(); - const initialStartLineNumber = range.startLineNumber; - const initialStartColumn = range.startColumn; - let startLineNumber = Math.floor((typeof initialStartLineNumber === 'number' && !isNaN(initialStartLineNumber)) ? initialStartLineNumber : 1); - let startColumn = Math.floor((typeof initialStartColumn === 'number' && !isNaN(initialStartColumn)) ? initialStartColumn : 1); - if (startLineNumber < 1) { - startLineNumber = 1; - startColumn = 1; - } - else if (startLineNumber > linesCount) { - startLineNumber = linesCount; - startColumn = this.getLineMaxColumn(startLineNumber); - } - else { - if (startColumn <= 1) { - startColumn = 1; - } - else { - const maxColumn = this.getLineMaxColumn(startLineNumber); - if (startColumn >= maxColumn) { - startColumn = maxColumn; - } - } - } - const initialEndLineNumber = range.endLineNumber; - const initialEndColumn = range.endColumn; - let endLineNumber = Math.floor((typeof initialEndLineNumber === 'number' && !isNaN(initialEndLineNumber)) ? initialEndLineNumber : 1); - let endColumn = Math.floor((typeof initialEndColumn === 'number' && !isNaN(initialEndColumn)) ? initialEndColumn : 1); - if (endLineNumber < 1) { - endLineNumber = 1; - endColumn = 1; - } - else if (endLineNumber > linesCount) { - endLineNumber = linesCount; - endColumn = this.getLineMaxColumn(endLineNumber); - } - else { - if (endColumn <= 1) { - endColumn = 1; - } - else { - const maxColumn = this.getLineMaxColumn(endLineNumber); - if (endColumn >= maxColumn) { - endColumn = maxColumn; - } - } - } - 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); - } - _isValidPosition(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; - } - const lineCount = this._buffer.getLineCount(); - if (lineNumber > lineCount) { - return false; - } - if (column === 1) { - return true; - } - const maxColumn = this.getLineMaxColumn(lineNumber); - if (column > maxColumn) { - return false; - } - if (validationType === 1 /* SurrogatePairs */) { - // !!At this point, column > 1 - const charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2); - if (strings.isHighSurrogate(charCodeBefore)) { - return false; - } - } - return true; - } - _validatePosition(_lineNumber, _column, validationType) { - const lineNumber = Math.floor((typeof _lineNumber === 'number' && !isNaN(_lineNumber)) ? _lineNumber : 1); - const column = Math.floor((typeof _column === 'number' && !isNaN(_column)) ? _column : 1); - const 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); - } - const 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 - const 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); - } - validatePosition(position) { - const 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); - } - _isValidRange(range, validationType) { - const startLineNumber = range.startLineNumber; - const startColumn = range.startColumn; - const endLineNumber = range.endLineNumber; - const 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 */) { - const charCodeBeforeStart = (startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0); - const charCodeBeforeEnd = (endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0); - const startInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeStart); - const endInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeEnd); - if (!startInsideSurrogatePair && !endInsideSurrogatePair) { - return true; - } - return false; - } - return true; - } - validateRange(_range) { - const 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; - } - } - const start = this._validatePosition(_range.startLineNumber, _range.startColumn, 0 /* Relaxed */); - const end = this._validatePosition(_range.endLineNumber, _range.endColumn, 0 /* Relaxed */); - const startLineNumber = start.lineNumber; - const startColumn = start.column; - const endLineNumber = end.lineNumber; - const endColumn = end.column; - if (validationType === 1 /* SurrogatePairs */) { - const charCodeBeforeStart = (startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0); - const charCodeBeforeEnd = (endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0); - const startInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeStart); - const 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); - } - modifyPosition(rawPosition, offset) { - this._assertNotDisposed(); - let candidate = this.getOffsetAt(rawPosition) + offset; - return this.getPositionAt(Math.min(this._buffer.getLength(), Math.max(0, candidate))); - } - getFullModelRange() { - this._assertNotDisposed(); - const lineCount = this.getLineCount(); - return new range_1.Range(1, 1, lineCount, this.getLineMaxColumn(lineCount)); - } - findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount) { - return this._buffer.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount); - } - findMatches(searchString, rawSearchScope, isRegex, matchCase, wordSeparators, captureMatches, limitResultCount = LIMIT_FIND_COUNT) { - this._assertNotDisposed(); - let searchRanges = null; - if (rawSearchScope !== null) { - if (!Array.isArray(rawSearchScope)) { - rawSearchScope = [rawSearchScope]; - } - if (rawSearchScope.every((searchScope) => range_1.Range.isIRange(searchScope))) { - searchRanges = rawSearchScope.map((searchScope) => this.validateRange(searchScope)); - } - } - if (searchRanges === null) { - searchRanges = [this.getFullModelRange()]; - } - searchRanges = searchRanges.sort((d1, d2) => d1.startLineNumber - d2.startLineNumber || d1.startColumn - d2.startColumn); - const uniqueSearchRanges = []; - uniqueSearchRanges.push(searchRanges.reduce((prev, curr) => { - if (range_1.Range.areIntersecting(prev, curr)) { - return prev.plusRange(curr); - } - uniqueSearchRanges.push(prev); - return curr; - })); - let matchMapper; - if (!isRegex && searchString.indexOf('\n') < 0) { - // not regex, not multi line - const searchParams = new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators); - const searchData = searchParams.parseSearchRequest(); - if (!searchData) { - return []; - } - matchMapper = (searchRange) => this.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount); - } - else { - matchMapper = (searchRange) => textModelSearch_1.TextModelSearch.findMatches(this, new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators), searchRange, captureMatches, limitResultCount); - } - return uniqueSearchRanges.map(matchMapper).reduce((arr, matches) => arr.concat(matches), []); - } - findNextMatch(searchString, rawSearchStart, isRegex, matchCase, wordSeparators, captureMatches) { - this._assertNotDisposed(); - const searchStart = this.validatePosition(rawSearchStart); - if (!isRegex && searchString.indexOf('\n') < 0) { - const searchParams = new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators); - const searchData = searchParams.parseSearchRequest(); - if (!searchData) { - return null; - } - const lineCount = this.getLineCount(); - let searchRange = new range_1.Range(searchStart.lineNumber, searchStart.column, lineCount, this.getLineMaxColumn(lineCount)); - let 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); - } - findPreviousMatch(searchString, rawSearchStart, isRegex, matchCase, wordSeparators, captureMatches) { - this._assertNotDisposed(); - const searchStart = this.validatePosition(rawSearchStart); - return textModelSearch_1.TextModelSearch.findPreviousMatch(this, new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators), searchStart, captureMatches); - } - //#endregion - //#region Editing - pushStackElement() { - this._commandManager.pushStackElement(); - } - popStackElement() { - this._commandManager.popStackElement(); - } - pushEOL(eol) { - const currentEOL = (this.getEOL() === '\n' ? 0 /* LF */ : 1 /* CRLF */); - if (currentEOL === eol) { - return; - } - try { - this._onDidChangeDecorations.beginDeferredEmit(); - this._eventEmitter.beginDeferredEmit(); - if (this._initialUndoRedoSnapshot === null) { - this._initialUndoRedoSnapshot = this._undoRedoService.createSnapshot(this.uri); - } - this._commandManager.pushEOL(eol); - } - finally { - this._eventEmitter.endDeferredEmit(); - this._onDidChangeDecorations.endDeferredEmit(); - } - } - _validateEditOperation(rawOperation) { - if (rawOperation instanceof model.ValidAnnotatedEditOperation) { - return rawOperation; - } - return new model.ValidAnnotatedEditOperation(rawOperation.identifier || null, this.validateRange(rawOperation.range), rawOperation.text, rawOperation.forceMoveMarkers || false, rawOperation.isAutoWhitespaceEdit || false, rawOperation._isTracked || false); - } - _validateEditOperations(rawOperations) { - const result = []; - for (let i = 0, len = rawOperations.length; i < len; i++) { - result[i] = this._validateEditOperation(rawOperations[i]); - } - return result; - } - pushEditOperations(beforeCursorState, editOperations, cursorStateComputer) { - try { - this._onDidChangeDecorations.beginDeferredEmit(); - this._eventEmitter.beginDeferredEmit(); - return this._pushEditOperations(beforeCursorState, this._validateEditOperations(editOperations), cursorStateComputer); - } - finally { - this._eventEmitter.endDeferredEmit(); - this._onDidChangeDecorations.endDeferredEmit(); - } - } - _pushEditOperations(beforeCursorState, editOperations, cursorStateComputer) { - 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). - let incomingEdits = editOperations.map((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 - let editsAreNearCursors = true; - if (beforeCursorState) { - for (let i = 0, len = beforeCursorState.length; i < len; i++) { - let sel = beforeCursorState[i]; - let foundEditNearSel = false; - for (let j = 0, lenJ = incomingEdits.length; j < lenJ; j++) { - let editRange = incomingEdits[j].range; - let selIsAbove = editRange.startLineNumber > sel.endLineNumber; - let selIsBelow = sel.startLineNumber > editRange.endLineNumber; - if (!selIsAbove && !selIsBelow) { - foundEditNearSel = true; - break; - } - } - if (!foundEditNearSel) { - editsAreNearCursors = false; - break; - } - } - } - if (editsAreNearCursors) { - for (let i = 0, len = this._trimAutoWhitespaceLines.length; i < len; i++) { - let trimLineNumber = this._trimAutoWhitespaceLines[i]; - let maxLineColumn = this.getLineMaxColumn(trimLineNumber); - let allowTrimLine = true; - for (let j = 0, lenJ = incomingEdits.length; j < lenJ; j++) { - let editRange = incomingEdits[j].range; - let 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) { - const trimRange = new range_1.Range(trimLineNumber, 1, trimLineNumber, maxLineColumn); - editOperations.push(new model.ValidAnnotatedEditOperation(null, trimRange, null, false, false, false)); - } - } - } - this._trimAutoWhitespaceLines = null; - } - if (this._initialUndoRedoSnapshot === null) { - this._initialUndoRedoSnapshot = this._undoRedoService.createSnapshot(this.uri); - } - return this._commandManager.pushEditOperation(beforeCursorState, editOperations, cursorStateComputer); - } - _applyUndo(changes, eol, resultingAlternativeVersionId, resultingSelection) { - const edits = changes.map((change) => { - const rangeStart = this.getPositionAt(change.newPosition); - const rangeEnd = this.getPositionAt(change.newEnd); - return { - range: new range_1.Range(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column), - text: change.oldText - }; - }); - this._applyUndoRedoEdits(edits, eol, true, false, resultingAlternativeVersionId, resultingSelection); - } - _applyRedo(changes, eol, resultingAlternativeVersionId, resultingSelection) { - const edits = changes.map((change) => { - const rangeStart = this.getPositionAt(change.oldPosition); - const rangeEnd = this.getPositionAt(change.oldEnd); - return { - range: new range_1.Range(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column), - text: change.newText - }; - }); - this._applyUndoRedoEdits(edits, eol, false, true, resultingAlternativeVersionId, resultingSelection); - } - _applyUndoRedoEdits(edits, eol, isUndoing, isRedoing, resultingAlternativeVersionId, resultingSelection) { - try { - this._onDidChangeDecorations.beginDeferredEmit(); - this._eventEmitter.beginDeferredEmit(); - this._isUndoing = isUndoing; - this._isRedoing = isRedoing; - this.applyEdits(edits, false); - this.setEOL(eol); - this._overwriteAlternativeVersionId(resultingAlternativeVersionId); - } - finally { - this._isUndoing = false; - this._isRedoing = false; - this._eventEmitter.endDeferredEmit(resultingSelection); - this._onDidChangeDecorations.endDeferredEmit(); - } - } - applyEdits(rawOperations, computeUndoEdits = false) { - try { - this._onDidChangeDecorations.beginDeferredEmit(); - this._eventEmitter.beginDeferredEmit(); - const operations = this._validateEditOperations(rawOperations); - return this._doApplyEdits(operations, computeUndoEdits); - } - finally { - this._eventEmitter.endDeferredEmit(); - this._onDidChangeDecorations.endDeferredEmit(); - } - } - _doApplyEdits(rawOperations, computeUndoEdits) { - const oldLineCount = this._buffer.getLineCount(); - const result = this._buffer.applyEdits(rawOperations, this._options.trimAutoWhitespace, computeUndoEdits); - const newLineCount = this._buffer.getLineCount(); - const contentChanges = result.changes; - this._trimAutoWhitespaceLines = result.trimAutoWhitespaceLineNumbers; - if (contentChanges.length !== 0) { - // We do a first pass to update tokens and decorations - // because we want to read decorations in the second pass - // where we will emit content change events - // and we want to read the final decorations - for (let i = 0, len = contentChanges.length; i < len; i++) { - const change = contentChanges[i]; - const [eolCount, firstLineLength, lastLineLength] = (0, tokensStore_1.countEOL)(change.text); - 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._decorationsTree.acceptReplace(change.rangeOffset, change.rangeLength, change.text.length, change.forceMoveMarkers); - } - let rawContentChanges = []; - this._increaseVersionId(); - let lineCount = oldLineCount; - for (let i = 0, len = contentChanges.length; i < len; i++) { - const change = contentChanges[i]; - const [eolCount] = (0, tokensStore_1.countEOL)(change.text); - this._onDidChangeDecorations.fire(); - const startLineNumber = change.range.startLineNumber; - const endLineNumber = change.range.endLineNumber; - const deletingLinesCnt = endLineNumber - startLineNumber; - const insertingLinesCnt = eolCount; - const editingLinesCnt = Math.min(deletingLinesCnt, insertingLinesCnt); - const changeLineCountDelta = (insertingLinesCnt - deletingLinesCnt); - const currentEditStartLineNumber = newLineCount - lineCount - changeLineCountDelta + startLineNumber; - const firstEditLineNumber = currentEditStartLineNumber; - const lastInsertedLineNumber = currentEditStartLineNumber + insertingLinesCnt; - const decorationsWithInjectedTextInEditedRange = this._decorationsTree.getInjectedTextInInterval(this, this.getOffsetAt(new position_1.Position(firstEditLineNumber, 1)), this.getOffsetAt(new position_1.Position(lastInsertedLineNumber, this.getLineMaxColumn(lastInsertedLineNumber))), 0); - const injectedTextInEditedRange = textModelEvents_1.LineInjectedText.fromDecorations(decorationsWithInjectedTextInEditedRange); - const injectedTextInEditedRangeQueue = new arrays_1.ArrayQueue(injectedTextInEditedRange); - for (let j = editingLinesCnt; j >= 0; j--) { - const editLineNumber = startLineNumber + j; - const currentEditLineNumber = currentEditStartLineNumber + j; - injectedTextInEditedRangeQueue.takeFromEndWhile(r => r.lineNumber > currentEditLineNumber); - const decorationsInCurrentLine = injectedTextInEditedRangeQueue.takeFromEndWhile(r => r.lineNumber === currentEditLineNumber); - rawContentChanges.push(new textModelEvents_1.ModelRawLineChanged(editLineNumber, this.getLineContent(currentEditLineNumber), decorationsInCurrentLine)); - } - if (editingLinesCnt < deletingLinesCnt) { - // Must delete some lines - const spliceStartLineNumber = startLineNumber + editingLinesCnt; - rawContentChanges.push(new textModelEvents_1.ModelRawLinesDeleted(spliceStartLineNumber + 1, endLineNumber)); - } - if (editingLinesCnt < insertingLinesCnt) { - const injectedTextInEditedRangeQueue = new arrays_1.ArrayQueue(injectedTextInEditedRange); - // Must insert some lines - const spliceLineNumber = startLineNumber + editingLinesCnt; - const cnt = insertingLinesCnt - editingLinesCnt; - const fromLineNumber = newLineCount - lineCount - cnt + spliceLineNumber + 1; - let injectedTexts = []; - let newLines = []; - for (let i = 0; i < cnt; i++) { - let lineNumber = fromLineNumber + i; - newLines[i] = this.getLineContent(lineNumber); - injectedTextInEditedRangeQueue.takeWhile(r => r.lineNumber < lineNumber); - injectedTexts[i] = injectedTextInEditedRangeQueue.takeWhile(r => r.lineNumber === lineNumber); - } - rawContentChanges.push(new textModelEvents_1.ModelRawLinesInserted(spliceLineNumber + 1, startLineNumber + insertingLinesCnt, newLines, injectedTexts)); - } - lineCount += changeLineCountDelta; - } - 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 === null ? undefined : result.reverseEdits); - } - undo() { - return this._undoRedoService.undo(this.uri); - } - canUndo() { - return this._undoRedoService.canUndo(this.uri); - } - redo() { - return this._undoRedoService.redo(this.uri); - } - canRedo() { - return this._undoRedoService.canRedo(this.uri); - } - //#endregion - //#region Decorations - handleBeforeFireDecorationsChangedEvent(affectedInjectedTextLines) { - // This is called before the decoration changed event is fired. - if (affectedInjectedTextLines === null || affectedInjectedTextLines.size === 0) { - return; - } - const affectedLines = [...affectedInjectedTextLines]; - const lineChangeEvents = affectedLines.map(lineNumber => new textModelEvents_1.ModelRawLineChanged(lineNumber, this.getLineContent(lineNumber), this._getInjectedTextInLine(lineNumber))); - this._onDidChangeContentOrInjectedText.fire(new textModelEvents_1.ModelInjectedTextChangedEvent(lineChangeEvents)); - } - changeDecorations(callback, ownerId = 0) { - this._assertNotDisposed(); - try { - this._onDidChangeDecorations.beginDeferredEmit(); - return this._changeDecorations(ownerId, callback); - } - finally { - this._onDidChangeDecorations.endDeferredEmit(); - } - } - _changeDecorations(ownerId, callback) { - let changeAccessor = { - addDecoration: (range, options) => { - return this._deltaDecorationsImpl(ownerId, [], [{ range: range, options: options }])[0]; - }, - changeDecoration: (id, newRange) => { - this._changeDecorationImpl(id, newRange); - }, - changeDecorationOptions: (id, options) => { - this._changeDecorationOptionsImpl(id, _normalizeOptions(options)); - }, - removeDecoration: (id) => { - this._deltaDecorationsImpl(ownerId, [id], []); - }, - deltaDecorations: (oldDecorations, newDecorations) => { - if (oldDecorations.length === 0 && newDecorations.length === 0) { - // nothing to do - return []; - } - return this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations); - } - }; - let result = null; - try { - result = callback(changeAccessor); - } - catch (e) { - (0, errors_1.onUnexpectedError)(e); - } - // Invalidate change accessor - changeAccessor.addDecoration = invalidFunc; - changeAccessor.changeDecoration = invalidFunc; - changeAccessor.changeDecorationOptions = invalidFunc; - changeAccessor.removeDecoration = invalidFunc; - changeAccessor.deltaDecorations = invalidFunc; - return result; - } - deltaDecorations(oldDecorations, newDecorations, ownerId = 0) { - this._assertNotDisposed(); - if (!oldDecorations) { - oldDecorations = []; - } - if (oldDecorations.length === 0 && newDecorations.length === 0) { - // nothing to do - return []; - } - try { - this._onDidChangeDecorations.beginDeferredEmit(); - return this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations); - } - finally { - this._onDidChangeDecorations.endDeferredEmit(); - } - } - _getTrackedRange(id) { - return this.getDecorationRange(id); - } - _setTrackedRange(id, newRange, newStickiness) { - const 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 - const range = this._validateRangeRelaxedNoAllocations(newRange); - const startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn); - const 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; - } - removeAllDecorationsWithOwnerId(ownerId) { - if (this._isDisposed) { - return; - } - const nodes = this._decorationsTree.collectNodesFromOwner(ownerId); - for (let i = 0, len = nodes.length; i < len; i++) { - const node = nodes[i]; - this._decorationsTree.delete(node); - delete this._decorations[node.id]; - } - } - getDecorationOptions(decorationId) { - const node = this._decorations[decorationId]; - if (!node) { - return null; - } - return node.options; - } - getDecorationRange(decorationId) { - const node = this._decorations[decorationId]; - if (!node) { - return null; - } - return this._decorationsTree.getNodeRange(this, node); - } - getLineDecorations(lineNumber, ownerId = 0, filterOutValidation = false) { - if (lineNumber < 1 || lineNumber > this.getLineCount()) { - return []; - } - return this.getLinesDecorations(lineNumber, lineNumber, ownerId, filterOutValidation); - } - getLinesDecorations(_startLineNumber, _endLineNumber, ownerId = 0, filterOutValidation = false) { - let lineCount = this.getLineCount(); - let startLineNumber = Math.min(lineCount, Math.max(1, _startLineNumber)); - let endLineNumber = Math.min(lineCount, Math.max(1, _endLineNumber)); - let endColumn = this.getLineMaxColumn(endLineNumber); - return this._getDecorationsInRange(new range_1.Range(startLineNumber, 1, endLineNumber, endColumn), ownerId, filterOutValidation); - } - getDecorationsInRange(range, ownerId = 0, filterOutValidation = false) { - let validatedRange = this.validateRange(range); - return this._getDecorationsInRange(validatedRange, ownerId, filterOutValidation); - } - getOverviewRulerDecorations(ownerId = 0, filterOutValidation = false) { - return this._decorationsTree.getAll(this, ownerId, filterOutValidation, true); - } - getInjectedTextDecorations(ownerId = 0) { - return this._decorationsTree.getAllInjectedText(this, ownerId); - } - _getInjectedTextInLine(lineNumber) { - const startOffset = this._buffer.getOffsetAt(lineNumber, 1); - const endOffset = startOffset + this._buffer.getLineLength(lineNumber); - const result = this._decorationsTree.getInjectedTextInInterval(this, startOffset, endOffset, 0); - return textModelEvents_1.LineInjectedText.fromDecorations(result).filter(t => t.lineNumber === lineNumber); - } - getAllDecorations(ownerId = 0, filterOutValidation = false) { - return this._decorationsTree.getAll(this, ownerId, filterOutValidation, false); - } - _getDecorationsInRange(filterRange, filterOwnerId, filterOutValidation) { - const startOffset = this._buffer.getOffsetAt(filterRange.startLineNumber, filterRange.startColumn); - const endOffset = this._buffer.getOffsetAt(filterRange.endLineNumber, filterRange.endColumn); - return this._decorationsTree.getAllInInterval(this, startOffset, endOffset, filterOwnerId, filterOutValidation); - } - getRangeAt(start, end) { - return this._buffer.getRangeAt(start, end - start); - } - _changeDecorationImpl(decorationId, _range) { - const node = this._decorations[decorationId]; - if (!node) { - return; - } - if (node.options.after) { - const oldRange = this.getDecorationRange(decorationId); - this._onDidChangeDecorations.recordLineAffectedByInjectedText(oldRange.endLineNumber); - } - if (node.options.before) { - const oldRange = this.getDecorationRange(decorationId); - this._onDidChangeDecorations.recordLineAffectedByInjectedText(oldRange.startLineNumber); - } - const range = this._validateRangeRelaxedNoAllocations(_range); - const startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn); - const endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn); - this._decorationsTree.delete(node); - node.reset(this.getVersionId(), startOffset, endOffset, range); - this._decorationsTree.insert(node); - this._onDidChangeDecorations.checkAffectedAndFire(node.options); - if (node.options.after) { - this._onDidChangeDecorations.recordLineAffectedByInjectedText(range.endLineNumber); - } - if (node.options.before) { - this._onDidChangeDecorations.recordLineAffectedByInjectedText(range.startLineNumber); - } - } - _changeDecorationOptionsImpl(decorationId, options) { - const node = this._decorations[decorationId]; - if (!node) { - return; - } - const nodeWasInOverviewRuler = (node.options.overviewRuler && node.options.overviewRuler.color ? true : false); - const nodeIsInOverviewRuler = (options.overviewRuler && options.overviewRuler.color ? true : false); - this._onDidChangeDecorations.checkAffectedAndFire(node.options); - this._onDidChangeDecorations.checkAffectedAndFire(options); - if (node.options.after || options.after) { - const nodeRange = this._decorationsTree.getNodeRange(this, node); - this._onDidChangeDecorations.recordLineAffectedByInjectedText(nodeRange.endLineNumber); - } - if (node.options.before || options.before) { - const nodeRange = this._decorationsTree.getNodeRange(this, node); - this._onDidChangeDecorations.recordLineAffectedByInjectedText(nodeRange.startLineNumber); - } - 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); - } - } - _deltaDecorationsImpl(ownerId, oldDecorationsIds, newDecorations) { - const versionId = this.getVersionId(); - const oldDecorationsLen = oldDecorationsIds.length; - let oldDecorationIndex = 0; - const newDecorationsLen = newDecorations.length; - let newDecorationIndex = 0; - let result = new Array(newDecorationsLen); - while (oldDecorationIndex < oldDecorationsLen || newDecorationIndex < newDecorationsLen) { - let 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) { - if (node.options.after) { - const nodeRange = this._decorationsTree.getNodeRange(this, node); - this._onDidChangeDecorations.recordLineAffectedByInjectedText(nodeRange.endLineNumber); - } - if (node.options.before) { - const nodeRange = this._decorationsTree.getNodeRange(this, node); - this._onDidChangeDecorations.recordLineAffectedByInjectedText(nodeRange.startLineNumber); - } - this._decorationsTree.delete(node); - this._onDidChangeDecorations.checkAffectedAndFire(node.options); - } - } - if (newDecorationIndex < newDecorationsLen) { - // (3) create a new node if necessary - if (!node) { - const internalDecorationId = (++this._lastDecorationId); - const decorationId = `${this._instanceId};${internalDecorationId}`; - node = new intervalTree_1.IntervalNode(decorationId, 0, 0); - this._decorations[decorationId] = node; - } - // (4) initialize node - const newDecoration = newDecorations[newDecorationIndex]; - const range = this._validateRangeRelaxedNoAllocations(newDecoration.range); - const options = _normalizeOptions(newDecoration.options); - const startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn); - const endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn); - node.ownerId = ownerId; - node.reset(versionId, startOffset, endOffset, range); - node.setOptions(options); - if (node.options.after) { - this._onDidChangeDecorations.recordLineAffectedByInjectedText(range.endLineNumber); - } - if (node.options.before) { - this._onDidChangeDecorations.recordLineAffectedByInjectedText(range.startLineNumber); - } - this._onDidChangeDecorations.checkAffectedAndFire(options); - this._decorationsTree.insert(node); - result[newDecorationIndex] = node.id; - newDecorationIndex++; - } - else { - if (node) { - delete this._decorations[node.id]; - } - } - } - return result; - } - setTokens(tokens) { - if (tokens.length === 0) { - return; - } - let ranges = []; - for (let i = 0, len = tokens.length; i < len; i++) { - const element = tokens[i]; - let minChangedLineNumber = 0; - let maxChangedLineNumber = 0; - let hasChange = false; - for (let j = 0, lenJ = element.tokens.length; j < lenJ; j++) { - const lineNumber = element.startLineNumber + j; - if (hasChange) { - this._tokens.setTokens(this._languageIdentifier.id, lineNumber - 1, this._buffer.getLineLength(lineNumber), element.tokens[j], false); - maxChangedLineNumber = lineNumber; - } - else { - const lineHasChange = this._tokens.setTokens(this._languageIdentifier.id, lineNumber - 1, this._buffer.getLineLength(lineNumber), element.tokens[j], true); - if (lineHasChange) { - hasChange = true; - minChangedLineNumber = lineNumber; - maxChangedLineNumber = lineNumber; - } - } - } - if (hasChange) { - ranges.push({ fromLineNumber: minChangedLineNumber, toLineNumber: maxChangedLineNumber }); - } - } - if (ranges.length > 0) { - this._emitModelTokensChangedEvent({ - tokenizationSupportChanged: false, - semanticTokensApplied: false, - ranges: ranges - }); - } - } - setSemanticTokens(tokens, isComplete) { - this._tokens2.set(tokens, isComplete); - this._emitModelTokensChangedEvent({ - tokenizationSupportChanged: false, - semanticTokensApplied: tokens !== null, - ranges: [{ fromLineNumber: 1, toLineNumber: this.getLineCount() }] - }); - } - hasCompleteSemanticTokens() { - return this._tokens2.isComplete(); - } - hasSomeSemanticTokens() { - return !this._tokens2.isEmpty(); - } - setPartialSemanticTokens(range, tokens) { - if (this.hasCompleteSemanticTokens()) { - return; - } - const changedRange = this._tokens2.setPartial(range, tokens); - this._emitModelTokensChangedEvent({ - tokenizationSupportChanged: false, - semanticTokensApplied: true, - ranges: [{ fromLineNumber: changedRange.startLineNumber, toLineNumber: changedRange.endLineNumber }] - }); - } - tokenizeViewport(startLineNumber, endLineNumber) { - startLineNumber = Math.max(1, startLineNumber); - endLineNumber = Math.min(this._buffer.getLineCount(), endLineNumber); - this._tokenization.tokenizeViewport(startLineNumber, endLineNumber); - } - clearTokens() { - this._tokens.flush(); - this._emitModelTokensChangedEvent({ - tokenizationSupportChanged: true, - semanticTokensApplied: false, - ranges: [{ - fromLineNumber: 1, - toLineNumber: this._buffer.getLineCount() - }] - }); - } - _emitModelTokensChangedEvent(e) { - if (!this._isDisposing) { - this._onDidChangeTokens.fire(e); - } - } - resetTokenization() { - this._tokenization.reset(); - } - forceTokenization(lineNumber) { - if (lineNumber < 1 || lineNumber > this.getLineCount()) { - throw new Error('Illegal value for lineNumber'); - } - this._tokenization.forceTokenization(lineNumber); - } - isCheapToTokenize(lineNumber) { - return this._tokenization.isCheapToTokenize(lineNumber); - } - tokenizeIfCheap(lineNumber) { - if (this.isCheapToTokenize(lineNumber)) { - this.forceTokenization(lineNumber); - } - } - getLineTokens(lineNumber) { - if (lineNumber < 1 || lineNumber > this.getLineCount()) { - throw new Error('Illegal value for lineNumber'); - } - return this._getLineTokens(lineNumber); - } - _getLineTokens(lineNumber) { - const lineText = this.getLineContent(lineNumber); - const syntacticTokens = this._tokens.getTokens(this._languageIdentifier.id, lineNumber - 1, lineText); - return this._tokens2.addSemanticTokens(lineNumber, syntacticTokens); - } - getLanguageIdentifier() { - return this._languageIdentifier; - } - getModeId() { - return this._languageIdentifier.language; - } - setMode(languageIdentifier) { - if (this._languageIdentifier.id === languageIdentifier.id) { - // There's nothing to do - return; - } - let e = { - oldLanguage: this._languageIdentifier.language, - newLanguage: languageIdentifier.language - }; - this._languageIdentifier = languageIdentifier; - this._onDidChangeLanguage.fire(e); - this._onDidChangeLanguageConfiguration.fire({}); - } - getLanguageIdAtPosition(lineNumber, column) { - const position = this.validatePosition(new position_1.Position(lineNumber, column)); - const lineTokens = this.getLineTokens(position.lineNumber); - return lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(position.column - 1)); - } - // Having tokens allows implementing additional helper methods - getWordAtPosition(_position) { - this._assertNotDisposed(); - const position = this.validatePosition(_position); - const lineContent = this.getLineContent(position.lineNumber); - const lineTokens = this._getLineTokens(position.lineNumber); - const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); - // (1). First try checking right biased word - const [rbStartOffset, rbEndOffset] = TextModel._findLanguageBoundaries(lineTokens, tokenIndex); - const rightBiasedWord = (0, 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 - const [lbStartOffset, lbEndOffset] = TextModel._findLanguageBoundaries(lineTokens, tokenIndex - 1); - const leftBiasedWord = (0, 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; - } - static _findLanguageBoundaries(lineTokens, tokenIndex) { - const languageId = lineTokens.getLanguageId(tokenIndex); - // go left until a different language is hit - let startOffset = 0; - for (let i = tokenIndex; i >= 0 && lineTokens.getLanguageId(i) === languageId; i--) { - startOffset = lineTokens.getStartOffset(i); - } - // go right until a different language is hit - let endOffset = lineTokens.getLineContent().length; - for (let i = tokenIndex, tokenCount = lineTokens.getCount(); i < tokenCount && lineTokens.getLanguageId(i) === languageId; i++) { - endOffset = lineTokens.getEndOffset(i); - } - return [startOffset, endOffset]; - } - getWordUntilPosition(position) { - const 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 - }; - } - findMatchingBracketUp(_bracket, _position) { - let bracket = _bracket.toLowerCase(); - let position = this.validatePosition(_position); - let lineTokens = this._getLineTokens(position.lineNumber); - let languageId = lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(position.column - 1)); - let bracketsSupport = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId); - if (!bracketsSupport) { - return null; - } - let data = bracketsSupport.textIsBracket[bracket]; - if (!data) { - return null; - } - return stripBracketSearchCanceled(this._findMatchingBracketUp(data, position, null)); - } - matchBracket(position) { - return this._matchBracket(this.validatePosition(position)); - } - _establishBracketSearchOffsets(position, lineTokens, modeBrackets, tokenIndex) { - const tokenCount = lineTokens.getCount(); - const currentLanguageId = lineTokens.getLanguageId(tokenIndex); - // limit search to not go before `maxBracketLength` - let searchStartOffset = Math.max(0, position.column - 1 - modeBrackets.maxBracketLength); - for (let i = tokenIndex - 1; i >= 0; i--) { - const tokenEndOffset = lineTokens.getEndOffset(i); - if (tokenEndOffset <= searchStartOffset) { - break; - } - if ((0, supports_1.ignoreBracketsInToken)(lineTokens.getStandardTokenType(i)) || lineTokens.getLanguageId(i) !== currentLanguageId) { - searchStartOffset = tokenEndOffset; - break; - } - } - // limit search to not go after `maxBracketLength` - let searchEndOffset = Math.min(lineTokens.getLineContent().length, position.column - 1 + modeBrackets.maxBracketLength); - for (let i = tokenIndex + 1; i < tokenCount; i++) { - const tokenStartOffset = lineTokens.getStartOffset(i); - if (tokenStartOffset >= searchEndOffset) { - break; - } - if ((0, supports_1.ignoreBracketsInToken)(lineTokens.getStandardTokenType(i)) || lineTokens.getLanguageId(i) !== currentLanguageId) { - searchEndOffset = tokenStartOffset; - break; - } - } - return { searchStartOffset, searchEndOffset }; - } - _matchBracket(position) { - const lineNumber = position.lineNumber; - const lineTokens = this._getLineTokens(lineNumber); - const lineText = this._buffer.getLineContent(lineNumber); - const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); - if (tokenIndex < 0) { - return null; - } - const currentModeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(lineTokens.getLanguageId(tokenIndex)); - // check that the token is not to be ignored - if (currentModeBrackets && !(0, supports_1.ignoreBracketsInToken)(lineTokens.getStandardTokenType(tokenIndex))) { - let { searchStartOffset, searchEndOffset } = this._establishBracketSearchOffsets(position, lineTokens, currentModeBrackets, tokenIndex); - // it might be the case that [currentTokenStart -> currentTokenEnd] contains multiple brackets - // `bestResult` will contain the most right-side result - let bestResult = null; - while (true) { - const 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) { - const foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase(); - const r = this._matchFoundBracket(foundBracket, currentModeBrackets.textIsBracket[foundBracketText], currentModeBrackets.textIsOpenBracket[foundBracketText], null); - if (r) { - if (r instanceof BracketSearchCanceled) { - return null; - } - 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) { - const prevTokenIndex = tokenIndex - 1; - const prevModeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(lineTokens.getLanguageId(prevTokenIndex)); - // check that previous token is not to be ignored - if (prevModeBrackets && !(0, supports_1.ignoreBracketsInToken)(lineTokens.getStandardTokenType(prevTokenIndex))) { - let { searchStartOffset, searchEndOffset } = this._establishBracketSearchOffsets(position, lineTokens, prevModeBrackets, prevTokenIndex); - const 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) { - const foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase(); - const r = this._matchFoundBracket(foundBracket, prevModeBrackets.textIsBracket[foundBracketText], prevModeBrackets.textIsOpenBracket[foundBracketText], null); - if (r) { - if (r instanceof BracketSearchCanceled) { - return null; - } - return r; - } - } - } - } - return null; - } - _matchFoundBracket(foundBracket, data, isOpen, continueSearchPredicate) { - if (!data) { - return null; - } - const matched = (isOpen - ? this._findMatchingBracketDown(data, foundBracket.getEndPosition(), continueSearchPredicate) - : this._findMatchingBracketUp(data, foundBracket.getStartPosition(), continueSearchPredicate)); - if (!matched) { - return null; - } - if (matched instanceof BracketSearchCanceled) { - return matched; - } - return [foundBracket, matched]; - } - _findMatchingBracketUp(bracket, position, continueSearchPredicate) { - // console.log('_findMatchingBracketUp: ', 'bracket: ', JSON.stringify(bracket), 'startPosition: ', String(position)); - const languageId = bracket.languageIdentifier.id; - const reversedBracketRegex = bracket.reversedRegex; - let count = -1; - let totalCallCount = 0; - const searchPrevMatchingBracketInRange = (lineNumber, lineText, searchStartOffset, searchEndOffset) => { - while (true) { - if (continueSearchPredicate && (++totalCallCount) % 100 === 0 && !continueSearchPredicate()) { - return BracketSearchCanceled.INSTANCE; - } - const r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(reversedBracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset); - if (!r) { - break; - } - const 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 (let lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) { - const lineTokens = this._getLineTokens(lineNumber); - const tokenCount = lineTokens.getCount(); - const lineText = this._buffer.getLineContent(lineNumber); - let tokenIndex = tokenCount - 1; - let searchStartOffset = lineText.length; - let searchEndOffset = lineText.length; - if (lineNumber === position.lineNumber) { - tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); - searchStartOffset = position.column - 1; - searchEndOffset = position.column - 1; - } - let prevSearchInToken = true; - for (; tokenIndex >= 0; tokenIndex--) { - const searchInToken = (lineTokens.getLanguageId(tokenIndex) === languageId && !(0, 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) { - const r = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset); - if (r) { - return r; - } - } - } - prevSearchInToken = searchInToken; - } - if (prevSearchInToken && searchStartOffset !== searchEndOffset) { - const r = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset); - if (r) { - return r; - } - } - } - return null; - } - _findMatchingBracketDown(bracket, position, continueSearchPredicate) { - // console.log('_findMatchingBracketDown: ', 'bracket: ', JSON.stringify(bracket), 'startPosition: ', String(position)); - const languageId = bracket.languageIdentifier.id; - const bracketRegex = bracket.forwardRegex; - let count = 1; - let totalCallCount = 0; - const searchNextMatchingBracketInRange = (lineNumber, lineText, searchStartOffset, searchEndOffset) => { - while (true) { - if (continueSearchPredicate && (++totalCallCount) % 100 === 0 && !continueSearchPredicate()) { - return BracketSearchCanceled.INSTANCE; - } - const r = richEditBrackets_1.BracketsUtils.findNextBracketInRange(bracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset); - if (!r) { - break; - } - const 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; - }; - const lineCount = this.getLineCount(); - for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) { - const lineTokens = this._getLineTokens(lineNumber); - const tokenCount = lineTokens.getCount(); - const lineText = this._buffer.getLineContent(lineNumber); - let tokenIndex = 0; - let searchStartOffset = 0; - let searchEndOffset = 0; - if (lineNumber === position.lineNumber) { - tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); - searchStartOffset = position.column - 1; - searchEndOffset = position.column - 1; - } - let prevSearchInToken = true; - for (; tokenIndex < tokenCount; tokenIndex++) { - const searchInToken = (lineTokens.getLanguageId(tokenIndex) === languageId && !(0, 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) { - const r = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset); - if (r) { - return r; - } - } - } - prevSearchInToken = searchInToken; - } - if (prevSearchInToken && searchStartOffset !== searchEndOffset) { - const r = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset); - if (r) { - return r; - } - } - } - return null; - } - findPrevBracket(_position) { - const position = this.validatePosition(_position); - let languageId = -1; - let modeBrackets = null; - for (let lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) { - const lineTokens = this._getLineTokens(lineNumber); - const tokenCount = lineTokens.getCount(); - const lineText = this._buffer.getLineContent(lineNumber); - let tokenIndex = tokenCount - 1; - let searchStartOffset = lineText.length; - let searchEndOffset = lineText.length; - if (lineNumber === position.lineNumber) { - tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); - searchStartOffset = position.column - 1; - searchEndOffset = position.column - 1; - const tokenLanguageId = lineTokens.getLanguageId(tokenIndex); - if (languageId !== tokenLanguageId) { - languageId = tokenLanguageId; - modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId); - } - } - let prevSearchInToken = true; - for (; tokenIndex >= 0; tokenIndex--) { - const tokenLanguageId = lineTokens.getLanguageId(tokenIndex); - if (languageId !== tokenLanguageId) { - // language id change! - if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) { - const 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); - } - const searchInToken = (!!modeBrackets && !(0, 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) { - const 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) { - const r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset); - if (r) { - return this._toFoundBracket(modeBrackets, r); - } - } - } - return null; - } - findNextBracket(_position) { - const position = this.validatePosition(_position); - const lineCount = this.getLineCount(); - let languageId = -1; - let modeBrackets = null; - for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) { - const lineTokens = this._getLineTokens(lineNumber); - const tokenCount = lineTokens.getCount(); - const lineText = this._buffer.getLineContent(lineNumber); - let tokenIndex = 0; - let searchStartOffset = 0; - let searchEndOffset = 0; - if (lineNumber === position.lineNumber) { - tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); - searchStartOffset = position.column - 1; - searchEndOffset = position.column - 1; - const tokenLanguageId = lineTokens.getLanguageId(tokenIndex); - if (languageId !== tokenLanguageId) { - languageId = tokenLanguageId; - modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId); - } - } - let prevSearchInToken = true; - for (; tokenIndex < tokenCount; tokenIndex++) { - const tokenLanguageId = lineTokens.getLanguageId(tokenIndex); - if (languageId !== tokenLanguageId) { - // language id change! - if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) { - const 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); - } - const searchInToken = (!!modeBrackets && !(0, 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) { - const 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) { - const r = richEditBrackets_1.BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset); - if (r) { - return this._toFoundBracket(modeBrackets, r); - } - } - } - return null; - } - findEnclosingBrackets(_position, maxDuration) { - let continueSearchPredicate; - if (typeof maxDuration === 'undefined') { - continueSearchPredicate = null; - } - else { - const startTime = Date.now(); - continueSearchPredicate = () => { - return (Date.now() - startTime <= maxDuration); - }; - } - const position = this.validatePosition(_position); - const lineCount = this.getLineCount(); - const savedCounts = new Map(); - let counts = []; - const resetCounts = (languageId, modeBrackets) => { - if (!savedCounts.has(languageId)) { - let tmp = []; - for (let i = 0, len = modeBrackets ? modeBrackets.brackets.length : 0; i < len; i++) { - tmp[i] = 0; - } - savedCounts.set(languageId, tmp); - } - counts = savedCounts.get(languageId); - }; - let totalCallCount = 0; - const searchInRange = (modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset) => { - while (true) { - if (continueSearchPredicate && (++totalCallCount) % 100 === 0 && !continueSearchPredicate()) { - return BracketSearchCanceled.INSTANCE; - } - const r = richEditBrackets_1.BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset); - if (!r) { - break; - } - const hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase(); - const 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, continueSearchPredicate); - } - } - searchStartOffset = r.endColumn - 1; - } - return null; - }; - let languageId = -1; - let modeBrackets = null; - for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) { - const lineTokens = this._getLineTokens(lineNumber); - const tokenCount = lineTokens.getCount(); - const lineText = this._buffer.getLineContent(lineNumber); - let tokenIndex = 0; - let searchStartOffset = 0; - let searchEndOffset = 0; - if (lineNumber === position.lineNumber) { - tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); - searchStartOffset = position.column - 1; - searchEndOffset = position.column - 1; - const tokenLanguageId = lineTokens.getLanguageId(tokenIndex); - if (languageId !== tokenLanguageId) { - languageId = tokenLanguageId; - modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId); - resetCounts(languageId, modeBrackets); - } - } - let prevSearchInToken = true; - for (; tokenIndex < tokenCount; tokenIndex++) { - const tokenLanguageId = lineTokens.getLanguageId(tokenIndex); - if (languageId !== tokenLanguageId) { - // language id change! - if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) { - const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset); - if (r) { - return stripBracketSearchCanceled(r); - } - prevSearchInToken = false; - } - languageId = tokenLanguageId; - modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId); - resetCounts(languageId, modeBrackets); - } - const searchInToken = (!!modeBrackets && !(0, 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) { - const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset); - if (r) { - return stripBracketSearchCanceled(r); - } - } - } - prevSearchInToken = searchInToken; - } - if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) { - const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset); - if (r) { - return stripBracketSearchCanceled(r); - } - } - } - return null; - } - _toFoundBracket(modeBrackets, r) { - if (!r) { - return null; - } - let text = this.getValueInRange(r); - text = text.toLowerCase(); - let 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 - */ - static computeIndentLevel(line, tabSize) { - let indent = 0; - let i = 0; - let len = line.length; - while (i < len) { - let 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; - } - _computeIndentLevel(lineIndex) { - return TextModel.computeIndentLevel(this._buffer.getLineContent(lineIndex + 1), this._options.tabSize); - } - getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber) { - this._assertNotDisposed(); - const lineCount = this.getLineCount(); - if (lineNumber < 1 || lineNumber > lineCount) { - throw new Error('Illegal value for lineNumber'); - } - const foldingRules = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getFoldingRules(this._languageIdentifier.id); - const offSide = Boolean(foldingRules && foldingRules.offSide); - let up_aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */ - let up_aboveContentLineIndent = -1; - let up_belowContentLineIndex = -2; /* -2 is a marker for not having computed it */ - let up_belowContentLineIndent = -1; - const up_resolveIndents = (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 (let lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) { - let indent = this._computeIndentLevel(lineIndex); - if (indent >= 0) { - up_aboveContentLineIndex = lineIndex; - up_aboveContentLineIndent = indent; - break; - } - } - } - if (up_belowContentLineIndex === -2) { - up_belowContentLineIndex = -1; - up_belowContentLineIndent = -1; - // must find next line with content - for (let lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) { - let indent = this._computeIndentLevel(lineIndex); - if (indent >= 0) { - up_belowContentLineIndex = lineIndex; - up_belowContentLineIndent = indent; - break; - } - } - } - }; - let down_aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */ - let down_aboveContentLineIndent = -1; - let down_belowContentLineIndex = -2; /* -2 is a marker for not having computed it */ - let down_belowContentLineIndent = -1; - const down_resolveIndents = (lineNumber) => { - if (down_aboveContentLineIndex === -2) { - down_aboveContentLineIndex = -1; - down_aboveContentLineIndent = -1; - // must find previous line with content - for (let lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) { - let indent = this._computeIndentLevel(lineIndex); - if (indent >= 0) { - down_aboveContentLineIndex = lineIndex; - down_aboveContentLineIndent = indent; - 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 (let lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) { - let indent = this._computeIndentLevel(lineIndex); - if (indent >= 0) { - down_belowContentLineIndex = lineIndex; - down_belowContentLineIndent = indent; - break; - } - } - } - }; - let startLineNumber = 0; - let goUp = true; - let endLineNumber = 0; - let goDown = true; - let indent = 0; - let initialIndent = 0; - for (let distance = 0; goUp || goDown; distance++) { - const upLineNumber = lineNumber - distance; - const downLineNumber = lineNumber + distance; - if (distance > 1 && (upLineNumber < 1 || upLineNumber < minLineNumber)) { - goUp = false; - } - if (distance > 1 && (downLineNumber > lineCount || downLineNumber > maxLineNumber)) { - goDown = false; - } - if (distance > 50000) { - // stop processing - goUp = false; - goDown = false; - } - let upLineIndentLevel = -1; - if (goUp) { - // compute indent level going up - const 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); - } - } - let downLineIndentLevel = -1; - if (goDown) { - // compute indent level going down - const 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 (distance === 0) { - initialIndent = upLineIndentLevel; - continue; - } - if (distance === 1) { - if (downLineNumber <= lineCount && downLineIndentLevel >= 0 && initialIndent + 1 === downLineIndentLevel) { - // This is the beginning of a scope, we have special handling here, since we want the - // child scope indent to be active, not the parent scope - goUp = false; - startLineNumber = downLineNumber; - endLineNumber = downLineNumber; - indent = downLineIndentLevel; - continue; - } - if (upLineNumber >= 1 && upLineIndentLevel >= 0 && upLineIndentLevel - 1 === initialIndent) { - // This is the end of a scope, just like above - goDown = false; - startLineNumber = upLineNumber; - endLineNumber = upLineNumber; - indent = upLineIndentLevel; - continue; - } - startLineNumber = lineNumber; - endLineNumber = lineNumber; - indent = initialIndent; - if (indent === 0) { - // No need to continue - return { startLineNumber, endLineNumber, indent }; - } - } - if (goUp) { - if (upLineIndentLevel >= indent) { - startLineNumber = upLineNumber; - } - else { - goUp = false; - } - } - if (goDown) { - if (downLineIndentLevel >= indent) { - endLineNumber = downLineNumber; - } - else { - goDown = false; - } - } - } - return { startLineNumber, endLineNumber, indent }; - } - getLinesIndentGuides(startLineNumber, endLineNumber) { - this._assertNotDisposed(); - const 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'); - } - const foldingRules = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getFoldingRules(this._languageIdentifier.id); - const offSide = Boolean(foldingRules && foldingRules.offSide); - let result = new Array(endLineNumber - startLineNumber + 1); - let aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */ - let aboveContentLineIndent = -1; - let belowContentLineIndex = -2; /* -2 is a marker for not having computed it */ - let belowContentLineIndent = -1; - for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { - let resultIndex = lineNumber - startLineNumber; - const 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 (let lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) { - let 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 (let lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) { - let indent = this._computeIndentLevel(lineIndex); - if (indent >= 0) { - belowContentLineIndex = lineIndex; - belowContentLineIndent = indent; - break; - } - } - } - result[resultIndex] = this._getIndentLevelForWhitespaceLine(offSide, aboveContentLineIndent, belowContentLineIndent); - } - return result; - } - _getIndentLevelForWhitespaceLine(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)); - } - } - } - //#endregion - normalizePosition(position, affinity) { - return position; - } - /** - * Gets the column at which indentation stops at a given line. - * @internal - */ - getLineIndentColumn(lineNumber) { - // Columns start with 1. - return indentOfLine(this.getLineContent(lineNumber)) + 1; - } - } - exports.TextModel = TextModel; - 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, - }; - function indentOfLine(line) { - let indent = 0; - for (const c of line) { - if (c === ' ' || c === '\t') { - indent++; - } - else { - break; - } - } - return indent; - } - //#region Decorations - function isNodeInOverviewRuler(node) { - return (node.options.overviewRuler && node.options.overviewRuler.color ? true : false); - } - function isNodeInjectedText(node) { - return !!node.options.after || !!node.options.before; - } - class DecorationsTrees { - constructor() { - this._decorationsTree0 = new intervalTree_1.IntervalTree(); - this._decorationsTree1 = new intervalTree_1.IntervalTree(); - this._injectedTextDecorationsTree = new intervalTree_1.IntervalTree(); - } - ensureAllNodesHaveRanges(host) { - this.getAll(host, 0, false, false); - } - _ensureNodesHaveRanges(host, nodes) { - for (const node of nodes) { - if (node.range === null) { - node.range = host.getRangeAt(node.cachedAbsoluteStart, node.cachedAbsoluteEnd); - } - } - return nodes; - } - getAllInInterval(host, start, end, filterOwnerId, filterOutValidation) { - const versionId = host.getVersionId(); - const result = this._intervalSearch(start, end, filterOwnerId, filterOutValidation, versionId); - return this._ensureNodesHaveRanges(host, result); - } - _intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId) { - const r0 = this._decorationsTree0.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId); - const r1 = this._decorationsTree1.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId); - const r2 = this._injectedTextDecorationsTree.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId); - return r0.concat(r1).concat(r2); - } - getInjectedTextInInterval(host, start, end, filterOwnerId) { - const versionId = host.getVersionId(); - const result = this._injectedTextDecorationsTree.intervalSearch(start, end, filterOwnerId, false, versionId); - return this._ensureNodesHaveRanges(host, result); - } - getAllInjectedText(host, filterOwnerId) { - const versionId = host.getVersionId(); - const result = this._injectedTextDecorationsTree.search(filterOwnerId, false, versionId); - return this._ensureNodesHaveRanges(host, result); - } - getAll(host, filterOwnerId, filterOutValidation, overviewRulerOnly) { - const versionId = host.getVersionId(); - const result = this._search(filterOwnerId, filterOutValidation, overviewRulerOnly, versionId); - return this._ensureNodesHaveRanges(host, result); - } - _search(filterOwnerId, filterOutValidation, overviewRulerOnly, cachedVersionId) { - if (overviewRulerOnly) { - return this._decorationsTree1.search(filterOwnerId, filterOutValidation, cachedVersionId); - } - else { - const r0 = this._decorationsTree0.search(filterOwnerId, filterOutValidation, cachedVersionId); - const r1 = this._decorationsTree1.search(filterOwnerId, filterOutValidation, cachedVersionId); - const r2 = this._injectedTextDecorationsTree.search(filterOwnerId, filterOutValidation, cachedVersionId); - return r0.concat(r1).concat(r2); - } - } - collectNodesFromOwner(ownerId) { - const r0 = this._decorationsTree0.collectNodesFromOwner(ownerId); - const r1 = this._decorationsTree1.collectNodesFromOwner(ownerId); - const r2 = this._injectedTextDecorationsTree.collectNodesFromOwner(ownerId); - return r0.concat(r1).concat(r2); - } - collectNodesPostOrder() { - const r0 = this._decorationsTree0.collectNodesPostOrder(); - const r1 = this._decorationsTree1.collectNodesPostOrder(); - const r2 = this._injectedTextDecorationsTree.collectNodesPostOrder(); - return r0.concat(r1).concat(r2); - } - insert(node) { - if (isNodeInjectedText(node)) { - this._injectedTextDecorationsTree.insert(node); - } - else if (isNodeInOverviewRuler(node)) { - this._decorationsTree1.insert(node); - } - else { - this._decorationsTree0.insert(node); - } - } - delete(node) { - if (isNodeInjectedText(node)) { - this._injectedTextDecorationsTree.delete(node); - } - else if (isNodeInOverviewRuler(node)) { - this._decorationsTree1.delete(node); - } - else { - this._decorationsTree0.delete(node); - } - } - getNodeRange(host, node) { - const versionId = host.getVersionId(); - if (node.cachedVersionId !== versionId) { - this._resolveNode(node, versionId); - } - if (node.range === null) { - node.range = host.getRangeAt(node.cachedAbsoluteStart, node.cachedAbsoluteEnd); - } - return node.range; - } - _resolveNode(node, cachedVersionId) { - if (isNodeInjectedText(node)) { - this._injectedTextDecorationsTree.resolveNode(node, cachedVersionId); - } - else if (isNodeInOverviewRuler(node)) { - this._decorationsTree1.resolveNode(node, cachedVersionId); - } - else { - this._decorationsTree0.resolveNode(node, cachedVersionId); - } - } - acceptReplace(offset, length, textLength, forceMoveMarkers) { - this._decorationsTree0.acceptReplace(offset, length, textLength, forceMoveMarkers); - this._decorationsTree1.acceptReplace(offset, length, textLength, forceMoveMarkers); - this._injectedTextDecorationsTree.acceptReplace(offset, length, textLength, forceMoveMarkers); - } - } - function cleanClassName(className) { - return className.replace(/[^a-z0-9\-_]/gi, ' '); - } - class DecorationOptions { - constructor(options) { - this.color = options.color || ''; - this.darkColor = options.darkColor || ''; - } - } - class ModelDecorationOverviewRulerOptions extends DecorationOptions { - constructor(options) { - super(options); - this._resolvedColor = null; - this.position = (typeof options.position === 'number' ? options.position : model.OverviewRulerLane.Center); - } - getColor(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; - } - invalidateCachedColor() { - this._resolvedColor = null; - } - _resolveColor(color, theme) { - if (typeof color === 'string') { - return color; - } - let c = color ? theme.getColor(color.id) : null; - if (!c) { - return ''; - } - return c.toString(); - } - } - exports.ModelDecorationOverviewRulerOptions = ModelDecorationOverviewRulerOptions; - class ModelDecorationMinimapOptions extends DecorationOptions { - constructor(options) { - super(options); - this.position = options.position; - } - getColor(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; - } - invalidateCachedColor() { - this._resolvedColor = undefined; - } - _resolveColor(color, theme) { - if (typeof color === 'string') { - return color_1.Color.fromHex(color); - } - return theme.getColor(color.id); - } - } - exports.ModelDecorationMinimapOptions = ModelDecorationMinimapOptions; - class ModelDecorationInjectedTextOptions { - constructor(options) { - this.content = options.content || ''; - this.inlineClassName = options.inlineClassName || null; - this.inlineClassNameAffectsLetterSpacing = options.inlineClassNameAffectsLetterSpacing || false; - } - static from(options) { - if (options instanceof ModelDecorationInjectedTextOptions) { - return options; - } - return new ModelDecorationInjectedTextOptions(options); - } - } - exports.ModelDecorationInjectedTextOptions = ModelDecorationInjectedTextOptions; - class ModelDecorationOptions { - constructor(options) { - this.description = options.description; - this.stickiness = options.stickiness || 0 /* AlwaysGrowsWhenTypingAtEdges */; - this.zIndex = options.zIndex || 0; - this.className = options.className ? cleanClassName(options.className) : null; - this.hoverMessage = options.hoverMessage || null; - this.glyphMarginHoverMessage = options.glyphMarginHoverMessage || null; - 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.firstLineDecorationClassName = options.firstLineDecorationClassName ? cleanClassName(options.firstLineDecorationClassName) : 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; - this.after = options.after ? ModelDecorationInjectedTextOptions.from(options.after) : null; - this.before = options.before ? ModelDecorationInjectedTextOptions.from(options.before) : null; - } - static register(options) { - return new ModelDecorationOptions(options); - } - static createDynamic(options) { - return new ModelDecorationOptions(options); - } - } - exports.ModelDecorationOptions = ModelDecorationOptions; - ModelDecorationOptions.EMPTY = ModelDecorationOptions.register({ description: 'empty' }); - /** - * The order carefully matches the values of the enum. - */ - const TRACKED_RANGE_OPTIONS = [ - ModelDecorationOptions.register({ description: 'tracked-range-always-grows-when-typing-at-edges', stickiness: 0 /* AlwaysGrowsWhenTypingAtEdges */ }), - ModelDecorationOptions.register({ description: 'tracked-range-never-grows-when-typing-at-edges', stickiness: 1 /* NeverGrowsWhenTypingAtEdges */ }), - ModelDecorationOptions.register({ description: 'tracked-range-grows-only-when-typing-before', stickiness: 2 /* GrowsOnlyWhenTypingBefore */ }), - ModelDecorationOptions.register({ description: 'tracked-range-grows-only-when-typing-after', stickiness: 3 /* GrowsOnlyWhenTypingAfter */ }), - ]; - function _normalizeOptions(options) { - if (options instanceof ModelDecorationOptions) { - return options; - } - return ModelDecorationOptions.createDynamic(options); - } - class DidChangeDecorationsEmitter extends lifecycle_1.Disposable { - constructor(handleBeforeFire) { - super(); - this.handleBeforeFire = handleBeforeFire; - this._actual = this._register(new event_1.Emitter()); - this.event = this._actual.event; - this._affectedInjectedTextLines = null; - this._deferredCnt = 0; - this._shouldFire = false; - this._affectsMinimap = false; - this._affectsOverviewRuler = false; - } - beginDeferredEmit() { - this._deferredCnt++; - } - endDeferredEmit() { - var _a; - this._deferredCnt--; - if (this._deferredCnt === 0) { - if (this._shouldFire) { - this.handleBeforeFire(this._affectedInjectedTextLines); - const event = { - affectsMinimap: this._affectsMinimap, - affectsOverviewRuler: this._affectsOverviewRuler - }; - this._shouldFire = false; - this._affectsMinimap = false; - this._affectsOverviewRuler = false; - this._actual.fire(event); - } - (_a = this._affectedInjectedTextLines) === null || _a === void 0 ? void 0 : _a.clear(); - this._affectedInjectedTextLines = null; - } - } - recordLineAffectedByInjectedText(lineNumber) { - if (!this._affectedInjectedTextLines) { - this._affectedInjectedTextLines = new Set(); - } - this._affectedInjectedTextLines.add(lineNumber); - } - checkAffectedAndFire(options) { - if (!this._affectsMinimap) { - this._affectsMinimap = options.minimap && options.minimap.position ? true : false; - } - if (!this._affectsOverviewRuler) { - this._affectsOverviewRuler = options.overviewRuler && options.overviewRuler.color ? true : false; - } - this._shouldFire = true; - } - fire() { - this._affectsMinimap = true; - this._affectsOverviewRuler = true; - this._shouldFire = true; - } - } - exports.DidChangeDecorationsEmitter = DidChangeDecorationsEmitter; - //#endregion - class DidChangeContentEmitter extends lifecycle_1.Disposable { - constructor() { - super(); - /** - * 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; - } - beginDeferredEmit() { - this._deferredCnt++; - } - endDeferredEmit(resultingSelection = null) { - this._deferredCnt--; - if (this._deferredCnt === 0) { - if (this._deferredEvent !== null) { - this._deferredEvent.rawContentChangedEvent.resultingSelection = resultingSelection; - const e = this._deferredEvent; - this._deferredEvent = null; - this._fastEmitter.fire(e); - this._slowEmitter.fire(e); - } - } - } - fire(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); - } - } - 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*/,12/*vs/base/common/errors*/,8/*vs/base/common/strings*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,31/*vs/editor/common/model/textModel*/,45/*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 }); - exports.isQuote = exports.CursorColumns = exports.EditOperationResult = exports.CursorState = exports.PartialViewCursorState = exports.PartialModelCursorState = exports.CursorContext = exports.SingleCursorState = exports.CursorConfiguration = void 0; - const autoCloseAlways = () => true; - const autoCloseNever = () => false; - const autoCloseBeforeWhitespace = (chr) => (chr === ' ' || chr === '\t'); - class CursorConfiguration { - constructor(languageIdentifier, modelOptions, configuration) { - this._cursorMoveConfigurationBrand = undefined; - this._languageIdentifier = languageIdentifier; - const options = configuration.options; - const layoutInfo = options.get(129 /* layoutInfo */); - this.readOnly = options.get(79 /* readOnly */); - this.tabSize = modelOptions.tabSize; - this.indentSize = modelOptions.indentSize; - this.insertSpaces = modelOptions.insertSpaces; - this.stickyTabStops = options.get(103 /* stickyTabStops */); - this.lineHeight = options.get(57 /* lineHeight */); - this.pageSize = Math.max(1, Math.floor(layoutInfo.height / this.lineHeight) - 2); - this.useTabStops = options.get(114 /* useTabStops */); - this.wordSeparators = options.get(115 /* wordSeparators */); - this.emptySelectionClipboard = options.get(30 /* emptySelectionClipboard */); - this.copyWithSyntaxHighlighting = options.get(19 /* copyWithSyntaxHighlighting */); - this.multiCursorMergeOverlapping = options.get(67 /* multiCursorMergeOverlapping */); - this.multiCursorPaste = options.get(69 /* multiCursorPaste */); - this.autoClosingBrackets = options.get(5 /* autoClosingBrackets */); - this.autoClosingQuotes = options.get(8 /* autoClosingQuotes */); - this.autoClosingDelete = options.get(6 /* autoClosingDelete */); - this.autoClosingOvertype = options.get(7 /* autoClosingOvertype */); - this.autoSurround = options.get(11 /* autoSurround */); - this.autoIndent = options.get(9 /* autoIndent */); - this.surroundingPairs = {}; - this._electricChars = null; - this.shouldAutoCloseBefore = { - quote: CursorConfiguration._getShouldAutoClose(languageIdentifier, this.autoClosingQuotes), - bracket: CursorConfiguration._getShouldAutoClose(languageIdentifier, this.autoClosingBrackets) - }; - this.autoClosingPairs = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getAutoClosingPairs(languageIdentifier.id); - let surroundingPairs = CursorConfiguration._getSurroundingPairs(languageIdentifier); - if (surroundingPairs) { - for (const pair of surroundingPairs) { - this.surroundingPairs[pair.open] = pair.close; - } - } - } - static shouldRecreate(e) { - return (e.hasChanged(129 /* layoutInfo */) - || e.hasChanged(115 /* wordSeparators */) - || e.hasChanged(30 /* emptySelectionClipboard */) - || e.hasChanged(67 /* multiCursorMergeOverlapping */) - || e.hasChanged(69 /* multiCursorPaste */) - || e.hasChanged(5 /* autoClosingBrackets */) - || e.hasChanged(8 /* autoClosingQuotes */) - || e.hasChanged(6 /* autoClosingDelete */) - || e.hasChanged(7 /* autoClosingOvertype */) - || e.hasChanged(11 /* autoSurround */) - || e.hasChanged(114 /* useTabStops */) - || e.hasChanged(57 /* lineHeight */) - || e.hasChanged(79 /* readOnly */)); - } - get electricChars() { - if (!this._electricChars) { - this._electricChars = {}; - let electricChars = CursorConfiguration._getElectricCharacters(this._languageIdentifier); - if (electricChars) { - for (const char of electricChars) { - this._electricChars[char] = true; - } - } - } - return this._electricChars; - } - normalizeIndentation(str) { - return textModel_1.TextModel.normalizeIndentation(str, this.indentSize, this.insertSpaces); - } - static _getElectricCharacters(languageIdentifier) { - try { - return languageConfigurationRegistry_1.LanguageConfigurationRegistry.getElectricCharacters(languageIdentifier.id); - } - catch (e) { - (0, errors_1.onUnexpectedError)(e); - return null; - } - } - static _getShouldAutoClose(languageIdentifier, autoCloseConfig) { - switch (autoCloseConfig) { - case 'beforeWhitespace': - return autoCloseBeforeWhitespace; - case 'languageDefined': - return CursorConfiguration._getLanguageDefinedShouldAutoClose(languageIdentifier); - case 'always': - return autoCloseAlways; - case 'never': - return autoCloseNever; - } - } - static _getLanguageDefinedShouldAutoClose(languageIdentifier) { - try { - const autoCloseBeforeSet = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getAutoCloseBeforeSet(languageIdentifier.id); - return c => autoCloseBeforeSet.indexOf(c) !== -1; - } - catch (e) { - (0, errors_1.onUnexpectedError)(e); - return autoCloseNever; - } - } - static _getSurroundingPairs(languageIdentifier) { - try { - return languageConfigurationRegistry_1.LanguageConfigurationRegistry.getSurroundingPairs(languageIdentifier.id); - } - catch (e) { - (0, errors_1.onUnexpectedError)(e); - return null; - } - } - } - exports.CursorConfiguration = CursorConfiguration; - /** - * Represents the cursor state on either the model or on the view model. - */ - class SingleCursorState { - constructor(selectionStart, selectionStartLeftoverVisibleColumns, position, leftoverVisibleColumns) { - this._singleCursorStateBrand = undefined; - this.selectionStart = selectionStart; - this.selectionStartLeftoverVisibleColumns = selectionStartLeftoverVisibleColumns; - this.position = position; - this.leftoverVisibleColumns = leftoverVisibleColumns; - this.selection = SingleCursorState._computeSelection(this.selectionStart, this.position); - } - equals(other) { - return (this.selectionStartLeftoverVisibleColumns === other.selectionStartLeftoverVisibleColumns - && this.leftoverVisibleColumns === other.leftoverVisibleColumns - && this.position.equals(other.position) - && this.selectionStart.equalsRange(other.selectionStart)); - } - hasSelection() { - return (!this.selection.isEmpty() || !this.selectionStart.isEmpty()); - } - move(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); - } - } - static _computeSelection(selectionStart, position) { - let 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); - } - } - exports.SingleCursorState = SingleCursorState; - class CursorContext { - constructor(model, viewModel, coordinatesConverter, cursorConfig) { - this._cursorContextBrand = undefined; - this.model = model; - this.viewModel = viewModel; - this.coordinatesConverter = coordinatesConverter; - this.cursorConfig = cursorConfig; - } - } - exports.CursorContext = CursorContext; - class PartialModelCursorState { - constructor(modelState) { - this.modelState = modelState; - this.viewState = null; - } - } - exports.PartialModelCursorState = PartialModelCursorState; - class PartialViewCursorState { - constructor(viewState) { - this.modelState = null; - this.viewState = viewState; - } - } - exports.PartialViewCursorState = PartialViewCursorState; - class CursorState { - constructor(modelState, viewState) { - this._cursorStateBrand = undefined; - this.modelState = modelState; - this.viewState = viewState; - } - static fromModelState(modelState) { - return new PartialModelCursorState(modelState); - } - static fromViewState(viewState) { - return new PartialViewCursorState(viewState); - } - static fromModelSelection(modelSelection) { - const selectionStartLineNumber = modelSelection.selectionStartLineNumber; - const selectionStartColumn = modelSelection.selectionStartColumn; - const positionLineNumber = modelSelection.positionLineNumber; - const positionColumn = modelSelection.positionColumn; - const modelState = new SingleCursorState(new range_1.Range(selectionStartLineNumber, selectionStartColumn, selectionStartLineNumber, selectionStartColumn), 0, new position_1.Position(positionLineNumber, positionColumn), 0); - return CursorState.fromModelState(modelState); - } - static fromModelSelections(modelSelections) { - let states = []; - for (let i = 0, len = modelSelections.length; i < len; i++) { - states[i] = this.fromModelSelection(modelSelections[i]); - } - return states; - } - equals(other) { - return (this.viewState.equals(other.viewState) && this.modelState.equals(other.modelState)); - } - } - exports.CursorState = CursorState; - class EditOperationResult { - constructor(type, commands, opts) { - this._editOperationResultBrand = undefined; - this.type = type; - this.commands = commands; - this.shouldPushStackElementBefore = opts.shouldPushStackElementBefore; - this.shouldPushStackElementAfter = opts.shouldPushStackElementAfter; - } - } - exports.EditOperationResult = EditOperationResult; - /** - * Common operations that work and make sense both on the model and on the view model. - */ - class CursorColumns { - static visibleColumnFromColumn(lineContent, column, tabSize) { - const lineContentLength = lineContent.length; - const endOffset = column - 1 < lineContentLength ? column - 1 : lineContentLength; - let result = 0; - let i = 0; - while (i < endOffset) { - const 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 { - let graphemeBreakType = strings.getGraphemeBreakType(codePoint); - while (i < endOffset) { - const nextCodePoint = strings.getNextCodePoint(lineContent, endOffset, i); - const 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; - } - /** - * Returns an array that maps one based columns to one based visible columns. The entry at position 0 is -1. - */ - static visibleColumnsByColumns(lineContent, tabSize) { - const endOffset = lineContent.length; - let result = new Array(); - result.push(-1); - let pos = 0; - let i = 0; - while (i < endOffset) { - const codePoint = strings.getNextCodePoint(lineContent, endOffset, i); - i += (codePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1); - result.push(pos); - if (codePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */) { - result.push(pos); - } - if (codePoint === 9 /* Tab */) { - pos = CursorColumns.nextRenderTabStop(pos, tabSize); - } - else { - let graphemeBreakType = strings.getGraphemeBreakType(codePoint); - while (i < endOffset) { - const nextCodePoint = strings.getNextCodePoint(lineContent, endOffset, i); - const nextGraphemeBreakType = strings.getGraphemeBreakType(nextCodePoint); - if (strings.breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) { - break; - } - i += (nextCodePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1); - result.push(pos); - if (codePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */) { - result.push(pos); - } - graphemeBreakType = nextGraphemeBreakType; - } - if (strings.isFullWidthCharacter(codePoint) || strings.isEmojiImprecise(codePoint)) { - pos = pos + 2; - } - else { - pos = pos + 1; - } - } - } - result.push(pos); - return result; - } - static visibleColumnFromColumn2(config, model, position) { - return this.visibleColumnFromColumn(model.getLineContent(position.lineNumber), position.column, config.tabSize); - } - static columnFromVisibleColumn(lineContent, visibleColumn, tabSize) { - if (visibleColumn <= 0) { - return 1; - } - const lineLength = lineContent.length; - let beforeVisibleColumn = 0; - let beforeColumn = 1; - let i = 0; - while (i < lineLength) { - const codePoint = strings.getNextCodePoint(lineContent, lineLength, i); - i += (codePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1); - let afterVisibleColumn; - if (codePoint === 9 /* Tab */) { - afterVisibleColumn = CursorColumns.nextRenderTabStop(beforeVisibleColumn, tabSize); - } - else { - let graphemeBreakType = strings.getGraphemeBreakType(codePoint); - while (i < lineLength) { - const nextCodePoint = strings.getNextCodePoint(lineContent, lineLength, i); - const 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; - } - } - const afterColumn = i + 1; - if (afterVisibleColumn >= visibleColumn) { - const beforeDelta = visibleColumn - beforeVisibleColumn; - const afterDelta = afterVisibleColumn - visibleColumn; - if (afterDelta < beforeDelta) { - return afterColumn; - } - else { - return beforeColumn; - } - } - beforeVisibleColumn = afterVisibleColumn; - beforeColumn = afterColumn; - } - // walked the entire string - return lineLength + 1; - } - static columnFromVisibleColumn2(config, model, lineNumber, visibleColumn) { - let result = this.columnFromVisibleColumn(model.getLineContent(lineNumber), visibleColumn, config.tabSize); - let minColumn = model.getLineMinColumn(lineNumber); - if (result < minColumn) { - return minColumn; - } - let 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) - */ - static nextRenderTabStop(visibleColumn, tabSize) { - return visibleColumn + tabSize - visibleColumn % tabSize; - } - /** - * ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns) - */ - static nextIndentTabStop(visibleColumn, indentSize) { - return visibleColumn + indentSize - visibleColumn % indentSize; - } - /** - * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns) - */ - static prevRenderTabStop(column, tabSize) { - return Math.max(0, column - 1 - (column - 1) % tabSize); - } - /** - * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns) - */ - static prevIndentTabStop(column, indentSize) { - return Math.max(0, column - 1 - (column - 1) % indentSize); - } - } - 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[184/*vs/editor/common/commands/shiftCommand*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,40/*vs/editor/common/controller/cursorCommon*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,45/*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 }); - exports.ShiftCommand = exports.cachedStringRepeat = void 0; - const repeatCache = Object.create(null); - function cachedStringRepeat(str, count) { - if (count <= 0) { - return ''; - } - if (!repeatCache[str]) { - repeatCache[str] = ['', str]; - } - const cache = repeatCache[str]; - for (let i = cache.length; i <= count; i++) { - cache[i] = cache[i - 1] + str; - } - return cache[count]; - } - exports.cachedStringRepeat = cachedStringRepeat; - class ShiftCommand { - constructor(range, opts) { - this._opts = opts; - this._selection = range; - this._selectionId = null; - this._useLastEditRangeForCursorEndPosition = false; - this._selectionStartColumnStaysPut = false; - } - static unshiftIndent(line, column, tabSize, indentSize, insertSpaces) { - // Determine the visible column where the content starts - const contentStartVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(line, column, tabSize); - if (insertSpaces) { - const indent = cachedStringRepeat(' ', indentSize); - const desiredTabStop = cursorCommon_1.CursorColumns.prevIndentTabStop(contentStartVisibleColumn, indentSize); - const indentCount = desiredTabStop / indentSize; // will be an integer - return cachedStringRepeat(indent, indentCount); - } - else { - const indent = '\t'; - const desiredTabStop = cursorCommon_1.CursorColumns.prevRenderTabStop(contentStartVisibleColumn, tabSize); - const indentCount = desiredTabStop / tabSize; // will be an integer - return cachedStringRepeat(indent, indentCount); - } - } - static shiftIndent(line, column, tabSize, indentSize, insertSpaces) { - // Determine the visible column where the content starts - const contentStartVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(line, column, tabSize); - if (insertSpaces) { - const indent = cachedStringRepeat(' ', indentSize); - const desiredTabStop = cursorCommon_1.CursorColumns.nextIndentTabStop(contentStartVisibleColumn, indentSize); - const indentCount = desiredTabStop / indentSize; // will be an integer - return cachedStringRepeat(indent, indentCount); - } - else { - const indent = '\t'; - const desiredTabStop = cursorCommon_1.CursorColumns.nextRenderTabStop(contentStartVisibleColumn, tabSize); - const indentCount = desiredTabStop / tabSize; // will be an integer - return cachedStringRepeat(indent, indentCount); - } - } - _addEditOperation(builder, range, text) { - if (this._useLastEditRangeForCursorEndPosition) { - builder.addTrackedEditOperation(range, text); - } - else { - builder.addEditOperation(range, text); - } - } - getEditOperations(model, builder) { - const startLine = this._selection.startLineNumber; - let endLine = this._selection.endLineNumber; - if (this._selection.endColumn === 1 && startLine !== endLine) { - endLine = endLine - 1; - } - const { tabSize, indentSize, insertSpaces } = this._opts; - const shouldIndentEmptyLines = (startLine === endLine); - if (this._opts.useTabStops) { - // if indenting or outdenting on a whitespace only line - if (this._selection.isEmpty()) { - if (/^\s*$/.test(model.getLineContent(startLine))) { - this._useLastEditRangeForCursorEndPosition = true; - } - } - // keep track of previous line's "miss-alignment" - let previousLineExtraSpaces = 0, extraSpaces = 0; - for (let lineNumber = startLine; lineNumber <= endLine; lineNumber++, previousLineExtraSpaces = extraSpaces) { - extraSpaces = 0; - let lineText = model.getLineContent(lineNumber); - let 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) { - let 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)) { - let 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 (let 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 (let 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; - } - let desiredIndent; - 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 { - // if indenting or outdenting on a whitespace only line - if (!this._opts.isUnshift && this._selection.isEmpty() && model.getLineLength(startLine) === 0) { - this._useLastEditRangeForCursorEndPosition = true; - } - const oneIndent = (insertSpaces ? cachedStringRepeat(' ', indentSize) : '\t'); - for (let lineNumber = startLine; lineNumber <= endLine; lineNumber++) { - const lineText = model.getLineContent(lineNumber); - let 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 (let i = 0; i < indentationEndIndex; i++) { - const 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); - } - computeCursorState(model, helper) { - if (this._useLastEditRangeForCursorEndPosition) { - let lastOp = helper.getInverseEditOperations()[0]; - return new selection_1.Selection(lastOp.range.endLineNumber, lastOp.range.endColumn, lastOp.range.endLineNumber, lastOp.range.endColumn); - } - const result = helper.getTrackedSelection(this._selectionId); - if (this._selectionStartColumnStaysPut) { - // The selection start should not move - let initialStartColumn = this._selection.startColumn; - let 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; - } - } - 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[243/*vs/editor/common/controller/cursorAtomicMoveOperations*/], __M([0/*require*/,1/*exports*/,40/*vs/editor/common/controller/cursorCommon*/]), function (require, exports, cursorCommon_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.AtomicTabMoveOperations = void 0; - class AtomicTabMoveOperations { - /** - * Get the visible column at the position. If we get to a non-whitespace character first - * or past the end of string then return -1. - * - * **Note** `position` and the return value are 0-based. - */ - static whitespaceVisibleColumn(lineContent, position, tabSize) { - const lineLength = lineContent.length; - let visibleColumn = 0; - let prevTabStopPosition = -1; - let prevTabStopVisibleColumn = -1; - for (let i = 0; i < lineLength; i++) { - if (i === position) { - return [prevTabStopPosition, prevTabStopVisibleColumn, visibleColumn]; - } - if (visibleColumn % tabSize === 0) { - prevTabStopPosition = i; - prevTabStopVisibleColumn = visibleColumn; - } - const chCode = lineContent.charCodeAt(i); - switch (chCode) { - case 32 /* Space */: - visibleColumn += 1; - break; - case 9 /* Tab */: - // Skip to the next multiple of tabSize. - visibleColumn = cursorCommon_1.CursorColumns.nextRenderTabStop(visibleColumn, tabSize); - break; - default: - return [-1, -1, -1]; - } - } - if (position === lineLength) { - return [prevTabStopPosition, prevTabStopVisibleColumn, visibleColumn]; - } - return [-1, -1, -1]; - } - /** - * Return the position that should result from a move left, right or to the - * nearest tab, if atomic tabs are enabled. Left and right are used for the - * arrow key movements, nearest is used for mouse selection. It returns - * -1 if atomic tabs are not relevant and you should fall back to normal - * behaviour. - * - * **Note**: `position` and the return value are 0-based. - */ - static atomicPosition(lineContent, position, tabSize, direction) { - const lineLength = lineContent.length; - // Get the 0-based visible column corresponding to the position, or return - // -1 if it is not in the initial whitespace. - const [prevTabStopPosition, prevTabStopVisibleColumn, visibleColumn] = AtomicTabMoveOperations.whitespaceVisibleColumn(lineContent, position, tabSize); - if (visibleColumn === -1) { - return -1; - } - // Is the output left or right of the current position. The case for nearest - // where it is the same as the current position is handled in the switch. - let left; - switch (direction) { - case 0 /* Left */: - left = true; - break; - case 1 /* Right */: - left = false; - break; - case 2 /* Nearest */: - // The code below assumes the output position is either left or right - // of the input position. If it is the same, return immediately. - if (visibleColumn % tabSize === 0) { - return position; - } - // Go to the nearest indentation. - left = visibleColumn % tabSize <= (tabSize / 2); - break; - } - // If going left, we can just use the info about the last tab stop position and - // last tab stop visible column that we computed in the first walk over the whitespace. - if (left) { - if (prevTabStopPosition === -1) { - return -1; - } - // If the direction is left, we need to keep scanning right to ensure - // that targetVisibleColumn + tabSize is before non-whitespace. - // This is so that when we press left at the end of a partial - // indentation it only goes one character. For example ' foo' with - // tabSize 4, should jump from position 6 to position 5, not 4. - let currentVisibleColumn = prevTabStopVisibleColumn; - for (let i = prevTabStopPosition; i < lineLength; ++i) { - if (currentVisibleColumn === prevTabStopVisibleColumn + tabSize) { - // It is a full indentation. - return prevTabStopPosition; - } - const chCode = lineContent.charCodeAt(i); - switch (chCode) { - case 32 /* Space */: - currentVisibleColumn += 1; - break; - case 9 /* Tab */: - currentVisibleColumn = cursorCommon_1.CursorColumns.nextRenderTabStop(currentVisibleColumn, tabSize); - break; - default: - return -1; - } - } - if (currentVisibleColumn === prevTabStopVisibleColumn + tabSize) { - return prevTabStopPosition; - } - // It must have been a partial indentation. - return -1; - } - // We are going right. - const targetVisibleColumn = cursorCommon_1.CursorColumns.nextRenderTabStop(visibleColumn, tabSize); - // We can just continue from where whitespaceVisibleColumn got to. - let currentVisibleColumn = visibleColumn; - for (let i = position; i < lineLength; i++) { - if (currentVisibleColumn === targetVisibleColumn) { - return i; - } - const chCode = lineContent.charCodeAt(i); - switch (chCode) { - case 32 /* Space */: - currentVisibleColumn += 1; - break; - case 9 /* Tab */: - currentVisibleColumn = cursorCommon_1.CursorColumns.nextRenderTabStop(currentVisibleColumn, tabSize); - break; - default: - return -1; - } - } - // This condition handles when the target column is at the end of the line. - if (currentVisibleColumn === targetVisibleColumn) { - return lineLength; - } - return -1; - } - } - exports.AtomicTabMoveOperations = AtomicTabMoveOperations; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[550/*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 }); - exports.ColumnSelection = void 0; - class ColumnSelection { - static columnSelect(config, model, fromLineNumber, fromVisibleColumn, toLineNumber, toVisibleColumn) { - let lineCount = Math.abs(toLineNumber - fromLineNumber) + 1; - let reversed = (fromLineNumber > toLineNumber); - let isRTL = (fromVisibleColumn > toVisibleColumn); - let isLTR = (fromVisibleColumn < toVisibleColumn); - let result = []; - // console.log(`fromVisibleColumn: ${fromVisibleColumn}, toVisibleColumn: ${toVisibleColumn}`); - for (let i = 0; i < lineCount; i++) { - let lineNumber = fromLineNumber + (reversed ? -i : i); - let startColumn = cursorCommon_1.CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, fromVisibleColumn); - let endColumn = cursorCommon_1.CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, toVisibleColumn); - let visibleStartColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, new position_1.Position(lineNumber, startColumn)); - let 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 (let i = 0; i < lineCount; i++) { - const lineNumber = fromLineNumber + (reversed ? -i : i); - const 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 - }; - } - static columnSelectLeft(config, model, prevColumnSelectData) { - let toViewVisualColumn = prevColumnSelectData.toViewVisualColumn; - if (toViewVisualColumn > 0) { - toViewVisualColumn--; - } - return ColumnSelection.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, prevColumnSelectData.toViewLineNumber, toViewVisualColumn); - } - static columnSelectRight(config, model, prevColumnSelectData) { - let maxVisualViewColumn = 0; - const minViewLineNumber = Math.min(prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.toViewLineNumber); - const maxViewLineNumber = Math.max(prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.toViewLineNumber); - for (let lineNumber = minViewLineNumber; lineNumber <= maxViewLineNumber; lineNumber++) { - const lineMaxViewColumn = model.getLineMaxColumn(lineNumber); - const lineMaxVisualViewColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, new position_1.Position(lineNumber, lineMaxViewColumn)); - maxVisualViewColumn = Math.max(maxVisualViewColumn, lineMaxVisualViewColumn); - } - let toViewVisualColumn = prevColumnSelectData.toViewVisualColumn; - if (toViewVisualColumn < maxVisualViewColumn) { - toViewVisualColumn++; - } - return this.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, prevColumnSelectData.toViewLineNumber, toViewVisualColumn); - } - static columnSelectUp(config, model, prevColumnSelectData, isPaged) { - const linesCount = isPaged ? config.pageSize : 1; - const toViewLineNumber = Math.max(1, prevColumnSelectData.toViewLineNumber - linesCount); - return this.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, toViewLineNumber, prevColumnSelectData.toViewVisualColumn); - } - static columnSelectDown(config, model, prevColumnSelectData, isPaged) { - const linesCount = isPaged ? config.pageSize : 1; - const toViewLineNumber = Math.min(model.getLineCount(), prevColumnSelectData.toViewLineNumber + linesCount); - return this.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, toViewLineNumber, prevColumnSelectData.toViewVisualColumn); - } - } - 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[185/*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*/,8/*vs/base/common/strings*/,243/*vs/editor/common/controller/cursorAtomicMoveOperations*/]), function (require, exports, cursorCommon_1, position_1, range_1, strings, cursorAtomicMoveOperations_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MoveOperations = exports.CursorPosition = void 0; - class CursorPosition { - constructor(lineNumber, column, leftoverVisibleColumns) { - this._cursorPositionBrand = undefined; - this.lineNumber = lineNumber; - this.column = column; - this.leftoverVisibleColumns = leftoverVisibleColumns; - } - } - exports.CursorPosition = CursorPosition; - class MoveOperations { - static leftPosition(model, position) { - if (position.column > model.getLineMinColumn(position.lineNumber)) { - return position.delta(undefined, -strings.prevCharLength(model.getLineContent(position.lineNumber), position.column - 1)); - } - else if (position.lineNumber > 1) { - const newLineNumber = position.lineNumber - 1; - return new position_1.Position(newLineNumber, model.getLineMaxColumn(newLineNumber)); - } - else { - return position; - } - } - static leftPositionAtomicSoftTabs(model, position, tabSize) { - if (position.column <= model.getLineIndentColumn(position.lineNumber)) { - const minColumn = model.getLineMinColumn(position.lineNumber); - const lineContent = model.getLineContent(position.lineNumber); - const newPosition = cursorAtomicMoveOperations_1.AtomicTabMoveOperations.atomicPosition(lineContent, position.column - 1, tabSize, 0 /* Left */); - if (newPosition !== -1 && newPosition + 1 >= minColumn) { - return new position_1.Position(position.lineNumber, newPosition + 1); - } - } - return this.leftPosition(model, position); - } - static left(config, model, position) { - const pos = config.stickyTabStops - ? MoveOperations.leftPositionAtomicSoftTabs(model, position, config.tabSize) - : MoveOperations.leftPosition(model, position); - return new CursorPosition(pos.lineNumber, pos.column, 0); - } - /** - * @param noOfColumns Must be either `1` - * or `Math.round(viewModel.getLineContent(viewLineNumber).length / 2)` (for half lines). - */ - static moveLeft(config, model, cursor, inSelectionMode, noOfColumns) { - let lineNumber, column; - if (cursor.hasSelection() && !inSelectionMode) { - // If the user has a selection and does not want to extend it, - // put the cursor at the beginning of the selection. - lineNumber = cursor.selection.startLineNumber; - column = cursor.selection.startColumn; - } - else { - // This has no effect if noOfColumns === 1. - // It is ok to do so in the half-line scenario. - const pos = cursor.position.delta(undefined, -(noOfColumns - 1)); - // We clip the position before normalization, as normalization is not defined - // for possibly negative columns. - const normalizedPos = model.normalizePosition(MoveOperations.clipPositionColumn(pos, model), 0 /* Left */); - const p = MoveOperations.left(config, model, normalizedPos); - lineNumber = p.lineNumber; - column = p.column; - } - return cursor.move(inSelectionMode, lineNumber, column, 0); - } - /** - * Adjusts the column so that it is within min/max of the line. - */ - static clipPositionColumn(position, model) { - return new position_1.Position(position.lineNumber, MoveOperations.clipRange(position.column, model.getLineMinColumn(position.lineNumber), model.getLineMaxColumn(position.lineNumber))); - } - static clipRange(value, min, max) { - if (value < min) { - return min; - } - if (value > max) { - return max; - } - return value; - } - static rightPosition(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); - } - static rightPositionAtomicSoftTabs(model, lineNumber, column, tabSize, indentSize) { - if (column < model.getLineIndentColumn(lineNumber)) { - const lineContent = model.getLineContent(lineNumber); - const newPosition = cursorAtomicMoveOperations_1.AtomicTabMoveOperations.atomicPosition(lineContent, column - 1, tabSize, 1 /* Right */); - if (newPosition !== -1) { - return new position_1.Position(lineNumber, newPosition + 1); - } - } - return this.rightPosition(model, lineNumber, column); - } - static right(config, model, position) { - const pos = config.stickyTabStops - ? MoveOperations.rightPositionAtomicSoftTabs(model, position.lineNumber, position.column, config.tabSize, config.indentSize) - : MoveOperations.rightPosition(model, position.lineNumber, position.column); - return new CursorPosition(pos.lineNumber, pos.column, 0); - } - static moveRight(config, model, cursor, inSelectionMode, noOfColumns) { - let 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 { - const pos = cursor.position.delta(undefined, noOfColumns - 1); - const normalizedPos = model.normalizePosition(MoveOperations.clipPositionColumn(pos, model), 1 /* Right */); - const r = MoveOperations.right(config, model, normalizedPos); - lineNumber = r.lineNumber; - column = r.column; - } - return cursor.move(inSelectionMode, lineNumber, column, 0); - } - static down(config, model, lineNumber, column, leftoverVisibleColumns, count, allowMoveOnLastLine) { - const currentVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize) + leftoverVisibleColumns; - const lineCount = model.getLineCount(); - const wasOnLastPosition = (lineNumber === lineCount && column === model.getLineMaxColumn(lineNumber)); - lineNumber = lineNumber + count; - 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); - } - if (wasOnLastPosition) { - leftoverVisibleColumns = 0; - } - else { - leftoverVisibleColumns = currentVisibleColumn - cursorCommon_1.CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize); - } - return new CursorPosition(lineNumber, column, leftoverVisibleColumns); - } - static moveDown(config, model, cursor, inSelectionMode, linesCount) { - let 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; - } - let r = MoveOperations.down(config, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true); - return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns); - } - static translateDown(config, model, cursor) { - let selection = cursor.selection; - let selectionStart = MoveOperations.down(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false); - let 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); - } - static up(config, model, lineNumber, column, leftoverVisibleColumns, count, allowMoveOnFirstLine) { - const currentVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize) + leftoverVisibleColumns; - const wasOnFirstPosition = (lineNumber === 1 && column === 1); - 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); - } - if (wasOnFirstPosition) { - leftoverVisibleColumns = 0; - } - else { - leftoverVisibleColumns = currentVisibleColumn - cursorCommon_1.CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize); - } - return new CursorPosition(lineNumber, column, leftoverVisibleColumns); - } - static moveUp(config, model, cursor, inSelectionMode, linesCount) { - let 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; - } - let r = MoveOperations.up(config, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true); - return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns); - } - static translateUp(config, model, cursor) { - let selection = cursor.selection; - let selectionStart = MoveOperations.up(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false); - let 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); - } - static _isBlankLine(model, lineNumber) { - if (model.getLineFirstNonWhitespaceColumn(lineNumber) === 0) { - // empty or contains only whitespace - return true; - } - return false; - } - static moveToPrevBlankLine(config, model, cursor, inSelectionMode) { - let lineNumber = cursor.position.lineNumber; - // If our current line is blank, move to the previous non-blank line - while (lineNumber > 1 && this._isBlankLine(model, lineNumber)) { - lineNumber--; - } - // Find the previous blank line - while (lineNumber > 1 && !this._isBlankLine(model, lineNumber)) { - lineNumber--; - } - return cursor.move(inSelectionMode, lineNumber, model.getLineMinColumn(lineNumber), 0); - } - static moveToNextBlankLine(config, model, cursor, inSelectionMode) { - const lineCount = model.getLineCount(); - let lineNumber = cursor.position.lineNumber; - // If our current line is blank, move to the next non-blank line - while (lineNumber < lineCount && this._isBlankLine(model, lineNumber)) { - lineNumber++; - } - // Find the next blank line - while (lineNumber < lineCount && !this._isBlankLine(model, lineNumber)) { - lineNumber++; - } - return cursor.move(inSelectionMode, lineNumber, model.getLineMinColumn(lineNumber), 0); - } - static moveToBeginningOfLine(config, model, cursor, inSelectionMode) { - let lineNumber = cursor.position.lineNumber; - let minColumn = model.getLineMinColumn(lineNumber); - let firstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(lineNumber) || minColumn; - let column; - let relevantColumnNumber = cursor.position.column; - if (relevantColumnNumber === firstNonBlankColumn) { - column = minColumn; - } - else { - column = firstNonBlankColumn; - } - return cursor.move(inSelectionMode, lineNumber, column, 0); - } - static moveToEndOfLine(config, model, cursor, inSelectionMode, sticky) { - let lineNumber = cursor.position.lineNumber; - let maxColumn = model.getLineMaxColumn(lineNumber); - return cursor.move(inSelectionMode, lineNumber, maxColumn, sticky ? 1073741824 /* MAX_SAFE_SMALL_INTEGER */ - maxColumn : 0); - } - static moveToBeginningOfBuffer(config, model, cursor, inSelectionMode) { - return cursor.move(inSelectionMode, 1, 1, 0); - } - static moveToEndOfBuffer(config, model, cursor, inSelectionMode) { - let lastLineNumber = model.getLineCount(); - let lastColumn = model.getLineMaxColumn(lastLineNumber); - return cursor.move(inSelectionMode, lastLineNumber, lastColumn, 0); - } - } - 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[186/*vs/editor/common/controller/cursorDeleteOperations*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,95/*vs/editor/common/commands/replaceCommand*/,40/*vs/editor/common/controller/cursorCommon*/,185/*vs/editor/common/controller/cursorMoveOperations*/,3/*vs/editor/common/core/range*/,13/*vs/editor/common/core/position*/]), function (require, exports, strings, replaceCommand_1, cursorCommon_1, cursorMoveOperations_1, range_1, position_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DeleteOperations = void 0; - class DeleteOperations { - static deleteRight(prevEditOperationType, config, model, selections) { - let commands = []; - let shouldPushStackElementBefore = (prevEditOperationType !== 3 /* DeletingRight */); - for (let i = 0, len = selections.length; i < len; i++) { - const selection = selections[i]; - let deleteSelection = selection; - if (deleteSelection.isEmpty()) { - let position = selection.getPosition(); - let rightOfPosition = cursorMoveOperations_1.MoveOperations.right(config, model, position); - 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]; - } - static isAutoClosingPairDelete(autoClosingDelete, autoClosingBrackets, autoClosingQuotes, autoClosingPairsOpen, model, selections, autoClosedCharacters) { - if (autoClosingBrackets === 'never' && autoClosingQuotes === 'never') { - return false; - } - if (autoClosingDelete === 'never') { - return false; - } - for (let i = 0, len = selections.length; i < len; i++) { - const selection = selections[i]; - const position = selection.getPosition(); - if (!selection.isEmpty()) { - return false; - } - const lineText = model.getLineContent(position.lineNumber); - if (position.column < 2 || position.column >= lineText.length + 1) { - return false; - } - const character = lineText.charAt(position.column - 2); - const autoClosingPairCandidates = autoClosingPairsOpen.get(character); - if (!autoClosingPairCandidates) { - return false; - } - if ((0, cursorCommon_1.isQuote)(character)) { - if (autoClosingQuotes === 'never') { - return false; - } - } - else { - if (autoClosingBrackets === 'never') { - return false; - } - } - const afterCharacter = lineText.charAt(position.column - 1); - let foundAutoClosingPair = false; - for (const autoClosingPairCandidate of autoClosingPairCandidates) { - if (autoClosingPairCandidate.open === character && autoClosingPairCandidate.close === afterCharacter) { - foundAutoClosingPair = true; - } - } - if (!foundAutoClosingPair) { - return false; - } - // Must delete the pair only if it was automatically inserted by the editor - if (autoClosingDelete === 'auto') { - let found = false; - for (let j = 0, lenJ = autoClosedCharacters.length; j < lenJ; j++) { - const autoClosedCharacter = autoClosedCharacters[j]; - if (position.lineNumber === autoClosedCharacter.startLineNumber && position.column === autoClosedCharacter.startColumn) { - found = true; - break; - } - } - if (!found) { - return false; - } - } - } - return true; - } - static _runAutoClosingPairDelete(config, model, selections) { - let commands = []; - for (let i = 0, len = selections.length; i < len; i++) { - const position = selections[i].getPosition(); - const 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]; - } - static deleteLeft(prevEditOperationType, config, model, selections, autoClosedCharacters) { - if (this.isAutoClosingPairDelete(config.autoClosingDelete, config.autoClosingBrackets, config.autoClosingQuotes, config.autoClosingPairs.autoClosingPairsOpenByEnd, model, selections, autoClosedCharacters)) { - return this._runAutoClosingPairDelete(config, model, selections); - } - const commands = []; - let shouldPushStackElementBefore = (prevEditOperationType !== 2 /* DeletingLeft */); - for (let i = 0, len = selections.length; i < len; i++) { - let deleteRange = DeleteOperations.getDeleteRange(selections[i], model, config); - // Ignore empty delete ranges, as they have no effect - // They happen if the cursor is at the beginning of the file. - if (deleteRange.isEmpty()) { - commands[i] = null; - continue; - } - if (deleteRange.startLineNumber !== deleteRange.endLineNumber) { - shouldPushStackElementBefore = true; - } - commands[i] = new replaceCommand_1.ReplaceCommand(deleteRange, ''); - } - return [shouldPushStackElementBefore, commands]; - } - static getDeleteRange(selection, model, config) { - if (!selection.isEmpty()) { - return selection; - } - const position = selection.getPosition(); - // Unintend when using tab stops and cursor is within indentation - if (config.useTabStops && position.column > 1) { - const lineContent = model.getLineContent(position.lineNumber); - const firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent); - const lastIndentationColumn = (firstNonWhitespaceIndex === -1 - ? /* entire string is whitespace */ lineContent.length + 1 - : firstNonWhitespaceIndex + 1); - if (position.column <= lastIndentationColumn) { - const fromVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, position); - const toVisibleColumn = cursorCommon_1.CursorColumns.prevIndentTabStop(fromVisibleColumn, config.indentSize); - const toColumn = cursorCommon_1.CursorColumns.columnFromVisibleColumn2(config, model, position.lineNumber, toVisibleColumn); - return new range_1.Range(position.lineNumber, toColumn, position.lineNumber, position.column); - } - } - return range_1.Range.fromPositions(DeleteOperations.getPositionAfterDeleteLeft(position, model), position); - } - static getPositionAfterDeleteLeft(position, model) { - if (position.column > 1) { - // Convert 1-based columns to 0-based offsets and back. - const idx = strings.getLeftDeleteOffset(position.column - 1, model.getLineContent(position.lineNumber)); - return position.with(undefined, idx + 1); - } - else if (position.lineNumber > 1) { - const newLine = position.lineNumber - 1; - return new position_1.Position(newLine, model.getLineMaxColumn(newLine)); - } - else { - return position; - } - } - static cut(config, model, selections) { - let commands = []; - for (let i = 0, len = selections.length; i < len; i++) { - const selection = selections[i]; - if (selection.isEmpty()) { - if (config.emptySelectionClipboard) { - // This is a full line cut - let position = selection.getPosition(); - let startLineNumber, startColumn, endLineNumber, endColumn; - 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); - } - let 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 - }); - } - } - 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[187/*vs/editor/common/controller/cursorTypeOperations*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,8/*vs/base/common/strings*/,95/*vs/editor/common/commands/replaceCommand*/,184/*vs/editor/common/commands/shiftCommand*/,376/*vs/editor/common/commands/surroundSelectionCommand*/,40/*vs/editor/common/controller/cursorCommon*/,109/*vs/editor/common/controller/wordCharacterClassifier*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,112/*vs/editor/common/modes/languageConfiguration*/,45/*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 }); - exports.TypeWithAutoClosingCommand = exports.TypeOperations = void 0; - class TypeOperations { - static indent(config, model, selections) { - if (model === null || selections === null) { - return []; - } - let commands = []; - for (let 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; - } - static outdent(config, model, selections) { - let commands = []; - for (let 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; - } - static shiftIndent(config, indentation, count) { - count = count || 1; - return shiftCommand_1.ShiftCommand.shiftIndent(indentation, indentation.length + count, config.tabSize, config.indentSize, config.insertSpaces); - } - static unshiftIndent(config, indentation, count) { - count = count || 1; - return shiftCommand_1.ShiftCommand.unshiftIndent(indentation, indentation.length + count, config.tabSize, config.indentSize, config.insertSpaces); - } - static _distributedPaste(config, model, selections, text) { - let commands = []; - for (let 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 - }); - } - static _simplePaste(config, model, selections, text, pasteOnNewLine) { - let commands = []; - for (let i = 0, len = selections.length; i < len; i++) { - const selection = selections[i]; - let 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 - let 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 - }); - } - static _distributePasteToCursors(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); - } - let lines = strings.splitLines(text); - if (lines.length === selections.length) { - return lines; - } - } - return null; - } - static paste(config, model, selections, text, pasteOnNewLine, multicursorText) { - const 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); - } - } - static _goodIndentForLine(config, model, lineNumber) { - let action = null; - let indentation = ''; - const expectedIndentAction = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getInheritIndentForLine(config.autoIndent, model, lineNumber, false); - if (expectedIndentAction) { - action = expectedIndentAction.action; - indentation = expectedIndentAction.indentation; - } - else if (lineNumber > 1) { - let lastLineNumber; - for (lastLineNumber = lineNumber - 1; lastLineNumber >= 1; lastLineNumber--) { - const lineText = model.getLineContent(lastLineNumber); - const nonWhitespaceIdx = strings.lastNonWhitespaceIndex(lineText); - if (nonWhitespaceIdx >= 0) { - break; - } - } - if (lastLineNumber < 1) { - // No previous line with content found - return null; - } - const maxColumn = model.getLineMaxColumn(lastLineNumber); - const 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; - } - static _replaceJumpToNextIndent(config, model, selection, insertsAutoWhitespace) { - let typeText = ''; - let position = selection.getStartPosition(); - if (config.insertSpaces) { - let visibleColumnFromColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, position); - let indentSize = config.indentSize; - let spacesCnt = indentSize - (visibleColumnFromColumn % indentSize); - for (let i = 0; i < spacesCnt; i++) { - typeText += ' '; - } - } - else { - typeText = '\t'; - } - return new replaceCommand_1.ReplaceCommand(selection, typeText, insertsAutoWhitespace); - } - static tab(config, model, selections) { - let commands = []; - for (let i = 0, len = selections.length; i < len; i++) { - const selection = selections[i]; - if (selection.isEmpty()) { - let lineText = model.getLineContent(selection.startLineNumber); - if (/^\s*$/.test(lineText) && model.isCheapToTokenize(selection.startLineNumber)) { - let goodIndent = this._goodIndentForLine(config, model, selection.startLineNumber); - goodIndent = goodIndent || '\t'; - let possibleTypeText = config.normalizeIndentation(goodIndent); - if (!lineText.startsWith(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) { - let 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; - } - static compositionType(prevEditOperationType, config, model, selections, text, replacePrevCharCnt, replaceNextCharCnt, positionDelta) { - const commands = selections.map(selection => this._compositionType(model, selection, text, replacePrevCharCnt, replaceNextCharCnt, positionDelta)); - return new cursorCommon_1.EditOperationResult(4 /* TypingOther */, commands, { - shouldPushStackElementBefore: shouldPushStackElementBetween(prevEditOperationType, 4 /* TypingOther */), - shouldPushStackElementAfter: false - }); - } - static _compositionType(model, selection, text, replacePrevCharCnt, replaceNextCharCnt, positionDelta) { - if (!selection.isEmpty()) { - // looks like https://github.com/microsoft/vscode/issues/2773 - // where a cursor operation occurred before a canceled composition - // => ignore composition - return null; - } - const pos = selection.getPosition(); - const startColumn = Math.max(1, pos.column - replacePrevCharCnt); - const endColumn = Math.min(model.getLineMaxColumn(pos.lineNumber), pos.column + replaceNextCharCnt); - const range = new range_1.Range(pos.lineNumber, startColumn, pos.lineNumber, endColumn); - const oldText = model.getValueInRange(range); - if (oldText === text && positionDelta === 0) { - // => ignore composition that doesn't do anything - return null; - } - return new replaceCommand_1.ReplaceCommandWithOffsetCursorState(range, text, 0, positionDelta); - } - static _typeCommand(range, text, keepPosition) { - if (keepPosition) { - return new replaceCommand_1.ReplaceCommandWithoutChangingPosition(range, text, true); - } - else { - return new replaceCommand_1.ReplaceCommand(range, text, true); - } - } - static _enter(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 */) { - let lineText = model.getLineContent(range.startLineNumber); - let indentation = strings.getLeadingWhitespace(lineText).substring(0, range.startColumn - 1); - return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(indentation), keepPosition); - } - const 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 - const normalIndent = config.normalizeIndentation(r.indentation); - const increasedIndent = config.normalizeIndentation(r.indentation + r.appendText); - const 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) { - const actualIndentation = TypeOperations.unshiftIndent(config, r.indentation); - return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(actualIndentation + r.appendText), keepPosition); - } - } - const lineText = model.getLineContent(range.startLineNumber); - const indentation = strings.getLeadingWhitespace(lineText).substring(0, range.startColumn - 1); - if (config.autoIndent >= 4 /* Full */) { - const ir = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentForEnter(config.autoIndent, model, range, { - unshiftIndent: (indent) => { - return TypeOperations.unshiftIndent(config, indent); - }, - shiftIndent: (indent) => { - return TypeOperations.shiftIndent(config, indent); - }, - normalizeIndentation: (indent) => { - return config.normalizeIndentation(indent); - } - }); - if (ir) { - let oldEndViewColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, range.getEndPosition()); - const oldEndColumn = range.endColumn; - const newLineContent = model.getLineContent(range.endLineNumber); - const 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, '\n' + config.normalizeIndentation(ir.afterEnter), true); - } - else { - let 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, '\n' + config.normalizeIndentation(ir.afterEnter), 0, offset, true); - } - } - } - return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(indentation), keepPosition); - } - static _isAutoIndentType(config, model, selections) { - if (config.autoIndent < 4 /* Full */) { - return false; - } - for (let i = 0, len = selections.length; i < len; i++) { - if (!model.isCheapToTokenize(selections[i].getEndPosition().lineNumber)) { - return false; - } - } - return true; - } - static _runAutoIndentType(config, model, range, ch) { - const currentIndentation = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentationAtPosition(model, range.startLineNumber, range.startColumn); - const actualIndentation = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentActionForType(config.autoIndent, model, range, ch, { - shiftIndent: (indentation) => { - return TypeOperations.shiftIndent(config, indentation); - }, - unshiftIndent: (indentation) => { - return TypeOperations.unshiftIndent(config, indentation); - }, - }); - if (actualIndentation === null) { - return null; - } - if (actualIndentation !== config.normalizeIndentation(currentIndentation)) { - const firstNonWhitespace = model.getLineFirstNonWhitespaceColumn(range.startLineNumber); - if (firstNonWhitespace === 0) { - return TypeOperations._typeCommand(new range_1.Range(range.startLineNumber, 1, range.endLineNumber, range.endColumn), config.normalizeIndentation(actualIndentation) + ch, false); - } - else { - return TypeOperations._typeCommand(new range_1.Range(range.startLineNumber, 1, range.endLineNumber, range.endColumn), config.normalizeIndentation(actualIndentation) + - model.getLineContent(range.startLineNumber).substring(firstNonWhitespace - 1, range.startColumn - 1) + ch, false); - } - } - return null; - } - static _isAutoClosingOvertype(config, model, selections, autoClosedCharacters, ch) { - if (config.autoClosingOvertype === 'never') { - return false; - } - if (!config.autoClosingPairs.autoClosingPairsCloseSingleChar.has(ch)) { - return false; - } - for (let i = 0, len = selections.length; i < len; i++) { - const selection = selections[i]; - if (!selection.isEmpty()) { - return false; - } - const position = selection.getPosition(); - const lineText = model.getLineContent(position.lineNumber); - const afterCharacter = lineText.charAt(position.column - 1); - if (afterCharacter !== ch) { - return false; - } - // Do not over-type quotes after a backslash - const chIsQuote = (0, cursorCommon_1.isQuote)(ch); - const 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') { - let found = false; - for (let j = 0, lenJ = autoClosedCharacters.length; j < lenJ; j++) { - const autoClosedCharacter = autoClosedCharacters[j]; - if (position.lineNumber === autoClosedCharacter.startLineNumber && position.column === autoClosedCharacter.startColumn) { - found = true; - break; - } - } - if (!found) { - return false; - } - } - } - return true; - } - static _runAutoClosingOvertype(prevEditOperationType, config, model, selections, ch) { - let commands = []; - for (let i = 0, len = selections.length; i < len; i++) { - const selection = selections[i]; - const position = selection.getPosition(); - const 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(4 /* TypingOther */, commands, { - shouldPushStackElementBefore: shouldPushStackElementBetween(prevEditOperationType, 4 /* TypingOther */), - shouldPushStackElementAfter: false - }); - } - static _isBeforeClosingBrace(config, lineAfter) { - // If the start of lineAfter can be interpretted as both a starting or ending brace, default to returning false - const nextChar = lineAfter.charAt(0); - const potentialStartingBraces = config.autoClosingPairs.autoClosingPairsOpenByStart.get(nextChar) || []; - const potentialClosingBraces = config.autoClosingPairs.autoClosingPairsCloseByStart.get(nextChar) || []; - const isBeforeStartingBrace = potentialStartingBraces.some(x => lineAfter.startsWith(x.open)); - const isBeforeClosingBrace = potentialClosingBraces.some(x => lineAfter.startsWith(x.close)); - return !isBeforeStartingBrace && isBeforeClosingBrace; - } - static _findAutoClosingPairOpen(config, model, positions, ch) { - const autoClosingPairCandidates = config.autoClosingPairs.autoClosingPairsOpenByEnd.get(ch); - if (!autoClosingPairCandidates) { - return null; - } - // Determine which auto-closing pair it is - let autoClosingPair = null; - for (const autoClosingPairCandidate of autoClosingPairCandidates) { - if (autoClosingPair === null || autoClosingPairCandidate.open.length > autoClosingPair.open.length) { - let candidateIsMatch = true; - for (const position of positions) { - const 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; - } - static _findSubAutoClosingPairClose(config, autoClosingPair) { - if (autoClosingPair.open.length <= 1) { - return ''; - } - const lastChar = autoClosingPair.close.charAt(autoClosingPair.close.length - 1); - // get candidates with the same last character as close - const subPairCandidates = config.autoClosingPairs.autoClosingPairsCloseByEnd.get(lastChar) || []; - let subPairMatch = null; - for (const x of subPairCandidates) { - if (x.open !== autoClosingPair.open && autoClosingPair.open.includes(x.open) && autoClosingPair.close.endsWith(x.close)) { - if (!subPairMatch || x.open.length > subPairMatch.open.length) { - subPairMatch = x; - } - } - } - if (subPairMatch) { - return subPairMatch.close; - } - else { - return ''; - } - } - static _getAutoClosingPairClose(config, model, selections, ch, insertOpenCharacter) { - const chIsQuote = (0, cursorCommon_1.isQuote)(ch); - const autoCloseConfig = chIsQuote ? config.autoClosingQuotes : config.autoClosingBrackets; - if (autoCloseConfig === 'never') { - return null; - } - const autoClosingPair = this._findAutoClosingPairOpen(config, model, selections.map(s => s.getPosition()), ch); - if (!autoClosingPair) { - return null; - } - const subAutoClosingPairClose = this._findSubAutoClosingPairClose(config, autoClosingPair); - let isSubAutoClosingPairPresent = true; - const shouldAutoCloseBefore = chIsQuote ? config.shouldAutoCloseBefore.quote : config.shouldAutoCloseBefore.bracket; - for (let i = 0, len = selections.length; i < len; i++) { - const selection = selections[i]; - if (!selection.isEmpty()) { - return null; - } - const position = selection.getPosition(); - const lineText = model.getLineContent(position.lineNumber); - const lineAfter = lineText.substring(position.column - 1); - if (!lineAfter.startsWith(subAutoClosingPairClose)) { - isSubAutoClosingPairPresent = false; - } - // Only consider auto closing the pair if an allowed character follows or if another autoclosed pair closing brace follows - if (lineText.length > position.column - 1) { - const characterAfter = lineText.charAt(position.column - 1); - const isBeforeCloseBrace = TypeOperations._isBeforeClosingBrace(config, lineAfter); - 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') { - const wordSeparators = (0, 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); - const lineTokens = model.getLineTokens(position.lineNumber); - let shouldAutoClosePair = false; - try { - shouldAutoClosePair = languageConfigurationRegistry_1.LanguageConfigurationRegistry.shouldAutoClosePair(autoClosingPair, lineTokens, insertOpenCharacter ? position.column : position.column - 1); - } - catch (e) { - (0, errors_1.onUnexpectedError)(e); - } - if (!shouldAutoClosePair) { - return null; - } - } - if (isSubAutoClosingPairPresent) { - return autoClosingPair.close.substring(0, autoClosingPair.close.length - subAutoClosingPairClose.length); - } - else { - return autoClosingPair.close; - } - } - static _runAutoClosingOpenCharType(prevEditOperationType, config, model, selections, ch, insertOpenCharacter, autoClosingPairClose) { - let commands = []; - for (let i = 0, len = selections.length; i < len; i++) { - const selection = selections[i]; - commands[i] = new TypeWithAutoClosingCommand(selection, ch, insertOpenCharacter, autoClosingPairClose); - } - return new cursorCommon_1.EditOperationResult(4 /* TypingOther */, commands, { - shouldPushStackElementBefore: true, - shouldPushStackElementAfter: false - }); - } - static _shouldSurroundChar(config, ch) { - if ((0, cursorCommon_1.isQuote)(ch)) { - return (config.autoSurround === 'quotes' || config.autoSurround === 'languageDefined'); - } - else { - // Character is a bracket - return (config.autoSurround === 'brackets' || config.autoSurround === 'languageDefined'); - } - } - static _isSurroundSelectionType(config, model, selections, ch) { - if (!TypeOperations._shouldSurroundChar(config, ch) || !config.surroundingPairs.hasOwnProperty(ch)) { - return false; - } - const isTypingAQuoteCharacter = (0, cursorCommon_1.isQuote)(ch); - for (let i = 0, len = selections.length; i < len; i++) { - const selection = selections[i]; - if (selection.isEmpty()) { - return false; - } - let selectionContainsOnlyWhitespace = true; - for (let lineNumber = selection.startLineNumber; lineNumber <= selection.endLineNumber; lineNumber++) { - const lineText = model.getLineContent(lineNumber); - const startIndex = (lineNumber === selection.startLineNumber ? selection.startColumn - 1 : 0); - const endIndex = (lineNumber === selection.endLineNumber ? selection.endColumn - 1 : lineText.length); - const 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) { - const selectionText = model.getValueInRange(selection); - if ((0, cursorCommon_1.isQuote)(selectionText)) { - // Typing a quote character on top of another quote character - // => disable surround selection type - return false; - } - } - } - return true; - } - static _runSurroundSelectionType(prevEditOperationType, config, model, selections, ch) { - let commands = []; - for (let i = 0, len = selections.length; i < len; i++) { - const selection = selections[i]; - const 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 - }); - } - static _isTypeInterceptorElectricChar(config, model, selections) { - if (selections.length === 1 && model.isCheapToTokenize(selections[0].getEndPosition().lineNumber)) { - return true; - } - return false; - } - static _typeInterceptorElectricChar(prevEditOperationType, config, model, selection, ch) { - if (!config.electricChars.hasOwnProperty(ch) || !selection.isEmpty()) { - return null; - } - let position = selection.getPosition(); - model.forceTokenization(position.lineNumber); - let lineTokens = model.getLineTokens(position.lineNumber); - let electricAction; - try { - electricAction = languageConfigurationRegistry_1.LanguageConfigurationRegistry.onElectricCharacter(ch, lineTokens, position.column); - } - catch (e) { - (0, errors_1.onUnexpectedError)(e); - return null; - } - if (!electricAction) { - return null; - } - if (electricAction.matchOpenBracket) { - let endColumn = (lineTokens.getLineContent() + ch).lastIndexOf(electricAction.matchOpenBracket) + 1; - let 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; - } - let matchLine = model.getLineContent(match.startLineNumber); - let matchLineIndentation = strings.getLeadingWhitespace(matchLine); - let newIndentation = config.normalizeIndentation(matchLineIndentation); - let lineText = model.getLineContent(position.lineNumber); - let lineFirstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(position.lineNumber) || position.column; - let prefix = lineText.substring(lineFirstNonBlankColumn - 1, position.column - 1); - let typeText = newIndentation + prefix + ch; - let typeSelection = new range_1.Range(position.lineNumber, 1, position.lineNumber, position.column); - const command = new replaceCommand_1.ReplaceCommand(typeSelection, typeText); - return new cursorCommon_1.EditOperationResult(getTypingOperation(typeText, prevEditOperationType), [command], { - shouldPushStackElementBefore: false, - shouldPushStackElementAfter: true - }); - } - } - return null; - } - /** - * This is very similar with typing, but the character is already in the text buffer! - */ - static compositionEndWithInterceptors(prevEditOperationType, config, model, selectionsWhenCompositionStarted, selections, autoClosedCharacters) { - if (!selectionsWhenCompositionStarted || selection_1.Selection.selectionsArrEqual(selectionsWhenCompositionStarted, selections)) { - // no content was typed - return null; - } - let ch = null; - // extract last typed character - for (const selection of selections) { - if (!selection.isEmpty()) { - return null; - } - const position = selection.getPosition(); - const 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... - const commands = selections.map(s => new replaceCommand_1.ReplaceCommand(new range_1.Range(s.positionLineNumber, s.positionColumn, s.positionLineNumber, s.positionColumn + 1), '', false)); - return new cursorCommon_1.EditOperationResult(4 /* TypingOther */, commands, { - shouldPushStackElementBefore: true, - shouldPushStackElementAfter: false - }); - } - const autoClosingPairClose = this._getAutoClosingPairClose(config, model, selections, ch, false); - if (autoClosingPairClose !== null) { - return this._runAutoClosingOpenCharType(prevEditOperationType, config, model, selections, ch, false, autoClosingPairClose); - } - return null; - } - static typeWithInterceptors(isDoingComposition, prevEditOperationType, config, model, selections, autoClosedCharacters, ch) { - if (!isDoingComposition && ch === '\n') { - let commands = []; - for (let i = 0, len = selections.length; i < len; i++) { - commands[i] = TypeOperations._enter(config, model, false, selections[i]); - } - return new cursorCommon_1.EditOperationResult(4 /* TypingOther */, commands, { - shouldPushStackElementBefore: true, - shouldPushStackElementAfter: false, - }); - } - if (!isDoingComposition && this._isAutoIndentType(config, model, selections)) { - let commands = []; - let autoIndentFails = false; - for (let i = 0, len = selections.length; i < len; i++) { - commands[i] = this._runAutoIndentType(config, model, selections[i], ch); - if (!commands[i]) { - autoIndentFails = true; - break; - } - } - if (!autoIndentFails) { - return new cursorCommon_1.EditOperationResult(4 /* TypingOther */, commands, { - shouldPushStackElementBefore: true, - shouldPushStackElementAfter: false, - }); - } - } - if (!isDoingComposition && this._isAutoClosingOvertype(config, model, selections, autoClosedCharacters, ch)) { - return this._runAutoClosingOvertype(prevEditOperationType, config, model, selections, ch); - } - if (!isDoingComposition) { - const autoClosingPairClose = this._getAutoClosingPairClose(config, model, selections, ch, true); - if (autoClosingPairClose) { - return this._runAutoClosingOpenCharType(prevEditOperationType, config, model, selections, ch, true, autoClosingPairClose); - } - } - 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 (!isDoingComposition && this._isTypeInterceptorElectricChar(config, model, selections)) { - const r = this._typeInterceptorElectricChar(prevEditOperationType, config, model, selections[0], ch); - if (r) { - return r; - } - } - // A simple character type - let commands = []; - for (let i = 0, len = selections.length; i < len; i++) { - commands[i] = new replaceCommand_1.ReplaceCommand(selections[i], ch); - } - const opType = getTypingOperation(ch, prevEditOperationType); - return new cursorCommon_1.EditOperationResult(opType, commands, { - shouldPushStackElementBefore: shouldPushStackElementBetween(prevEditOperationType, opType), - shouldPushStackElementAfter: false - }); - } - static typeWithoutInterceptors(prevEditOperationType, config, model, selections, str) { - let commands = []; - for (let i = 0, len = selections.length; i < len; i++) { - commands[i] = new replaceCommand_1.ReplaceCommand(selections[i], str); - } - const opType = getTypingOperation(str, prevEditOperationType); - return new cursorCommon_1.EditOperationResult(opType, commands, { - shouldPushStackElementBefore: shouldPushStackElementBetween(prevEditOperationType, opType), - shouldPushStackElementAfter: false - }); - } - static lineInsertBefore(config, model, selections) { - if (model === null || selections === null) { - return []; - } - let commands = []; - for (let i = 0, len = selections.length; i < len; i++) { - let lineNumber = selections[i].positionLineNumber; - if (lineNumber === 1) { - commands[i] = new replaceCommand_1.ReplaceCommandWithoutChangingPosition(new range_1.Range(1, 1, 1, 1), '\n'); - } - else { - lineNumber--; - let column = model.getLineMaxColumn(lineNumber); - commands[i] = this._enter(config, model, false, new range_1.Range(lineNumber, column, lineNumber, column)); - } - } - return commands; - } - static lineInsertAfter(config, model, selections) { - if (model === null || selections === null) { - return []; - } - let commands = []; - for (let i = 0, len = selections.length; i < len; i++) { - const lineNumber = selections[i].positionLineNumber; - let column = model.getLineMaxColumn(lineNumber); - commands[i] = this._enter(config, model, false, new range_1.Range(lineNumber, column, lineNumber, column)); - } - return commands; - } - static lineBreakInsert(config, model, selections) { - let commands = []; - for (let i = 0, len = selections.length; i < len; i++) { - commands[i] = this._enter(config, model, true, selections[i]); - } - return commands; - } - } - exports.TypeOperations = TypeOperations; - class TypeWithAutoClosingCommand extends replaceCommand_1.ReplaceCommandWithOffsetCursorState { - constructor(selection, openCharacter, insertOpenCharacter, closeCharacter) { - super(selection, (insertOpenCharacter ? openCharacter : '') + closeCharacter, 0, -closeCharacter.length); - this._openCharacter = openCharacter; - this._closeCharacter = closeCharacter; - this.closeCharacterRange = null; - this.enclosingRange = null; - } - computeCursorState(model, helper) { - let inverseEditOperations = helper.getInverseEditOperations(); - let 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.computeCursorState(model, helper); - } - } - exports.TypeWithAutoClosingCommand = TypeWithAutoClosingCommand; - function getTypingOperation(typedText, previousTypingOperation) { - if (typedText === ' ') { - return previousTypingOperation === 5 /* TypingFirstSpace */ - || previousTypingOperation === 6 /* TypingConsecutiveSpace */ - ? 6 /* TypingConsecutiveSpace */ - : 5 /* TypingFirstSpace */; - } - return 4 /* TypingOther */; - } - function shouldPushStackElementBetween(previousTypingOperation, typingOperation) { - if (isTypingOperation(previousTypingOperation) && !isTypingOperation(typingOperation)) { - // Always set an undo stop before non-type operations - return true; - } - if (previousTypingOperation === 5 /* TypingFirstSpace */) { - // `abc |d`: No undo stop - // `abc |d`: Undo stop - return false; - } - // Insert undo stop between different operation types - return normalizeOperationType(previousTypingOperation) !== normalizeOperationType(typingOperation); - } - function normalizeOperationType(type) { - return (type === 6 /* TypingConsecutiveSpace */ || type === 5 /* TypingFirstSpace */) - ? 'space' - : type; - } - function isTypingOperation(type) { - return type === 4 /* TypingOther */ - || type === 5 /* TypingFirstSpace */ - || type === 6 /* TypingConsecutiveSpace */; - } -}); - -/*--------------------------------------------------------------------------------------------- - * 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/common/controller/cursorWordOperations*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,40/*vs/editor/common/controller/cursorCommon*/,186/*vs/editor/common/controller/cursorDeleteOperations*/,109/*vs/editor/common/controller/wordCharacterClassifier*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/]), function (require, exports, strings, cursorCommon_1, cursorDeleteOperations_1, wordCharacterClassifier_1, position_1, range_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.WordPartOperations = exports.WordOperations = void 0; - class WordOperations { - static _createWord(lineContent, wordType, nextCharClass, start, end) { - // console.log('WORD ==> ' + start + ' => ' + end + ':::: <<<' + lineContent.substring(start, end) + '>>>'); - return { start: start, end: end, wordType: wordType, nextCharClass: nextCharClass }; - } - static _findPreviousWordOnLine(wordSeparators, model, position) { - let lineContent = model.getLineContent(position.lineNumber); - return this._doFindPreviousWordOnLine(lineContent, wordSeparators, position); - } - static _doFindPreviousWordOnLine(lineContent, wordSeparators, position) { - let wordType = 0 /* None */; - for (let chIndex = position.column - 2; chIndex >= 0; chIndex--) { - let chCode = lineContent.charCodeAt(chIndex); - let 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; - } - static _findEndOfWord(lineContent, wordSeparators, wordType, startIndex) { - let len = lineContent.length; - for (let chIndex = startIndex; chIndex < len; chIndex++) { - let chCode = lineContent.charCodeAt(chIndex); - let 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; - } - static _findNextWordOnLine(wordSeparators, model, position) { - let lineContent = model.getLineContent(position.lineNumber); - return this._doFindNextWordOnLine(lineContent, wordSeparators, position); - } - static _doFindNextWordOnLine(lineContent, wordSeparators, position) { - let wordType = 0 /* None */; - let len = lineContent.length; - for (let chIndex = position.column - 1; chIndex < len; chIndex++) { - let chCode = lineContent.charCodeAt(chIndex); - let 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; - } - static _findStartOfWord(lineContent, wordSeparators, wordType, startIndex) { - for (let chIndex = startIndex; chIndex >= 0; chIndex--) { - let chCode = lineContent.charCodeAt(chIndex); - let 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; - } - static moveWordLeft(wordSeparators, model, position, wordNavigationType) { - let lineNumber = position.lineNumber; - let column = position.column; - if (column === 1) { - if (lineNumber > 1) { - lineNumber = lineNumber - 1; - column = model.getLineMaxColumn(lineNumber); - } - } - let prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, column)); - if (wordNavigationType === 0 /* WordStart */) { - 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); - } - static _moveWordPartLeft(model, position) { - const lineNumber = position.lineNumber; - const maxColumn = model.getLineMaxColumn(lineNumber); - if (position.column === 1) { - return (lineNumber > 1 ? new position_1.Position(lineNumber - 1, model.getLineMaxColumn(lineNumber - 1)) : position); - } - const lineContent = model.getLineContent(lineNumber); - for (let column = position.column - 1; column > 1; column--) { - const left = lineContent.charCodeAt(column - 2); - const 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) { - const rightRight = lineContent.charCodeAt(column); - if (strings.isLowerAsciiLetter(rightRight)) { - return new position_1.Position(lineNumber, column); - } - } - } - } - return new position_1.Position(lineNumber, 1); - } - static moveWordRight(wordSeparators, model, position, wordNavigationType) { - let lineNumber = position.lineNumber; - let column = position.column; - let movedDown = false; - if (column === model.getLineMaxColumn(lineNumber)) { - if (lineNumber < model.getLineCount()) { - movedDown = true; - lineNumber = lineNumber + 1; - column = 1; - } - } - let 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); - } - static _moveWordPartRight(model, position) { - const lineNumber = position.lineNumber; - const maxColumn = model.getLineMaxColumn(lineNumber); - if (position.column === maxColumn) { - return (lineNumber < model.getLineCount() ? new position_1.Position(lineNumber + 1, 1) : position); - } - const lineContent = model.getLineContent(lineNumber); - for (let column = position.column + 1; column < maxColumn; column++) { - const left = lineContent.charCodeAt(column - 2); - const 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) { - const rightRight = lineContent.charCodeAt(column); - if (strings.isLowerAsciiLetter(rightRight)) { - return new position_1.Position(lineNumber, column); - } - } - } - } - return new position_1.Position(lineNumber, maxColumn); - } - static _deleteWordLeftWhitespace(model, position) { - const lineContent = model.getLineContent(position.lineNumber); - const startIndex = position.column - 2; - const lastNonWhitespace = strings.lastNonWhitespaceIndex(lineContent, startIndex); - if (lastNonWhitespace + 1 < startIndex) { - return new range_1.Range(position.lineNumber, lastNonWhitespace + 2, position.lineNumber, position.column); - } - return null; - } - static deleteWordLeft(ctx, wordNavigationType) { - const wordSeparators = ctx.wordSeparators; - const model = ctx.model; - const selection = ctx.selection; - const whitespaceHeuristics = ctx.whitespaceHeuristics; - if (!selection.isEmpty()) { - return selection; - } - if (cursorDeleteOperations_1.DeleteOperations.isAutoClosingPairDelete(ctx.autoClosingDelete, ctx.autoClosingBrackets, ctx.autoClosingQuotes, ctx.autoClosingPairs.autoClosingPairsOpenByEnd, ctx.model, [ctx.selection], ctx.autoClosedCharacters)) { - const position = ctx.selection.getPosition(); - return new range_1.Range(position.lineNumber, position.column - 1, position.lineNumber, position.column + 1); - } - const position = new position_1.Position(selection.positionLineNumber, selection.positionColumn); - let lineNumber = position.lineNumber; - let column = position.column; - if (lineNumber === 1 && column === 1) { - // Ignore deleting at beginning of file - return null; - } - if (whitespaceHeuristics) { - let r = this._deleteWordLeftWhitespace(model, position); - if (r) { - return r; - } - } - let 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); - } - static deleteInsideWord(wordSeparators, model, selection) { - if (!selection.isEmpty()) { - return selection; - } - const position = new position_1.Position(selection.positionLineNumber, selection.positionColumn); - let r = this._deleteInsideWordWhitespace(model, position); - if (r) { - return r; - } - return this._deleteInsideWordDetermineDeleteRange(wordSeparators, model, position); - } - static _charAtIsWhitespace(str, index) { - const charCode = str.charCodeAt(index); - return (charCode === 32 /* Space */ || charCode === 9 /* Tab */); - } - static _deleteInsideWordWhitespace(model, position) { - const lineContent = model.getLineContent(position.lineNumber); - const lineContentLength = lineContent.length; - if (lineContentLength === 0) { - // empty line - return null; - } - let leftIndex = Math.max(position.column - 2, 0); - if (!this._charAtIsWhitespace(lineContent, leftIndex)) { - // touches a non-whitespace character to the left - return null; - } - let rightIndex = Math.min(position.column - 1, lineContentLength - 1); - if (!this._charAtIsWhitespace(lineContent, rightIndex)) { - // touches a non-whitespace character to the right - return null; - } - // walk over whitespace to the left - while (leftIndex > 0 && this._charAtIsWhitespace(lineContent, leftIndex - 1)) { - leftIndex--; - } - // walk over whitespace to the right - while (rightIndex + 1 < lineContentLength && this._charAtIsWhitespace(lineContent, rightIndex + 1)) { - rightIndex++; - } - return new range_1.Range(position.lineNumber, leftIndex + 1, position.lineNumber, rightIndex + 2); - } - static _deleteInsideWordDetermineDeleteRange(wordSeparators, model, position) { - const lineContent = model.getLineContent(position.lineNumber); - const lineLength = lineContent.length; - if (lineLength === 0) { - // empty line - if (position.lineNumber > 1) { - return new range_1.Range(position.lineNumber - 1, model.getLineMaxColumn(position.lineNumber - 1), position.lineNumber, 1); - } - else { - if (position.lineNumber < model.getLineCount()) { - return new range_1.Range(position.lineNumber, 1, position.lineNumber + 1, 1); - } - else { - // empty model - return new range_1.Range(position.lineNumber, 1, position.lineNumber, 1); - } - } - } - const touchesWord = (word) => { - return (word.start + 1 <= position.column && position.column <= word.end + 1); - }; - const createRangeWithPosition = (startColumn, endColumn) => { - startColumn = Math.min(startColumn, position.column); - endColumn = Math.max(endColumn, position.column); - return new range_1.Range(position.lineNumber, startColumn, position.lineNumber, endColumn); - }; - const deleteWordAndAdjacentWhitespace = (word) => { - let startColumn = word.start + 1; - let endColumn = word.end + 1; - let expandedToTheRight = false; - while (endColumn - 1 < lineLength && this._charAtIsWhitespace(lineContent, endColumn - 1)) { - expandedToTheRight = true; - endColumn++; - } - if (!expandedToTheRight) { - while (startColumn > 1 && this._charAtIsWhitespace(lineContent, startColumn - 2)) { - startColumn--; - } - } - return createRangeWithPosition(startColumn, endColumn); - }; - const prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, position); - if (prevWordOnLine && touchesWord(prevWordOnLine)) { - return deleteWordAndAdjacentWhitespace(prevWordOnLine); - } - const nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, position); - if (nextWordOnLine && touchesWord(nextWordOnLine)) { - return deleteWordAndAdjacentWhitespace(nextWordOnLine); - } - if (prevWordOnLine && nextWordOnLine) { - return createRangeWithPosition(prevWordOnLine.end + 1, nextWordOnLine.start + 1); - } - if (prevWordOnLine) { - return createRangeWithPosition(prevWordOnLine.start + 1, prevWordOnLine.end + 1); - } - if (nextWordOnLine) { - return createRangeWithPosition(nextWordOnLine.start + 1, nextWordOnLine.end + 1); - } - return createRangeWithPosition(1, lineLength + 1); - } - static _deleteWordPartLeft(model, selection) { - if (!selection.isEmpty()) { - return selection; - } - const pos = selection.getPosition(); - const toPosition = WordOperations._moveWordPartLeft(model, pos); - return new range_1.Range(pos.lineNumber, pos.column, toPosition.lineNumber, toPosition.column); - } - static _findFirstNonWhitespaceChar(str, startIndex) { - let len = str.length; - for (let chIndex = startIndex; chIndex < len; chIndex++) { - let ch = str.charAt(chIndex); - if (ch !== ' ' && ch !== '\t') { - return chIndex; - } - } - return len; - } - static _deleteWordRightWhitespace(model, position) { - const lineContent = model.getLineContent(position.lineNumber); - const startIndex = position.column - 1; - const 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; - } - static deleteWordRight(ctx, wordNavigationType) { - const wordSeparators = ctx.wordSeparators; - const model = ctx.model; - const selection = ctx.selection; - const whitespaceHeuristics = ctx.whitespaceHeuristics; - if (!selection.isEmpty()) { - return selection; - } - const position = new position_1.Position(selection.positionLineNumber, selection.positionColumn); - let lineNumber = position.lineNumber; - let column = position.column; - const lineCount = model.getLineCount(); - const maxColumn = model.getLineMaxColumn(lineNumber); - if (lineNumber === lineCount && column === maxColumn) { - // Ignore deleting at end of file - return null; - } - if (whitespaceHeuristics) { - let r = this._deleteWordRightWhitespace(model, position); - if (r) { - return r; - } - } - let 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); - } - static _deleteWordPartRight(model, selection) { - if (!selection.isEmpty()) { - return selection; - } - const pos = selection.getPosition(); - const toPosition = WordOperations._moveWordPartRight(model, pos); - return new range_1.Range(pos.lineNumber, pos.column, toPosition.lineNumber, toPosition.column); - } - static _createWordAtPosition(model, lineNumber, word) { - const range = new range_1.Range(lineNumber, word.start + 1, lineNumber, word.end + 1); - return { - word: model.getValueInRange(range), - startColumn: range.startColumn, - endColumn: range.endColumn - }; - } - static getWordAtPosition(model, _wordSeparators, position) { - const wordSeparators = (0, wordCharacterClassifier_1.getMapForWordSeparators)(_wordSeparators); - const prevWord = WordOperations._findPreviousWordOnLine(wordSeparators, model, position); - if (prevWord && prevWord.wordType === 1 /* Regular */ && prevWord.start <= position.column - 1 && position.column - 1 <= prevWord.end) { - return WordOperations._createWordAtPosition(model, position.lineNumber, prevWord); - } - const nextWord = WordOperations._findNextWordOnLine(wordSeparators, model, position); - if (nextWord && nextWord.wordType === 1 /* Regular */ && nextWord.start <= position.column - 1 && position.column - 1 <= nextWord.end) { - return WordOperations._createWordAtPosition(model, position.lineNumber, nextWord); - } - return null; - } - static word(config, model, cursor, inSelectionMode, position) { - const wordSeparators = (0, wordCharacterClassifier_1.getMapForWordSeparators)(config.wordSeparators); - let prevWord = WordOperations._findPreviousWordOnLine(wordSeparators, model, position); - let nextWord = WordOperations._findNextWordOnLine(wordSeparators, model, position); - if (!inSelectionMode) { - // Entering word selection for the first time - let startColumn; - let endColumn; - if (prevWord && prevWord.wordType === 1 /* Regular */ && prevWord.start <= position.column - 1 && position.column - 1 <= prevWord.end) { - // isTouchingPrevWord - 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) { - // isTouchingNextWord - startColumn = nextWord.start + 1; - endColumn = nextWord.end + 1; - } - else { - if (prevWord) { - startColumn = prevWord.end + 1; - } - else { - startColumn = 1; - } - if (nextWord) { - endColumn = nextWord.start + 1; - } - else { - endColumn = model.getLineMaxColumn(position.lineNumber); - } - } - return new cursorCommon_1.SingleCursorState(new range_1.Range(position.lineNumber, startColumn, position.lineNumber, endColumn), 0, new position_1.Position(position.lineNumber, endColumn), 0); - } - let startColumn; - let 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; - } - let lineNumber = position.lineNumber; - let column; - if (cursor.selectionStart.containsPosition(position)) { - column = cursor.selectionStart.endColumn; - } - else if (position.isBeforeOrEqual(cursor.selectionStart.getStartPosition())) { - column = startColumn; - let possiblePosition = new position_1.Position(lineNumber, column); - if (cursor.selectionStart.containsPosition(possiblePosition)) { - column = cursor.selectionStart.endColumn; - } - } - else { - column = endColumn; - let possiblePosition = new position_1.Position(lineNumber, column); - if (cursor.selectionStart.containsPosition(possiblePosition)) { - column = cursor.selectionStart.startColumn; - } - } - return cursor.move(true, lineNumber, column, 0); - } - } - exports.WordOperations = WordOperations; - class WordPartOperations extends WordOperations { - static deleteWordPartLeft(ctx) { - const candidates = enforceDefined([ - WordOperations.deleteWordLeft(ctx, 0 /* WordStart */), - WordOperations.deleteWordLeft(ctx, 2 /* WordEnd */), - WordOperations._deleteWordPartLeft(ctx.model, ctx.selection) - ]); - candidates.sort(range_1.Range.compareRangesUsingEnds); - return candidates[2]; - } - static deleteWordPartRight(ctx) { - const candidates = enforceDefined([ - WordOperations.deleteWordRight(ctx, 0 /* WordStart */), - WordOperations.deleteWordRight(ctx, 2 /* WordEnd */), - WordOperations._deleteWordPartRight(ctx.model, ctx.selection) - ]); - candidates.sort(range_1.Range.compareRangesUsingStarts); - return candidates[0]; - } - static moveWordPartLeft(wordSeparators, model, position) { - const 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]; - } - static moveWordPartRight(wordSeparators, model, position) { - const 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]; - } - } - exports.WordPartOperations = WordPartOperations; - function enforceDefined(arr) { - return arr.filter(el => 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[244/*vs/editor/common/controller/cursorMoveCommands*/], __M([0/*require*/,1/*exports*/,20/*vs/base/common/types*/,40/*vs/editor/common/controller/cursorCommon*/,185/*vs/editor/common/controller/cursorMoveOperations*/,141/*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 }); - exports.CursorMove = exports.CursorMoveCommands = void 0; - class CursorMoveCommands { - static addCursorDown(viewModel, cursors, useLogicalLine) { - let result = [], resultLen = 0; - for (let i = 0, len = cursors.length; i < len; i++) { - const 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(viewModel.cursorConfig, viewModel.model, cursor.modelState)); - } - else { - result[resultLen++] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.translateDown(viewModel.cursorConfig, viewModel, cursor.viewState)); - } - } - return result; - } - static addCursorUp(viewModel, cursors, useLogicalLine) { - let result = [], resultLen = 0; - for (let i = 0, len = cursors.length; i < len; i++) { - const 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(viewModel.cursorConfig, viewModel.model, cursor.modelState)); - } - else { - result[resultLen++] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.translateUp(viewModel.cursorConfig, viewModel, cursor.viewState)); - } - } - return result; - } - static moveToBeginningOfLine(viewModel, cursors, inSelectionMode) { - let result = []; - for (let i = 0, len = cursors.length; i < len; i++) { - const cursor = cursors[i]; - result[i] = this._moveToLineStart(viewModel, cursor, inSelectionMode); - } - return result; - } - static _moveToLineStart(viewModel, cursor, inSelectionMode) { - const currentViewStateColumn = cursor.viewState.position.column; - const currentModelStateColumn = cursor.modelState.position.column; - const isFirstLineOfWrappedLine = currentViewStateColumn === currentModelStateColumn; - const currentViewStatelineNumber = cursor.viewState.position.lineNumber; - const firstNonBlankColumn = viewModel.getLineFirstNonWhitespaceColumn(currentViewStatelineNumber); - const isBeginningOfViewLine = currentViewStateColumn === firstNonBlankColumn; - if (!isFirstLineOfWrappedLine && !isBeginningOfViewLine) { - return this._moveToLineStartByView(viewModel, cursor, inSelectionMode); - } - else { - return this._moveToLineStartByModel(viewModel, cursor, inSelectionMode); - } - } - static _moveToLineStartByView(viewModel, cursor, inSelectionMode) { - return cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveToBeginningOfLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode)); - } - static _moveToLineStartByModel(viewModel, cursor, inSelectionMode) { - return cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveToBeginningOfLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode)); - } - static moveToEndOfLine(viewModel, cursors, inSelectionMode, sticky) { - let result = []; - for (let i = 0, len = cursors.length; i < len; i++) { - const cursor = cursors[i]; - result[i] = this._moveToLineEnd(viewModel, cursor, inSelectionMode, sticky); - } - return result; - } - static _moveToLineEnd(viewModel, cursor, inSelectionMode, sticky) { - const viewStatePosition = cursor.viewState.position; - const viewModelMaxColumn = viewModel.getLineMaxColumn(viewStatePosition.lineNumber); - const isEndOfViewLine = viewStatePosition.column === viewModelMaxColumn; - const modelStatePosition = cursor.modelState.position; - const modelMaxColumn = viewModel.model.getLineMaxColumn(modelStatePosition.lineNumber); - const isEndLineOfWrappedLine = viewModelMaxColumn - viewStatePosition.column === modelMaxColumn - modelStatePosition.column; - if (isEndOfViewLine || isEndLineOfWrappedLine) { - return this._moveToLineEndByModel(viewModel, cursor, inSelectionMode, sticky); - } - else { - return this._moveToLineEndByView(viewModel, cursor, inSelectionMode, sticky); - } - } - static _moveToLineEndByView(viewModel, cursor, inSelectionMode, sticky) { - return cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveToEndOfLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, sticky)); - } - static _moveToLineEndByModel(viewModel, cursor, inSelectionMode, sticky) { - return cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveToEndOfLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, sticky)); - } - static expandLineSelection(viewModel, cursors) { - let result = []; - for (let i = 0, len = cursors.length; i < len; i++) { - const cursor = cursors[i]; - const startLineNumber = cursor.modelState.selection.startLineNumber; - const lineCount = viewModel.model.getLineCount(); - let endLineNumber = cursor.modelState.selection.endLineNumber; - let endColumn; - if (endLineNumber === lineCount) { - endColumn = viewModel.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; - } - static moveToBeginningOfBuffer(viewModel, cursors, inSelectionMode) { - let result = []; - for (let i = 0, len = cursors.length; i < len; i++) { - const cursor = cursors[i]; - result[i] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveToBeginningOfBuffer(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode)); - } - return result; - } - static moveToEndOfBuffer(viewModel, cursors, inSelectionMode) { - let result = []; - for (let i = 0, len = cursors.length; i < len; i++) { - const cursor = cursors[i]; - result[i] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveToEndOfBuffer(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode)); - } - return result; - } - static selectAll(viewModel, cursor) { - const lineCount = viewModel.model.getLineCount(); - const maxColumn = viewModel.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)); - } - static line(viewModel, cursor, inSelectionMode, _position, _viewPosition) { - const position = viewModel.model.validatePosition(_position); - const viewPosition = (_viewPosition - ? viewModel.coordinatesConverter.validateViewPosition(new position_1.Position(_viewPosition.lineNumber, _viewPosition.column), position) - : viewModel.coordinatesConverter.convertModelPositionToViewPosition(position)); - if (!inSelectionMode || !cursor.modelState.hasSelection()) { - // Entering line selection for the first time - const lineCount = viewModel.model.getLineCount(); - let selectToLineNumber = position.lineNumber + 1; - let selectToColumn = 1; - if (selectToLineNumber > lineCount) { - selectToLineNumber = lineCount; - selectToColumn = viewModel.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 - const 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) { - const lineCount = viewModel.getLineCount(); - let selectToViewLineNumber = viewPosition.lineNumber + 1; - let selectToViewColumn = 1; - if (selectToViewLineNumber > lineCount) { - selectToViewLineNumber = lineCount; - selectToViewColumn = viewModel.getLineMaxColumn(selectToViewLineNumber); - } - return cursorCommon_1.CursorState.fromViewState(cursor.viewState.move(cursor.modelState.hasSelection(), selectToViewLineNumber, selectToViewColumn, 0)); - } - else { - const endPositionOfSelectionStart = cursor.modelState.selectionStart.getEndPosition(); - return cursorCommon_1.CursorState.fromModelState(cursor.modelState.move(cursor.modelState.hasSelection(), endPositionOfSelectionStart.lineNumber, endPositionOfSelectionStart.column, 0)); - } - } - static word(viewModel, cursor, inSelectionMode, _position) { - const position = viewModel.model.validatePosition(_position); - return cursorCommon_1.CursorState.fromModelState(cursorWordOperations_1.WordOperations.word(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, position)); - } - static cancelSelection(viewModel, cursor) { - if (!cursor.modelState.hasSelection()) { - return new cursorCommon_1.CursorState(cursor.modelState, cursor.viewState); - } - const lineNumber = cursor.viewState.position.lineNumber; - const 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)); - } - static moveTo(viewModel, cursor, inSelectionMode, _position, _viewPosition) { - const position = viewModel.model.validatePosition(_position); - const viewPosition = (_viewPosition - ? viewModel.coordinatesConverter.validateViewPosition(new position_1.Position(_viewPosition.lineNumber, _viewPosition.column), position) - : viewModel.coordinatesConverter.convertModelPositionToViewPosition(position)); - return cursorCommon_1.CursorState.fromViewState(cursor.viewState.move(inSelectionMode, viewPosition.lineNumber, viewPosition.column, 0)); - } - static simpleMove(viewModel, cursors, direction, inSelectionMode, value, unit) { - switch (direction) { - case 0 /* Left */: { - if (unit === 4 /* HalfLine */) { - // Move left by half the current line length - return this._moveHalfLineLeft(viewModel, cursors, inSelectionMode); - } - else { - // Move left by `moveParams.value` columns - return this._moveLeft(viewModel, cursors, inSelectionMode, value); - } - } - case 1 /* Right */: { - if (unit === 4 /* HalfLine */) { - // Move right by half the current line length - return this._moveHalfLineRight(viewModel, cursors, inSelectionMode); - } - else { - // Move right by `moveParams.value` columns - return this._moveRight(viewModel, cursors, inSelectionMode, value); - } - } - case 2 /* Up */: { - if (unit === 2 /* WrappedLine */) { - // Move up by view lines - return this._moveUpByViewLines(viewModel, cursors, inSelectionMode, value); - } - else { - // Move up by model lines - return this._moveUpByModelLines(viewModel, cursors, inSelectionMode, value); - } - } - case 3 /* Down */: { - if (unit === 2 /* WrappedLine */) { - // Move down by view lines - return this._moveDownByViewLines(viewModel, cursors, inSelectionMode, value); - } - else { - // Move down by model lines - return this._moveDownByModelLines(viewModel, cursors, inSelectionMode, value); - } - } - case 4 /* PrevBlankLine */: { - if (unit === 2 /* WrappedLine */) { - return cursors.map(cursor => cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveToPrevBlankLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode))); - } - else { - return cursors.map(cursor => cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveToPrevBlankLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode))); - } - } - case 5 /* NextBlankLine */: { - if (unit === 2 /* WrappedLine */) { - return cursors.map(cursor => cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveToNextBlankLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode))); - } - else { - return cursors.map(cursor => cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveToNextBlankLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode))); - } - } - case 6 /* WrappedLineStart */: { - // Move to the beginning of the current view line - return this._moveToViewMinColumn(viewModel, cursors, inSelectionMode); - } - case 7 /* WrappedLineFirstNonWhitespaceCharacter */: { - // Move to the first non-whitespace column of the current view line - return this._moveToViewFirstNonWhitespaceColumn(viewModel, cursors, inSelectionMode); - } - case 8 /* WrappedLineColumnCenter */: { - // Move to the "center" of the current view line - return this._moveToViewCenterColumn(viewModel, cursors, inSelectionMode); - } - case 9 /* WrappedLineEnd */: { - // Move to the end of the current view line - return this._moveToViewMaxColumn(viewModel, cursors, inSelectionMode); - } - case 10 /* WrappedLineLastNonWhitespaceCharacter */: { - // Move to the last non-whitespace column of the current view line - return this._moveToViewLastNonWhitespaceColumn(viewModel, cursors, inSelectionMode); - } - default: - return null; - } - } - static viewportMove(viewModel, cursors, direction, inSelectionMode, value) { - const visibleViewRange = viewModel.getCompletelyVisibleViewRange(); - const visibleModelRange = viewModel.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange); - switch (direction) { - case 11 /* ViewPortTop */: { - // Move to the nth line start in the viewport (from the top) - const modelLineNumber = this._firstLineNumberInRange(viewModel.model, visibleModelRange, value); - const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber); - return [this._moveToModelPosition(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)]; - } - case 13 /* ViewPortBottom */: { - // Move to the nth line start in the viewport (from the bottom) - const modelLineNumber = this._lastLineNumberInRange(viewModel.model, visibleModelRange, value); - const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber); - return [this._moveToModelPosition(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)]; - } - case 12 /* ViewPortCenter */: { - // Move to the line start in the viewport center - const modelLineNumber = Math.round((visibleModelRange.startLineNumber + visibleModelRange.endLineNumber) / 2); - const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber); - return [this._moveToModelPosition(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)]; - } - case 14 /* ViewPortIfOutside */: { - // Move to a position inside the viewport - let result = []; - for (let i = 0, len = cursors.length; i < len; i++) { - const cursor = cursors[i]; - result[i] = this.findPositionInViewportIfOutside(viewModel, cursor, visibleViewRange, inSelectionMode); - } - return result; - } - default: - return null; - } - } - static findPositionInViewportIfOutside(viewModel, cursor, visibleViewRange, inSelectionMode) { - let 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; - } - const viewColumn = viewModel.getLineFirstNonWhitespaceColumn(viewLineNumber); - return this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn); - } - } - /** - * Find the nth line start included in the range (from the start). - */ - static _firstLineNumberInRange(model, range, count) { - let 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). - */ - static _lastLineNumberInRange(model, range, count) { - let 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); - } - static _moveLeft(viewModel, cursors, inSelectionMode, noOfColumns) { - return cursors.map(cursor => cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveLeft(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, noOfColumns))); - } - static _moveHalfLineLeft(viewModel, cursors, inSelectionMode) { - let result = []; - for (let i = 0, len = cursors.length; i < len; i++) { - const cursor = cursors[i]; - const viewLineNumber = cursor.viewState.position.lineNumber; - const halfLine = Math.round(viewModel.getLineContent(viewLineNumber).length / 2); - result[i] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveLeft(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, halfLine)); - } - return result; - } - static _moveRight(viewModel, cursors, inSelectionMode, noOfColumns) { - return cursors.map(cursor => cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveRight(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, noOfColumns))); - } - static _moveHalfLineRight(viewModel, cursors, inSelectionMode) { - let result = []; - for (let i = 0, len = cursors.length; i < len; i++) { - const cursor = cursors[i]; - const viewLineNumber = cursor.viewState.position.lineNumber; - const halfLine = Math.round(viewModel.getLineContent(viewLineNumber).length / 2); - result[i] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveRight(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, halfLine)); - } - return result; - } - static _moveDownByViewLines(viewModel, cursors, inSelectionMode, linesCount) { - let result = []; - for (let i = 0, len = cursors.length; i < len; i++) { - const cursor = cursors[i]; - result[i] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveDown(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, linesCount)); - } - return result; - } - static _moveDownByModelLines(viewModel, cursors, inSelectionMode, linesCount) { - let result = []; - for (let i = 0, len = cursors.length; i < len; i++) { - const cursor = cursors[i]; - result[i] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveDown(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, linesCount)); - } - return result; - } - static _moveUpByViewLines(viewModel, cursors, inSelectionMode, linesCount) { - let result = []; - for (let i = 0, len = cursors.length; i < len; i++) { - const cursor = cursors[i]; - result[i] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveUp(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, linesCount)); - } - return result; - } - static _moveUpByModelLines(viewModel, cursors, inSelectionMode, linesCount) { - let result = []; - for (let i = 0, len = cursors.length; i < len; i++) { - const cursor = cursors[i]; - result[i] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveUp(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, linesCount)); - } - return result; - } - static _moveToViewPosition(viewModel, cursor, inSelectionMode, toViewLineNumber, toViewColumn) { - return cursorCommon_1.CursorState.fromViewState(cursor.viewState.move(inSelectionMode, toViewLineNumber, toViewColumn, 0)); - } - static _moveToModelPosition(viewModel, cursor, inSelectionMode, toModelLineNumber, toModelColumn) { - return cursorCommon_1.CursorState.fromModelState(cursor.modelState.move(inSelectionMode, toModelLineNumber, toModelColumn, 0)); - } - static _moveToViewMinColumn(viewModel, cursors, inSelectionMode) { - let result = []; - for (let i = 0, len = cursors.length; i < len; i++) { - const cursor = cursors[i]; - const viewLineNumber = cursor.viewState.position.lineNumber; - const viewColumn = viewModel.getLineMinColumn(viewLineNumber); - result[i] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn); - } - return result; - } - static _moveToViewFirstNonWhitespaceColumn(viewModel, cursors, inSelectionMode) { - let result = []; - for (let i = 0, len = cursors.length; i < len; i++) { - const cursor = cursors[i]; - const viewLineNumber = cursor.viewState.position.lineNumber; - const viewColumn = viewModel.getLineFirstNonWhitespaceColumn(viewLineNumber); - result[i] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn); - } - return result; - } - static _moveToViewCenterColumn(viewModel, cursors, inSelectionMode) { - let result = []; - for (let i = 0, len = cursors.length; i < len; i++) { - const cursor = cursors[i]; - const viewLineNumber = cursor.viewState.position.lineNumber; - const viewColumn = Math.round((viewModel.getLineMaxColumn(viewLineNumber) + viewModel.getLineMinColumn(viewLineNumber)) / 2); - result[i] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn); - } - return result; - } - static _moveToViewMaxColumn(viewModel, cursors, inSelectionMode) { - let result = []; - for (let i = 0, len = cursors.length; i < len; i++) { - const cursor = cursors[i]; - const viewLineNumber = cursor.viewState.position.lineNumber; - const viewColumn = viewModel.getLineMaxColumn(viewLineNumber); - result[i] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn); - } - return result; - } - static _moveToViewLastNonWhitespaceColumn(viewModel, cursors, inSelectionMode) { - let result = []; - for (let i = 0, len = cursors.length; i < len; i++) { - const cursor = cursors[i]; - const viewLineNumber = cursor.viewState.position.lineNumber; - const viewColumn = viewModel.getLineLastNonWhitespaceColumn(viewLineNumber); - result[i] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn); - } - return result; - } - } - exports.CursorMoveCommands = CursorMoveCommands; - var CursorMove; - (function (CursorMove) { - const isCursorMoveArgs = function (arg) { - if (!types.isObject(arg)) { - return false; - } - let 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: - * 'to': A mandatory logical position value providing where to move the cursor. - \`\`\` - 'left', 'right', 'up', 'down', 'prevBlankLine', 'nextBlankLine', - 'wrappedLineStart', 'wrappedLineEnd', 'wrappedLineColumnCenter' - 'wrappedLineFirstNonWhitespaceCharacter', 'wrappedLineLastNonWhitespaceCharacter' - 'viewPortTop', 'viewPortCenter', 'viewPortBottom', 'viewPortIfOutside' - \`\`\` - * 'by': Unit to move. Default is computed based on 'to' value. - \`\`\` - 'line', 'wrappedLine', 'character', 'halfLine' - \`\`\` - * 'value': Number of units to move. Default is '1'. - * 'select': If 'true' makes the selection. Default is 'false'. - `, - constraint: isCursorMoveArgs, - schema: { - 'type': 'object', - 'required': ['to'], - 'properties': { - 'to': { - 'type': 'string', - 'enum': ['left', 'right', 'up', 'down', 'prevBlankLine', 'nextBlankLine', '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', - PrevBlankLine: 'prevBlankLine', - NextBlankLine: 'nextBlankLine', - 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; - } - let 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.PrevBlankLine: - direction = 4 /* PrevBlankLine */; - break; - case CursorMove.RawDirection.NextBlankLine: - direction = 5 /* NextBlankLine */; - break; - case CursorMove.RawDirection.WrappedLineStart: - direction = 6 /* WrappedLineStart */; - break; - case CursorMove.RawDirection.WrappedLineFirstNonWhitespaceCharacter: - direction = 7 /* WrappedLineFirstNonWhitespaceCharacter */; - break; - case CursorMove.RawDirection.WrappedLineColumnCenter: - direction = 8 /* WrappedLineColumnCenter */; - break; - case CursorMove.RawDirection.WrappedLineEnd: - direction = 9 /* WrappedLineEnd */; - break; - case CursorMove.RawDirection.WrappedLineLastNonWhitespaceCharacter: - direction = 10 /* WrappedLineLastNonWhitespaceCharacter */; - break; - case CursorMove.RawDirection.ViewPortTop: - direction = 11 /* ViewPortTop */; - break; - case CursorMove.RawDirection.ViewPortBottom: - direction = 13 /* ViewPortBottom */; - break; - case CursorMove.RawDirection.ViewPortCenter: - direction = 12 /* ViewPortCenter */; - break; - case CursorMove.RawDirection.ViewPortIfOutside: - direction = 14 /* ViewPortIfOutside */; - break; - default: - // illegal arguments - return null; - } - let 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[551/*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*/,21/*vs/editor/common/core/selection*/]), function (require, exports, cursorCommon_1, position_1, range_1, selection_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Cursor = void 0; - /** - * Represents a single cursor. - */ - class Cursor { - constructor(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)); - } - dispose(context) { - this._removeTrackedRange(context); - } - startTrackingSelection(context) { - this._trackSelection = true; - this._updateTrackedRange(context); - } - stopTrackingSelection(context) { - this._trackSelection = false; - this._removeTrackedRange(context); - } - _updateTrackedRange(context) { - if (!this._trackSelection) { - // don't track the selection - return; - } - this._selTrackedRange = context.model._setTrackedRange(this._selTrackedRange, this.modelState.selection, 0 /* AlwaysGrowsWhenTypingAtEdges */); - } - _removeTrackedRange(context) { - this._selTrackedRange = context.model._setTrackedRange(this._selTrackedRange, null, 0 /* AlwaysGrowsWhenTypingAtEdges */); - } - asCursorState() { - return new cursorCommon_1.CursorState(this.modelState, this.viewState); - } - readSelectionFromMarkers(context) { - const 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); - } - ensureValidState(context) { - this._setState(context, this.modelState, this.viewState); - } - setState(context, modelState, viewState) { - this._setState(context, modelState, viewState); - } - static _validatePositionWithCache(viewModel, position, cacheInput, cacheOutput) { - if (position.equals(cacheInput)) { - return cacheOutput; - } - return viewModel.normalizePosition(position, 2 /* None */); - } - static _validateViewState(viewModel, viewState) { - const position = viewState.position; - const sStartPosition = viewState.selectionStart.getStartPosition(); - const sEndPosition = viewState.selectionStart.getEndPosition(); - const validPosition = viewModel.normalizePosition(position, 2 /* None */); - const validSStartPosition = this._validatePositionWithCache(viewModel, sStartPosition, position, validPosition); - const validSEndPosition = this._validatePositionWithCache(viewModel, sEndPosition, sStartPosition, validSStartPosition); - if (position.equals(validPosition) && sStartPosition.equals(validSStartPosition) && sEndPosition.equals(validSEndPosition)) { - // fast path: the state is valid - return viewState; - } - return new cursorCommon_1.SingleCursorState(range_1.Range.fromPositions(validSStartPosition, validSEndPosition), viewState.selectionStartLeftoverVisibleColumns + sStartPosition.column - validSStartPosition.column, validPosition, viewState.leftoverVisibleColumns + position.column - validPosition.column); - } - _setState(context, modelState, viewState) { - if (viewState) { - viewState = Cursor._validateViewState(context.viewModel, viewState); - } - if (!modelState) { - if (!viewState) { - return; - } - // We only have the view state => compute the model state - const selectionStart = context.model.validateRange(context.coordinatesConverter.convertViewRangeToModelRange(viewState.selectionStart)); - const position = context.model.validatePosition(context.coordinatesConverter.convertViewPositionToModelPosition(viewState.position)); - modelState = new cursorCommon_1.SingleCursorState(selectionStart, viewState.selectionStartLeftoverVisibleColumns, position, viewState.leftoverVisibleColumns); - } - else { - // Validate new model state - const selectionStart = context.model.validateRange(modelState.selectionStart); - const selectionStartLeftoverVisibleColumns = modelState.selectionStart.equalsRange(selectionStart) ? modelState.selectionStartLeftoverVisibleColumns : 0; - const position = context.model.validatePosition(modelState.position); - const 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 - const viewSelectionStart1 = context.coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelState.selectionStart.startLineNumber, modelState.selectionStart.startColumn)); - const viewSelectionStart2 = context.coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelState.selectionStart.endLineNumber, modelState.selectionStart.endColumn)); - const viewSelectionStart = new range_1.Range(viewSelectionStart1.lineNumber, viewSelectionStart1.column, viewSelectionStart2.lineNumber, viewSelectionStart2.column); - const viewPosition = context.coordinatesConverter.convertModelPositionToViewPosition(modelState.position); - viewState = new cursorCommon_1.SingleCursorState(viewSelectionStart, modelState.selectionStartLeftoverVisibleColumns, viewPosition, modelState.leftoverVisibleColumns); - } - else { - // Validate new view state - const viewSelectionStart = context.coordinatesConverter.validateViewRange(viewState.selectionStart, modelState.selectionStart); - const viewPosition = context.coordinatesConverter.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); - } - } - exports.Cursor = Cursor; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[552/*vs/editor/common/controller/cursorCollection*/], __M([0/*require*/,1/*exports*/,40/*vs/editor/common/controller/cursorCommon*/,551/*vs/editor/common/controller/oneCursor*/,21/*vs/editor/common/core/selection*/]), function (require, exports, cursorCommon_1, oneCursor_1, selection_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CursorCollection = void 0; - class CursorCollection { - constructor(context) { - this.context = context; - this.primaryCursor = new oneCursor_1.Cursor(context); - this.secondaryCursors = []; - this.lastAddedCursorIndex = 0; - } - dispose() { - this.primaryCursor.dispose(this.context); - this.killSecondaryCursors(); - } - startTrackingSelections() { - this.primaryCursor.startTrackingSelection(this.context); - for (let i = 0, len = this.secondaryCursors.length; i < len; i++) { - this.secondaryCursors[i].startTrackingSelection(this.context); - } - } - stopTrackingSelections() { - this.primaryCursor.stopTrackingSelection(this.context); - for (let i = 0, len = this.secondaryCursors.length; i < len; i++) { - this.secondaryCursors[i].stopTrackingSelection(this.context); - } - } - updateContext(context) { - this.context = context; - } - ensureValidState() { - this.primaryCursor.ensureValidState(this.context); - for (let i = 0, len = this.secondaryCursors.length; i < len; i++) { - this.secondaryCursors[i].ensureValidState(this.context); - } - } - readSelectionFromMarkers() { - let result = []; - result[0] = this.primaryCursor.readSelectionFromMarkers(this.context); - for (let i = 0, len = this.secondaryCursors.length; i < len; i++) { - result[i + 1] = this.secondaryCursors[i].readSelectionFromMarkers(this.context); - } - return result; - } - getAll() { - let result = []; - result[0] = this.primaryCursor.asCursorState(); - for (let i = 0, len = this.secondaryCursors.length; i < len; i++) { - result[i + 1] = this.secondaryCursors[i].asCursorState(); - } - return result; - } - getViewPositions() { - let result = []; - result[0] = this.primaryCursor.viewState.position; - for (let i = 0, len = this.secondaryCursors.length; i < len; i++) { - result[i + 1] = this.secondaryCursors[i].viewState.position; - } - return result; - } - getTopMostViewPosition() { - let result = this.primaryCursor.viewState.position; - for (let i = 0, len = this.secondaryCursors.length; i < len; i++) { - const viewPosition = this.secondaryCursors[i].viewState.position; - if (viewPosition.isBefore(result)) { - result = viewPosition; - } - } - return result; - } - getBottomMostViewPosition() { - let result = this.primaryCursor.viewState.position; - for (let i = 0, len = this.secondaryCursors.length; i < len; i++) { - const viewPosition = this.secondaryCursors[i].viewState.position; - if (result.isBeforeOrEqual(viewPosition)) { - result = viewPosition; - } - } - return result; - } - getSelections() { - let result = []; - result[0] = this.primaryCursor.modelState.selection; - for (let i = 0, len = this.secondaryCursors.length; i < len; i++) { - result[i + 1] = this.secondaryCursors[i].modelState.selection; - } - return result; - } - getViewSelections() { - let result = []; - result[0] = this.primaryCursor.viewState.selection; - for (let i = 0, len = this.secondaryCursors.length; i < len; i++) { - result[i + 1] = this.secondaryCursors[i].viewState.selection; - } - return result; - } - setSelections(selections) { - this.setStates(cursorCommon_1.CursorState.fromModelSelections(selections)); - } - getPrimaryCursor() { - return this.primaryCursor.asCursorState(); - } - setStates(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`. - */ - _setSecondaryStates(secondaryStates) { - const secondaryCursorsLength = this.secondaryCursors.length; - const secondaryStatesLength = secondaryStates.length; - if (secondaryCursorsLength < secondaryStatesLength) { - let createCnt = secondaryStatesLength - secondaryCursorsLength; - for (let i = 0; i < createCnt; i++) { - this._addSecondaryCursor(); - } - } - else if (secondaryCursorsLength > secondaryStatesLength) { - let removeCnt = secondaryCursorsLength - secondaryStatesLength; - for (let i = 0; i < removeCnt; i++) { - this._removeSecondaryCursor(this.secondaryCursors.length - 1); - } - } - for (let i = 0; i < secondaryStatesLength; i++) { - this.secondaryCursors[i].setState(this.context, secondaryStates[i].modelState, secondaryStates[i].viewState); - } - } - killSecondaryCursors() { - this._setSecondaryStates([]); - } - _addSecondaryCursor() { - this.secondaryCursors.push(new oneCursor_1.Cursor(this.context)); - this.lastAddedCursorIndex = this.secondaryCursors.length; - } - getLastAddedCursorIndex() { - if (this.secondaryCursors.length === 0 || this.lastAddedCursorIndex === 0) { - return 0; - } - return this.lastAddedCursorIndex; - } - _removeSecondaryCursor(removeIndex) { - if (this.lastAddedCursorIndex >= removeIndex + 1) { - this.lastAddedCursorIndex--; - } - this.secondaryCursors[removeIndex].dispose(this.context); - this.secondaryCursors.splice(removeIndex, 1); - } - _getAll() { - let result = []; - result[0] = this.primaryCursor; - for (let i = 0, len = this.secondaryCursors.length; i < len; i++) { - result[i + 1] = this.secondaryCursors[i]; - } - return result; - } - normalize() { - if (this.secondaryCursors.length === 0) { - return; - } - let cursors = this._getAll(); - let sortedCursors = []; - for (let i = 0, len = cursors.length; i < len; i++) { - sortedCursors.push({ - index: i, - selection: cursors[i].modelState.selection, - }); - } - sortedCursors.sort((a, b) => { - if (a.selection.startLineNumber === b.selection.startLineNumber) { - return a.selection.startColumn - b.selection.startColumn; - } - return a.selection.startLineNumber - b.selection.startLineNumber; - }); - for (let sortedCursorIndex = 0; sortedCursorIndex < sortedCursors.length - 1; sortedCursorIndex++) { - const current = sortedCursors[sortedCursorIndex]; - const next = sortedCursors[sortedCursorIndex + 1]; - const currentSelection = current.selection; - const nextSelection = next.selection; - if (!this.context.cursorConfig.multiCursorMergeOverlapping) { - continue; - } - let shouldMergeCursors; - 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) { - const winnerSortedCursorIndex = current.index < next.index ? sortedCursorIndex : sortedCursorIndex + 1; - const looserSortedCursorIndex = current.index < next.index ? sortedCursorIndex + 1 : sortedCursorIndex; - const looserIndex = sortedCursors[looserSortedCursorIndex].index; - const winnerIndex = sortedCursors[winnerSortedCursorIndex].index; - const looserSelection = sortedCursors[looserSortedCursorIndex].selection; - const winnerSelection = sortedCursors[winnerSortedCursorIndex].selection; - if (!looserSelection.equalsSelection(winnerSelection)) { - const resultingRange = looserSelection.plusRange(winnerSelection); - const looserSelectionIsLTR = (looserSelection.selectionStartLineNumber === looserSelection.startLineNumber && looserSelection.selectionStartColumn === looserSelection.startColumn); - const winnerSelectionIsLTR = (winnerSelection.selectionStartLineNumber === winnerSelection.startLineNumber && winnerSelection.selectionStartColumn === winnerSelection.startColumn); - // Give more importance to the last added cursor (think Ctrl-dragging + hitting another cursor) - let resultingSelectionIsLTR; - if (looserIndex === this.lastAddedCursorIndex) { - resultingSelectionIsLTR = looserSelectionIsLTR; - this.lastAddedCursorIndex = winnerIndex; - } - else { - // Winner takes it all - resultingSelectionIsLTR = winnerSelectionIsLTR; - } - let resultingSelection; - 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; - const resultingState = cursorCommon_1.CursorState.fromModelSelection(resultingSelection); - cursors[winnerIndex].setState(this.context, resultingState.modelState, resultingState.viewState); - } - for (const sortedCursor of sortedCursors) { - if (sortedCursor.index > looserIndex) { - sortedCursor.index--; - } - } - cursors.splice(looserIndex, 1); - sortedCursors.splice(looserSortedCursorIndex, 1); - this._removeSecondaryCursor(looserIndex - 1); - sortedCursorIndex--; - } - } - } - } - 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[245/*vs/editor/common/controller/cursor*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,8/*vs/base/common/strings*/,552/*vs/editor/common/controller/cursorCollection*/,40/*vs/editor/common/controller/cursorCommon*/,186/*vs/editor/common/controller/cursorDeleteOperations*/,187/*vs/editor/common/controller/cursorTypeOperations*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,96/*vs/editor/common/model/textModelEvents*/,175/*vs/editor/common/view/viewEvents*/,2/*vs/base/common/lifecycle*/,177/*vs/editor/common/viewModel/viewModelEventDispatcher*/]), function (require, exports, errors_1, strings, cursorCollection_1, cursorCommon_1, cursorDeleteOperations_1, cursorTypeOperations_1, range_1, selection_1, textModelEvents_1, viewEvents_1, lifecycle_1, viewModelEventDispatcher_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CursorsController = exports.CursorModelState = void 0; - /** - * A snapshot of the cursor and the model state - */ - class CursorModelState { - constructor(model, cursor) { - this.modelVersionId = model.getVersionId(); - this.cursorState = cursor.getCursorStates(); - } - equals(other) { - if (!other) { - return false; - } - if (this.modelVersionId !== other.modelVersionId) { - return false; - } - if (this.cursorState.length !== other.cursorState.length) { - return false; - } - for (let i = 0, len = this.cursorState.length; i < len; i++) { - if (!this.cursorState[i].equals(other.cursorState[i])) { - return false; - } - } - return true; - } - } - exports.CursorModelState = CursorModelState; - class AutoClosedAction { - constructor(model, autoClosedCharactersDecorations, autoClosedEnclosingDecorations) { - this._model = model; - this._autoClosedCharactersDecorations = autoClosedCharactersDecorations; - this._autoClosedEnclosingDecorations = autoClosedEnclosingDecorations; - } - static getAllAutoClosedCharacters(autoClosedActions) { - let autoClosedCharacters = []; - for (const autoClosedAction of autoClosedActions) { - autoClosedCharacters = autoClosedCharacters.concat(autoClosedAction.getAutoClosedCharactersRanges()); - } - return autoClosedCharacters; - } - dispose() { - this._autoClosedCharactersDecorations = this._model.deltaDecorations(this._autoClosedCharactersDecorations, []); - this._autoClosedEnclosingDecorations = this._model.deltaDecorations(this._autoClosedEnclosingDecorations, []); - } - getAutoClosedCharactersRanges() { - let result = []; - for (let i = 0; i < this._autoClosedCharactersDecorations.length; i++) { - const decorationRange = this._model.getDecorationRange(this._autoClosedCharactersDecorations[i]); - if (decorationRange) { - result.push(decorationRange); - } - } - return result; - } - isValid(selections) { - let enclosingRanges = []; - for (let i = 0; i < this._autoClosedEnclosingDecorations.length; i++) { - const 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 (let i = 0; i < selections.length; i++) { - if (i >= enclosingRanges.length) { - return false; - } - if (!enclosingRanges[i].strictContainsRange(selections[i])) { - return false; - } - } - return true; - } - } - class CursorsController extends lifecycle_1.Disposable { - constructor(model, viewModel, coordinatesConverter, cursorConfig) { - super(); - this._model = model; - this._knownModelVersionId = this._model.getVersionId(); - this._viewModel = viewModel; - this._coordinatesConverter = coordinatesConverter; - this.context = new cursorCommon_1.CursorContext(this._model, this._viewModel, this._coordinatesConverter, cursorConfig); - this._cursors = new cursorCollection_1.CursorCollection(this.context); - this._hasFocus = false; - this._isHandling = false; - this._isDoingComposition = false; - this._selectionsWhenCompositionStarted = null; - this._columnSelectData = null; - this._autoClosedActions = []; - this._prevEditOperationType = 0 /* Other */; - } - dispose() { - this._cursors.dispose(); - this._autoClosedActions = (0, lifecycle_1.dispose)(this._autoClosedActions); - super.dispose(); - } - updateConfiguration(cursorConfig) { - this.context = new cursorCommon_1.CursorContext(this._model, this._viewModel, this._coordinatesConverter, cursorConfig); - this._cursors.updateContext(this.context); - } - onLineMappingChanged(eventsCollector) { - 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(eventsCollector, 'viewModel', 0 /* NotSet */, this.getCursorStates()); - } - setHasFocus(hasFocus) { - this._hasFocus = hasFocus; - } - _validateAutoClosedActions() { - if (this._autoClosedActions.length > 0) { - let selections = this._cursors.getSelections(); - for (let i = 0; i < this._autoClosedActions.length; i++) { - const autoClosedAction = this._autoClosedActions[i]; - if (!autoClosedAction.isValid(selections)) { - autoClosedAction.dispose(); - this._autoClosedActions.splice(i, 1); - i--; - } - } - } - } - // ------ some getters/setters - getPrimaryCursorState() { - return this._cursors.getPrimaryCursor(); - } - getLastAddedCursorIndex() { - return this._cursors.getLastAddedCursorIndex(); - } - getCursorStates() { - return this._cursors.getAll(); - } - setStates(eventsCollector, source, reason, states) { - let reachedMaxCursorCount = false; - if (states !== null && states.length > CursorsController.MAX_CURSOR_COUNT) { - states = states.slice(0, CursorsController.MAX_CURSOR_COUNT); - reachedMaxCursorCount = true; - } - const oldState = new CursorModelState(this._model, this); - this._cursors.setStates(states); - this._cursors.normalize(); - this._columnSelectData = null; - this._validateAutoClosedActions(); - return this._emitStateChangedIfNecessary(eventsCollector, source, reason, oldState, reachedMaxCursorCount); - } - setCursorColumnSelectData(columnSelectData) { - this._columnSelectData = columnSelectData; - } - revealPrimary(eventsCollector, source, revealHorizontal, scrollType) { - const viewPositions = this._cursors.getViewPositions(); - if (viewPositions.length > 1) { - this._emitCursorRevealRange(eventsCollector, source, null, this._cursors.getViewSelections(), 0 /* Simple */, revealHorizontal, scrollType); - return; - } - else { - const viewPosition = viewPositions[0]; - const viewRange = new range_1.Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column); - this._emitCursorRevealRange(eventsCollector, source, viewRange, null, 0 /* Simple */, revealHorizontal, scrollType); - } - } - _revealPrimaryCursor(eventsCollector, source, verticalType, revealHorizontal, scrollType) { - const viewPositions = this._cursors.getViewPositions(); - if (viewPositions.length > 1) { - this._emitCursorRevealRange(eventsCollector, source, null, this._cursors.getViewSelections(), verticalType, revealHorizontal, scrollType); - } - else { - const viewPosition = viewPositions[0]; - const viewRange = new range_1.Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column); - this._emitCursorRevealRange(eventsCollector, source, viewRange, null, verticalType, revealHorizontal, scrollType); - } - } - _emitCursorRevealRange(eventsCollector, source, viewRange, viewSelections, verticalType, revealHorizontal, scrollType) { - eventsCollector.emitViewEvent(new viewEvents_1.ViewRevealRangeRequestEvent(source, viewRange, viewSelections, verticalType, revealHorizontal, scrollType)); - } - saveState() { - let result = []; - const selections = this._cursors.getSelections(); - for (let i = 0, len = selections.length; i < len; i++) { - const selection = selections[i]; - result.push({ - inSelectionMode: !selection.isEmpty(), - selectionStart: { - lineNumber: selection.selectionStartLineNumber, - column: selection.selectionStartColumn, - }, - position: { - lineNumber: selection.positionLineNumber, - column: selection.positionColumn, - } - }); - } - return result; - } - restoreState(eventsCollector, states) { - let desiredSelections = []; - for (let i = 0, len = states.length; i < len; i++) { - const state = states[i]; - let positionLineNumber = 1; - let 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; - } - let selectionStartLineNumber = positionLineNumber; - let 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(eventsCollector, 'restoreState', 0 /* NotSet */, cursorCommon_1.CursorState.fromModelSelections(desiredSelections)); - this.revealPrimary(eventsCollector, 'restoreState', true, 1 /* Immediate */); - } - onModelContentChanged(eventsCollector, e) { - if (e instanceof textModelEvents_1.ModelInjectedTextChangedEvent) { - // If injected texts change, the view positions of all cursors need to be updated. - const selectionsFromMarkers = this._cursors.readSelectionFromMarkers(); - this.setStates(eventsCollector, 'modelChange', 2 /* RecoverFromMarkers */, cursorCommon_1.CursorState.fromModelSelections(selectionsFromMarkers)); - } - else { - this._knownModelVersionId = e.versionId; - if (this._isHandling) { - return; - } - const hadFlushEvent = e.containsEvent(1 /* Flush */); - 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(eventsCollector, 'model', 1 /* ContentFlush */, null, false); - } - else { - if (this._hasFocus && e.resultingSelection && e.resultingSelection.length > 0) { - const cursorState = cursorCommon_1.CursorState.fromModelSelections(e.resultingSelection); - if (this.setStates(eventsCollector, 'modelChange', e.isUndoing ? 5 /* Undo */ : e.isRedoing ? 6 /* Redo */ : 2 /* RecoverFromMarkers */, cursorState)) { - this._revealPrimaryCursor(eventsCollector, 'modelChange', 0 /* Simple */, true, 0 /* Smooth */); - } - } - else { - const selectionsFromMarkers = this._cursors.readSelectionFromMarkers(); - this.setStates(eventsCollector, 'modelChange', 2 /* RecoverFromMarkers */, cursorCommon_1.CursorState.fromModelSelections(selectionsFromMarkers)); - } - } - } - } - getSelection() { - return this._cursors.getPrimaryCursor().modelState.selection; - } - getTopMostViewPosition() { - return this._cursors.getTopMostViewPosition(); - } - getBottomMostViewPosition() { - return this._cursors.getBottomMostViewPosition(); - } - getCursorColumnSelectData() { - if (this._columnSelectData) { - return this._columnSelectData; - } - const primaryCursor = this._cursors.getPrimaryCursor(); - const viewSelectionStart = primaryCursor.viewState.selectionStart.getStartPosition(); - const viewPosition = primaryCursor.viewState.position; - return { - isReal: false, - fromViewLineNumber: viewSelectionStart.lineNumber, - fromViewVisualColumn: cursorCommon_1.CursorColumns.visibleColumnFromColumn2(this.context.cursorConfig, this._viewModel, viewSelectionStart), - toViewLineNumber: viewPosition.lineNumber, - toViewVisualColumn: cursorCommon_1.CursorColumns.visibleColumnFromColumn2(this.context.cursorConfig, this._viewModel, viewPosition), - }; - } - getSelections() { - return this._cursors.getSelections(); - } - setSelections(eventsCollector, source, selections, reason) { - this.setStates(eventsCollector, source, reason, cursorCommon_1.CursorState.fromModelSelections(selections)); - } - getPrevEditOperationType() { - return this._prevEditOperationType; - } - setPrevEditOperationType(type) { - this._prevEditOperationType = type; - } - // ------ auxiliary handling logic - _pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges) { - let autoClosedCharactersDeltaDecorations = []; - let autoClosedEnclosingDeltaDecorations = []; - for (let i = 0, len = autoClosedCharactersRanges.length; i < len; i++) { - autoClosedCharactersDeltaDecorations.push({ - range: autoClosedCharactersRanges[i], - options: { - description: 'auto-closed-character', - inlineClassName: 'auto-closed-character', - stickiness: 1 /* NeverGrowsWhenTypingAtEdges */ - } - }); - autoClosedEnclosingDeltaDecorations.push({ - range: autoClosedEnclosingRanges[i], - options: { - description: 'auto-closed-enclosing', - stickiness: 1 /* NeverGrowsWhenTypingAtEdges */ - } - }); - } - const autoClosedCharactersDecorations = this._model.deltaDecorations([], autoClosedCharactersDeltaDecorations); - const autoClosedEnclosingDecorations = this._model.deltaDecorations([], autoClosedEnclosingDeltaDecorations); - this._autoClosedActions.push(new AutoClosedAction(this._model, autoClosedCharactersDecorations, autoClosedEnclosingDecorations)); - } - _executeEditOperation(opResult) { - if (!opResult) { - // Nothing to execute - return; - } - if (opResult.shouldPushStackElementBefore) { - this._model.pushStackElement(); - } - const 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 - let autoClosedCharactersRanges = []; - let autoClosedEnclosingRanges = []; - for (let i = 0; i < opResult.commands.length; i++) { - const 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(); - } - } - _interpretCommandResult(cursorState) { - if (!cursorState || cursorState.length === 0) { - cursorState = this._cursors.readSelectionFromMarkers(); - } - this._columnSelectData = null; - this._cursors.setSelections(cursorState); - this._cursors.normalize(); - } - // ----------------------------------------------------------------------------------------------------------- - // ----- emitting events - _emitStateChangedIfNecessary(eventsCollector, source, reason, oldState, reachedMaxCursorCount) { - const newState = new CursorModelState(this._model, this); - if (newState.equals(oldState)) { - return false; - } - const selections = this._cursors.getSelections(); - const viewSelections = this._cursors.getViewSelections(); - // Let the view get the event first. - eventsCollector.emitViewEvent(new viewEvents_1.ViewCursorStateChangedEvent(viewSelections, selections)); - // 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((newCursorState, i) => !newCursorState.modelState.equals(oldState.cursorState[i].modelState))) { - const oldSelections = oldState ? oldState.cursorState.map(s => s.modelState.selection) : null; - const oldModelVersionId = oldState ? oldState.modelVersionId : 0; - eventsCollector.emitOutgoingEvent(new viewModelEventDispatcher_1.CursorStateChangedEvent(oldSelections, selections, oldModelVersionId, newState.modelVersionId, source || 'keyboard', reason, reachedMaxCursorCount)); - } - return true; - } - // ----------------------------------------------------------------------------------------------------------- - // ----- handlers beyond this point - _findAutoClosingPairs(edits) { - if (!edits.length) { - return null; - } - let indices = []; - for (let i = 0, len = edits.length; i < len; i++) { - const edit = edits[i]; - if (!edit.text || edit.text.indexOf('\n') >= 0) { - return null; - } - const m = edit.text.match(/([)\]}>'"`])([^)\]}>'"`]*)$/); - if (!m) { - return null; - } - const closeChar = m[1]; - const autoClosingPairsCandidates = this.context.cursorConfig.autoClosingPairs.autoClosingPairsCloseSingleChar.get(closeChar); - if (!autoClosingPairsCandidates || autoClosingPairsCandidates.length !== 1) { - return null; - } - const openChar = autoClosingPairsCandidates[0].open; - const closeCharIndex = edit.text.length - m[2].length - 1; - const openCharIndex = edit.text.lastIndexOf(openChar, closeCharIndex - 1); - if (openCharIndex === -1) { - return null; - } - indices.push([openCharIndex, closeCharIndex]); - } - return indices; - } - executeEdits(eventsCollector, source, edits, cursorStateComputer) { - let autoClosingIndices = null; - if (source === 'snippet') { - autoClosingIndices = this._findAutoClosingPairs(edits); - } - if (autoClosingIndices) { - edits[0]._isTracked = true; - } - let autoClosedCharactersRanges = []; - let autoClosedEnclosingRanges = []; - const selections = this._model.pushEditOperations(this.getSelections(), edits, (undoEdits) => { - if (autoClosingIndices) { - for (let i = 0, len = autoClosingIndices.length; i < len; i++) { - const [openCharInnerIndex, closeCharInnerIndex] = autoClosingIndices[i]; - const undoEdit = undoEdits[i]; - const lineNumber = undoEdit.range.startLineNumber; - const openCharIndex = undoEdit.range.startColumn - 1 + openCharInnerIndex; - const 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)); - } - } - const 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(eventsCollector, source, selections, 0 /* NotSet */); - } - if (autoClosedCharactersRanges.length > 0) { - this._pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges); - } - } - _executeEdit(callback, eventsCollector, source, cursorChangeReason = 0 /* NotSet */) { - if (this.context.cursorConfig.readOnly) { - // we cannot edit when read only... - return; - } - const oldState = new CursorModelState(this._model, this); - this._cursors.stopTrackingSelections(); - this._isHandling = true; - try { - this._cursors.ensureValidState(); - callback(); - } - catch (err) { - (0, errors_1.onUnexpectedError)(err); - } - this._isHandling = false; - this._cursors.startTrackingSelections(); - this._validateAutoClosedActions(); - if (this._emitStateChangedIfNecessary(eventsCollector, source, cursorChangeReason, oldState, false)) { - this._revealPrimaryCursor(eventsCollector, source, 0 /* Simple */, true, 0 /* Smooth */); - } - } - setIsDoingComposition(isDoingComposition) { - this._isDoingComposition = isDoingComposition; - } - getAutoClosedCharacters() { - return AutoClosedAction.getAllAutoClosedCharacters(this._autoClosedActions); - } - startComposition(eventsCollector) { - this._selectionsWhenCompositionStarted = this.getSelections().slice(0); - } - endComposition(eventsCollector, source) { - this._executeEdit(() => { - if (source === 'keyboard') { - // composition finishes, let's check if we need to auto complete if necessary. - this._executeEditOperation(cursorTypeOperations_1.TypeOperations.compositionEndWithInterceptors(this._prevEditOperationType, this.context.cursorConfig, this._model, this._selectionsWhenCompositionStarted, this.getSelections(), this.getAutoClosedCharacters())); - this._selectionsWhenCompositionStarted = null; - } - }, eventsCollector, source); - } - type(eventsCollector, text, source) { - this._executeEdit(() => { - if (source === 'keyboard') { - // If this event is coming straight from the keyboard, look for electric characters and enter - const len = text.length; - let offset = 0; - while (offset < len) { - const charLength = strings.nextCharLength(text, offset); - const chr = text.substr(offset, charLength); - // Here we must interpret each typed character individually - this._executeEditOperation(cursorTypeOperations_1.TypeOperations.typeWithInterceptors(this._isDoingComposition, this._prevEditOperationType, this.context.cursorConfig, this._model, this.getSelections(), this.getAutoClosedCharacters(), chr)); - offset += charLength; - } - } - else { - this._executeEditOperation(cursorTypeOperations_1.TypeOperations.typeWithoutInterceptors(this._prevEditOperationType, this.context.cursorConfig, this._model, this.getSelections(), text)); - } - }, eventsCollector, source); - } - compositionType(eventsCollector, text, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source) { - if (text.length === 0 && replacePrevCharCnt === 0 && replaceNextCharCnt === 0) { - // this edit is a no-op - if (positionDelta !== 0) { - // but it still wants to move the cursor - const newSelections = this.getSelections().map(selection => { - const position = selection.getPosition(); - return new selection_1.Selection(position.lineNumber, position.column + positionDelta, position.lineNumber, position.column + positionDelta); - }); - this.setSelections(eventsCollector, source, newSelections, 0 /* NotSet */); - } - return; - } - this._executeEdit(() => { - this._executeEditOperation(cursorTypeOperations_1.TypeOperations.compositionType(this._prevEditOperationType, this.context.cursorConfig, this._model, this.getSelections(), text, replacePrevCharCnt, replaceNextCharCnt, positionDelta)); - }, eventsCollector, source); - } - paste(eventsCollector, text, pasteOnNewLine, multicursorText, source) { - this._executeEdit(() => { - this._executeEditOperation(cursorTypeOperations_1.TypeOperations.paste(this.context.cursorConfig, this._model, this.getSelections(), text, pasteOnNewLine, multicursorText || [])); - }, eventsCollector, source, 4 /* Paste */); - } - cut(eventsCollector, source) { - this._executeEdit(() => { - this._executeEditOperation(cursorDeleteOperations_1.DeleteOperations.cut(this.context.cursorConfig, this._model, this.getSelections())); - }, eventsCollector, source); - } - executeCommand(eventsCollector, command, source) { - this._executeEdit(() => { - this._cursors.killSecondaryCursors(); - this._executeEditOperation(new cursorCommon_1.EditOperationResult(0 /* Other */, [command], { - shouldPushStackElementBefore: false, - shouldPushStackElementAfter: false - })); - }, eventsCollector, source); - } - executeCommands(eventsCollector, commands, source) { - this._executeEdit(() => { - this._executeEditOperation(new cursorCommon_1.EditOperationResult(0 /* Other */, commands, { - shouldPushStackElementBefore: false, - shouldPushStackElementAfter: false - })); - }, eventsCollector, source); - } - } - exports.CursorsController = CursorsController; - CursorsController.MAX_CURSOR_COUNT = 10000; - class CommandExecutor { - static executeCommands(model, selectionsBefore, commands) { - const ctx = { - model: model, - selectionsBefore: selectionsBefore, - trackedRanges: [], - trackedRangesDirection: [] - }; - const result = this._innerExecuteCommands(ctx, commands); - for (let i = 0, len = ctx.trackedRanges.length; i < len; i++) { - ctx.model._setTrackedRange(ctx.trackedRanges[i], null, 0 /* AlwaysGrowsWhenTypingAtEdges */); - } - return result; - } - static _innerExecuteCommands(ctx, commands) { - if (this._arrayIsEmpty(commands)) { - return null; - } - const commandsData = this._getEditOperations(ctx, commands); - if (commandsData.operations.length === 0) { - return null; - } - const rawOperations = commandsData.operations; - const 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 - let filteredOperations = []; - for (let 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; - } - let selectionsAfter = ctx.model.pushEditOperations(ctx.selectionsBefore, filteredOperations, (inverseEditOperations) => { - let groupedInverseEditOperations = []; - for (let i = 0; i < ctx.selectionsBefore.length; i++) { - groupedInverseEditOperations[i] = []; - } - for (const op of inverseEditOperations) { - if (!op.identifier) { - // perhaps auto whitespace trim edits - continue; - } - groupedInverseEditOperations[op.identifier.major].push(op); - } - const minorBasedSorter = (a, b) => { - return a.identifier.minor - b.identifier.minor; - }; - let cursorSelections = []; - for (let i = 0; i < ctx.selectionsBefore.length; i++) { - if (groupedInverseEditOperations[i].length > 0) { - groupedInverseEditOperations[i].sort(minorBasedSorter); - cursorSelections[i] = commands[i].computeCursorState(ctx.model, { - getInverseEditOperations: () => { - return groupedInverseEditOperations[i]; - }, - getTrackedSelection: (id) => { - const idx = parseInt(id, 10); - const 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]; - } - } - return cursorSelections; - }); - if (!selectionsAfter) { - selectionsAfter = ctx.selectionsBefore; - } - // Extract losing cursors - let losingCursors = []; - for (let losingCursorIndex in loserCursorsMap) { - if (loserCursorsMap.hasOwnProperty(losingCursorIndex)) { - losingCursors.push(parseInt(losingCursorIndex, 10)); - } - } - // Sort losing cursors descending - losingCursors.sort((a, b) => { - return b - a; - }); - // Remove losing cursors - for (const losingCursor of losingCursors) { - selectionsAfter.splice(losingCursor, 1); - } - return selectionsAfter; - } - static _arrayIsEmpty(commands) { - for (let i = 0, len = commands.length; i < len; i++) { - if (commands[i]) { - return false; - } - } - return true; - } - static _getEditOperations(ctx, commands) { - let operations = []; - let hadTrackedEditOperation = false; - for (let i = 0, len = commands.length; i < len; i++) { - const command = commands[i]; - if (command) { - const r = this._getEditOperationsFromCommand(ctx, i, command); - operations = operations.concat(r.operations); - hadTrackedEditOperation = hadTrackedEditOperation || r.hadTrackedEditOperation; - } - } - return { - operations: operations, - hadTrackedEditOperation: hadTrackedEditOperation - }; - } - static _getEditOperationsFromCommand(ctx, majorIdentifier, command) { - // This method acts as a transaction, if the command fails - // everything it has done is ignored - let operations = []; - let operationMinor = 0; - const addEditOperation = (range, text, forceMoveMarkers = false) => { - if (range_1.Range.isEmpty(range) && text === '') { - // This command wants to add a no-op => no thank you - return; - } - operations.push({ - identifier: { - major: majorIdentifier, - minor: operationMinor++ - }, - range: range, - text: text, - forceMoveMarkers: forceMoveMarkers, - isAutoWhitespaceEdit: command.insertsAutoWhitespace - }); - }; - let hadTrackedEditOperation = false; - const addTrackedEditOperation = (selection, text, forceMoveMarkers) => { - hadTrackedEditOperation = true; - addEditOperation(selection, text, forceMoveMarkers); - }; - const trackSelection = (_selection, trackPreviousOnEmpty) => { - const selection = selection_1.Selection.liftSelection(_selection); - let 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 - const maxLineColumn = ctx.model.getLineMaxColumn(selection.startLineNumber); - if (selection.startColumn === maxLineColumn) { - stickiness = 2 /* GrowsOnlyWhenTypingBefore */; - } - else { - stickiness = 3 /* GrowsOnlyWhenTypingAfter */; - } - } - } - else { - stickiness = 1 /* NeverGrowsWhenTypingAtEdges */; - } - const l = ctx.trackedRanges.length; - const id = ctx.model._setTrackedRange(null, selection, stickiness); - ctx.trackedRanges[l] = id; - ctx.trackedRangesDirection[l] = selection.getDirection(); - return l.toString(); - }; - const 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."); - (0, errors_1.onUnexpectedError)(e); - return { - operations: [], - hadTrackedEditOperation: false - }; - } - return { - operations: operations, - hadTrackedEditOperation: hadTrackedEditOperation - }; - } - static _getLoserCursorMap(operations) { - // This is destructive on the array - operations = operations.slice(0); - // Sort operations with last one first - operations.sort((a, b) => { - // Note the minus! - return -(range_1.Range.compareRangesUsingEnds(a.range, b.range)); - }); - // Operations can not overlap! - let loserCursorsMap = {}; - for (let i = 1; i < operations.length; i++) { - const previousOp = operations[i - 1]; - const currentOp = operations[i]; - if (range_1.Range.getStartPosition(previousOp.range).isBefore(range_1.Range.getEndPosition(currentOp.range))) { - let loserMajor; - 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 (let 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; - } - } -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[246/*vs/editor/common/modes/textToHtmlTokenizer*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,85/*vs/editor/common/core/lineTokens*/,77/*vs/editor/common/modes/nullMode*/]), function (require, exports, strings, lineTokens_1, nullMode_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.tokenizeLineToHTML = exports.tokenizeToString = void 0; - const fallback = { - getInitialState: () => nullMode_1.NULL_STATE, - tokenize2: (buffer, hasEOL, state, deltaOffset) => (0, nullMode_1.nullTokenize2)(0 /* Null */, buffer, state, deltaOffset) - }; - function tokenizeToString(text, tokenizationSupport = fallback) { - return _tokenizeToString(text, tokenizationSupport || fallback); - } - exports.tokenizeToString = tokenizeToString; - function tokenizeLineToHTML(text, viewLineTokens, colorMap, startOffset, endOffset, tabSize, useNbsp) { - let result = `
    `; - let charIndex = startOffset; - let tabsCharDelta = 0; - for (let tokenIndex = 0, tokenCount = viewLineTokens.getCount(); tokenIndex < tokenCount; tokenIndex++) { - const tokenEndIndex = viewLineTokens.getEndOffset(tokenIndex); - if (tokenEndIndex <= startOffset) { - continue; - } - let partContent = ''; - for (; charIndex < tokenEndIndex && charIndex < endOffset; charIndex++) { - const charCode = text.charCodeAt(charIndex); - switch (charCode) { - case 9 /* Tab */: - let 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 */: - case 8233 /* PARAGRAPH_SEPARATOR */: - case 133 /* NEXT_LINE */: - 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) { - let result = `
    `; - let lines = strings.splitLines(text); - let currentState = tokenizationSupport.getInitialState(); - for (let i = 0, len = lines.length; i < len; i++) { - let line = lines[i]; - if (i > 0) { - result += `
    `; - } - let tokenizationResult = tokenizationSupport.tokenize2(line, true, currentState, 0); - lineTokens_1.LineTokens.convertToEndOffset(tokenizationResult.tokens, line.length); - let lineTokens = new lineTokens_1.LineTokens(tokenizationResult.tokens, line); - let viewLineTokens = lineTokens.inflate(); - let startOffset = 0; - for (let j = 0, lenJ = viewLineTokens.getCount(); j < lenJ; j++) { - const type = viewLineTokens.getClassName(j); - const 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[68/*vs/editor/common/services/resolverService*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ITextModelService = void 0; - exports.ITextModelService = (0, instantiation_1.createDecorator)('textModelService'); -}); - -define(__m[142/*vs/editor/common/services/textResourceConfigurationService*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ITextResourcePropertiesService = exports.ITextResourceConfigurationService = void 0; - exports.ITextResourceConfigurationService = (0, instantiation_1.createDecorator)('textResourceConfigurationService'); - exports.ITextResourcePropertiesService = (0, 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[247/*vs/editor/common/viewModel/minimapTokensColorTracker*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,218/*vs/editor/common/core/rgba*/,18/*vs/editor/common/modes*/]), function (require, exports, event_1, lifecycle_1, rgba_1, modes_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MinimapTokensColorTracker = void 0; - class MinimapTokensColorTracker extends lifecycle_1.Disposable { - constructor() { - super(); - this._onDidChange = new event_1.Emitter(); - this.onDidChange = this._onDidChange.event; - this._updateColorMap(); - this._register(modes_1.TokenizationRegistry.onDidChange(e => { - if (e.changedColorMap) { - this._updateColorMap(); - } - })); - } - static getInstance() { - if (!this._INSTANCE) { - this._INSTANCE = (0, lifecycle_1.markAsSingleton)(new MinimapTokensColorTracker()); - } - return this._INSTANCE; - } - _updateColorMap() { - const colorMap = modes_1.TokenizationRegistry.getColorMap(); - if (!colorMap) { - this._colors = [rgba_1.RGBA8.Empty]; - this._backgroundIsLight = true; - return; - } - this._colors = [rgba_1.RGBA8.Empty]; - for (let colorId = 1; colorId < colorMap.length; colorId++) { - const 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)); - } - let backgroundLuminosity = colorMap[2 /* DefaultBackground */].getRelativeLuminance(); - this._backgroundIsLight = backgroundLuminosity >= 0.5; - this._onDidChange.fire(undefined); - } - getColor(colorId) { - if (colorId < 1 || colorId >= this._colors.length) { - // background color (basically invisible) - colorId = 2 /* DefaultBackground */; - } - return this._colors[colorId]; - } - backgroundIsLight() { - return this._backgroundIsLight; - } - } - exports.MinimapTokensColorTracker = MinimapTokensColorTracker; - MinimapTokensColorTracker._INSTANCE = 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[553/*vs/editor/common/viewModel/splitLinesCollection*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,85/*vs/editor/common/core/lineTokens*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,31/*vs/editor/common/model/textModel*/,175/*vs/editor/common/view/viewEvents*/,224/*vs/editor/common/viewModel/prefixSumComputer*/,62/*vs/editor/common/viewModel/viewModel*/,96/*vs/editor/common/model/textModelEvents*/]), function (require, exports, arrays, lineTokens_1, position_1, range_1, textModel_1, viewEvents, prefixSumComputer_1, viewModel_1, textModelEvents_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.IdentityLinesCollection = exports.IdentityCoordinatesConverter = exports.SplitLine = exports.SplitLinesCollection = exports.CoordinatesConverter = void 0; - class CoordinatesConverter { - constructor(lines) { - this._lines = lines; - } - // View -> Model conversion and related methods - convertViewPositionToModelPosition(viewPosition) { - return this._lines.convertViewPositionToModelPosition(viewPosition.lineNumber, viewPosition.column); - } - convertViewRangeToModelRange(viewRange) { - return this._lines.convertViewRangeToModelRange(viewRange); - } - validateViewPosition(viewPosition, expectedModelPosition) { - return this._lines.validateViewPosition(viewPosition.lineNumber, viewPosition.column, expectedModelPosition); - } - validateViewRange(viewRange, expectedModelRange) { - return this._lines.validateViewRange(viewRange, expectedModelRange); - } - // Model -> View conversion and related methods - convertModelPositionToViewPosition(modelPosition, affinity) { - return this._lines.convertModelPositionToViewPosition(modelPosition.lineNumber, modelPosition.column, affinity); - } - convertModelRangeToViewRange(modelRange, affinity) { - return this._lines.convertModelRangeToViewRange(modelRange, affinity); - } - modelPositionIsVisible(modelPosition) { - return this._lines.modelPositionIsVisible(modelPosition.lineNumber, modelPosition.column); - } - getModelLineViewLineCount(modelLineNumber) { - return this._lines.getModelLineViewLineCount(modelLineNumber); - } - } - exports.CoordinatesConverter = CoordinatesConverter; - class LineNumberMapper { - constructor(viewLineCounts) { - this._counts = viewLineCounts; - this._isValid = false; - this._validEndIndex = -1; - this._modelToView = []; - this._viewToModel = []; - } - _invalidate(index) { - this._isValid = false; - this._validEndIndex = Math.min(this._validEndIndex, index - 1); - } - _ensureValid() { - if (this._isValid) { - return; - } - for (let i = this._validEndIndex + 1, len = this._counts.length; i < len; i++) { - const viewLineCount = this._counts[i]; - const viewLinesAbove = (i > 0 ? this._modelToView[i - 1] : 0); - this._modelToView[i] = viewLinesAbove + viewLineCount; - for (let 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; - } - changeValue(index, value) { - if (this._counts[index] === value) { - // no change - return; - } - this._counts[index] = value; - this._invalidate(index); - } - removeValues(start, deleteCount) { - this._counts.splice(start, deleteCount); - this._invalidate(start); - } - insertValues(insertIndex, insertArr) { - this._counts = arrays.arrayInsert(this._counts, insertIndex, insertArr); - this._invalidate(insertIndex); - } - getTotalValue() { - this._ensureValid(); - return this._viewToModel.length; - } - getAccumulatedValue(index) { - this._ensureValid(); - return this._modelToView[index]; - } - getIndexOf(accumulatedValue) { - this._ensureValid(); - const modelLineIndex = this._viewToModel[accumulatedValue]; - const viewLinesAbove = (modelLineIndex > 0 ? this._modelToView[modelLineIndex - 1] : 0); - return new prefixSumComputer_1.PrefixSumIndexOfResult(modelLineIndex, accumulatedValue - viewLinesAbove); - } - } - class SplitLinesCollection { - constructor(editorId, model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, tabSize, wrappingStrategy, wrappingColumn, wrappingIndent) { - this._editorId = editorId; - 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); - } - dispose() { - this.hiddenAreasIds = this.model.deltaDecorations(this.hiddenAreasIds, []); - } - createCoordinatesConverter() { - return new CoordinatesConverter(this); - } - _constructLines(resetHiddenAreas, previousLineBreaks) { - this.lines = []; - if (resetHiddenAreas) { - this.hiddenAreasIds = []; - } - const linesContent = this.model.getLinesContent(); - const injectedTextDecorations = this.model.getInjectedTextDecorations(this._editorId); - const injectedText = textModelEvents_1.LineInjectedText.fromDecorations(injectedTextDecorations); - const lineCount = linesContent.length; - const lineBreaksComputer = this.createLineBreaksComputer(); - const injectedTextLength = injectedText.length; - let injectedTextIndex = 0; - let nextLineNumberWithInjectedText = (injectedTextIndex < injectedTextLength ? injectedText[injectedTextIndex].lineNumber : lineCount + 1); - for (let i = 0; i < lineCount; i++) { - let lineInjectedText = null; - if (i + 1 === nextLineNumberWithInjectedText) { - // There is some injected text on this line - lineInjectedText = []; - while (i + 1 === nextLineNumberWithInjectedText && injectedTextIndex < injectedTextLength) { - lineInjectedText.push(injectedText[injectedTextIndex]); - injectedTextIndex++; - nextLineNumberWithInjectedText = (injectedTextIndex < injectedTextLength ? injectedText[injectedTextIndex].lineNumber : lineCount + 1); - } - } - lineBreaksComputer.addRequest(linesContent[i], lineInjectedText, previousLineBreaks ? previousLineBreaks[i] : null); - } - const linesBreaks = lineBreaksComputer.finalize(); - let values = []; - let hiddenAreas = this.hiddenAreasIds.map((areaId) => this.model.getDecorationRange(areaId)).sort(range_1.Range.compareRangesUsingStarts); - let hiddenAreaStart = 1, hiddenAreaEnd = 0; - let hiddenAreaIdx = -1; - let nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : lineCount + 2; - for (let i = 0; i < lineCount; i++) { - let lineNumber = i + 1; - if (lineNumber === nextLineNumberToUpdateHiddenArea) { - hiddenAreaIdx++; - hiddenAreaStart = hiddenAreas[hiddenAreaIdx].startLineNumber; - hiddenAreaEnd = hiddenAreas[hiddenAreaIdx].endLineNumber; - nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : lineCount + 2; - } - let isInHiddenArea = (lineNumber >= hiddenAreaStart && lineNumber <= hiddenAreaEnd); - let line = createSplitLine(linesBreaks[i], !isInHiddenArea); - values[i] = line.getViewLineCount(); - this.lines[i] = line; - } - this._validModelVersionId = this.model.getVersionId(); - this.prefixSumComputer = new LineNumberMapper(values); - } - getHiddenAreas() { - return this.hiddenAreasIds.map((decId) => { - return this.model.getDecorationRange(decId); - }); - } - _reduceRanges(_ranges) { - if (_ranges.length === 0) { - return []; - } - let ranges = _ranges.map(r => this.model.validateRange(r)).sort(range_1.Range.compareRangesUsingStarts); - let result = []; - let currentRangeStart = ranges[0].startLineNumber; - let currentRangeEnd = ranges[0].endLineNumber; - for (let i = 1, len = ranges.length; i < len; i++) { - let 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; - } - setHiddenAreas(_ranges) { - let newRanges = this._reduceRanges(_ranges); - // BEGIN TODO@Martin: Please stop calling this method on each model change! - let oldRanges = this.hiddenAreasIds.map((areaId) => this.model.getDecorationRange(areaId)).sort(range_1.Range.compareRangesUsingStarts); - if (newRanges.length === oldRanges.length) { - let hasDifference = false; - for (let 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! - let newDecorations = []; - for (const newRange of newRanges) { - newDecorations.push({ - range: newRange, - options: textModel_1.ModelDecorationOptions.EMPTY - }); - } - this.hiddenAreasIds = this.model.deltaDecorations(this.hiddenAreasIds, newDecorations); - let hiddenAreas = newRanges; - let hiddenAreaStart = 1, hiddenAreaEnd = 0; - let hiddenAreaIdx = -1; - let nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : this.lines.length + 2; - let hasVisibleLine = false; - for (let i = 0; i < this.lines.length; i++) { - let 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; - } - let 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) { - let newOutputLineCount = this.lines[i].getViewLineCount(); - this.prefixSumComputer.changeValue(i, newOutputLineCount); - } - } - if (!hasVisibleLine) { - // Cannot have everything be hidden => reveal everything! - this.setHiddenAreas([]); - } - return true; - } - modelPositionIsVisible(modelLineNumber, _modelColumn) { - if (modelLineNumber < 1 || modelLineNumber > this.lines.length) { - // invalid arguments - return false; - } - return this.lines[modelLineNumber - 1].isVisible(); - } - getModelLineViewLineCount(modelLineNumber) { - if (modelLineNumber < 1 || modelLineNumber > this.lines.length) { - // invalid arguments - return 1; - } - return this.lines[modelLineNumber - 1].getViewLineCount(); - } - setTabSize(newTabSize) { - if (this.tabSize === newTabSize) { - return false; - } - this.tabSize = newTabSize; - this._constructLines(/*resetHiddenAreas*/ false, null); - return true; - } - setWrappingSettings(fontInfo, wrappingStrategy, wrappingColumn, wrappingIndent) { - const equalFontInfo = this.fontInfo.equals(fontInfo); - const equalWrappingStrategy = (this.wrappingStrategy === wrappingStrategy); - const equalWrappingColumn = (this.wrappingColumn === wrappingColumn); - const equalWrappingIndent = (this.wrappingIndent === wrappingIndent); - if (equalFontInfo && equalWrappingStrategy && equalWrappingColumn && equalWrappingIndent) { - return false; - } - const onlyWrappingColumnChanged = (equalFontInfo && equalWrappingStrategy && !equalWrappingColumn && equalWrappingIndent); - this.fontInfo = fontInfo; - this.wrappingStrategy = wrappingStrategy; - this.wrappingColumn = wrappingColumn; - this.wrappingIndent = wrappingIndent; - let previousLineBreaks = null; - if (onlyWrappingColumnChanged) { - previousLineBreaks = []; - for (let i = 0, len = this.lines.length; i < len; i++) { - previousLineBreaks[i] = this.lines[i].getLineBreakData(); - } - } - this._constructLines(/*resetHiddenAreas*/ false, previousLineBreaks); - return true; - } - createLineBreaksComputer() { - const lineBreaksComputerFactory = (this.wrappingStrategy === 'advanced' - ? this._domLineBreaksComputerFactory - : this._monospaceLineBreaksComputerFactory); - return lineBreaksComputerFactory.createLineBreaksComputer(this.fontInfo, this.tabSize, this.wrappingColumn, this.wrappingIndent); - } - onModelFlushed() { - this._constructLines(/*resetHiddenAreas*/ true, null); - } - onModelLinesDeleted(versionId, fromLineNumber, toLineNumber) { - if (!versionId || 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; - } - let outputFromLineNumber = (fromLineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(fromLineNumber - 2) + 1); - let 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); - } - onModelLinesInserted(versionId, fromLineNumber, _toLineNumber, lineBreaks) { - if (!versionId || 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; - } - // cannot use this.getHiddenAreas() because those decorations have already seen the effect of this model change - const isInHiddenArea = (fromLineNumber > 2 && !this.lines[fromLineNumber - 2].isVisible()); - let outputFromLineNumber = (fromLineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(fromLineNumber - 2) + 1); - let totalOutputLineCount = 0; - let insertLines = []; - let insertPrefixSumValues = []; - for (let i = 0, len = lineBreaks.length; i < len; i++) { - let line = createSplitLine(lineBreaks[i], !isInHiddenArea); - insertLines.push(line); - let 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); - } - onModelLineChanged(versionId, lineNumber, lineBreakData) { - if (versionId !== null && 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]; - } - let lineIndex = lineNumber - 1; - let oldOutputLineCount = this.lines[lineIndex].getViewLineCount(); - let isVisible = this.lines[lineIndex].isVisible(); - let line = createSplitLine(lineBreakData, isVisible); - this.lines[lineIndex] = line; - let newOutputLineCount = this.lines[lineIndex].getViewLineCount(); - let lineMappingChanged = false; - let changeFrom = 0; - let changeTo = -1; - let insertFrom = 0; - let insertTo = -1; - let deleteFrom = 0; - let 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); - const viewLinesChangedEvent = (changeFrom <= changeTo ? new viewEvents.ViewLinesChangedEvent(changeFrom, changeTo) : null); - const viewLinesInsertedEvent = (insertFrom <= insertTo ? new viewEvents.ViewLinesInsertedEvent(insertFrom, insertTo) : null); - const viewLinesDeletedEvent = (deleteFrom <= deleteTo ? new viewEvents.ViewLinesDeletedEvent(deleteFrom, deleteTo) : null); - return [lineMappingChanged, viewLinesChangedEvent, viewLinesInsertedEvent, viewLinesDeletedEvent]; - } - acceptVersionId(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([]); - } - } - getViewLineCount() { - return this.prefixSumComputer.getTotalValue(); - } - _toValidViewLineNumber(viewLineNumber) { - if (viewLineNumber < 1) { - return 1; - } - const viewLineCount = this.getViewLineCount(); - if (viewLineNumber > viewLineCount) { - return viewLineCount; - } - return viewLineNumber | 0; - } - getActiveIndentGuide(viewLineNumber, minLineNumber, maxLineNumber) { - viewLineNumber = this._toValidViewLineNumber(viewLineNumber); - minLineNumber = this._toValidViewLineNumber(minLineNumber); - maxLineNumber = this._toValidViewLineNumber(maxLineNumber); - const modelPosition = this.convertViewPositionToModelPosition(viewLineNumber, this.getViewLineMinColumn(viewLineNumber)); - const modelMinPosition = this.convertViewPositionToModelPosition(minLineNumber, this.getViewLineMinColumn(minLineNumber)); - const modelMaxPosition = this.convertViewPositionToModelPosition(maxLineNumber, this.getViewLineMinColumn(maxLineNumber)); - const result = this.model.getActiveIndentGuide(modelPosition.lineNumber, modelMinPosition.lineNumber, modelMaxPosition.lineNumber); - const viewStartPosition = this.convertModelPositionToViewPosition(result.startLineNumber, 1); - const viewEndPosition = this.convertModelPositionToViewPosition(result.endLineNumber, this.model.getLineMaxColumn(result.endLineNumber)); - return { - startLineNumber: viewStartPosition.lineNumber, - endLineNumber: viewEndPosition.lineNumber, - indent: result.indent - }; - } - getViewLinesIndentGuides(viewStartLineNumber, viewEndLineNumber) { - viewStartLineNumber = this._toValidViewLineNumber(viewStartLineNumber); - viewEndLineNumber = this._toValidViewLineNumber(viewEndLineNumber); - const modelStart = this.convertViewPositionToModelPosition(viewStartLineNumber, this.getViewLineMinColumn(viewStartLineNumber)); - const modelEnd = this.convertViewPositionToModelPosition(viewEndLineNumber, this.getViewLineMaxColumn(viewEndLineNumber)); - let result = []; - let resultRepeatCount = []; - let resultRepeatOption = []; - const modelStartLineIndex = modelStart.lineNumber - 1; - const modelEndLineIndex = modelEnd.lineNumber - 1; - let reqStart = null; - for (let modelLineIndex = modelStartLineIndex; modelLineIndex <= modelEndLineIndex; modelLineIndex++) { - const line = this.lines[modelLineIndex]; - if (line.isVisible()) { - let viewLineStartIndex = line.getViewLineNumberOfModelPosition(0, modelLineIndex === modelStartLineIndex ? modelStart.column : 1); - let viewLineEndIndex = line.getViewLineNumberOfModelPosition(0, this.model.getLineMaxColumn(modelLineIndex + 1)); - let count = viewLineEndIndex - viewLineStartIndex + 1; - let 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; - } - const viewLineCount = viewEndLineNumber - viewStartLineNumber + 1; - let viewIndents = new Array(viewLineCount); - let currIndex = 0; - for (let i = 0, len = result.length; i < len; i++) { - let value = result[i]; - let count = Math.min(viewLineCount - currIndex, resultRepeatCount[i]); - let option = resultRepeatOption[i]; - let blockAtIndex; - if (option === 2 /* BlockAll */) { - blockAtIndex = 0; - } - else if (option === 1 /* BlockSubsequent */) { - blockAtIndex = 1; - } - else { - blockAtIndex = count; - } - for (let j = 0; j < count; j++) { - if (j === blockAtIndex) { - value = 0; - } - viewIndents[currIndex++] = value; - } - } - return viewIndents; - } - getViewLineContent(viewLineNumber) { - viewLineNumber = this._toValidViewLineNumber(viewLineNumber); - let r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1); - let lineIndex = r.index; - let remainder = r.remainder; - return this.lines[lineIndex].getViewLineContent(this.model, lineIndex + 1, remainder); - } - getViewLineLength(viewLineNumber) { - viewLineNumber = this._toValidViewLineNumber(viewLineNumber); - let r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1); - let lineIndex = r.index; - let remainder = r.remainder; - return this.lines[lineIndex].getViewLineLength(this.model, lineIndex + 1, remainder); - } - getViewLineMinColumn(viewLineNumber) { - viewLineNumber = this._toValidViewLineNumber(viewLineNumber); - let r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1); - let lineIndex = r.index; - let remainder = r.remainder; - return this.lines[lineIndex].getViewLineMinColumn(this.model, lineIndex + 1, remainder); - } - getViewLineMaxColumn(viewLineNumber) { - viewLineNumber = this._toValidViewLineNumber(viewLineNumber); - let r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1); - let lineIndex = r.index; - let remainder = r.remainder; - return this.lines[lineIndex].getViewLineMaxColumn(this.model, lineIndex + 1, remainder); - } - getViewLineData(viewLineNumber) { - viewLineNumber = this._toValidViewLineNumber(viewLineNumber); - let r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1); - let lineIndex = r.index; - let remainder = r.remainder; - return this.lines[lineIndex].getViewLineData(this.model, lineIndex + 1, remainder); - } - getViewLinesData(viewStartLineNumber, viewEndLineNumber, needed) { - viewStartLineNumber = this._toValidViewLineNumber(viewStartLineNumber); - viewEndLineNumber = this._toValidViewLineNumber(viewEndLineNumber); - let start = this.prefixSumComputer.getIndexOf(viewStartLineNumber - 1); - let viewLineNumber = viewStartLineNumber; - let startModelLineIndex = start.index; - let startRemainder = start.remainder; - let result = []; - for (let modelLineIndex = startModelLineIndex, len = this.model.getLineCount(); modelLineIndex < len; modelLineIndex++) { - let line = this.lines[modelLineIndex]; - if (!line.isVisible()) { - continue; - } - let fromViewLineIndex = (modelLineIndex === startModelLineIndex ? startRemainder : 0); - let remainingViewLineCount = line.getViewLineCount() - fromViewLineIndex; - let lastLine = false; - if (viewLineNumber + remainingViewLineCount > viewEndLineNumber) { - lastLine = true; - remainingViewLineCount = viewEndLineNumber - viewLineNumber + 1; - } - let toViewLineIndex = fromViewLineIndex + remainingViewLineCount; - line.getViewLinesData(this.model, modelLineIndex + 1, fromViewLineIndex, toViewLineIndex, viewLineNumber - viewStartLineNumber, needed, result); - viewLineNumber += remainingViewLineCount; - if (lastLine) { - break; - } - } - return result; - } - validateViewPosition(viewLineNumber, viewColumn, expectedModelPosition) { - viewLineNumber = this._toValidViewLineNumber(viewLineNumber); - let r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1); - let lineIndex = r.index; - let remainder = r.remainder; - let line = this.lines[lineIndex]; - let minColumn = line.getViewLineMinColumn(this.model, lineIndex + 1, remainder); - let maxColumn = line.getViewLineMaxColumn(this.model, lineIndex + 1, remainder); - if (viewColumn < minColumn) { - viewColumn = minColumn; - } - if (viewColumn > maxColumn) { - viewColumn = maxColumn; - } - let computedModelColumn = line.getModelColumnOfViewPosition(remainder, viewColumn); - let 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); - } - validateViewRange(viewRange, expectedModelRange) { - const validViewStart = this.validateViewPosition(viewRange.startLineNumber, viewRange.startColumn, expectedModelRange.getStartPosition()); - const validViewEnd = this.validateViewPosition(viewRange.endLineNumber, viewRange.endColumn, expectedModelRange.getEndPosition()); - return new range_1.Range(validViewStart.lineNumber, validViewStart.column, validViewEnd.lineNumber, validViewEnd.column); - } - convertViewPositionToModelPosition(viewLineNumber, viewColumn) { - viewLineNumber = this._toValidViewLineNumber(viewLineNumber); - let r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1); - let lineIndex = r.index; - let remainder = r.remainder; - let 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)); - } - convertViewRangeToModelRange(viewRange) { - const start = this.convertViewPositionToModelPosition(viewRange.startLineNumber, viewRange.startColumn); - const end = this.convertViewPositionToModelPosition(viewRange.endLineNumber, viewRange.endColumn); - return new range_1.Range(start.lineNumber, start.column, end.lineNumber, end.column); - } - convertModelPositionToViewPosition(_modelLineNumber, _modelColumn, affinity = 2 /* None */) { - const validPosition = this.model.validatePosition(new position_1.Position(_modelLineNumber, _modelColumn)); - const inputLineNumber = validPosition.lineNumber; - const inputColumn = validPosition.column; - let 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); - } - const deltaLineNumber = 1 + (lineIndex === 0 ? 0 : this.prefixSumComputer.getAccumulatedValue(lineIndex - 1)); - let r; - if (lineIndexChanged) { - r = this.lines[lineIndex].getViewPositionOfModelPosition(deltaLineNumber, this.model.getLineMaxColumn(lineIndex + 1), affinity); - } - else { - r = this.lines[inputLineNumber - 1].getViewPositionOfModelPosition(deltaLineNumber, inputColumn, affinity); - } - // console.log('in -> out ' + inputLineNumber + ',' + inputColumn + ' ===> ' + r.lineNumber + ',' + r); - return r; - } - /** - * @param affinity The affinity in case of an empty range. Has no effect for non-empty ranges. - */ - convertModelRangeToViewRange(modelRange, affinity = 0 /* Left */) { - if (modelRange.isEmpty()) { - const start = this.convertModelPositionToViewPosition(modelRange.startLineNumber, modelRange.startColumn, affinity); - return range_1.Range.fromPositions(start); - } - else { - const start = this.convertModelPositionToViewPosition(modelRange.startLineNumber, modelRange.startColumn, 1 /* Right */); - const end = this.convertModelPositionToViewPosition(modelRange.endLineNumber, modelRange.endColumn, 0 /* Left */); - return new range_1.Range(start.lineNumber, start.column, end.lineNumber, end.column); - } - } - _getViewLineNumberForModelPosition(inputLineNumber, inputColumn) { - let lineIndex = inputLineNumber - 1; - if (this.lines[lineIndex].isVisible()) { - // this model line is visible - const deltaLineNumber = 1 + (lineIndex === 0 ? 0 : this.prefixSumComputer.getAccumulatedValue(lineIndex - 1)); - return this.lines[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber, 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; - } - const deltaLineNumber = 1 + (lineIndex === 0 ? 0 : this.prefixSumComputer.getAccumulatedValue(lineIndex - 1)); - return this.lines[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber, this.model.getLineMaxColumn(lineIndex + 1)); - } - getAllOverviewRulerDecorations(ownerId, filterOutValidation, theme) { - const decorations = this.model.getOverviewRulerDecorations(ownerId, filterOutValidation); - const result = new OverviewRulerDecorations(); - for (const decoration of decorations) { - const opts = decoration.options.overviewRuler; - const lane = opts ? opts.position : 0; - if (lane === 0) { - continue; - } - const color = opts.getColor(theme); - const viewStartLineNumber = this._getViewLineNumberForModelPosition(decoration.range.startLineNumber, decoration.range.startColumn); - const viewEndLineNumber = this._getViewLineNumberForModelPosition(decoration.range.endLineNumber, decoration.range.endColumn); - result.accept(color, viewStartLineNumber, viewEndLineNumber, lane); - } - return result.result; - } - getDecorationsInRange(range, ownerId, filterOutValidation) { - const modelStart = this.convertViewPositionToModelPosition(range.startLineNumber, range.startColumn); - const 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); - } - let result = []; - const modelStartLineIndex = modelStart.lineNumber - 1; - const modelEndLineIndex = modelEnd.lineNumber - 1; - let reqStart = null; - for (let modelLineIndex = modelStartLineIndex; modelLineIndex <= modelEndLineIndex; modelLineIndex++) { - const 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) { - const 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((a, b) => { - const 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 - let finalResult = [], finalResultLen = 0; - let prevDecId = null; - for (const dec of result) { - const decId = dec.id; - if (prevDecId === decId) { - // skip - continue; - } - prevDecId = decId; - finalResult[finalResultLen++] = dec; - } - return finalResult; - } - getInjectedTextAt(position) { - const viewLineNumber = this._toValidViewLineNumber(position.lineNumber); - const r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1); - const lineIndex = r.index; - const remainder = r.remainder; - return this.lines[lineIndex].getInjectedTextAt(remainder, position.column); - } - normalizePosition(position, affinity) { - const viewLineNumber = this._toValidViewLineNumber(position.lineNumber); - const r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1); - const lineIndex = r.index; - const remainder = r.remainder; - return this.lines[lineIndex].normalizePosition(this.model, lineIndex + 1, remainder, position, affinity); - } - getLineIndentColumn(lineNumber) { - const viewLineNumber = this._toValidViewLineNumber(lineNumber); - const r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1); - const lineIndex = r.index; - const remainder = r.remainder; - if (remainder === 0) { - return this.model.getLineIndentColumn(lineIndex + 1); - } - // wrapped lines have no indentation. - // We deliberately don't handle the case that indentation is wrapped - // to avoid two view lines reporting indentation for the very same model line. - return 0; - } - } - exports.SplitLinesCollection = SplitLinesCollection; - class VisibleIdentitySplitLine { - constructor() { } - isVisible() { - return true; - } - setVisible(isVisible) { - if (isVisible) { - return this; - } - return InvisibleIdentitySplitLine.INSTANCE; - } - getLineBreakData() { - return null; - } - getViewLineCount() { - return 1; - } - getViewLineContent(model, modelLineNumber, _outputLineIndex) { - return model.getLineContent(modelLineNumber); - } - getViewLineLength(model, modelLineNumber, _outputLineIndex) { - return model.getLineLength(modelLineNumber); - } - getViewLineMinColumn(model, modelLineNumber, _outputLineIndex) { - return model.getLineMinColumn(modelLineNumber); - } - getViewLineMaxColumn(model, modelLineNumber, _outputLineIndex) { - return model.getLineMaxColumn(modelLineNumber); - } - getViewLineData(model, modelLineNumber, _outputLineIndex) { - let lineTokens = model.getLineTokens(modelLineNumber); - let lineContent = lineTokens.getLineContent(); - return new viewModel_1.ViewLineData(lineContent, false, 1, lineContent.length + 1, 0, lineTokens.inflate(), null); - } - getViewLinesData(model, modelLineNumber, _fromOuputLineIndex, _toOutputLineIndex, globalStartIndex, needed, result) { - if (!needed[globalStartIndex]) { - result[globalStartIndex] = null; - return; - } - result[globalStartIndex] = this.getViewLineData(model, modelLineNumber, 0); - } - getModelColumnOfViewPosition(_outputLineIndex, outputColumn) { - return outputColumn; - } - getViewPositionOfModelPosition(deltaLineNumber, inputColumn) { - return new position_1.Position(deltaLineNumber, inputColumn); - } - getViewLineNumberOfModelPosition(deltaLineNumber, _inputColumn) { - return deltaLineNumber; - } - normalizePosition(model, modelLineNumber, outputLineIndex, outputPosition, affinity) { - return outputPosition; - } - getInjectedTextAt(_outputLineIndex, _outputColumn) { - return null; - } - } - VisibleIdentitySplitLine.INSTANCE = new VisibleIdentitySplitLine(); - class InvisibleIdentitySplitLine { - constructor() { } - isVisible() { - return false; - } - setVisible(isVisible) { - if (!isVisible) { - return this; - } - return VisibleIdentitySplitLine.INSTANCE; - } - getLineBreakData() { - return null; - } - getViewLineCount() { - return 0; - } - getViewLineContent(_model, _modelLineNumber, _outputLineIndex) { - throw new Error('Not supported'); - } - getViewLineLength(_model, _modelLineNumber, _outputLineIndex) { - throw new Error('Not supported'); - } - getViewLineMinColumn(_model, _modelLineNumber, _outputLineIndex) { - throw new Error('Not supported'); - } - getViewLineMaxColumn(_model, _modelLineNumber, _outputLineIndex) { - throw new Error('Not supported'); - } - getViewLineData(_model, _modelLineNumber, _outputLineIndex) { - throw new Error('Not supported'); - } - getViewLinesData(_model, _modelLineNumber, _fromOuputLineIndex, _toOutputLineIndex, _globalStartIndex, _needed, _result) { - throw new Error('Not supported'); - } - getModelColumnOfViewPosition(_outputLineIndex, _outputColumn) { - throw new Error('Not supported'); - } - getViewPositionOfModelPosition(_deltaLineNumber, _inputColumn) { - throw new Error('Not supported'); - } - getViewLineNumberOfModelPosition(_deltaLineNumber, _inputColumn) { - throw new Error('Not supported'); - } - normalizePosition(model, modelLineNumber, outputLineIndex, outputPosition, affinity) { - throw new Error('Not supported'); - } - getInjectedTextAt(_outputLineIndex, _outputColumn) { - throw new Error('Not supported'); - } - } - InvisibleIdentitySplitLine.INSTANCE = new InvisibleIdentitySplitLine(); - class SplitLine { - constructor(lineBreakData, isVisible) { - this._lineBreakData = lineBreakData; - this._isVisible = isVisible; - } - isVisible() { - return this._isVisible; - } - setVisible(isVisible) { - this._isVisible = isVisible; - return this; - } - getLineBreakData() { - return this._lineBreakData; - } - getViewLineCount() { - if (!this._isVisible) { - return 0; - } - return this._lineBreakData.breakOffsets.length; - } - getInputStartOffsetOfOutputLineIndex(outputLineIndex) { - return this._lineBreakData.getInputOffsetOfOutputPosition(outputLineIndex, 0); - } - getInputEndOffsetOfOutputLineIndex(model, modelLineNumber, outputLineIndex) { - if (outputLineIndex + 1 === this._lineBreakData.breakOffsets.length) { - return model.getLineMaxColumn(modelLineNumber) - 1; - } - return this._lineBreakData.getInputOffsetOfOutputPosition(outputLineIndex + 1, 0); - } - getViewLineContent(model, modelLineNumber, outputLineIndex) { - if (!this._isVisible) { - throw new Error('Not supported'); - } - // These offsets refer to model text with injected text. - const startOffset = outputLineIndex > 0 ? this._lineBreakData.breakOffsets[outputLineIndex - 1] : 0; - const endOffset = outputLineIndex < this._lineBreakData.breakOffsets.length - ? this._lineBreakData.breakOffsets[outputLineIndex] - // This case might not be possible anyway, but we clamp the value to be on the safe side. - : this._lineBreakData.breakOffsets[this._lineBreakData.breakOffsets.length - 1]; - let r; - if (this._lineBreakData.injectionOffsets !== null) { - const injectedTexts = this._lineBreakData.injectionOffsets.map((offset, idx) => new textModelEvents_1.LineInjectedText(0, 0, offset + 1, this._lineBreakData.injectionOptions[idx], 0)); - r = textModelEvents_1.LineInjectedText.applyInjectedText(model.getLineContent(modelLineNumber), injectedTexts).substring(startOffset, endOffset); - } - else { - r = model.getValueInRange({ - startLineNumber: modelLineNumber, - startColumn: startOffset + 1, - endLineNumber: modelLineNumber, - endColumn: endOffset + 1 - }); - } - if (outputLineIndex > 0) { - r = spaces(this._lineBreakData.wrappedTextIndentLength) + r; - } - return r; - } - getViewLineLength(model, modelLineNumber, outputLineIndex) { - // TODO @hediet make this method a member of LineBreakData. - if (!this._isVisible) { - throw new Error('Not supported'); - } - // These offsets refer to model text with injected text. - const startOffset = outputLineIndex > 0 ? this._lineBreakData.breakOffsets[outputLineIndex - 1] : 0; - const endOffset = outputLineIndex < this._lineBreakData.breakOffsets.length - ? this._lineBreakData.breakOffsets[outputLineIndex] - // This case might not be possible anyway, but we clamp the value to be on the safe side. - : this._lineBreakData.breakOffsets[this._lineBreakData.breakOffsets.length - 1]; - let r = endOffset - startOffset; - if (outputLineIndex > 0) { - r = this._lineBreakData.wrappedTextIndentLength + r; - } - return r; - } - getViewLineMinColumn(_model, _modelLineNumber, outputLineIndex) { - if (!this._isVisible) { - throw new Error('Not supported'); - } - return this._getViewLineMinColumn(outputLineIndex); - } - _getViewLineMinColumn(outputLineIndex) { - if (outputLineIndex > 0) { - return this._lineBreakData.wrappedTextIndentLength + 1; - } - return 1; - } - getViewLineMaxColumn(model, modelLineNumber, outputLineIndex) { - if (!this._isVisible) { - throw new Error('Not supported'); - } - return this.getViewLineLength(model, modelLineNumber, outputLineIndex) + 1; - } - getViewLineData(model, modelLineNumber, outputLineIndex) { - if (!this._isVisible) { - throw new Error('Not supported'); - } - const lineBreakData = this._lineBreakData; - const deltaStartIndex = (outputLineIndex > 0 ? lineBreakData.wrappedTextIndentLength : 0); - const injectionOffsets = lineBreakData.injectionOffsets; - const injectionOptions = lineBreakData.injectionOptions; - let lineContent; - let tokens; - let inlineDecorations; - if (injectionOffsets) { - const lineTokens = model.getLineTokens(modelLineNumber).withInserted(injectionOffsets.map((offset, idx) => ({ - offset, - text: injectionOptions[idx].content, - tokenMetadata: lineTokens_1.LineTokens.defaultTokenMetadata - }))); - const lineStartOffsetInUnwrappedLine = outputLineIndex > 0 ? lineBreakData.breakOffsets[outputLineIndex - 1] : 0; - const lineEndOffsetInUnwrappedLine = lineBreakData.breakOffsets[outputLineIndex]; - lineContent = lineTokens.getLineContent().substring(lineStartOffsetInUnwrappedLine, lineEndOffsetInUnwrappedLine); - tokens = lineTokens.sliceAndInflate(lineStartOffsetInUnwrappedLine, lineEndOffsetInUnwrappedLine, deltaStartIndex); - inlineDecorations = new Array(); - let totalInjectedTextLengthBefore = 0; - for (let i = 0; i < injectionOffsets.length; i++) { - const length = injectionOptions[i].content.length; - const injectedTextStartOffsetInUnwrappedLine = injectionOffsets[i] + totalInjectedTextLengthBefore; - const injectedTextEndOffsetInUnwrappedLine = injectionOffsets[i] + totalInjectedTextLengthBefore + length; - if (injectedTextStartOffsetInUnwrappedLine > lineEndOffsetInUnwrappedLine) { - // Injected text only starts in later wrapped lines. - break; - } - if (lineStartOffsetInUnwrappedLine < injectedTextEndOffsetInUnwrappedLine) { - // Injected text ends after or in this line (but also starts in or before this line). - const options = injectionOptions[i]; - if (options.inlineClassName) { - const offset = (outputLineIndex > 0 ? lineBreakData.wrappedTextIndentLength : 0); - const start = offset + Math.max(injectedTextStartOffsetInUnwrappedLine - lineStartOffsetInUnwrappedLine, 0); - const end = offset + Math.min(injectedTextEndOffsetInUnwrappedLine - lineStartOffsetInUnwrappedLine, lineEndOffsetInUnwrappedLine); - if (start !== end) { - inlineDecorations.push(new viewModel_1.SingleLineInlineDecoration(start, end, options.inlineClassName, options.inlineClassNameAffectsLetterSpacing)); - } - } - } - totalInjectedTextLengthBefore += length; - } - } - else { - const startOffset = this.getInputStartOffsetOfOutputLineIndex(outputLineIndex); - const endOffset = this.getInputEndOffsetOfOutputLineIndex(model, modelLineNumber, outputLineIndex); - const lineTokens = model.getLineTokens(modelLineNumber); - lineContent = model.getValueInRange({ - startLineNumber: modelLineNumber, - startColumn: startOffset + 1, - endLineNumber: modelLineNumber, - endColumn: endOffset + 1 - }); - tokens = lineTokens.sliceAndInflate(startOffset, endOffset, deltaStartIndex); - inlineDecorations = null; - } - if (outputLineIndex > 0) { - lineContent = spaces(lineBreakData.wrappedTextIndentLength) + lineContent; - } - const minColumn = (outputLineIndex > 0 ? lineBreakData.wrappedTextIndentLength + 1 : 1); - const maxColumn = lineContent.length + 1; - const continuesWithWrappedLine = (outputLineIndex + 1 < this.getViewLineCount()); - const startVisibleColumn = (outputLineIndex === 0 ? 0 : lineBreakData.breakOffsetsVisibleColumn[outputLineIndex - 1]); - return new viewModel_1.ViewLineData(lineContent, continuesWithWrappedLine, minColumn, maxColumn, startVisibleColumn, tokens, inlineDecorations); - } - getViewLinesData(model, modelLineNumber, fromOuputLineIndex, toOutputLineIndex, globalStartIndex, needed, result) { - if (!this._isVisible) { - throw new Error('Not supported'); - } - for (let outputLineIndex = fromOuputLineIndex; outputLineIndex < toOutputLineIndex; outputLineIndex++) { - let globalIndex = globalStartIndex + outputLineIndex - fromOuputLineIndex; - if (!needed[globalIndex]) { - result[globalIndex] = null; - continue; - } - result[globalIndex] = this.getViewLineData(model, modelLineNumber, outputLineIndex); - } - } - getModelColumnOfViewPosition(outputLineIndex, outputColumn) { - if (!this._isVisible) { - throw new Error('Not supported'); - } - let adjustedColumn = outputColumn - 1; - if (outputLineIndex > 0) { - if (adjustedColumn < this._lineBreakData.wrappedTextIndentLength) { - adjustedColumn = 0; - } - else { - adjustedColumn -= this._lineBreakData.wrappedTextIndentLength; - } - } - return this._lineBreakData.getInputOffsetOfOutputPosition(outputLineIndex, adjustedColumn) + 1; - } - getViewPositionOfModelPosition(deltaLineNumber, inputColumn, affinity = 2 /* None */) { - if (!this._isVisible) { - throw new Error('Not supported'); - } - let r = this._lineBreakData.getOutputPositionOfInputOffset(inputColumn - 1, affinity); - let outputLineIndex = r.outputLineIndex; - let 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); - } - getViewLineNumberOfModelPosition(deltaLineNumber, inputColumn) { - if (!this._isVisible) { - throw new Error('Not supported'); - } - const r = this._lineBreakData.getOutputPositionOfInputOffset(inputColumn - 1); - return (deltaLineNumber + r.outputLineIndex); - } - normalizePosition(model, modelLineNumber, outputLineIndex, outputPosition, affinity) { - if (this._lineBreakData.injectionOffsets !== null) { - const baseViewLineNumber = outputPosition.lineNumber - outputLineIndex; - const offsetInUnwrappedLine = this._lineBreakData.outputPositionToOffsetInUnwrappedLine(outputLineIndex, outputPosition.column - 1); - const normalizedOffsetInUnwrappedLine = this._lineBreakData.normalizeOffsetAroundInjections(offsetInUnwrappedLine, affinity); - if (normalizedOffsetInUnwrappedLine !== offsetInUnwrappedLine) { - // injected text caused a change - return this._lineBreakData.getOutputPositionOfOffsetInUnwrappedLine(normalizedOffsetInUnwrappedLine, affinity).toPosition(baseViewLineNumber, this._lineBreakData.wrappedTextIndentLength); - } - } - if (affinity === 0 /* Left */) { - if (outputLineIndex > 0 && outputPosition.column === this._getViewLineMinColumn(outputLineIndex)) { - return new position_1.Position(outputPosition.lineNumber - 1, this.getViewLineMaxColumn(model, modelLineNumber, outputLineIndex - 1)); - } - } - else if (affinity === 1 /* Right */) { - const maxOutputLineIndex = this.getViewLineCount() - 1; - if (outputLineIndex < maxOutputLineIndex && outputPosition.column === this.getViewLineMaxColumn(model, modelLineNumber, outputLineIndex)) { - return new position_1.Position(outputPosition.lineNumber + 1, this._getViewLineMinColumn(outputLineIndex + 1)); - } - } - return outputPosition; - } - getInjectedTextAt(outputLineIndex, outputColumn) { - return this._lineBreakData.getInjectedText(outputLineIndex, outputColumn - 1); - } - } - exports.SplitLine = SplitLine; - let _spaces = ['']; - function spaces(count) { - if (count >= _spaces.length) { - for (let 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); - } - } - class IdentityCoordinatesConverter { - constructor(lines) { - this._lines = lines; - } - _validPosition(pos) { - return this._lines.model.validatePosition(pos); - } - _validRange(range) { - return this._lines.model.validateRange(range); - } - // View -> Model conversion and related methods - convertViewPositionToModelPosition(viewPosition) { - return this._validPosition(viewPosition); - } - convertViewRangeToModelRange(viewRange) { - return this._validRange(viewRange); - } - validateViewPosition(_viewPosition, expectedModelPosition) { - return this._validPosition(expectedModelPosition); - } - validateViewRange(_viewRange, expectedModelRange) { - return this._validRange(expectedModelRange); - } - // Model -> View conversion and related methods - convertModelPositionToViewPosition(modelPosition) { - return this._validPosition(modelPosition); - } - convertModelRangeToViewRange(modelRange) { - return this._validRange(modelRange); - } - modelPositionIsVisible(modelPosition) { - const lineCount = this._lines.model.getLineCount(); - if (modelPosition.lineNumber < 1 || modelPosition.lineNumber > lineCount) { - // invalid arguments - return false; - } - return true; - } - getModelLineViewLineCount(modelLineNumber) { - return 1; - } - } - exports.IdentityCoordinatesConverter = IdentityCoordinatesConverter; - class IdentityLinesCollection { - constructor(model) { - this.model = model; - } - dispose() { - } - createCoordinatesConverter() { - return new IdentityCoordinatesConverter(this); - } - getHiddenAreas() { - return []; - } - setHiddenAreas(_ranges) { - return false; - } - setTabSize(_newTabSize) { - return false; - } - setWrappingSettings(_fontInfo, _wrappingStrategy, _wrappingColumn, _wrappingIndent) { - return false; - } - createLineBreaksComputer() { - let result = []; - return { - addRequest: (lineText, injectedText, previousLineBreakData) => { - result.push(null); - }, - finalize: () => { - return result; - } - }; - } - onModelFlushed() { - } - onModelLinesDeleted(_versionId, fromLineNumber, toLineNumber) { - return new viewEvents.ViewLinesDeletedEvent(fromLineNumber, toLineNumber); - } - onModelLinesInserted(_versionId, fromLineNumber, toLineNumber, lineBreaks) { - return new viewEvents.ViewLinesInsertedEvent(fromLineNumber, toLineNumber); - } - onModelLineChanged(_versionId, lineNumber, lineBreakData) { - return [false, new viewEvents.ViewLinesChangedEvent(lineNumber, lineNumber), null, null]; - } - acceptVersionId(_versionId) { - } - getViewLineCount() { - return this.model.getLineCount(); - } - getActiveIndentGuide(viewLineNumber, _minLineNumber, _maxLineNumber) { - return { - startLineNumber: viewLineNumber, - endLineNumber: viewLineNumber, - indent: 0 - }; - } - getViewLinesIndentGuides(viewStartLineNumber, viewEndLineNumber) { - const viewLineCount = viewEndLineNumber - viewStartLineNumber + 1; - let result = new Array(viewLineCount); - for (let i = 0; i < viewLineCount; i++) { - result[i] = 0; - } - return result; - } - getViewLineContent(viewLineNumber) { - return this.model.getLineContent(viewLineNumber); - } - getViewLineLength(viewLineNumber) { - return this.model.getLineLength(viewLineNumber); - } - getViewLineMinColumn(viewLineNumber) { - return this.model.getLineMinColumn(viewLineNumber); - } - getViewLineMaxColumn(viewLineNumber) { - return this.model.getLineMaxColumn(viewLineNumber); - } - getViewLineData(viewLineNumber) { - let lineTokens = this.model.getLineTokens(viewLineNumber); - let lineContent = lineTokens.getLineContent(); - return new viewModel_1.ViewLineData(lineContent, false, 1, lineContent.length + 1, 0, lineTokens.inflate(), null); - } - getViewLinesData(viewStartLineNumber, viewEndLineNumber, needed) { - const lineCount = this.model.getLineCount(); - viewStartLineNumber = Math.min(Math.max(1, viewStartLineNumber), lineCount); - viewEndLineNumber = Math.min(Math.max(1, viewEndLineNumber), lineCount); - let result = []; - for (let lineNumber = viewStartLineNumber; lineNumber <= viewEndLineNumber; lineNumber++) { - let idx = lineNumber - viewStartLineNumber; - if (!needed[idx]) { - result[idx] = null; - } - result[idx] = this.getViewLineData(lineNumber); - } - return result; - } - getAllOverviewRulerDecorations(ownerId, filterOutValidation, theme) { - const decorations = this.model.getOverviewRulerDecorations(ownerId, filterOutValidation); - const result = new OverviewRulerDecorations(); - for (const decoration of decorations) { - const opts = decoration.options.overviewRuler; - const lane = opts ? opts.position : 0; - if (lane === 0) { - continue; - } - const color = opts.getColor(theme); - const viewStartLineNumber = decoration.range.startLineNumber; - const viewEndLineNumber = decoration.range.endLineNumber; - result.accept(color, viewStartLineNumber, viewEndLineNumber, lane); - } - return result.result; - } - getDecorationsInRange(range, ownerId, filterOutValidation) { - return this.model.getDecorationsInRange(range, ownerId, filterOutValidation); - } - normalizePosition(position, affinity) { - return this.model.normalizePosition(position, affinity); - } - getLineIndentColumn(lineNumber) { - return this.model.getLineIndentColumn(lineNumber); - } - getInjectedTextAt(position) { - // Identity lines collection does not support injected text. - return null; - } - } - exports.IdentityLinesCollection = IdentityLinesCollection; - class OverviewRulerDecorations { - constructor() { - this.result = Object.create(null); - } - accept(color, startLineNumber, endLineNumber, lane) { - let prev = this.result[color]; - if (prev) { - const prevLane = prev[prev.length - 3]; - const 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]; - } - } - } -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[554/*vs/editor/common/viewModel/viewModelImpl*/], __M([0/*require*/,1/*exports*/,29/*vs/base/common/color*/,2/*vs/base/common/lifecycle*/,8/*vs/base/common/strings*/,35/*vs/editor/common/config/editorOptions*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,96/*vs/editor/common/model/textModelEvents*/,18/*vs/editor/common/modes*/,246/*vs/editor/common/modes/textToHtmlTokenizer*/,247/*vs/editor/common/viewModel/minimapTokensColorTracker*/,175/*vs/editor/common/view/viewEvents*/,406/*vs/editor/common/viewLayout/viewLayout*/,553/*vs/editor/common/viewModel/splitLinesCollection*/,62/*vs/editor/common/viewModel/viewModel*/,465/*vs/editor/common/viewModel/viewModelDecorations*/,15/*vs/base/common/async*/,17/*vs/base/common/platform*/,245/*vs/editor/common/controller/cursor*/,40/*vs/editor/common/controller/cursorCommon*/,177/*vs/editor/common/viewModel/viewModelEventDispatcher*/]), function (require, exports, color_1, lifecycle_1, strings, editorOptions_1, position_1, range_1, textModelEvents, modes_1, textToHtmlTokenizer_1, minimapTokensColorTracker_1, viewEvents, viewLayout_1, splitLinesCollection_1, viewModel_1, viewModelDecorations_1, async_1, platform, cursor_1, cursorCommon_1, viewModelEventDispatcher_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ViewModel = void 0; - const USE_IDENTITY_LINES_COLLECTION = true; - class ViewModel extends lifecycle_1.Disposable { - constructor(editorId, configuration, model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, scheduleAtNextAnimationFrame) { - super(); - this._editorId = editorId; - this._configuration = configuration; - this.model = model; - this._eventDispatcher = new viewModelEventDispatcher_1.ViewModelEventDispatcher(); - this.onEvent = this._eventDispatcher.onEvent; - this.cursorConfig = new cursorCommon_1.CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), this._configuration); - this._tokenizeViewportSoon = this._register(new async_1.RunOnceScheduler(() => this.tokenizeViewport(), 50)); - this._updateConfigurationViewLineCount = this._register(new async_1.RunOnceScheduler(() => this._updateConfigurationViewLineCountNow(), 0)); - 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 { - const options = this._configuration.options; - const fontInfo = options.get(41 /* fontInfo */); - const wrappingStrategy = options.get(123 /* wrappingStrategy */); - const wrappingInfo = options.get(130 /* wrappingInfo */); - const wrappingIndent = options.get(122 /* wrappingIndent */); - this._lines = new splitLinesCollection_1.SplitLinesCollection(this._editorId, this.model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, this.model.getOptions().tabSize, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent); - } - this.coordinatesConverter = this._lines.createCoordinatesConverter(); - this._cursor = this._register(new cursor_1.CursorsController(model, this, this.coordinatesConverter, this.cursorConfig)); - this.viewLayout = this._register(new viewLayout_1.ViewLayout(this._configuration, this.getLineCount(), scheduleAtNextAnimationFrame)); - this._register(this.viewLayout.onDidScroll((e) => { - if (e.scrollTopChanged) { - this._tokenizeViewportSoon.schedule(); - } - this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewScrollChangedEvent(e)); - this._eventDispatcher.emitOutgoingEvent(new viewModelEventDispatcher_1.ScrollChangedEvent(e.oldScrollWidth, e.oldScrollLeft, e.oldScrollHeight, e.oldScrollTop, e.scrollWidth, e.scrollLeft, e.scrollHeight, e.scrollTop)); - })); - this._register(this.viewLayout.onDidContentSizeChange((e) => { - this._eventDispatcher.emitOutgoingEvent(e); - })); - this._decorations = new viewModelDecorations_1.ViewModelDecorations(this._editorId, this.model, this._configuration, this._lines, this.coordinatesConverter); - this._registerModelEvents(); - this._register(this._configuration.onDidChangeFast((e) => { - try { - const eventsCollector = this._eventDispatcher.beginEmitViewEvents(); - this._onConfigurationChanged(eventsCollector, e); - } - finally { - this._eventDispatcher.endEmitViewEvents(); - } - })); - this._register(minimapTokensColorTracker_1.MinimapTokensColorTracker.getInstance().onDidChange(() => { - this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewTokensColorsChangedEvent()); - })); - this._updateConfigurationViewLineCountNow(); - } - dispose() { - // First remove listeners, as disposing the lines might end up sending - // model decoration changed events ... and we no longer care about them ... - super.dispose(); - this._decorations.dispose(); - this._lines.dispose(); - this.invalidateMinimapColorCache(); - this._viewportStartLineTrackedRange = this.model._setTrackedRange(this._viewportStartLineTrackedRange, null, 1 /* NeverGrowsWhenTypingAtEdges */); - this._eventDispatcher.dispose(); - } - createLineBreaksComputer() { - return this._lines.createLineBreaksComputer(); - } - addViewEventHandler(eventHandler) { - this._eventDispatcher.addViewEventHandler(eventHandler); - } - removeViewEventHandler(eventHandler) { - this._eventDispatcher.removeViewEventHandler(eventHandler); - } - _updateConfigurationViewLineCountNow() { - this._configuration.setViewLineCount(this._lines.getViewLineCount()); - } - tokenizeViewport() { - const linesViewportData = this.viewLayout.getLinesViewportData(); - const startPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(linesViewportData.startLineNumber, 1)); - const endPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(linesViewportData.endLineNumber, 1)); - this.model.tokenizeViewport(startPosition.lineNumber, endPosition.lineNumber); - } - setHasFocus(hasFocus) { - this._hasFocus = hasFocus; - this._cursor.setHasFocus(hasFocus); - this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewFocusChangedEvent(hasFocus)); - this._eventDispatcher.emitOutgoingEvent(new viewModelEventDispatcher_1.FocusChangedEvent(!hasFocus, hasFocus)); - } - onCompositionStart() { - this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewCompositionStartEvent()); - } - onCompositionEnd() { - this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewCompositionEndEvent()); - } - onDidColorThemeChange() { - this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewThemeChangedEvent()); - } - _onConfigurationChanged(eventsCollector, e) { - // We might need to restore the current centered view range, so save it (if available) - let previousViewportStartModelPosition = null; - if (this._viewportStartLine !== -1) { - let previousViewportStartViewPosition = new position_1.Position(this._viewportStartLine, this.getLineMinColumn(this._viewportStartLine)); - previousViewportStartModelPosition = this.coordinatesConverter.convertViewPositionToModelPosition(previousViewportStartViewPosition); - } - let restorePreviousViewportStart = false; - const options = this._configuration.options; - const fontInfo = options.get(41 /* fontInfo */); - const wrappingStrategy = options.get(123 /* wrappingStrategy */); - const wrappingInfo = options.get(130 /* wrappingInfo */); - const wrappingIndent = options.get(122 /* wrappingIndent */); - if (this._lines.setWrappingSettings(fontInfo, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent)) { - eventsCollector.emitViewEvent(new viewEvents.ViewFlushedEvent()); - eventsCollector.emitViewEvent(new viewEvents.ViewLineMappingChangedEvent()); - eventsCollector.emitViewEvent(new viewEvents.ViewDecorationsChangedEvent(null)); - this._cursor.onLineMappingChanged(eventsCollector); - 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; - } - this._updateConfigurationViewLineCount.schedule(); - } - if (e.hasChanged(79 /* readOnly */)) { - // Must read again all decorations due to readOnly filtering - this._decorations.reset(); - eventsCollector.emitViewEvent(new viewEvents.ViewDecorationsChangedEvent(null)); - } - eventsCollector.emitViewEvent(new viewEvents.ViewConfigurationChangedEvent(e)); - this.viewLayout.onConfigurationChanged(e); - if (restorePreviousViewportStart && previousViewportStartModelPosition) { - const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(previousViewportStartModelPosition); - const viewPositionTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber); - this.viewLayout.setScrollPosition({ scrollTop: viewPositionTop + this._viewportStartLineDelta }, 1 /* Immediate */); - } - if (cursorCommon_1.CursorConfiguration.shouldRecreate(e)) { - this.cursorConfig = new cursorCommon_1.CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), this._configuration); - this._cursor.updateConfiguration(this.cursorConfig); - } - } - _registerModelEvents() { - this._register(this.model.onDidChangeContentOrInjectedText((e) => { - try { - const eventsCollector = this._eventDispatcher.beginEmitViewEvents(); - let hadOtherModelChange = false; - let hadModelLineChangeThatChangedLineMapping = false; - const changes = e.changes; - const versionId = (e instanceof textModelEvents.ModelRawContentChangedEvent ? e.versionId : null); - // Do a first pass to compute line mappings, and a second pass to actually interpret them - const lineBreaksComputer = this._lines.createLineBreaksComputer(); - for (const change of changes) { - switch (change.changeType) { - case 4 /* LinesInserted */: { - for (let lineIdx = 0; lineIdx < change.detail.length; lineIdx++) { - const line = change.detail[lineIdx]; - let injectedText = change.injectedTexts[lineIdx]; - if (injectedText) { - injectedText = injectedText.filter(element => (!element.ownerId || element.ownerId === this._editorId)); - } - lineBreaksComputer.addRequest(line, injectedText, null); - } - break; - } - case 2 /* LineChanged */: { - let injectedText = null; - if (change.injectedText) { - injectedText = change.injectedText.filter(element => (!element.ownerId || element.ownerId === this._editorId)); - } - lineBreaksComputer.addRequest(change.detail, injectedText, null); - break; - } - } - } - const lineBreaks = lineBreaksComputer.finalize(); - let lineBreaksOffset = 0; - for (const change of changes) { - switch (change.changeType) { - case 1 /* Flush */: { - this._lines.onModelFlushed(); - eventsCollector.emitViewEvent(new viewEvents.ViewFlushedEvent()); - this._decorations.reset(); - this.viewLayout.onFlushed(this.getLineCount()); - hadOtherModelChange = true; - break; - } - case 3 /* LinesDeleted */: { - const linesDeletedEvent = this._lines.onModelLinesDeleted(versionId, change.fromLineNumber, change.toLineNumber); - if (linesDeletedEvent !== null) { - eventsCollector.emitViewEvent(linesDeletedEvent); - this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber); - } - hadOtherModelChange = true; - break; - } - case 4 /* LinesInserted */: { - const insertedLineBreaks = lineBreaks.slice(lineBreaksOffset, lineBreaksOffset + change.detail.length); - lineBreaksOffset += change.detail.length; - const linesInsertedEvent = this._lines.onModelLinesInserted(versionId, change.fromLineNumber, change.toLineNumber, insertedLineBreaks); - if (linesInsertedEvent !== null) { - eventsCollector.emitViewEvent(linesInsertedEvent); - this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber); - } - hadOtherModelChange = true; - break; - } - case 2 /* LineChanged */: { - const changedLineBreakData = lineBreaks[lineBreaksOffset]; - lineBreaksOffset++; - const [lineMappingChanged, linesChangedEvent, linesInsertedEvent, linesDeletedEvent] = this._lines.onModelLineChanged(versionId, change.lineNumber, changedLineBreakData); - hadModelLineChangeThatChangedLineMapping = lineMappingChanged; - if (linesChangedEvent) { - eventsCollector.emitViewEvent(linesChangedEvent); - } - if (linesInsertedEvent) { - eventsCollector.emitViewEvent(linesInsertedEvent); - this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber); - } - if (linesDeletedEvent) { - eventsCollector.emitViewEvent(linesDeletedEvent); - this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber); - } - break; - } - case 5 /* EOLChanged */: { - // Nothing to do. The new version will be accepted below - break; - } - } - } - if (versionId !== null) { - this._lines.acceptVersionId(versionId); - } - this.viewLayout.onHeightMaybeChanged(); - if (!hadOtherModelChange && hadModelLineChangeThatChangedLineMapping) { - eventsCollector.emitViewEvent(new viewEvents.ViewLineMappingChangedEvent()); - eventsCollector.emitViewEvent(new viewEvents.ViewDecorationsChangedEvent(null)); - this._cursor.onLineMappingChanged(eventsCollector); - this._decorations.onLineMappingChanged(); - } - } - finally { - this._eventDispatcher.endEmitViewEvents(); - } - // Update the configuration and reset the centered view line - this._viewportStartLine = -1; - this._configuration.setMaxLineNumber(this.model.getLineCount()); - this._updateConfigurationViewLineCountNow(); - // Recover viewport - if (!this._hasFocus && this.model.getAttachedEditorCount() >= 2 && this._viewportStartLineTrackedRange) { - const modelRange = this.model._getTrackedRange(this._viewportStartLineTrackedRange); - if (modelRange) { - const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(modelRange.getStartPosition()); - const viewPositionTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber); - this.viewLayout.setScrollPosition({ scrollTop: viewPositionTop + this._viewportStartLineDelta }, 1 /* Immediate */); - } - } - try { - const eventsCollector = this._eventDispatcher.beginEmitViewEvents(); - this._cursor.onModelContentChanged(eventsCollector, e); - } - finally { - this._eventDispatcher.endEmitViewEvents(); - } - })); - this._register(this.model.onDidChangeTokens((e) => { - let viewRanges = []; - for (let j = 0, lenJ = e.ranges.length; j < lenJ; j++) { - const modelRange = e.ranges[j]; - const viewStartLineNumber = this.coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelRange.fromLineNumber, 1)).lineNumber; - const viewEndLineNumber = this.coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelRange.toLineNumber, this.model.getLineMaxColumn(modelRange.toLineNumber))).lineNumber; - viewRanges[j] = { - fromLineNumber: viewStartLineNumber, - toLineNumber: viewEndLineNumber - }; - } - this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewTokensChangedEvent(viewRanges)); - if (e.tokenizationSupportChanged) { - this._tokenizeViewportSoon.schedule(); - } - })); - this._register(this.model.onDidChangeLanguageConfiguration((e) => { - this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewLanguageConfigurationEvent()); - this.cursorConfig = new cursorCommon_1.CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), this._configuration); - this._cursor.updateConfiguration(this.cursorConfig); - })); - this._register(this.model.onDidChangeLanguage((e) => { - this.cursorConfig = new cursorCommon_1.CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), this._configuration); - this._cursor.updateConfiguration(this.cursorConfig); - })); - this._register(this.model.onDidChangeOptions((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)) { - try { - const eventsCollector = this._eventDispatcher.beginEmitViewEvents(); - eventsCollector.emitViewEvent(new viewEvents.ViewFlushedEvent()); - eventsCollector.emitViewEvent(new viewEvents.ViewLineMappingChangedEvent()); - eventsCollector.emitViewEvent(new viewEvents.ViewDecorationsChangedEvent(null)); - this._cursor.onLineMappingChanged(eventsCollector); - this._decorations.onLineMappingChanged(); - this.viewLayout.onFlushed(this.getLineCount()); - } - finally { - this._eventDispatcher.endEmitViewEvents(); - } - this._updateConfigurationViewLineCount.schedule(); - } - this.cursorConfig = new cursorCommon_1.CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), this._configuration); - this._cursor.updateConfiguration(this.cursorConfig); - })); - this._register(this.model.onDidChangeDecorations((e) => { - this._decorations.onModelDecorationsChanged(); - this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewDecorationsChangedEvent(e)); - })); - } - setHiddenAreas(ranges) { - try { - const eventsCollector = this._eventDispatcher.beginEmitViewEvents(); - let lineMappingChanged = this._lines.setHiddenAreas(ranges); - if (lineMappingChanged) { - eventsCollector.emitViewEvent(new viewEvents.ViewFlushedEvent()); - eventsCollector.emitViewEvent(new viewEvents.ViewLineMappingChangedEvent()); - eventsCollector.emitViewEvent(new viewEvents.ViewDecorationsChangedEvent(null)); - this._cursor.onLineMappingChanged(eventsCollector); - this._decorations.onLineMappingChanged(); - this.viewLayout.onFlushed(this.getLineCount()); - this.viewLayout.onHeightMaybeChanged(); - } - } - finally { - this._eventDispatcher.endEmitViewEvents(); - } - this._updateConfigurationViewLineCount.schedule(); - } - getVisibleRangesPlusViewportAboveBelow() { - const layoutInfo = this._configuration.options.get(129 /* layoutInfo */); - const lineHeight = this._configuration.options.get(57 /* lineHeight */); - const linesAround = Math.max(20, Math.round(layoutInfo.height / lineHeight)); - const partialData = this.viewLayout.getLinesViewportData(); - const startViewLineNumber = Math.max(1, partialData.completelyVisibleStartLineNumber - linesAround); - const endViewLineNumber = Math.min(this.getLineCount(), partialData.completelyVisibleEndLineNumber + linesAround); - return this._toModelVisibleRanges(new range_1.Range(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber))); - } - getVisibleRanges() { - const visibleViewRange = this.getCompletelyVisibleViewRange(); - return this._toModelVisibleRanges(visibleViewRange); - } - _toModelVisibleRanges(visibleViewRange) { - const visibleRange = this.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange); - const hiddenAreas = this._lines.getHiddenAreas(); - if (hiddenAreas.length === 0) { - return [visibleRange]; - } - let result = [], resultLen = 0; - let startLineNumber = visibleRange.startLineNumber; - let startColumn = visibleRange.startColumn; - let endLineNumber = visibleRange.endLineNumber; - let endColumn = visibleRange.endColumn; - for (let i = 0, len = hiddenAreas.length; i < len; i++) { - const hiddenStartLineNumber = hiddenAreas[i].startLineNumber; - const 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; - } - getCompletelyVisibleViewRange() { - const partialData = this.viewLayout.getLinesViewportData(); - const startViewLineNumber = partialData.completelyVisibleStartLineNumber; - const endViewLineNumber = partialData.completelyVisibleEndLineNumber; - return new range_1.Range(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber)); - } - getCompletelyVisibleViewRangeAtScrollTop(scrollTop) { - const partialData = this.viewLayout.getLinesViewportDataAtScrollTop(scrollTop); - const startViewLineNumber = partialData.completelyVisibleStartLineNumber; - const endViewLineNumber = partialData.completelyVisibleEndLineNumber; - return new range_1.Range(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber)); - } - saveState() { - const compatViewState = this.viewLayout.saveState(); - const scrollTop = compatViewState.scrollTop; - const firstViewLineNumber = this.viewLayout.getLineNumberAtVerticalOffset(scrollTop); - const firstPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(firstViewLineNumber, this.getLineMinColumn(firstViewLineNumber))); - const firstPositionDeltaTop = this.viewLayout.getVerticalOffsetForLineNumber(firstViewLineNumber) - scrollTop; - return { - scrollLeft: compatViewState.scrollLeft, - firstPosition: firstPosition, - firstPositionDeltaTop: firstPositionDeltaTop - }; - } - reduceRestoreState(state) { - if (typeof state.firstPosition === 'undefined') { - // This is a view state serialized by an older version - return this._reduceRestoreStateCompatibility(state); - } - const modelPosition = this.model.validatePosition(state.firstPosition); - const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(modelPosition); - const scrollTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber) - state.firstPositionDeltaTop; - return { - scrollLeft: state.scrollLeft, - scrollTop: scrollTop - }; - } - _reduceRestoreStateCompatibility(state) { - return { - scrollLeft: state.scrollLeft, - scrollTop: state.scrollTopWithoutViewZones - }; - } - getTabSize() { - return this.model.getOptions().tabSize; - } - getTextModelOptions() { - return this.model.getOptions(); - } - getLineCount() { - return this._lines.getViewLineCount(); - } - /** - * Gives a hint that a lot of requests are about to come in for these line numbers. - */ - setViewport(startLineNumber, endLineNumber, centeredLineNumber) { - this._viewportStartLine = startLineNumber; - let 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 */); - const viewportStartLineTop = this.viewLayout.getVerticalOffsetForLineNumber(startLineNumber); - const scrollTop = this.viewLayout.getCurrentScrollTop(); - this._viewportStartLineDelta = scrollTop - viewportStartLineTop; - } - getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber) { - return this._lines.getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber); - } - getLinesIndentGuides(startLineNumber, endLineNumber) { - return this._lines.getViewLinesIndentGuides(startLineNumber, endLineNumber); - } - getLineContent(lineNumber) { - return this._lines.getViewLineContent(lineNumber); - } - getLineLength(lineNumber) { - return this._lines.getViewLineLength(lineNumber); - } - getLineMinColumn(lineNumber) { - return this._lines.getViewLineMinColumn(lineNumber); - } - getLineMaxColumn(lineNumber) { - return this._lines.getViewLineMaxColumn(lineNumber); - } - getLineFirstNonWhitespaceColumn(lineNumber) { - const result = strings.firstNonWhitespaceIndex(this.getLineContent(lineNumber)); - if (result === -1) { - return 0; - } - return result + 1; - } - getLineLastNonWhitespaceColumn(lineNumber) { - const result = strings.lastNonWhitespaceIndex(this.getLineContent(lineNumber)); - if (result === -1) { - return 0; - } - return result + 2; - } - getDecorationsInViewport(visibleRange) { - return this._decorations.getDecorationsViewportData(visibleRange).decorations; - } - getInjectedTextAt(viewPosition) { - return this._lines.getInjectedTextAt(viewPosition); - } - getViewLineRenderingData(visibleRange, lineNumber) { - let mightContainRTL = this.model.mightContainRTL(); - let mightContainNonBasicASCII = this.model.mightContainNonBasicASCII(); - let tabSize = this.getTabSize(); - let lineData = this._lines.getViewLineData(lineNumber); - let allInlineDecorations = this._decorations.getDecorationsViewportData(visibleRange).inlineDecorations; - let inlineDecorations = allInlineDecorations[lineNumber - visibleRange.startLineNumber]; - if (lineData.inlineDecorations) { - inlineDecorations = [ - ...inlineDecorations, - ...lineData.inlineDecorations.map(d => d.toInlineDecoration(lineNumber)) - ]; - } - return new viewModel_1.ViewLineRenderingData(lineData.minColumn, lineData.maxColumn, lineData.content, lineData.continuesWithWrappedLine, mightContainRTL, mightContainNonBasicASCII, lineData.tokens, inlineDecorations, tabSize, lineData.startVisibleColumn); - } - getViewLineData(lineNumber) { - return this._lines.getViewLineData(lineNumber); - } - getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed) { - let result = this._lines.getViewLinesData(startLineNumber, endLineNumber, needed); - return new viewModel_1.MinimapLinesRenderingData(this.getTabSize(), result); - } - getAllOverviewRulerDecorations(theme) { - return this._lines.getAllOverviewRulerDecorations(this._editorId, (0, editorOptions_1.filterValidationDecorations)(this._configuration.options), theme); - } - invalidateOverviewRulerColorCache() { - const decorations = this.model.getOverviewRulerDecorations(); - for (const decoration of decorations) { - const opts = decoration.options.overviewRuler; - if (opts) { - opts.invalidateCachedColor(); - } - } - } - invalidateMinimapColorCache() { - const decorations = this.model.getAllDecorations(); - for (const decoration of decorations) { - const opts = decoration.options.minimap; - if (opts) { - opts.invalidateCachedColor(); - } - } - } - getValueInRange(range, eol) { - const modelRange = this.coordinatesConverter.convertViewRangeToModelRange(range); - return this.model.getValueInRange(modelRange, eol); - } - getModelLineMaxColumn(modelLineNumber) { - return this.model.getLineMaxColumn(modelLineNumber); - } - validateModelPosition(position) { - return this.model.validatePosition(position); - } - validateModelRange(range) { - return this.model.validateRange(range); - } - deduceModelPositionRelativeToViewPosition(viewAnchorPosition, deltaOffset, lineFeedCnt) { - const 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; - } - } - const modelAnchorOffset = this.model.getOffsetAt(modelAnchor); - const resultOffset = modelAnchorOffset + deltaOffset; - return this.model.getPositionAt(resultOffset); - } - getEOL() { - return this.model.getEOL(); - } - getPlainTextToCopy(modelRanges, emptySelectionClipboard, forceCRLF) { - const newLineCharacter = forceCRLF ? '\r\n' : this.model.getEOL(); - modelRanges = modelRanges.slice(0); - modelRanges.sort(range_1.Range.compareRangesUsingStarts); - let hasEmptyRange = false; - let hasNonEmptyRange = false; - for (const range of modelRanges) { - if (range.isEmpty()) { - hasEmptyRange = true; - } - else { - hasNonEmptyRange = true; - } - } - if (!hasNonEmptyRange) { - // all ranges are empty - if (!emptySelectionClipboard) { - return ''; - } - const modelLineNumbers = modelRanges.map((r) => r.startLineNumber); - let result = ''; - for (let i = 0; i < modelLineNumbers.length; i++) { - if (i > 0 && modelLineNumbers[i - 1] === modelLineNumbers[i]) { - continue; - } - result += this.model.getLineContent(modelLineNumbers[i]) + newLineCharacter; - } - return result; - } - if (hasEmptyRange && emptySelectionClipboard) { - // mixed empty selections and non-empty selections - let result = []; - let prevModelLineNumber = 0; - for (const modelRange of modelRanges) { - const modelLineNumber = modelRange.startLineNumber; - if (modelRange.isEmpty()) { - if (modelLineNumber !== prevModelLineNumber) { - result.push(this.model.getLineContent(modelLineNumber)); - } - } - else { - result.push(this.model.getValueInRange(modelRange, forceCRLF ? 2 /* CRLF */ : 0 /* TextDefined */)); - } - prevModelLineNumber = modelLineNumber; - } - return result.length === 1 ? result[0] : result; - } - let result = []; - for (const modelRange of modelRanges) { - if (!modelRange.isEmpty()) { - result.push(this.model.getValueInRange(modelRange, forceCRLF ? 2 /* CRLF */ : 0 /* TextDefined */)); - } - } - return result.length === 1 ? result[0] : result; - } - getRichTextToCopy(modelRanges, emptySelectionClipboard) { - const languageId = this.model.getLanguageIdentifier(); - if (languageId.id === 1 /* PlainText */) { - return null; - } - if (modelRanges.length !== 1) { - // no multiple selection support at this time - return null; - } - let range = modelRanges[0]; - if (range.isEmpty()) { - if (!emptySelectionClipboard) { - // nothing to copy - return null; - } - const lineNumber = range.startLineNumber; - range = new range_1.Range(lineNumber, this.model.getLineMinColumn(lineNumber), lineNumber, this.model.getLineMaxColumn(lineNumber)); - } - const fontInfo = this._configuration.options.get(41 /* fontInfo */); - const colorMap = this._getColorMap(); - const hasBadChars = (/[:;\\\/<>]/.test(fontInfo.fontFamily)); - const useDefaultFontFamily = (hasBadChars || fontInfo.fontFamily === editorOptions_1.EDITOR_FONT_DEFAULTS.fontFamily); - let fontFamily; - if (useDefaultFontFamily) { - fontFamily = editorOptions_1.EDITOR_FONT_DEFAULTS.fontFamily; - } - else { - fontFamily = fontInfo.fontFamily; - fontFamily = fontFamily.replace(/"/g, '\''); - const hasQuotesOrIsList = /[,']/.test(fontFamily); - if (!hasQuotesOrIsList) { - const needsQuotes = /[+ ]/.test(fontFamily); - if (needsQuotes) { - fontFamily = `'${fontFamily}'`; - } - } - fontFamily = `${fontFamily}, ${editorOptions_1.EDITOR_FONT_DEFAULTS.fontFamily}`; - } - return { - mode: languageId.language, - html: (`
    ` - + this._getHTMLToCopy(range, colorMap) - + '
    ') - }; - } - _getHTMLToCopy(modelRange, colorMap) { - const startLineNumber = modelRange.startLineNumber; - const startColumn = modelRange.startColumn; - const endLineNumber = modelRange.endLineNumber; - const endColumn = modelRange.endColumn; - const tabSize = this.getTabSize(); - let result = ''; - for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { - const lineTokens = this.model.getLineTokens(lineNumber); - const lineContent = lineTokens.getLineContent(); - const startOffset = (lineNumber === startLineNumber ? startColumn - 1 : 0); - const endOffset = (lineNumber === endLineNumber ? endColumn - 1 : lineContent.length); - if (lineContent === '') { - result += '
    '; - } - else { - result += (0, textToHtmlTokenizer_1.tokenizeLineToHTML)(lineContent, lineTokens.inflate(), colorMap, startOffset, endOffset, tabSize, platform.isWindows); - } - } - return result; - } - _getColorMap() { - let colorMap = modes_1.TokenizationRegistry.getColorMap(); - let result = ['#000000']; - if (colorMap) { - for (let i = 1, len = colorMap.length; i < len; i++) { - result[i] = color_1.Color.Format.CSS.formatHex(colorMap[i]); - } - } - return result; - } - //#region model - pushStackElement() { - this.model.pushStackElement(); - } - //#endregion - //#region cursor operations - getPrimaryCursorState() { - return this._cursor.getPrimaryCursorState(); - } - getLastAddedCursorIndex() { - return this._cursor.getLastAddedCursorIndex(); - } - getCursorStates() { - return this._cursor.getCursorStates(); - } - setCursorStates(source, reason, states) { - this._withViewEventsCollector(eventsCollector => this._cursor.setStates(eventsCollector, source, reason, states)); - } - getCursorColumnSelectData() { - return this._cursor.getCursorColumnSelectData(); - } - getCursorAutoClosedCharacters() { - return this._cursor.getAutoClosedCharacters(); - } - setCursorColumnSelectData(columnSelectData) { - this._cursor.setCursorColumnSelectData(columnSelectData); - } - getPrevEditOperationType() { - return this._cursor.getPrevEditOperationType(); - } - setPrevEditOperationType(type) { - this._cursor.setPrevEditOperationType(type); - } - getSelection() { - return this._cursor.getSelection(); - } - getSelections() { - return this._cursor.getSelections(); - } - getPosition() { - return this._cursor.getPrimaryCursorState().modelState.position; - } - setSelections(source, selections, reason = 0 /* NotSet */) { - this._withViewEventsCollector(eventsCollector => this._cursor.setSelections(eventsCollector, source, selections, reason)); - } - saveCursorState() { - return this._cursor.saveState(); - } - restoreCursorState(states) { - this._withViewEventsCollector(eventsCollector => this._cursor.restoreState(eventsCollector, states)); - } - _executeCursorEdit(callback) { - if (this._cursor.context.cursorConfig.readOnly) { - // we cannot edit when read only... - this._eventDispatcher.emitOutgoingEvent(new viewModelEventDispatcher_1.ReadOnlyEditAttemptEvent()); - return; - } - this._withViewEventsCollector(callback); - } - executeEdits(source, edits, cursorStateComputer) { - this._executeCursorEdit(eventsCollector => this._cursor.executeEdits(eventsCollector, source, edits, cursorStateComputer)); - } - startComposition() { - this._cursor.setIsDoingComposition(true); - this._executeCursorEdit(eventsCollector => this._cursor.startComposition(eventsCollector)); - } - endComposition(source) { - this._cursor.setIsDoingComposition(false); - this._executeCursorEdit(eventsCollector => this._cursor.endComposition(eventsCollector, source)); - } - type(text, source) { - this._executeCursorEdit(eventsCollector => this._cursor.type(eventsCollector, text, source)); - } - compositionType(text, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source) { - this._executeCursorEdit(eventsCollector => this._cursor.compositionType(eventsCollector, text, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source)); - } - paste(text, pasteOnNewLine, multicursorText, source) { - this._executeCursorEdit(eventsCollector => this._cursor.paste(eventsCollector, text, pasteOnNewLine, multicursorText, source)); - } - cut(source) { - this._executeCursorEdit(eventsCollector => this._cursor.cut(eventsCollector, source)); - } - executeCommand(command, source) { - this._executeCursorEdit(eventsCollector => this._cursor.executeCommand(eventsCollector, command, source)); - } - executeCommands(commands, source) { - this._executeCursorEdit(eventsCollector => this._cursor.executeCommands(eventsCollector, commands, source)); - } - revealPrimaryCursor(source, revealHorizontal) { - this._withViewEventsCollector(eventsCollector => this._cursor.revealPrimary(eventsCollector, source, revealHorizontal, 0 /* Smooth */)); - } - revealTopMostCursor(source) { - const viewPosition = this._cursor.getTopMostViewPosition(); - const viewRange = new range_1.Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column); - this._withViewEventsCollector(eventsCollector => eventsCollector.emitViewEvent(new viewEvents.ViewRevealRangeRequestEvent(source, viewRange, null, 0 /* Simple */, true, 0 /* Smooth */))); - } - revealBottomMostCursor(source) { - const viewPosition = this._cursor.getBottomMostViewPosition(); - const viewRange = new range_1.Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column); - this._withViewEventsCollector(eventsCollector => eventsCollector.emitViewEvent(new viewEvents.ViewRevealRangeRequestEvent(source, viewRange, null, 0 /* Simple */, true, 0 /* Smooth */))); - } - revealRange(source, revealHorizontal, viewRange, verticalType, scrollType) { - this._withViewEventsCollector(eventsCollector => eventsCollector.emitViewEvent(new viewEvents.ViewRevealRangeRequestEvent(source, viewRange, null, verticalType, revealHorizontal, scrollType))); - } - //#endregion - //#region viewLayout - getVerticalOffsetForLineNumber(viewLineNumber) { - return this.viewLayout.getVerticalOffsetForLineNumber(viewLineNumber); - } - getScrollTop() { - return this.viewLayout.getCurrentScrollTop(); - } - setScrollTop(newScrollTop, scrollType) { - this.viewLayout.setScrollPosition({ scrollTop: newScrollTop }, scrollType); - } - setScrollPosition(position, type) { - this.viewLayout.setScrollPosition(position, type); - } - deltaScrollNow(deltaScrollLeft, deltaScrollTop) { - this.viewLayout.deltaScrollNow(deltaScrollLeft, deltaScrollTop); - } - changeWhitespace(callback) { - const hadAChange = this.viewLayout.changeWhitespace(callback); - if (hadAChange) { - this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewZonesChangedEvent()); - this._eventDispatcher.emitOutgoingEvent(new viewModelEventDispatcher_1.ViewZonesChangedEvent()); - } - } - setMaxLineWidth(maxLineWidth) { - this.viewLayout.setMaxLineWidth(maxLineWidth); - } - //#endregion - _withViewEventsCollector(callback) { - try { - const eventsCollector = this._eventDispatcher.beginEmitViewEvents(); - callback(eventsCollector); - } - finally { - this._eventDispatcher.endEmitViewEvents(); - } - } - normalizePosition(position, affinity) { - return this._lines.normalizePosition(position, affinity); - } - /** - * Gets the column at which indentation stops at a given line. - * @internal - */ - getLineIndentColumn(lineNumber) { - return this._lines.getLineIndentColumn(lineNumber); - } - } - 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[248/*vs/editor/contrib/documentSymbols/outlineModel*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,23/*vs/base/common/cancellation*/,12/*vs/base/common/errors*/,49/*vs/base/common/map*/,3/*vs/editor/common/core/range*/,18/*vs/editor/common/modes*/,54/*vs/base/common/iterator*/,139/*vs/editor/common/modes/languageFeatureRegistry*/]), function (require, exports, arrays_1, cancellation_1, errors_1, map_1, range_1, modes_1, iterator_1, languageFeatureRegistry_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.OutlineModel = exports.OutlineGroup = exports.OutlineElement = exports.TreeElement = void 0; - class TreeElement { - remove() { - if (this.parent) { - this.parent.children.delete(this.id); - } - } - static findId(candidate, container) { - // complex id-computation which contains the origin/extension, - // the parent path, and some dedupe logic when names collide - let candidateId; - if (typeof candidate === 'string') { - candidateId = `${container.id}/${candidate}`; - } - else { - candidateId = `${container.id}/${candidate.name}`; - if (container.children.get(candidateId) !== undefined) { - candidateId = `${container.id}/${candidate.name}_${candidate.range.startLineNumber}_${candidate.range.startColumn}`; - } - } - let id = candidateId; - for (let i = 0; container.children.get(id) !== undefined; i++) { - id = `${candidateId}_${i}`; - } - return id; - } - static empty(element) { - return element.children.size === 0; - } - } - exports.TreeElement = TreeElement; - class OutlineElement extends TreeElement { - constructor(id, parent, symbol) { - super(); - this.id = id; - this.parent = parent; - this.symbol = symbol; - this.children = new Map(); - } - } - exports.OutlineElement = OutlineElement; - class OutlineGroup extends TreeElement { - constructor(id, parent, label, order) { - super(); - this.id = id; - this.parent = parent; - this.label = label; - this.order = order; - this.children = new Map(); - } - } - exports.OutlineGroup = OutlineGroup; - class OutlineModel extends TreeElement { - constructor(uri) { - super(); - this.uri = uri; - this.id = 'root'; - this.parent = undefined; - this._groups = new Map(); - this.children = new Map(); - this.id = 'root'; - this.parent = undefined; - } - static create(textModel, token) { - let key = this._keys.for(textModel, true); - let data = OutlineModel._requests.get(key); - if (!data) { - let source = new cancellation_1.CancellationTokenSource(); - data = { - promiseCnt: 0, - source, - promise: OutlineModel._create(textModel, source.token), - model: undefined, - }; - OutlineModel._requests.set(key, data); - // keep moving average of request durations - const now = Date.now(); - data.promise.then(() => { - this._requestDurations.update(textModel, Date.now() - now); - }); - } - if (data.model) { - // resolved -> return data - return Promise.resolve(data.model); - } - // increase usage counter - data.promiseCnt += 1; - token.onCancellationRequested(() => { - // last -> cancel provider request, remove cached promise - if (--data.promiseCnt === 0) { - data.source.cancel(); - OutlineModel._requests.delete(key); - } - }); - return new Promise((resolve, reject) => { - data.promise.then(model => { - data.model = model; - resolve(model); - }, err => { - OutlineModel._requests.delete(key); - reject(err); - }); - }); - } - static _create(textModel, token) { - const cts = new cancellation_1.CancellationTokenSource(token); - const result = new OutlineModel(textModel.uri); - const provider = modes_1.DocumentSymbolProviderRegistry.ordered(textModel); - const promises = provider.map((provider, index) => { - var _a; - let id = TreeElement.findId(`provider_${index}`, result); - let group = new OutlineGroup(id, result, (_a = provider.displayName) !== null && _a !== void 0 ? _a : 'Unknown Outline Provider', index); - return Promise.resolve(provider.provideDocumentSymbols(textModel, cts.token)).then(result => { - for (const info of result || []) { - OutlineModel._makeOutlineElement(info, group); - } - return group; - }, err => { - (0, errors_1.onUnexpectedExternalError)(err); - return group; - }).then(group => { - if (!TreeElement.empty(group)) { - result._groups.set(id, group); - } - else { - group.remove(); - } - }); - }); - const listener = modes_1.DocumentSymbolProviderRegistry.onDidChange(() => { - const newProvider = modes_1.DocumentSymbolProviderRegistry.ordered(textModel); - if (!(0, arrays_1.equals)(newProvider, provider)) { - cts.cancel(); - } - }); - return Promise.all(promises).then(() => { - if (cts.token.isCancellationRequested && !token.isCancellationRequested) { - return OutlineModel._create(textModel, token); - } - else { - return result._compact(); - } - }).finally(() => { - listener.dispose(); - }); - } - static _makeOutlineElement(info, container) { - let id = TreeElement.findId(info, container); - let res = new OutlineElement(id, container, info); - if (info.children) { - for (const childInfo of info.children) { - OutlineModel._makeOutlineElement(childInfo, res); - } - } - container.children.set(res.id, res); - } - _compact() { - let count = 0; - for (const [key, group] of this._groups) { - if (group.children.size === 0) { // empty - this._groups.delete(key); - } - else { - count += 1; - } - } - if (count !== 1) { - // - this.children = this._groups; - } - else { - // adopt all elements of the first group - let group = iterator_1.Iterable.first(this._groups.values()); - for (let [, child] of group.children) { - child.parent = this; - this.children.set(child.id, child); - } - } - return this; - } - getTopLevelSymbols() { - const roots = []; - for (const child of this.children.values()) { - if (child instanceof OutlineElement) { - roots.push(child.symbol); - } - else { - roots.push(...iterator_1.Iterable.map(child.children.values(), child => child.symbol)); - } - } - return roots.sort((a, b) => range_1.Range.compareRangesUsingStarts(a.range, b.range)); - } - asListOfDocumentSymbols() { - const roots = this.getTopLevelSymbols(); - const bucket = []; - OutlineModel._flattenDocumentSymbols(bucket, roots, ''); - return bucket.sort((a, b) => range_1.Range.compareRangesUsingStarts(a.range, b.range)); - } - static _flattenDocumentSymbols(bucket, entries, overrideContainerLabel) { - for (const entry of entries) { - 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, // we flatten it... - }); - // Recurse over children - if (entry.children) { - OutlineModel._flattenDocumentSymbols(bucket, entry.children, entry.name); - } - } - } - } - exports.OutlineModel = OutlineModel; - OutlineModel._requestDurations = new languageFeatureRegistry_1.LanguageFeatureRequestDelays(modes_1.DocumentSymbolProviderRegistry, 350); - OutlineModel._requests = new map_1.LRUCache(9, 0.75); - OutlineModel._keys = new class { - constructor() { - this._counter = 1; - this._data = new WeakMap(); - } - for(textModel, version) { - return `${textModel.id}/${version ? textModel.getVersionId() : ''}/${this._hash(modes_1.DocumentSymbolProviderRegistry.all(textModel))}`; - } - _hash(providers) { - let result = ''; - for (const provider of providers) { - let n = this._data.get(provider); - if (typeof n === 'undefined') { - n = this._counter++; - this._data.set(provider, n); - } - result += n; - } - 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[555/*vs/editor/contrib/folding/indentRangeProvider*/], __M([0/*require*/,1/*exports*/,178/*vs/editor/contrib/folding/foldingRanges*/,31/*vs/editor/common/model/textModel*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, foldingRanges_1, textModel_1, languageConfigurationRegistry_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.computeRanges = exports.RangesCollector = exports.IndentRangeProvider = exports.ID_INDENT_PROVIDER = void 0; - const MAX_FOLDING_REGIONS_FOR_INDENT_LIMIT = 5000; - exports.ID_INDENT_PROVIDER = 'indent'; - class IndentRangeProvider { - constructor(editorModel) { - this.editorModel = editorModel; - this.id = exports.ID_INDENT_PROVIDER; - } - dispose() { - } - compute(cancelationToken) { - let foldingRules = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getFoldingRules(this.editorModel.getLanguageIdentifier().id); - let offSide = foldingRules && !!foldingRules.offSide; - let markers = foldingRules && foldingRules.markers; - return Promise.resolve(computeRanges(this.editorModel, offSide, markers)); - } - } - exports.IndentRangeProvider = IndentRangeProvider; - // public only for testing - class RangesCollector { - constructor(foldingRangesLimit) { - this._startIndexes = []; - this._endIndexes = []; - this._indentOccurrences = []; - this._length = 0; - this._foldingRangesLimit = foldingRangesLimit; - } - insertFirst(startLineNumber, endLineNumber, indent) { - if (startLineNumber > foldingRanges_1.MAX_LINE_NUMBER || endLineNumber > foldingRanges_1.MAX_LINE_NUMBER) { - return; - } - let index = this._length; - this._startIndexes[index] = startLineNumber; - this._endIndexes[index] = endLineNumber; - this._length++; - if (indent < 1000) { - this._indentOccurrences[indent] = (this._indentOccurrences[indent] || 0) + 1; - } - } - toIndentRanges(model) { - if (this._length <= this._foldingRangesLimit) { - // reverse and create arrays of the exact length - let startIndexes = new Uint32Array(this._length); - let endIndexes = new Uint32Array(this._length); - for (let 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 { - let entries = 0; - let maxIndent = this._indentOccurrences.length; - for (let i = 0; i < this._indentOccurrences.length; i++) { - let n = this._indentOccurrences[i]; - if (n) { - if (n + entries > this._foldingRangesLimit) { - maxIndent = i; - break; - } - entries += n; - } - } - const tabSize = model.getOptions().tabSize; - // reverse and create arrays of the exact length - let startIndexes = new Uint32Array(this._foldingRangesLimit); - let endIndexes = new Uint32Array(this._foldingRangesLimit); - for (let i = this._length - 1, k = 0; i >= 0; i--) { - let startIndex = this._startIndexes[i]; - let lineContent = model.getLineContent(startIndex); - let 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); - } - } - } - exports.RangesCollector = RangesCollector; - function computeRanges(model, offSide, markers, foldingRangesLimit = MAX_FOLDING_REGIONS_FOR_INDENT_LIMIT) { - const tabSize = model.getOptions().tabSize; - let result = new RangesCollector(foldingRangesLimit); - let pattern = undefined; - if (markers) { - pattern = new RegExp(`(${markers.start.source})|(?:${markers.end.source})`); - } - let previousRegions = []; - let line = model.getLineCount() + 1; - previousRegions.push({ indent: -1, endAbove: line, line }); // sentinel, to make sure there's at least one entry - for (let line = model.getLineCount(); line > 0; line--) { - let lineContent = model.getLineContent(line); - let indent = textModel_1.TextModel.computeIndentLevel(lineContent, tabSize); - let 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; - } - continue; // only whitespace - } - let m; - if (pattern && (m = lineContent.match(pattern))) { - // folding pattern match - if (m[1]) { // start pattern match - // discard all regions until the folding pattern - let 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, previous.line, indent); - previous.line = line; - previous.indent = indent; - previous.endAbove = line; - continue; - } - else { - // no end marker found, treat line as a regular line - } - } - else { // end pattern match - previousRegions.push({ indent: -2, endAbove: line, line }); - 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 - let endLineNumber = previous.endAbove - 1; - if (endLineNumber - line >= 1) { // needs at east size 1 - result.insertFirst(line, endLineNumber, indent); - } - } - if (previous.indent === indent) { - previous.endAbove = line; - } - else { // previous.indent < indent - // new region with a bigger indent - previousRegions.push({ indent, endAbove: line, line }); - } - } - 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[556/*vs/editor/contrib/linesOperations/moveLinesCommand*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,184/*vs/editor/common/commands/shiftCommand*/,3/*vs/editor/common/core/range*/,21/*vs/editor/common/core/selection*/,112/*vs/editor/common/modes/languageConfiguration*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/,232/*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 }); - exports.MoveLinesCommand = void 0; - class MoveLinesCommand { - constructor(selection, isMovingDown, autoIndent) { - this._selection = selection; - this._isMovingDown = isMovingDown; - this._autoIndent = autoIndent; - this._selectionId = null; - this._moveEndLineSelectionShrink = false; - } - getEditOperations(model, builder) { - let 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; - let 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)); - } - const { tabSize, indentSize, insertSpaces } = model.getOptions(); - let indentConverter = this.buildIndentConverter(tabSize, indentSize, insertSpaces); - let virtualModel = { - getLineTokens: (lineNumber) => { - return model.getLineTokens(lineNumber); - }, - getLanguageIdentifier: () => { - return model.getLanguageIdentifier(); - }, - getLanguageIdAtPosition: (lineNumber, column) => { - return model.getLanguageIdAtPosition(lineNumber, column); - }, - getLineContent: null, - }; - if (s.startLineNumber === s.endLineNumber && model.getLineMaxColumn(s.startLineNumber) === 1) { - // Current line is empty - let lineNumber = s.startLineNumber; - let 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 { - let movingLineNumber; - let movingLineText; - if (this._isMovingDown) { - movingLineNumber = s.endLineNumber + 1; - movingLineText = model.getLineContent(movingLineNumber); - // Delete line that needs to be moved - builder.addEditOperation(new range_1.Range(movingLineNumber - 1, model.getLineMaxColumn(movingLineNumber - 1), movingLineNumber, model.getLineMaxColumn(movingLineNumber)), null); - let insertingText = movingLineText; - if (this.shouldAutoIndent(model, s)) { - let movingLineMatchResult = this.matchEnterRule(model, indentConverter, tabSize, movingLineNumber, s.startLineNumber - 1); - // if s.startLineNumber - 1 matches onEnter rule, we still honor that. - if (movingLineMatchResult !== null) { - let oldIndentation = strings.getLeadingWhitespace(model.getLineContent(movingLineNumber)); - let newSpaceCnt = movingLineMatchResult + indentUtils.getSpaceCnt(oldIndentation, tabSize); - let newIndentation = indentUtils.generateIndent(newSpaceCnt, tabSize, insertSpaces); - insertingText = newIndentation + this.trimLeft(movingLineText); - } - else { - // no enter rule matches, let's check indentatin rules then. - virtualModel.getLineContent = (lineNumber) => { - if (lineNumber === s.startLineNumber) { - return model.getLineContent(movingLineNumber); - } - else { - return model.getLineContent(lineNumber); - } - }; - let indentOfMovingLine = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(movingLineNumber, 1), s.startLineNumber, indentConverter); - if (indentOfMovingLine !== null) { - let oldIndentation = strings.getLeadingWhitespace(model.getLineContent(movingLineNumber)); - let newSpaceCnt = indentUtils.getSpaceCnt(indentOfMovingLine, tabSize); - let oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize); - if (newSpaceCnt !== oldSpaceCnt) { - let newIndentation = indentUtils.generateIndent(newSpaceCnt, tabSize, insertSpaces); - insertingText = 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 + '\n'); - let ret = this.matchEnterRuleMovingDown(model, indentConverter, tabSize, s.startLineNumber, movingLineNumber, insertingText); - // 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 = (lineNumber) => { - if (lineNumber === s.startLineNumber) { - return insertingText; - } - else if (lineNumber >= s.startLineNumber + 1 && lineNumber <= s.endLineNumber + 1) { - return model.getLineContent(lineNumber - 1); - } - else { - return model.getLineContent(lineNumber); - } - }; - let newIndentatOfMovingBlock = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(movingLineNumber, 1), s.startLineNumber + 1, indentConverter); - if (newIndentatOfMovingBlock !== null) { - const oldIndentation = strings.getLeadingWhitespace(model.getLineContent(s.startLineNumber)); - const newSpaceCnt = indentUtils.getSpaceCnt(newIndentatOfMovingBlock, tabSize); - const oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize); - if (newSpaceCnt !== oldSpaceCnt) { - const 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 + '\n'); - } - } - else { - movingLineNumber = s.startLineNumber - 1; - movingLineText = model.getLineContent(movingLineNumber); - // Delete line that needs to be moved - builder.addEditOperation(new range_1.Range(movingLineNumber, 1, movingLineNumber + 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 = (lineNumber) => { - if (lineNumber === movingLineNumber) { - return model.getLineContent(s.startLineNumber); - } - else { - return model.getLineContent(lineNumber); - } - }; - let 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. - let indentOfFirstLine = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(s.startLineNumber, 1), movingLineNumber, indentConverter); - if (indentOfFirstLine !== null) { - // adjust the indentation of the moving block - let oldIndent = strings.getLeadingWhitespace(model.getLineContent(s.startLineNumber)); - let newSpaceCnt = indentUtils.getSpaceCnt(indentOfFirstLine, tabSize); - let oldSpaceCnt = indentUtils.getSpaceCnt(oldIndent, tabSize); - if (newSpaceCnt !== oldSpaceCnt) { - let spaceCntOffset = newSpaceCnt - oldSpaceCnt; - this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, spaceCntOffset); - } - } - } - } - } - } - this._selectionId = builder.trackSelection(s); - } - buildIndentConverter(tabSize, indentSize, insertSpaces) { - return { - shiftIndent: (indentation) => { - return shiftCommand_1.ShiftCommand.shiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces); - }, - unshiftIndent: (indentation) => { - return shiftCommand_1.ShiftCommand.unshiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces); - } - }; - } - parseEnterResult(model, indentConverter, tabSize, line, enter) { - if (enter) { - let 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; - } - let movingLineText = model.getLineContent(line); - if (this.trimLeft(movingLineText).indexOf(this.trimLeft(enterPrefix)) >= 0) { - let oldIndentation = strings.getLeadingWhitespace(model.getLineContent(line)); - let newIndentation = strings.getLeadingWhitespace(enterPrefix); - let indentMetadataOfMovelingLine = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentMetadata(model, line); - if (indentMetadataOfMovelingLine !== null && indentMetadataOfMovelingLine & 2 /* DECREASE_MASK */) { - newIndentation = indentConverter.unshiftIndent(newIndentation); - } - let newSpaceCnt = indentUtils.getSpaceCnt(newIndentation, tabSize); - let oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize); - return newSpaceCnt - oldSpaceCnt; - } - } - return null; - } - /** - * - * @param model - * @param indentConverter - * @param tabSize - * @param line the line moving down - * @param futureAboveLineNumber the line which will be at the `line` position - * @param futureAboveLineText - */ - matchEnterRuleMovingDown(model, indentConverter, tabSize, line, futureAboveLineNumber, futureAboveLineText) { - if (strings.lastNonWhitespaceIndex(futureAboveLineText) >= 0) { - // break - let maxColumn = model.getLineMaxColumn(futureAboveLineNumber); - let enter = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getEnterAction(this._autoIndent, model, new range_1.Range(futureAboveLineNumber, maxColumn, futureAboveLineNumber, maxColumn)); - return this.parseEnterResult(model, indentConverter, tabSize, line, enter); - } - else { - // go upwards, starting from `line - 1` - let validPrecedingLine = line - 1; - while (validPrecedingLine >= 1) { - let lineContent = model.getLineContent(validPrecedingLine); - let nonWhitespaceIdx = strings.lastNonWhitespaceIndex(lineContent); - if (nonWhitespaceIdx >= 0) { - break; - } - validPrecedingLine--; - } - if (validPrecedingLine < 1 || line > model.getLineCount()) { - return null; - } - let maxColumn = model.getLineMaxColumn(validPrecedingLine); - let enter = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getEnterAction(this._autoIndent, model, new range_1.Range(validPrecedingLine, maxColumn, validPrecedingLine, maxColumn)); - return this.parseEnterResult(model, indentConverter, tabSize, line, enter); - } - } - matchEnterRule(model, indentConverter, tabSize, line, oneLineAbove, previousLineText) { - let validPrecedingLine = oneLineAbove; - while (validPrecedingLine >= 1) { - // ship empty lines as empty lines just inherit indentation - let lineContent; - if (validPrecedingLine === oneLineAbove && previousLineText !== undefined) { - lineContent = previousLineText; - } - else { - lineContent = model.getLineContent(validPrecedingLine); - } - let nonWhitespaceIdx = strings.lastNonWhitespaceIndex(lineContent); - if (nonWhitespaceIdx >= 0) { - break; - } - validPrecedingLine--; - } - if (validPrecedingLine < 1 || line > model.getLineCount()) { - return null; - } - let maxColumn = model.getLineMaxColumn(validPrecedingLine); - let enter = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getEnterAction(this._autoIndent, model, new range_1.Range(validPrecedingLine, maxColumn, validPrecedingLine, maxColumn)); - return this.parseEnterResult(model, indentConverter, tabSize, line, enter); - } - trimLeft(str) { - return str.replace(/^\s+/, ''); - } - shouldAutoIndent(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; - } - let languageAtSelectionStart = model.getLanguageIdAtPosition(selection.startLineNumber, 1); - let languageAtSelectionEnd = model.getLanguageIdAtPosition(selection.endLineNumber, 1); - if (languageAtSelectionStart !== languageAtSelectionEnd) { - return false; - } - if (languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentRulesSupport(languageAtSelectionStart) === null) { - return false; - } - return true; - } - getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, offset) { - for (let i = s.startLineNumber; i <= s.endLineNumber; i++) { - let lineContent = model.getLineContent(i); - let originalIndent = strings.getLeadingWhitespace(lineContent); - let originalSpacesCnt = indentUtils.getSpaceCnt(originalIndent, tabSize); - let newSpacesCnt = originalSpacesCnt + offset; - let 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; - } - } - } - } - computeCursorState(model, helper) { - let 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; - } - } - 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[557/*vs/editor/contrib/zoneWidget/zoneWidget*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,107/*vs/base/browser/ui/sash/sash*/,29/*vs/base/common/color*/,125/*vs/base/common/idGenerator*/,2/*vs/base/common/lifecycle*/,42/*vs/base/common/objects*/,3/*vs/editor/common/core/range*/,31/*vs/editor/common/model/textModel*/,362/*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 }); - exports.ZoneWidget = exports.OverlayWidgetDelegate = exports.ViewZoneDelegate = void 0; - const defaultColor = new color_1.Color(new color_1.RGBA(0, 122, 204)); - const defaultOptions = { - showArrow: true, - showFrame: true, - className: '', - frameColor: defaultColor, - arrowColor: defaultColor, - keepEditorSelection: false - }; - const WIDGET_ID = 'vs.editor.contrib.zoneWidget'; - class ViewZoneDelegate { - constructor(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; - } - onDomNodeTop(top) { - this._onDomNodeTop(top); - } - onComputedHeight(height) { - this._onComputedHeight(height); - } - } - exports.ViewZoneDelegate = ViewZoneDelegate; - class OverlayWidgetDelegate { - constructor(id, domNode) { - this._id = id; - this._domNode = domNode; - } - getId() { - return this._id; - } - getDomNode() { - return this._domNode; - } - getPosition() { - return null; - } - } - exports.OverlayWidgetDelegate = OverlayWidgetDelegate; - class Arrow { - constructor(_editor) { - this._editor = _editor; - this._ruleName = Arrow._IdGenerator.nextId(); - this._decorations = []; - this._color = null; - this._height = -1; - // - } - dispose() { - this.hide(); - dom.removeCSSRulesContainingSelector(this._ruleName); - } - set color(value) { - if (this._color !== value) { - this._color = value; - this._updateStyle(); - } - } - set height(value) { - if (this._height !== value) { - this._height = value; - this._updateStyle(); - } - } - _updateStyle() { - 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; `); - } - show(where) { - this._decorations = this._editor.deltaDecorations(this._decorations, [{ range: range_1.Range.fromPositions(where), options: { description: 'zone-widget-arrow', className: this._ruleName, stickiness: 1 /* NeverGrowsWhenTypingAtEdges */ } }]); - } - hide() { - this._editor.deltaDecorations(this._decorations, []); - } - } - Arrow._IdGenerator = new idGenerator_1.IdGenerator('.arrow-decoration-'); - class ZoneWidget { - constructor(editor, 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((info) => { - const width = this._getWidth(info); - this.domNode.style.width = width + 'px'; - this.domNode.style.left = this._getLeft(info) + 'px'; - this._onWidth(width); - })); - } - dispose() { - if (this._overlayWidget) { - this.editor.removeOverlayWidget(this._overlayWidget); - this._overlayWidget = null; - } - if (this._viewZone) { - this.editor.changeViewZones(accessor => { - if (this._viewZone) { - accessor.removeZone(this._viewZone.id); - } - this._viewZone = null; - }); - } - this.editor.deltaDecorations(this._positionMarkerId, []); - this._positionMarkerId = []; - this._disposables.dispose(); - } - create() { - this.domNode.classList.add('zone-widget'); - if (this.options.className) { - this.domNode.classList.add(this.options.className); - } - this.container = document.createElement('div'); - this.container.classList.add('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(); - } - style(styles) { - if (styles.frameColor) { - this.options.frameColor = styles.frameColor; - } - if (styles.arrowColor) { - this.options.arrowColor = styles.arrowColor; - } - this._applyStyles(); - } - _applyStyles() { - if (this.container && this.options.frameColor) { - let frameColor = this.options.frameColor.toString(); - this.container.style.borderTopColor = frameColor; - this.container.style.borderBottomColor = frameColor; - } - if (this._arrow && this.options.arrowColor) { - let arrowColor = this.options.arrowColor.toString(); - this._arrow.color = arrowColor; - } - } - _getWidth(info) { - return info.width - info.minimap.minimapWidth - info.verticalScrollbarWidth; - } - _getLeft(info) { - // If minimap is to the left, we move beyond it - if (info.minimap.minimapWidth > 0 && info.minimap.minimapLeft === 0) { - return info.minimap.minimapWidth; - } - return 0; - } - _onViewZoneTop(top) { - this.domNode.style.top = top + 'px'; - } - _onViewZoneHeight(height) { - this.domNode.style.height = `${height}px`; - if (this.container) { - let containerHeight = height - this._decoratingElementsHeight(); - this.container.style.height = `${containerHeight}px`; - const layoutInfo = this.editor.getLayoutInfo(); - this._doLayout(containerHeight, this._getWidth(layoutInfo)); - } - if (this._resizeSash) { - this._resizeSash.layout(); - } - } - get position() { - const [id] = this._positionMarkerId; - if (!id) { - return undefined; - } - const model = this.editor.getModel(); - if (!model) { - return undefined; - } - const range = model.getDecorationRange(id); - if (!range) { - return undefined; - } - return range.getStartPosition(); - } - show(rangeOrPos, heightInLines) { - const 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, options: textModel_1.ModelDecorationOptions.EMPTY }]); - } - hide() { - if (this._viewZone) { - this.editor.changeViewZones(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(); - } - } - _decoratingElementsHeight() { - let lineHeight = this.editor.getOption(57 /* lineHeight */); - let result = 0; - if (this.options.showArrow) { - let arrowHeight = Math.round(lineHeight / 3); - result += 2 * arrowHeight; - } - if (this.options.showFrame) { - let frameThickness = Math.round(lineHeight / 9); - result += 2 * frameThickness; - } - return result; - } - _showImpl(where, heightInLines) { - const position = where.getStartPosition(); - const layoutInfo = this.editor.getLayoutInfo(); - const 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) - const viewZoneDomNode = document.createElement('div'); - viewZoneDomNode.style.overflow = 'hidden'; - const lineHeight = this.editor.getOption(57 /* lineHeight */); - // adjust heightInLines to viewport - const maxHeightInLines = Math.max(12, (this.editor.getLayoutInfo().height / lineHeight) * 0.8); - heightInLines = Math.min(heightInLines, maxHeightInLines); - let arrowHeight = 0; - let 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((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, (top) => this._onViewZoneTop(top), (height) => 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) { - const width = this.options.frameWidth ? this.options.frameWidth : frameThickness; - this.container.style.borderTopWidth = width + 'px'; - this.container.style.borderBottomWidth = width + 'px'; - } - let 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); - } - const model = this.editor.getModel(); - if (model) { - const 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); - } - } - } - revealLine(lineNumber, isLastLine) { - if (isLastLine) { - this.editor.revealLineInCenter(lineNumber, 0 /* Smooth */); - } - else { - this.editor.revealLine(lineNumber, 0 /* Smooth */); - } - } - setCssClass(className, classToReplace) { - if (!this.container) { - return; - } - if (classToReplace) { - this.container.classList.remove(classToReplace); - } - this.container.classList.add(className); - } - _onWidth(widthInPixel) { - // implement in subclass - } - _doLayout(heightInPixel, widthInPixel) { - // implement in subclass - } - _relayout(newHeightInLines) { - if (this._viewZone && this._viewZone.heightInLines !== newHeightInLines) { - this.editor.changeViewZones(accessor => { - if (this._viewZone) { - this._viewZone.heightInLines = newHeightInLines; - accessor.layoutZone(this._viewZone.id); - } - }); - } - } - // --- sash - _initSash() { - 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 */; - } - let data; - this._disposables.add(this._resizeSash.onDidStart((e) => { - if (this._viewZone) { - data = { - startY: e.startY, - heightInLines: this._viewZone.heightInLines, - }; - } - })); - this._disposables.add(this._resizeSash.onDidEnd(() => { - data = undefined; - })); - this._disposables.add(this._resizeSash.onDidChange((evt) => { - if (data) { - let lineDelta = (evt.currentY - data.startY) / this.editor.getOption(57 /* lineHeight */); - let roundedLineDelta = lineDelta < 0 ? Math.ceil(lineDelta) : Math.floor(lineDelta); - let newHeightInLines = data.heightInLines + roundedLineDelta; - if (newHeightInLines > 5 && newHeightInLines < 35) { - this._relayout(newHeightInLines); - } - } - })); - } - getHorizontalSashLeft() { - return 0; - } - getHorizontalSashTop() { - return (this.domNode.style.height === null ? 0 : parseInt(this.domNode.style.height)) - (this._decoratingElementsHeight() / 2); - } - getHorizontalSashWidth() { - const layoutInfo = this.editor.getLayoutInfo(); - return layoutInfo.width - layoutInfo.minimap.minimapWidth; - } - } - 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[249/*vs/editor/standalone/common/monarch/monarchLexer*/], __M([0/*require*/,1/*exports*/,134/*vs/editor/common/core/token*/,18/*vs/editor/common/modes*/,77/*vs/editor/common/modes/nullMode*/,236/*vs/editor/standalone/common/monarch/monarchCommon*/]), function (require, exports, token_1, modes, nullMode_1, monarchCommon) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.createTokenizationSupport = exports.MonarchTokenizer = void 0; - const CACHE_STACK_DEPTH = 5; - /** - * Reuse the same stack elements up to a certain depth. - */ - class MonarchStackElementFactory { - constructor(maxCacheDepth) { - this._maxCacheDepth = maxCacheDepth; - this._entries = Object.create(null); - } - static create(parent, state) { - return this._INSTANCE.create(parent, state); - } - create(parent, state) { - if (parent !== null && parent.depth >= this._maxCacheDepth) { - // no caching above a certain depth - return new MonarchStackElement(parent, state); - } - let stackElementId = MonarchStackElement.getStackElementId(parent); - if (stackElementId.length > 0) { - stackElementId += '|'; - } - stackElementId += state; - let 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); - class MonarchStackElement { - constructor(parent, state) { - this.parent = parent; - this.state = state; - this.depth = (this.parent ? this.parent.depth : 0) + 1; - } - static getStackElementId(element) { - let result = ''; - while (element !== null) { - if (result.length > 0) { - result += '|'; - } - result += element.state; - element = element.parent; - } - return result; - } - static _equals(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; - } - equals(other) { - return MonarchStackElement._equals(this, other); - } - push(state) { - return MonarchStackElementFactory.create(this, state); - } - pop() { - return this.parent; - } - popall() { - let result = this; - while (result.parent) { - result = result.parent; - } - return result; - } - switchTo(state) { - return MonarchStackElementFactory.create(this.parent, state); - } - } - class EmbeddedModeData { - constructor(modeId, state) { - this.modeId = modeId; - this.state = state; - } - equals(other) { - return (this.modeId === other.modeId - && this.state.equals(other.state)); - } - clone() { - let stateClone = this.state.clone(); - // save an object - if (stateClone === this.state) { - return this; - } - return new EmbeddedModeData(this.modeId, this.state); - } - } - /** - * Reuse the same line states up to a certain depth. - */ - class MonarchLineStateFactory { - constructor(maxCacheDepth) { - this._maxCacheDepth = maxCacheDepth; - this._entries = Object.create(null); - } - static create(stack, embeddedModeData) { - return this._INSTANCE.create(stack, embeddedModeData); - } - create(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); - } - let stackElementId = MonarchStackElement.getStackElementId(stack); - let 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); - class MonarchLineState { - constructor(stack, embeddedModeData) { - this.stack = stack; - this.embeddedModeData = embeddedModeData; - } - clone() { - let embeddedModeDataClone = this.embeddedModeData ? this.embeddedModeData.clone() : null; - // save an object - if (embeddedModeDataClone === this.embeddedModeData) { - return this; - } - return MonarchLineStateFactory.create(this.stack, this.embeddedModeData); - } - equals(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); - } - } - class MonarchClassicTokensCollector { - constructor() { - this._tokens = []; - this._language = null; - this._lastTokenType = null; - this._lastTokenLanguage = null; - } - enterMode(startOffset, modeId) { - this._language = modeId; - } - emit(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)); - } - nestedModeTokenize(embeddedModeLine, hasEOL, embeddedModeData, offsetDelta) { - const nestedModeId = embeddedModeData.modeId; - const embeddedModeState = embeddedModeData.state; - const nestedModeTokenizationSupport = modes.TokenizationRegistry.get(nestedModeId); - if (!nestedModeTokenizationSupport) { - this.enterMode(offsetDelta, nestedModeId); - this.emit(offsetDelta, ''); - return embeddedModeState; - } - let nestedResult = nestedModeTokenizationSupport.tokenize(embeddedModeLine, hasEOL, embeddedModeState, offsetDelta); - this._tokens = this._tokens.concat(nestedResult.tokens); - this._lastTokenType = null; - this._lastTokenLanguage = null; - this._language = null; - return nestedResult.endState; - } - finalize(endState) { - return new token_1.TokenizationResult(this._tokens, endState); - } - } - class MonarchModernTokensCollector { - constructor(modeService, theme) { - this._modeService = modeService; - this._theme = theme; - this._prependTokens = null; - this._tokens = []; - this._currentLanguageId = 0 /* Null */; - this._lastTokenMetadata = 0; - } - enterMode(startOffset, modeId) { - this._currentLanguageId = this._modeService.getLanguageIdentifier(modeId).id; - } - emit(startOffset, type) { - let metadata = this._theme.match(this._currentLanguageId, type); - if (this._lastTokenMetadata === metadata) { - return; - } - this._lastTokenMetadata = metadata; - this._tokens.push(startOffset); - this._tokens.push(metadata); - } - static _merge(a, b, c) { - let aLen = (a !== null ? a.length : 0); - let bLen = b.length; - let 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; - } - let result = new Uint32Array(aLen + bLen + cLen); - if (a !== null) { - result.set(a); - } - for (let i = 0; i < bLen; i++) { - result[aLen + i] = b[i]; - } - if (c !== null) { - result.set(c, aLen + bLen); - } - return result; - } - nestedModeTokenize(embeddedModeLine, hasEOL, embeddedModeData, offsetDelta) { - const nestedModeId = embeddedModeData.modeId; - const embeddedModeState = embeddedModeData.state; - const nestedModeTokenizationSupport = modes.TokenizationRegistry.get(nestedModeId); - if (!nestedModeTokenizationSupport) { - this.enterMode(offsetDelta, nestedModeId); - this.emit(offsetDelta, ''); - return embeddedModeState; - } - let nestedResult = nestedModeTokenizationSupport.tokenize2(embeddedModeLine, hasEOL, embeddedModeState, offsetDelta); - this._prependTokens = MonarchModernTokensCollector._merge(this._prependTokens, this._tokens, nestedResult.tokens); - this._tokens = []; - this._currentLanguageId = 0; - this._lastTokenMetadata = 0; - return nestedResult.endState; - } - finalize(endState) { - return new token_1.TokenizationResult2(MonarchModernTokensCollector._merge(this._prependTokens, this._tokens, null), endState); - } - } - class MonarchTokenizer { - constructor(modeService, standaloneThemeService, modeId, lexer) { - 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 - let emitting = false; - this._tokenizationRegistryListener = modes.TokenizationRegistry.onDidChange((e) => { - if (emitting) { - return; - } - let isOneOfMyEmbeddedModes = false; - for (let i = 0, len = e.changedLanguages.length; i < len; i++) { - let language = e.changedLanguages[i]; - if (this._embeddedModes[language]) { - isOneOfMyEmbeddedModes = true; - break; - } - } - if (isOneOfMyEmbeddedModes) { - emitting = true; - modes.TokenizationRegistry.fire([this._modeId]); - emitting = false; - } - }); - } - dispose() { - this._tokenizationRegistryListener.dispose(); - } - getLoadStatus() { - let promises = []; - for (let nestedModeId in this._embeddedModes) { - const tokenizationSupport = modes.TokenizationRegistry.get(nestedModeId); - if (tokenizationSupport) { - // The nested mode is already loaded - if (tokenizationSupport instanceof MonarchTokenizer) { - const nestedModeStatus = tokenizationSupport.getLoadStatus(); - if (nestedModeStatus.loaded === false) { - promises.push(nestedModeStatus.promise); - } - } - continue; - } - const 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(_ => undefined) - }; - } - getInitialState() { - let rootState = MonarchStackElementFactory.create(null, this._lexer.start); - return MonarchLineStateFactory.create(rootState, null); - } - tokenize(line, hasEOL, lineState, offsetDelta) { - let tokensCollector = new MonarchClassicTokensCollector(); - let endLineState = this._tokenize(line, hasEOL, lineState, offsetDelta, tokensCollector); - return tokensCollector.finalize(endLineState); - } - tokenize2(line, hasEOL, lineState, offsetDelta) { - let tokensCollector = new MonarchModernTokensCollector(this._modeService, this._standaloneThemeService.getColorTheme().tokenTheme); - let endLineState = this._tokenize(line, hasEOL, lineState, offsetDelta, tokensCollector); - return tokensCollector.finalize(endLineState); - } - _tokenize(line, hasEOL, lineState, offsetDelta, collector) { - if (lineState.embeddedModeData) { - return this._nestedTokenize(line, hasEOL, lineState, offsetDelta, collector); - } - else { - return this._myTokenize(line, hasEOL, lineState, offsetDelta, collector); - } - } - _findLeavingNestedModeOffset(line, state) { - let 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); - } - } - let popOffset = -1; - let hasEmbeddedPopRule = false; - for (const rule of rules) { - if (!monarchCommon.isIAction(rule.action) || rule.action.nextEmbedded !== '@pop') { - continue; - } - hasEmbeddedPopRule = true; - let regex = rule.regex; - let regexSource = rule.regex.source; - if (regexSource.substr(0, 4) === '^(?:' && regexSource.substr(regexSource.length - 1, 1) === ')') { - let flags = (regex.ignoreCase ? 'i' : '') + (regex.unicode ? 'u' : ''); - regex = new RegExp(regexSource.substr(4, regexSource.length - 5), flags); - } - let 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; - } - _nestedTokenize(line, hasEOL, lineState, offsetDelta, tokensCollector) { - let popOffset = this._findLeavingNestedModeOffset(line, lineState); - if (popOffset === -1) { - // tokenization will not leave nested mode - let nestedEndState = tokensCollector.nestedModeTokenize(line, hasEOL, lineState.embeddedModeData, offsetDelta); - return MonarchLineStateFactory.create(lineState.stack, new EmbeddedModeData(lineState.embeddedModeData.modeId, nestedEndState)); - } - let nestedModeLine = line.substring(0, popOffset); - if (nestedModeLine.length > 0) { - // tokenize with the nested mode - tokensCollector.nestedModeTokenize(nestedModeLine, false, lineState.embeddedModeData, offsetDelta); - } - let restOfTheLine = line.substring(popOffset); - return this._myTokenize(restOfTheLine, hasEOL, lineState, offsetDelta + popOffset, tokensCollector); - } - _safeRuleName(rule) { - if (rule) { - return rule.name; - } - return '(unknown)'; - } - _myTokenize(lineWithoutLF, hasEOL, lineState, offsetDelta, tokensCollector) { - tokensCollector.enterMode(offsetDelta, this._modeId); - const lineWithoutLFLength = lineWithoutLF.length; - const line = (hasEOL && this._lexer.includeLF ? lineWithoutLF + '\n' : lineWithoutLF); - const lineLength = line.length; - let embeddedModeData = lineState.embeddedModeData; - let stack = lineState.stack; - let pos = 0; - let groupMatching = null; - // See https://github.com/microsoft/monaco-editor/issues/1235 - // Evaluate rules at least once for an empty line - let forceEvaluation = true; - while (forceEvaluation || pos < lineLength) { - const pos0 = pos; - const stackLen0 = stack.depth; - const groupLen0 = groupMatching ? groupMatching.groups.length : 0; - const state = stack.state; - let matches = null; - let matched = null; - let action = null; - let rule = null; - let enteringEmbeddedMode = null; - // check if we need to process group matches first - if (groupMatching) { - matches = groupMatching.matches; - const 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 - let 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 - let restOfLine = line.substr(pos); - for (const rule of rules) { - if (pos === 0 || !rule.matchOnlyAtLineStart) { - matches = restOfLine.match(rule.regex); - if (matches) { - matched = matches[0]; - action = rule.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); - } - let 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') { - let 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 { - let 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)); - } - const computeNewStateForEmbeddedMode = (enteringEmbeddedMode) => { - // substitute language alias to known modes to support syntax highlighting - let enteringEmbeddedModeId = this._modeService.getModeIdForLanguageName(enteringEmbeddedMode); - if (enteringEmbeddedModeId) { - enteringEmbeddedMode = enteringEmbeddedModeId; - } - const embeddedModeData = this._getNestedEmbeddedModeData(enteringEmbeddedMode); - if (pos < lineLength) { - // there is content from the embedded mode on this line - const restOfLine = lineWithoutLF.substr(pos); - return this._nestedTokenize(restOfLine, hasEOL, MonarchLineStateFactory.create(stack, embeddedModeData), offsetDelta + pos, tokensCollector); - } - else { - return MonarchLineStateFactory.create(stack, embeddedModeData); - } - }; - // 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)); - } - let totalLen = 0; - for (let 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 (let 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 = ''; - // Even though `@rematch` was specified, if `nextEmbedded` also specified, - // a state transition should occur. - if (enteringEmbeddedMode !== null) { - return computeNewStateForEmbeddedMode(enteringEmbeddedMode); - } - } - // 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 - let tokenType = null; - if (monarchCommon.isString(result) && result.indexOf('@brackets') === 0) { - let rest = result.substr('@brackets'.length); - let 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 { - let token = (result === '' ? '' : result + this._lexer.tokenPostfix); - tokenType = monarchCommon.sanitize(token); - } - if (pos0 < lineWithoutLFLength) { - tokensCollector.emit(pos0 + offsetDelta, tokenType); - } - } - if (enteringEmbeddedMode !== null) { - return computeNewStateForEmbeddedMode(enteringEmbeddedMode); - } - } - return MonarchLineStateFactory.create(stack, embeddedModeData); - } - _getNestedEmbeddedModeData(mimetypeOrModeId) { - let nestedModeId = this._locateMode(mimetypeOrModeId); - if (nestedModeId) { - let 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); - } - _locateMode(mimetypeOrModeId) { - if (!mimetypeOrModeId || !this._modeService.isRegisteredMode(mimetypeOrModeId)) { - return null; - } - if (mimetypeOrModeId === this._modeId) { - // embedding myself... - return mimetypeOrModeId; - } - let modeId = this._modeService.getModeId(mimetypeOrModeId); - if (modeId) { - // Fire mode loading event - this._modeService.triggerMode(modeId); - this._embeddedModes[modeId] = true; - } - return modeId; - } - } - 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); - let brackets = lexer.brackets; - for (const bracket of brackets) { - 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[558/*vs/editor/standalone/browser/colorizer*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,8/*vs/base/common/strings*/,85/*vs/editor/common/core/lineTokens*/,18/*vs/editor/common/modes*/,114/*vs/editor/common/viewLayout/viewLineRenderer*/,62/*vs/editor/common/viewModel/viewModel*/,249/*vs/editor/standalone/common/monarch/monarchLexer*/]), function (require, exports, async_1, strings, lineTokens_1, modes_1, viewLineRenderer_1, viewModel_1, monarchLexer_1) { - "use strict"; - var _a; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Colorizer = void 0; - const ttPolicy = (_a = window.trustedTypes) === null || _a === void 0 ? void 0 : _a.createPolicy('standaloneColorizer', { createHTML: value => value }); - class Colorizer { - static colorizeElement(themeService, modeService, domNode, options) { - options = options || {}; - let theme = options.theme || 'vs'; - let mimeType = options.mimeType || domNode.getAttribute('lang') || domNode.getAttribute('data-lang'); - if (!mimeType) { - console.error('Mode not detected'); - return Promise.resolve(); - } - themeService.setTheme(theme); - let text = domNode.firstChild ? domNode.firstChild.nodeValue : ''; - domNode.className += ' ' + theme; - let render = (str) => { - var _a; - const trustedhtml = (_a = ttPolicy === null || ttPolicy === void 0 ? void 0 : ttPolicy.createHTML(str)) !== null && _a !== void 0 ? _a : str; - domNode.innerHTML = trustedhtml; - }; - return this.colorize(modeService, text || '', mimeType, options).then(render, (err) => console.error(err)); - } - static colorize(modeService, text, mimeType, options) { - let tabSize = 4; - if (options && typeof options.tabSize === 'number') { - tabSize = options.tabSize; - } - if (strings.startsWithUTF8BOM(text)) { - text = text.substr(1); - } - let lines = strings.splitLines(text); - let language = modeService.getModeId(mimeType); - if (!language) { - return Promise.resolve(_fakeColorize(lines, tabSize)); - } - // Send out the event to create the mode - modeService.triggerMode(language); - const tokenizationSupport = modes_1.TokenizationRegistry.get(language); - if (tokenizationSupport) { - return _colorize(lines, tabSize, tokenizationSupport); - } - const tokenizationSupportPromise = modes_1.TokenizationRegistry.getPromise(language); - if (tokenizationSupportPromise) { - // A tokenizer will be registered soon - return new Promise((resolve, reject) => { - tokenizationSupportPromise.then(tokenizationSupport => { - _colorize(lines, tabSize, tokenizationSupport).then(resolve, reject); - }, reject); - }); - } - return new Promise((resolve, reject) => { - let listener = null; - let timeout = null; - const execute = () => { - if (listener) { - listener.dispose(); - listener = null; - } - if (timeout) { - timeout.dispose(); - timeout = null; - } - const 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((e) => { - if (e.changedLanguages.indexOf(language) >= 0) { - execute(); - } - }); - }); - } - static colorizeLine(line, mightContainNonBasicASCII, mightContainRTL, tokens, tabSize = 4) { - const isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(line, mightContainNonBasicASCII); - const containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(line, isBasicASCII, mightContainRTL); - let renderResult = (0, viewLineRenderer_1.renderViewLine2)(new viewLineRenderer_1.RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, tokens, [], tabSize, 0, 0, 0, 0, -1, 'none', false, false, null)); - return renderResult.html; - } - static colorizeModelLine(model, lineNumber, tabSize = 4) { - let content = model.getLineContent(lineNumber); - model.forceTokenization(lineNumber); - let tokens = model.getLineTokens(lineNumber); - let inflatedTokens = tokens.inflate(); - return this.colorizeLine(content, model.mightContainNonBasicASCII(), model.mightContainRTL(), inflatedTokens, tabSize); - } - } - exports.Colorizer = Colorizer; - function _colorize(lines, tabSize, tokenizationSupport) { - return new Promise((c, e) => { - const execute = () => { - const result = _actualColorize(lines, tabSize, tokenizationSupport); - if (tokenizationSupport instanceof monarchLexer_1.MonarchTokenizer) { - const status = tokenizationSupport.getLoadStatus(); - if (status.loaded === false) { - status.promise.then(execute, e); - return; - } - } - c(result); - }; - execute(); - }); - } - function _fakeColorize(lines, tabSize) { - let html = []; - const defaultMetadata = ((0 /* None */ << 11 /* FONT_STYLE_OFFSET */) - | (1 /* DefaultForeground */ << 14 /* FOREGROUND_OFFSET */) - | (2 /* DefaultBackground */ << 23 /* BACKGROUND_OFFSET */)) >>> 0; - const tokens = new Uint32Array(2); - tokens[0] = 0; - tokens[1] = defaultMetadata; - for (let i = 0, length = lines.length; i < length; i++) { - let line = lines[i]; - tokens[0] = line.length; - const lineTokens = new lineTokens_1.LineTokens(tokens, line); - const isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(line, /* check for basic ASCII */ true); - const containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(line, isBasicASCII, /* check for RTL */ true); - let renderResult = (0, viewLineRenderer_1.renderViewLine2)(new viewLineRenderer_1.RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, lineTokens, [], tabSize, 0, 0, 0, 0, -1, 'none', false, false, null)); - html = html.concat(renderResult.html); - html.push('
    '); - } - return html.join(''); - } - function _actualColorize(lines, tabSize, tokenizationSupport) { - let html = []; - let state = tokenizationSupport.getInitialState(); - for (let i = 0, length = lines.length; i < length; i++) { - let line = lines[i]; - let tokenizeResult = tokenizationSupport.tokenize2(line, true, state, 0); - lineTokens_1.LineTokens.convertToEndOffset(tokenizeResult.tokens, line.length); - let lineTokens = new lineTokens_1.LineTokens(tokenizeResult.tokens, line); - const isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(line, /* check for basic ASCII */ true); - const containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(line, isBasicASCII, /* check for RTL */ true); - let renderResult = (0, viewLineRenderer_1.renderViewLine2)(new viewLineRenderer_1.RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, lineTokens.inflate(), [], tabSize, 0, 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[119/*vs/editor/standalone/common/standaloneThemeService*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.IStandaloneThemeService = void 0; - exports.IStandaloneThemeService = (0, 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[86/*vs/platform/clipboard/common/clipboardService*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.IClipboardService = void 0; - exports.IClipboardService = (0, 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. - *--------------------------------------------------------------------------------------------*/ -define(__m[26/*vs/platform/commands/common/commands*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,20/*vs/base/common/types*/,9/*vs/platform/instantiation/common/instantiation*/,6/*vs/base/common/event*/,72/*vs/base/common/linkedList*/,54/*vs/base/common/iterator*/]), function (require, exports, lifecycle_1, types_1, instantiation_1, event_1, linkedList_1, iterator_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CommandsRegistry = exports.ICommandService = void 0; - exports.ICommandService = (0, instantiation_1.createDecorator)('commandService'); - exports.CommandsRegistry = new class { - constructor() { - this._commands = new Map(); - this._onDidRegisterCommand = new event_1.Emitter(); - this.onDidRegisterCommand = this._onDidRegisterCommand.event; - } - registerCommand(idOrCommand, handler) { - if (!idOrCommand) { - throw new Error(`invalid command`); - } - if (typeof idOrCommand === 'string') { - if (!handler) { - throw new Error(`invalid command`); - } - return this.registerCommand({ id: idOrCommand, handler }); - } - // add argument validation if rich command metadata is provided - if (idOrCommand.description) { - const constraints = []; - for (let arg of idOrCommand.description.args) { - constraints.push(arg.constraint); - } - const actualHandler = idOrCommand.handler; - idOrCommand.handler = function (accessor, ...args) { - (0, types_1.validateConstraints)(args, constraints); - return actualHandler(accessor, ...args); - }; - } - // find a place to store the command - const { id } = idOrCommand; - let commands = this._commands.get(id); - if (!commands) { - commands = new linkedList_1.LinkedList(); - this._commands.set(id, commands); - } - let removeFn = commands.unshift(idOrCommand); - let ret = (0, lifecycle_1.toDisposable)(() => { - removeFn(); - const 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; - } - registerCommandAlias(oldId, newId) { - return exports.CommandsRegistry.registerCommand(oldId, (accessor, ...args) => accessor.get(exports.ICommandService).executeCommand(newId, ...args)); - } - getCommand(id) { - const list = this._commands.get(id); - if (!list || list.isEmpty()) { - return undefined; - } - return iterator_1.Iterable.first(list); - } - getCommands() { - const result = new Map(); - for (const key of this._commands.keys()) { - const command = this.getCommand(key); - if (command) { - result.set(key, command); - } - } - return result; - } - }; - exports.CommandsRegistry.registerCommand('noop', () => { }); -}); - -/*--------------------------------------------------------------------------------------------- - * 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/editor/common/services/getSemanticTokens*/], __M([0/*require*/,1/*exports*/,23/*vs/base/common/cancellation*/,12/*vs/base/common/errors*/,24/*vs/base/common/uri*/,18/*vs/editor/common/modes*/,36/*vs/editor/common/services/modelService*/,26/*vs/platform/commands/common/commands*/,20/*vs/base/common/types*/,391/*vs/editor/common/services/semanticTokensDto*/,3/*vs/editor/common/core/range*/]), function (require, exports, cancellation_1, errors_1, uri_1, modes_1, modelService_1, commands_1, types_1, semanticTokensDto_1, range_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getDocumentRangeSemanticTokensProvider = exports.getDocumentSemanticTokens = exports.isSemanticTokensEdits = exports.isSemanticTokens = void 0; - function isSemanticTokens(v) { - return v && !!(v.data); - } - exports.isSemanticTokens = isSemanticTokens; - function isSemanticTokensEdits(v) { - return v && Array.isArray(v.edits); - } - exports.isSemanticTokensEdits = isSemanticTokensEdits; - function getDocumentSemanticTokens(model, lastResultId, token) { - const provider = _getDocumentSemanticTokensProvider(model); - if (!provider) { - return null; - } - return { - provider: provider, - request: Promise.resolve(provider.provideDocumentSemanticTokens(model, lastResultId, token)) - }; - } - exports.getDocumentSemanticTokens = getDocumentSemanticTokens; - function _getDocumentSemanticTokensProvider(model) { - const result = modes_1.DocumentSemanticTokensProviderRegistry.ordered(model); - return (result.length > 0 ? result[0] : null); - } - function getDocumentRangeSemanticTokensProvider(model) { - const result = modes_1.DocumentRangeSemanticTokensProviderRegistry.ordered(model); - return (result.length > 0 ? result[0] : null); - } - exports.getDocumentRangeSemanticTokensProvider = getDocumentRangeSemanticTokensProvider; - commands_1.CommandsRegistry.registerCommand('_provideDocumentSemanticTokensLegend', (accessor, ...args) => __awaiter(void 0, void 0, void 0, function* () { - const [uri] = args; - (0, types_1.assertType)(uri instanceof uri_1.URI); - const model = accessor.get(modelService_1.IModelService).getModel(uri); - if (!model) { - return undefined; - } - const provider = _getDocumentSemanticTokensProvider(model); - if (!provider) { - // there is no provider => fall back to a document range semantic tokens provider - return accessor.get(commands_1.ICommandService).executeCommand('_provideDocumentRangeSemanticTokensLegend', uri); - } - return provider.getLegend(); - })); - commands_1.CommandsRegistry.registerCommand('_provideDocumentSemanticTokens', (accessor, ...args) => __awaiter(void 0, void 0, void 0, function* () { - const [uri] = args; - (0, types_1.assertType)(uri instanceof uri_1.URI); - const model = accessor.get(modelService_1.IModelService).getModel(uri); - if (!model) { - return undefined; - } - const r = getDocumentSemanticTokens(model, null, cancellation_1.CancellationToken.None); - if (!r) { - // there is no provider => fall back to a document range semantic tokens provider - return accessor.get(commands_1.ICommandService).executeCommand('_provideDocumentRangeSemanticTokens', uri, model.getFullModelRange()); - } - const { provider, request } = r; - let result; - try { - result = yield request; - } - catch (err) { - (0, errors_1.onUnexpectedExternalError)(err); - return undefined; - } - if (!result || !isSemanticTokens(result)) { - return undefined; - } - const buff = (0, semanticTokensDto_1.encodeSemanticTokensDto)({ - id: 0, - type: 'full', - data: result.data - }); - if (result.resultId) { - provider.releaseDocumentSemanticTokens(result.resultId); - } - return buff; - })); - commands_1.CommandsRegistry.registerCommand('_provideDocumentRangeSemanticTokensLegend', (accessor, ...args) => __awaiter(void 0, void 0, void 0, function* () { - const [uri] = args; - (0, types_1.assertType)(uri instanceof uri_1.URI); - const model = accessor.get(modelService_1.IModelService).getModel(uri); - if (!model) { - return undefined; - } - const provider = getDocumentRangeSemanticTokensProvider(model); - if (!provider) { - return undefined; - } - return provider.getLegend(); - })); - commands_1.CommandsRegistry.registerCommand('_provideDocumentRangeSemanticTokens', (accessor, ...args) => __awaiter(void 0, void 0, void 0, function* () { - const [uri, range] = args; - (0, types_1.assertType)(uri instanceof uri_1.URI); - (0, types_1.assertType)(range_1.Range.isIRange(range)); - const model = accessor.get(modelService_1.IModelService).getModel(uri); - if (!model) { - return undefined; - } - const provider = getDocumentRangeSemanticTokensProvider(model); - if (!provider) { - // there is no provider - return undefined; - } - let result; - try { - result = yield provider.provideDocumentRangeSemanticTokens(model, range_1.Range.lift(range), cancellation_1.CancellationToken.None); - } - catch (err) { - (0, errors_1.onUnexpectedExternalError)(err); - return undefined; - } - if (!result || !isSemanticTokens(result)) { - return undefined; - } - return (0, semanticTokensDto_1.encodeSemanticTokensDto)({ - id: 0, - type: 'full', - data: result.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[251/*vs/editor/contrib/codelens/codelens*/], __M([0/*require*/,1/*exports*/,23/*vs/base/common/cancellation*/,12/*vs/base/common/errors*/,24/*vs/base/common/uri*/,18/*vs/editor/common/modes*/,36/*vs/editor/common/services/modelService*/,2/*vs/base/common/lifecycle*/,26/*vs/platform/commands/common/commands*/,20/*vs/base/common/types*/]), function (require, exports, cancellation_1, errors_1, uri_1, modes_1, modelService_1, lifecycle_1, commands_1, types_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getCodeLensModel = exports.CodeLensModel = void 0; - class CodeLensModel { - constructor() { - this.lenses = []; - this._disposables = new lifecycle_1.DisposableStore(); - } - dispose() { - this._disposables.dispose(); - } - add(list, provider) { - this._disposables.add(list); - for (const symbol of list.lenses) { - this.lenses.push({ symbol, provider }); - } - } - } - exports.CodeLensModel = CodeLensModel; - function getCodeLensModel(model, token) { - return __awaiter(this, void 0, void 0, function* () { - const provider = modes_1.CodeLensProviderRegistry.ordered(model); - const providerRanks = new Map(); - const result = new CodeLensModel(); - const promises = provider.map((provider, i) => __awaiter(this, void 0, void 0, function* () { - providerRanks.set(provider, i); - try { - const list = yield Promise.resolve(provider.provideCodeLenses(model, token)); - if (list) { - result.add(list, provider); - } - } - catch (err) { - (0, errors_1.onUnexpectedExternalError)(err); - } - })); - yield Promise.all(promises); - result.lenses = result.lenses.sort((a, b) => { - // sort by lineNumber, provider-rank, and column - if (a.symbol.range.startLineNumber < b.symbol.range.startLineNumber) { - return -1; - } - else if (a.symbol.range.startLineNumber > b.symbol.range.startLineNumber) { - return 1; - } - else if ((providerRanks.get(a.provider)) < (providerRanks.get(b.provider))) { - return -1; - } - else if ((providerRanks.get(a.provider)) > (providerRanks.get(b.provider))) { - return 1; - } - else if (a.symbol.range.startColumn < b.symbol.range.startColumn) { - return -1; - } - else if (a.symbol.range.startColumn > b.symbol.range.startColumn) { - return 1; - } - else { - return 0; - } - }); - return result; - }); - } - exports.getCodeLensModel = getCodeLensModel; - commands_1.CommandsRegistry.registerCommand('_executeCodeLensProvider', function (accessor, ...args) { - let [uri, itemResolveCount] = args; - (0, types_1.assertType)(uri_1.URI.isUri(uri)); - (0, types_1.assertType)(typeof itemResolveCount === 'number' || !itemResolveCount); - const model = accessor.get(modelService_1.IModelService).getModel(uri); - if (!model) { - throw (0, errors_1.illegalArgument)(); - } - const result = []; - const disposables = new lifecycle_1.DisposableStore(); - return getCodeLensModel(model, cancellation_1.CancellationToken.None).then(value => { - disposables.add(value); - let resolve = []; - for (const item of value.lenses) { - if (itemResolveCount === undefined || itemResolveCount === null || Boolean(item.symbol.command)) { - result.push(item.symbol); - } - else if (itemResolveCount-- > 0 && item.provider.resolveCodeLens) { - resolve.push(Promise.resolve(item.provider.resolveCodeLens(model, item.symbol, cancellation_1.CancellationToken.None)).then(symbol => result.push(symbol || item.symbol))); - } - } - return Promise.all(resolve); - }).then(() => { - return result; - }).finally(() => { - // make sure to return results, then (on next tick) - // dispose the results - setTimeout(() => disposables.dispose(), 100); - }); - }); -}); - -/*--------------------------------------------------------------------------------------------- - * 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/editor/contrib/colorPicker/color*/], __M([0/*require*/,1/*exports*/,23/*vs/base/common/cancellation*/,12/*vs/base/common/errors*/,24/*vs/base/common/uri*/,3/*vs/editor/common/core/range*/,18/*vs/editor/common/modes*/,36/*vs/editor/common/services/modelService*/,26/*vs/platform/commands/common/commands*/]), function (require, exports, cancellation_1, errors_1, uri_1, range_1, modes_1, modelService_1, commands_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getColorPresentations = exports.getColors = void 0; - function getColors(model, token) { - const colors = []; - const providers = modes_1.ColorProviderRegistry.ordered(model).reverse(); - const promises = providers.map(provider => Promise.resolve(provider.provideDocumentColors(model, token)).then(result => { - if (Array.isArray(result)) { - for (let colorInfo of result) { - colors.push({ colorInfo, provider }); - } - } - })); - return Promise.all(promises).then(() => colors); - } - exports.getColors = getColors; - function getColorPresentations(model, colorInfo, provider, token) { - return Promise.resolve(provider.provideColorPresentations(model, colorInfo, token)); - } - exports.getColorPresentations = getColorPresentations; - commands_1.CommandsRegistry.registerCommand('_executeDocumentColorProvider', function (accessor, ...args) { - const [resource] = args; - if (!(resource instanceof uri_1.URI)) { - throw (0, errors_1.illegalArgument)(); - } - const model = accessor.get(modelService_1.IModelService).getModel(resource); - if (!model) { - throw (0, errors_1.illegalArgument)(); - } - const rawCIs = []; - const providers = modes_1.ColorProviderRegistry.ordered(model).reverse(); - const promises = providers.map(provider => Promise.resolve(provider.provideDocumentColors(model, cancellation_1.CancellationToken.None)).then(result => { - if (Array.isArray(result)) { - for (let ci of result) { - rawCIs.push({ range: ci.range, color: [ci.color.red, ci.color.green, ci.color.blue, ci.color.alpha] }); - } - } - })); - return Promise.all(promises).then(() => rawCIs); - }); - commands_1.CommandsRegistry.registerCommand('_executeColorPresentationProvider', function (accessor, ...args) { - const [color, context] = args; - const { uri, range } = context; - if (!(uri instanceof uri_1.URI) || !Array.isArray(color) || color.length !== 4 || !range_1.Range.isIRange(range)) { - throw (0, errors_1.illegalArgument)(); - } - const [red, green, blue, alpha] = color; - const model = accessor.get(modelService_1.IModelService).getModel(uri); - if (!model) { - throw (0, errors_1.illegalArgument)(); - } - const colorInfo = { - range, - color: { red, green, blue, alpha } - }; - const presentations = []; - const providers = modes_1.ColorProviderRegistry.ordered(model).reverse(); - const promises = providers.map(provider => Promise.resolve(provider.provideColorPresentations(model, colorInfo, cancellation_1.CancellationToken.None)).then(result => { - if (Array.isArray(result)) { - presentations.push(...result); - } - })); - return Promise.all(promises).then(() => presentations); - }); -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - - - - - - - - - -define(__m[559/*vs/editor/contrib/documentSymbols/documentSymbols*/], __M([0/*require*/,1/*exports*/,24/*vs/base/common/uri*/,36/*vs/editor/common/services/modelService*/,23/*vs/base/common/cancellation*/,68/*vs/editor/common/services/resolverService*/,248/*vs/editor/contrib/documentSymbols/outlineModel*/,26/*vs/platform/commands/common/commands*/,20/*vs/base/common/types*/]), function (require, exports, uri_1, modelService_1, cancellation_1, resolverService_1, outlineModel_1, commands_1, types_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getDocumentSymbols = void 0; - function getDocumentSymbols(document, flat, token) { - return __awaiter(this, void 0, void 0, function* () { - const model = yield outlineModel_1.OutlineModel.create(document, token); - return flat - ? model.asListOfDocumentSymbols() - : model.getTopLevelSymbols(); - }); - } - exports.getDocumentSymbols = getDocumentSymbols; - commands_1.CommandsRegistry.registerCommand('_executeDocumentSymbolProvider', function (accessor, ...args) { - return __awaiter(this, void 0, void 0, function* () { - const [resource] = args; - (0, types_1.assertType)(uri_1.URI.isUri(resource)); - const model = accessor.get(modelService_1.IModelService).getModel(resource); - if (model) { - return getDocumentSymbols(model, false, cancellation_1.CancellationToken.None); - } - const reference = yield accessor.get(resolverService_1.ITextModelService).createModelReference(resource); - try { - return yield getDocumentSymbols(reference.object.textEditorModel, false, cancellation_1.CancellationToken.None); - } - finally { - reference.dispose(); - } - }); - }); -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - - - - - - - - - -define(__m[560/*vs/editor/contrib/links/getLinks*/], __M([0/*require*/,1/*exports*/,23/*vs/base/common/cancellation*/,12/*vs/base/common/errors*/,24/*vs/base/common/uri*/,3/*vs/editor/common/core/range*/,18/*vs/editor/common/modes*/,36/*vs/editor/common/services/modelService*/,26/*vs/platform/commands/common/commands*/,2/*vs/base/common/lifecycle*/,19/*vs/base/common/arrays*/,20/*vs/base/common/types*/]), function (require, exports, cancellation_1, errors_1, uri_1, range_1, modes_1, modelService_1, commands_1, lifecycle_1, arrays_1, types_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getLinks = exports.LinksList = exports.Link = void 0; - class Link { - constructor(link, provider) { - this._link = link; - this._provider = provider; - } - toJSON() { - return { - range: this.range, - url: this.url, - tooltip: this.tooltip - }; - } - get range() { - return this._link.range; - } - get url() { - return this._link.url; - } - get tooltip() { - return this._link.tooltip; - } - resolve(token) { - return __awaiter(this, void 0, void 0, function* () { - if (this._link.url) { - return this._link.url; - } - if (typeof this._provider.resolveLink === 'function') { - return Promise.resolve(this._provider.resolveLink(this._link, token)).then(value => { - this._link = value || this._link; - if (this._link.url) { - // recurse - return this.resolve(token); - } - return Promise.reject(new Error('missing')); - }); - } - return Promise.reject(new Error('missing')); - }); - } - } - exports.Link = Link; - class LinksList { - constructor(tuples) { - this._disposables = new lifecycle_1.DisposableStore(); - let links = []; - for (const [list, provider] of tuples) { - // merge all links - const newLinks = list.links.map(link => new Link(link, provider)); - links = LinksList._union(links, newLinks); - // register disposables - if ((0, lifecycle_1.isDisposable)(list)) { - this._disposables.add(list); - } - } - this.links = links; - } - dispose() { - this._disposables.dispose(); - this.links.length = 0; - } - static _union(oldLinks, newLinks) { - // reunite oldLinks with newLinks and remove duplicates - let result = []; - let oldIndex; - let oldLen; - let newIndex; - let newLen; - for (oldIndex = 0, newIndex = 0, oldLen = oldLinks.length, newLen = newLinks.length; oldIndex < oldLen && newIndex < newLen;) { - const oldLink = oldLinks[oldIndex]; - const newLink = newLinks[newIndex]; - if (range_1.Range.areIntersectingOrTouching(oldLink.range, newLink.range)) { - // Remove the oldLink - oldIndex++; - continue; - } - const 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; - } - } - exports.LinksList = LinksList; - function getLinks(model, token) { - const lists = []; - // ask all providers for links in parallel - const promises = modes_1.LinkProviderRegistry.ordered(model).reverse().map((provider, i) => { - return Promise.resolve(provider.provideLinks(model, token)).then(result => { - if (result) { - lists[i] = [result, provider]; - } - }, errors_1.onUnexpectedExternalError); - }); - return Promise.all(promises).then(() => { - const result = new LinksList((0, arrays_1.coalesce)(lists)); - if (!token.isCancellationRequested) { - return result; - } - result.dispose(); - return new LinksList([]); - }); - } - exports.getLinks = getLinks; - commands_1.CommandsRegistry.registerCommand('_executeLinkProvider', (accessor, ...args) => __awaiter(void 0, void 0, void 0, function* () { - let [uri, resolveCount] = args; - (0, types_1.assertType)(uri instanceof uri_1.URI); - if (typeof resolveCount !== 'number') { - resolveCount = 0; - } - const model = accessor.get(modelService_1.IModelService).getModel(uri); - if (!model) { - return []; - } - const list = yield getLinks(model, cancellation_1.CancellationToken.None); - if (!list) { - return []; - } - // resolve links - for (let i = 0; i < Math.min(resolveCount, list.links.length); i++) { - yield list.links[i].resolve(cancellation_1.CancellationToken.None); - } - const result = list.links.slice(0); - list.dispose(); - 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[16/*vs/platform/contextkey/common/contextkey*/], __M([0/*require*/,1/*exports*/,8/*vs/base/common/strings*/,9/*vs/platform/instantiation/common/instantiation*/,17/*vs/base/common/platform*/]), function (require, exports, strings_1, instantiation_1, platform_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.SET_CONTEXT_COMMAND_ID = exports.IContextKeyService = exports.RawContextKey = exports.ContextKeyOrExpr = exports.ContextKeyAndExpr = exports.ContextKeyNotRegexExpr = exports.ContextKeyRegexExpr = exports.ContextKeySmallerEqualsExpr = exports.ContextKeySmallerExpr = exports.ContextKeyGreaterEqualsExpr = exports.ContextKeyGreaterExpr = exports.ContextKeyNotExpr = exports.ContextKeyNotEqualsExpr = exports.ContextKeyNotInExpr = exports.ContextKeyInExpr = exports.ContextKeyEqualsExpr = exports.ContextKeyDefinedExpr = exports.ContextKeyTrueExpr = exports.ContextKeyFalseExpr = exports.ContextKeyExpr = void 0; - let _userAgent = platform_1.userAgent || ''; - const STATIC_VALUES = new Map(); - STATIC_VALUES.set('false', false); - STATIC_VALUES.set('true', true); - STATIC_VALUES.set('isMac', platform_1.isMacintosh); - STATIC_VALUES.set('isLinux', platform_1.isLinux); - STATIC_VALUES.set('isWindows', platform_1.isWindows); - STATIC_VALUES.set('isWeb', platform_1.isWeb); - STATIC_VALUES.set('isMacNative', platform_1.isMacintosh && !platform_1.isWeb); - STATIC_VALUES.set('isEdge', _userAgent.indexOf('Edg/') >= 0); - STATIC_VALUES.set('isFirefox', _userAgent.indexOf('Firefox') >= 0); - STATIC_VALUES.set('isChrome', _userAgent.indexOf('Chrome') >= 0); - STATIC_VALUES.set('isSafari', _userAgent.indexOf('Safari') >= 0); - const hasOwnProperty = Object.prototype.hasOwnProperty; - class ContextKeyExpr { - static has(key) { - return ContextKeyDefinedExpr.create(key); - } - static equals(key, value) { - return ContextKeyEqualsExpr.create(key, value); - } - static regex(key, value) { - return ContextKeyRegexExpr.create(key, value); - } - static not(key) { - return ContextKeyNotExpr.create(key); - } - static and(...expr) { - return ContextKeyAndExpr.create(expr); - } - static or(...expr) { - return ContextKeyOrExpr.create(expr); - } - static deserialize(serialized, strict = false) { - if (!serialized) { - return undefined; - } - return this._deserializeOrExpression(serialized, strict); - } - static _deserializeOrExpression(serialized, strict) { - let pieces = serialized.split('||'); - return ContextKeyOrExpr.create(pieces.map(p => this._deserializeAndExpression(p, strict))); - } - static _deserializeAndExpression(serialized, strict) { - let pieces = serialized.split('&&'); - return ContextKeyAndExpr.create(pieces.map(p => this._deserializeOne(p, strict))); - } - static _deserializeOne(serializedOne, strict) { - serializedOne = serializedOne.trim(); - if (serializedOne.indexOf('!=') >= 0) { - let pieces = serializedOne.split('!='); - return ContextKeyNotEqualsExpr.create(pieces[0].trim(), this._deserializeValue(pieces[1], strict)); - } - if (serializedOne.indexOf('==') >= 0) { - let pieces = serializedOne.split('=='); - return ContextKeyEqualsExpr.create(pieces[0].trim(), this._deserializeValue(pieces[1], strict)); - } - if (serializedOne.indexOf('=~') >= 0) { - let pieces = serializedOne.split('=~'); - return ContextKeyRegexExpr.create(pieces[0].trim(), this._deserializeRegexValue(pieces[1], strict)); - } - if (serializedOne.indexOf(' in ') >= 0) { - let pieces = serializedOne.split(' in '); - return ContextKeyInExpr.create(pieces[0].trim(), pieces[1].trim()); - } - if (/^[^<=>]+>=[^<=>]+$/.test(serializedOne)) { - const pieces = serializedOne.split('>='); - return ContextKeyGreaterEqualsExpr.create(pieces[0].trim(), pieces[1].trim()); - } - if (/^[^<=>]+>[^<=>]+$/.test(serializedOne)) { - const pieces = serializedOne.split('>'); - return ContextKeyGreaterExpr.create(pieces[0].trim(), pieces[1].trim()); - } - if (/^[^<=>]+<=[^<=>]+$/.test(serializedOne)) { - const pieces = serializedOne.split('<='); - return ContextKeySmallerEqualsExpr.create(pieces[0].trim(), pieces[1].trim()); - } - if (/^[^<=>]+<[^<=>]+$/.test(serializedOne)) { - const pieces = serializedOne.split('<'); - return ContextKeySmallerExpr.create(pieces[0].trim(), pieces[1].trim()); - } - if (/^\!\s*/.test(serializedOne)) { - return ContextKeyNotExpr.create(serializedOne.substr(1).trim()); - } - return ContextKeyDefinedExpr.create(serializedOne); - } - static _deserializeValue(serializedValue, strict) { - serializedValue = serializedValue.trim(); - if (serializedValue === 'true') { - return true; - } - if (serializedValue === 'false') { - return false; - } - let m = /^'([^']*)'$/.exec(serializedValue); - if (m) { - return m[1].trim(); - } - return serializedValue; - } - static _deserializeRegexValue(serializedValue, strict) { - if ((0, strings_1.isFalsyOrWhitespace)(serializedValue)) { - if (strict) { - throw new Error('missing regexp-value for =~-expression'); - } - else { - console.warn('missing regexp-value for =~-expression'); - } - return null; - } - let start = serializedValue.indexOf('/'); - let 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; - } - let value = serializedValue.slice(start + 1, end); - let 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; - } - } - } - exports.ContextKeyExpr = ContextKeyExpr; - function cmp(a, b) { - return a.cmp(b); - } - class ContextKeyFalseExpr { - constructor() { - this.type = 0 /* False */; - } - cmp(other) { - return this.type - other.type; - } - equals(other) { - return (other.type === this.type); - } - evaluate(context) { - return false; - } - serialize() { - return 'false'; - } - keys() { - return []; - } - negate() { - return ContextKeyTrueExpr.INSTANCE; - } - } - exports.ContextKeyFalseExpr = ContextKeyFalseExpr; - ContextKeyFalseExpr.INSTANCE = new ContextKeyFalseExpr(); - class ContextKeyTrueExpr { - constructor() { - this.type = 1 /* True */; - } - cmp(other) { - return this.type - other.type; - } - equals(other) { - return (other.type === this.type); - } - evaluate(context) { - return true; - } - serialize() { - return 'true'; - } - keys() { - return []; - } - negate() { - return ContextKeyFalseExpr.INSTANCE; - } - } - exports.ContextKeyTrueExpr = ContextKeyTrueExpr; - ContextKeyTrueExpr.INSTANCE = new ContextKeyTrueExpr(); - class ContextKeyDefinedExpr { - constructor(key) { - this.key = key; - this.type = 2 /* Defined */; - } - static create(key) { - const staticValue = STATIC_VALUES.get(key); - if (typeof staticValue === 'boolean') { - return staticValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE; - } - return new ContextKeyDefinedExpr(key); - } - cmp(other) { - if (other.type !== this.type) { - return this.type - other.type; - } - return cmp1(this.key, other.key); - } - equals(other) { - if (other.type === this.type) { - return (this.key === other.key); - } - return false; - } - evaluate(context) { - return (!!context.getValue(this.key)); - } - serialize() { - return this.key; - } - keys() { - return [this.key]; - } - negate() { - return ContextKeyNotExpr.create(this.key); - } - } - exports.ContextKeyDefinedExpr = ContextKeyDefinedExpr; - class ContextKeyEqualsExpr { - constructor(key, value) { - this.key = key; - this.value = value; - this.type = 4 /* Equals */; - } - static create(key, value) { - if (typeof value === 'boolean') { - return (value ? ContextKeyDefinedExpr.create(key) : ContextKeyNotExpr.create(key)); - } - const staticValue = STATIC_VALUES.get(key); - if (typeof staticValue === 'boolean') { - const trueValue = staticValue ? 'true' : 'false'; - return (value === trueValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE); - } - return new ContextKeyEqualsExpr(key, value); - } - cmp(other) { - if (other.type !== this.type) { - return this.type - other.type; - } - return cmp2(this.key, this.value, other.key, other.value); - } - equals(other) { - if (other.type === this.type) { - return (this.key === other.key && this.value === other.value); - } - return false; - } - evaluate(context) { - // Intentional == - // eslint-disable-next-line eqeqeq - return (context.getValue(this.key) == this.value); - } - serialize() { - return `${this.key} == '${this.value}'`; - } - keys() { - return [this.key]; - } - negate() { - return ContextKeyNotEqualsExpr.create(this.key, this.value); - } - } - exports.ContextKeyEqualsExpr = ContextKeyEqualsExpr; - class ContextKeyInExpr { - constructor(key, valueKey) { - this.key = key; - this.valueKey = valueKey; - this.type = 10 /* In */; - } - static create(key, valueKey) { - return new ContextKeyInExpr(key, valueKey); - } - cmp(other) { - if (other.type !== this.type) { - return this.type - other.type; - } - return cmp2(this.key, this.valueKey, other.key, other.valueKey); - } - equals(other) { - if (other.type === this.type) { - return (this.key === other.key && this.valueKey === other.valueKey); - } - return false; - } - evaluate(context) { - const source = context.getValue(this.valueKey); - const item = context.getValue(this.key); - if (Array.isArray(source)) { - return (source.indexOf(item) >= 0); - } - if (typeof item === 'string' && typeof source === 'object' && source !== null) { - return hasOwnProperty.call(source, item); - } - return false; - } - serialize() { - return `${this.key} in '${this.valueKey}'`; - } - keys() { - return [this.key, this.valueKey]; - } - negate() { - return ContextKeyNotInExpr.create(this); - } - } - exports.ContextKeyInExpr = ContextKeyInExpr; - class ContextKeyNotInExpr { - constructor(_actual) { - this._actual = _actual; - this.type = 11 /* NotIn */; - // - } - static create(actual) { - return new ContextKeyNotInExpr(actual); - } - cmp(other) { - if (other.type !== this.type) { - return this.type - other.type; - } - return this._actual.cmp(other._actual); - } - equals(other) { - if (other.type === this.type) { - return this._actual.equals(other._actual); - } - return false; - } - evaluate(context) { - return !this._actual.evaluate(context); - } - serialize() { - throw new Error('Method not implemented.'); - } - keys() { - return this._actual.keys(); - } - negate() { - return this._actual; - } - } - exports.ContextKeyNotInExpr = ContextKeyNotInExpr; - class ContextKeyNotEqualsExpr { - constructor(key, value) { - this.key = key; - this.value = value; - this.type = 5 /* NotEquals */; - } - static create(key, value) { - if (typeof value === 'boolean') { - if (value) { - return ContextKeyNotExpr.create(key); - } - return ContextKeyDefinedExpr.create(key); - } - const staticValue = STATIC_VALUES.get(key); - if (typeof staticValue === 'boolean') { - const falseValue = staticValue ? 'true' : 'false'; - return (value === falseValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE); - } - return new ContextKeyNotEqualsExpr(key, value); - } - cmp(other) { - if (other.type !== this.type) { - return this.type - other.type; - } - return cmp2(this.key, this.value, other.key, other.value); - } - equals(other) { - if (other.type === this.type) { - return (this.key === other.key && this.value === other.value); - } - return false; - } - evaluate(context) { - // Intentional != - // eslint-disable-next-line eqeqeq - return (context.getValue(this.key) != this.value); - } - serialize() { - return `${this.key} != '${this.value}'`; - } - keys() { - return [this.key]; - } - negate() { - return ContextKeyEqualsExpr.create(this.key, this.value); - } - } - exports.ContextKeyNotEqualsExpr = ContextKeyNotEqualsExpr; - class ContextKeyNotExpr { - constructor(key) { - this.key = key; - this.type = 3 /* Not */; - } - static create(key) { - const staticValue = STATIC_VALUES.get(key); - if (typeof staticValue === 'boolean') { - return (staticValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE); - } - return new ContextKeyNotExpr(key); - } - cmp(other) { - if (other.type !== this.type) { - return this.type - other.type; - } - return cmp1(this.key, other.key); - } - equals(other) { - if (other.type === this.type) { - return (this.key === other.key); - } - return false; - } - evaluate(context) { - return (!context.getValue(this.key)); - } - serialize() { - return `!${this.key}`; - } - keys() { - return [this.key]; - } - negate() { - return ContextKeyDefinedExpr.create(this.key); - } - } - exports.ContextKeyNotExpr = ContextKeyNotExpr; - class ContextKeyGreaterExpr { - constructor(key, value) { - this.key = key; - this.value = value; - this.type = 12 /* Greater */; - } - static create(key, value) { - return new ContextKeyGreaterExpr(key, value); - } - cmp(other) { - if (other.type !== this.type) { - return this.type - other.type; - } - return cmp2(this.key, this.value, other.key, other.value); - } - equals(other) { - if (other.type === this.type) { - return (this.key === other.key && this.value === other.value); - } - return false; - } - evaluate(context) { - return (parseFloat(context.getValue(this.key)) > parseFloat(this.value)); - } - serialize() { - return `${this.key} > ${this.value}`; - } - keys() { - return [this.key]; - } - negate() { - return ContextKeySmallerEqualsExpr.create(this.key, this.value); - } - } - exports.ContextKeyGreaterExpr = ContextKeyGreaterExpr; - class ContextKeyGreaterEqualsExpr { - constructor(key, value) { - this.key = key; - this.value = value; - this.type = 13 /* GreaterEquals */; - } - static create(key, value) { - return new ContextKeyGreaterEqualsExpr(key, value); - } - cmp(other) { - if (other.type !== this.type) { - return this.type - other.type; - } - return cmp2(this.key, this.value, other.key, other.value); - } - equals(other) { - if (other.type === this.type) { - return (this.key === other.key && this.value === other.value); - } - return false; - } - evaluate(context) { - return (parseFloat(context.getValue(this.key)) >= parseFloat(this.value)); - } - serialize() { - return `${this.key} >= ${this.value}`; - } - keys() { - return [this.key]; - } - negate() { - return ContextKeySmallerExpr.create(this.key, this.value); - } - } - exports.ContextKeyGreaterEqualsExpr = ContextKeyGreaterEqualsExpr; - class ContextKeySmallerExpr { - constructor(key, value) { - this.key = key; - this.value = value; - this.type = 14 /* Smaller */; - } - static create(key, value) { - return new ContextKeySmallerExpr(key, value); - } - cmp(other) { - if (other.type !== this.type) { - return this.type - other.type; - } - return cmp2(this.key, this.value, other.key, other.value); - } - equals(other) { - if (other.type === this.type) { - return (this.key === other.key && this.value === other.value); - } - return false; - } - evaluate(context) { - return (parseFloat(context.getValue(this.key)) < parseFloat(this.value)); - } - serialize() { - return `${this.key} < ${this.value}`; - } - keys() { - return [this.key]; - } - negate() { - return ContextKeyGreaterEqualsExpr.create(this.key, this.value); - } - } - exports.ContextKeySmallerExpr = ContextKeySmallerExpr; - class ContextKeySmallerEqualsExpr { - constructor(key, value) { - this.key = key; - this.value = value; - this.type = 15 /* SmallerEquals */; - } - static create(key, value) { - return new ContextKeySmallerEqualsExpr(key, value); - } - cmp(other) { - if (other.type !== this.type) { - return this.type - other.type; - } - return cmp2(this.key, this.value, other.key, other.value); - } - equals(other) { - if (other.type === this.type) { - return (this.key === other.key && this.value === other.value); - } - return false; - } - evaluate(context) { - return (parseFloat(context.getValue(this.key)) <= parseFloat(this.value)); - } - serialize() { - return `${this.key} <= ${this.value}`; - } - keys() { - return [this.key]; - } - negate() { - return ContextKeyGreaterExpr.create(this.key, this.value); - } - } - exports.ContextKeySmallerEqualsExpr = ContextKeySmallerEqualsExpr; - class ContextKeyRegexExpr { - constructor(key, regexp) { - this.key = key; - this.regexp = regexp; - this.type = 7 /* Regex */; - // - } - static create(key, regexp) { - return new ContextKeyRegexExpr(key, regexp); - } - cmp(other) { - if (other.type !== this.type) { - return this.type - other.type; - } - if (this.key < other.key) { - return -1; - } - if (this.key > other.key) { - return 1; - } - const thisSource = this.regexp ? this.regexp.source : ''; - const otherSource = other.regexp ? other.regexp.source : ''; - if (thisSource < otherSource) { - return -1; - } - if (thisSource > otherSource) { - return 1; - } - return 0; - } - equals(other) { - if (other.type === this.type) { - const thisSource = this.regexp ? this.regexp.source : ''; - const otherSource = other.regexp ? other.regexp.source : ''; - return (this.key === other.key && thisSource === otherSource); - } - return false; - } - evaluate(context) { - let value = context.getValue(this.key); - return this.regexp ? this.regexp.test(value) : false; - } - serialize() { - const value = this.regexp - ? `/${this.regexp.source}/${this.regexp.ignoreCase ? 'i' : ''}` - : '/invalid/'; - return `${this.key} =~ ${value}`; - } - keys() { - return [this.key]; - } - negate() { - return ContextKeyNotRegexExpr.create(this); - } - } - exports.ContextKeyRegexExpr = ContextKeyRegexExpr; - class ContextKeyNotRegexExpr { - constructor(_actual) { - this._actual = _actual; - this.type = 8 /* NotRegex */; - // - } - static create(actual) { - return new ContextKeyNotRegexExpr(actual); - } - cmp(other) { - if (other.type !== this.type) { - return this.type - other.type; - } - return this._actual.cmp(other._actual); - } - equals(other) { - if (other.type === this.type) { - return this._actual.equals(other._actual); - } - return false; - } - evaluate(context) { - return !this._actual.evaluate(context); - } - serialize() { - throw new Error('Method not implemented.'); - } - keys() { - return this._actual.keys(); - } - negate() { - return this._actual; - } - } - exports.ContextKeyNotRegexExpr = ContextKeyNotRegexExpr; - class ContextKeyAndExpr { - constructor(expr) { - this.expr = expr; - this.type = 6 /* And */; - } - static create(_expr) { - return ContextKeyAndExpr._normalizeArr(_expr); - } - cmp(other) { - if (other.type !== this.type) { - return this.type - other.type; - } - if (this.expr.length < other.expr.length) { - return -1; - } - if (this.expr.length > other.expr.length) { - return 1; - } - for (let i = 0, len = this.expr.length; i < len; i++) { - const r = cmp(this.expr[i], other.expr[i]); - if (r !== 0) { - return r; - } - } - return 0; - } - equals(other) { - if (other.type === this.type) { - if (this.expr.length !== other.expr.length) { - return false; - } - for (let i = 0, len = this.expr.length; i < len; i++) { - if (!this.expr[i].equals(other.expr[i])) { - return false; - } - } - return true; - } - return false; - } - evaluate(context) { - for (let i = 0, len = this.expr.length; i < len; i++) { - if (!this.expr[i].evaluate(context)) { - return false; - } - } - return true; - } - static _normalizeArr(arr) { - const expr = []; - let hasTrue = false; - for (const e of arr) { - if (!e) { - continue; - } - if (e.type === 1 /* True */) { - // anything && true ==> anything - hasTrue = true; - continue; - } - if (e.type === 0 /* False */) { - // anything && false ==> false - return ContextKeyFalseExpr.INSTANCE; - } - if (e.type === 6 /* And */) { - expr.push(...e.expr); - continue; - } - expr.push(e); - } - if (expr.length === 0 && hasTrue) { - return ContextKeyTrueExpr.INSTANCE; - } - if (expr.length === 0) { - return undefined; - } - if (expr.length === 1) { - return expr[0]; - } - expr.sort(cmp); - // We must distribute any OR expression because we don't support parens - // OR extensions will be at the end (due to sorting rules) - while (expr.length > 1) { - const lastElement = expr[expr.length - 1]; - if (lastElement.type !== 9 /* Or */) { - break; - } - // pop the last element - expr.pop(); - // pop the second to last element - const secondToLastElement = expr.pop(); - // distribute `lastElement` over `secondToLastElement` - const resultElement = ContextKeyOrExpr.create(lastElement.expr.map(el => ContextKeyAndExpr.create([el, secondToLastElement]))); - if (resultElement) { - expr.push(resultElement); - expr.sort(cmp); - } - } - if (expr.length === 1) { - return expr[0]; - } - return new ContextKeyAndExpr(expr); - } - serialize() { - return this.expr.map(e => e.serialize()).join(' && '); - } - keys() { - const result = []; - for (let expr of this.expr) { - result.push(...expr.keys()); - } - return result; - } - negate() { - let result = []; - for (let expr of this.expr) { - result.push(expr.negate()); - } - return ContextKeyOrExpr.create(result); - } - } - exports.ContextKeyAndExpr = ContextKeyAndExpr; - class ContextKeyOrExpr { - constructor(expr) { - this.expr = expr; - this.type = 9 /* Or */; - } - static create(_expr) { - const expr = ContextKeyOrExpr._normalizeArr(_expr); - if (expr.length === 0) { - return undefined; - } - if (expr.length === 1) { - return expr[0]; - } - return new ContextKeyOrExpr(expr); - } - cmp(other) { - if (other.type !== this.type) { - return this.type - other.type; - } - if (this.expr.length < other.expr.length) { - return -1; - } - if (this.expr.length > other.expr.length) { - return 1; - } - for (let i = 0, len = this.expr.length; i < len; i++) { - const r = cmp(this.expr[i], other.expr[i]); - if (r !== 0) { - return r; - } - } - return 0; - } - equals(other) { - if (other.type === this.type) { - if (this.expr.length !== other.expr.length) { - return false; - } - for (let i = 0, len = this.expr.length; i < len; i++) { - if (!this.expr[i].equals(other.expr[i])) { - return false; - } - } - return true; - } - return false; - } - evaluate(context) { - for (let i = 0, len = this.expr.length; i < len; i++) { - if (this.expr[i].evaluate(context)) { - return true; - } - } - return false; - } - static _normalizeArr(arr) { - let expr = []; - let hasFalse = false; - if (arr) { - for (let i = 0, len = arr.length; i < len; i++) { - const e = arr[i]; - if (!e) { - continue; - } - if (e.type === 0 /* False */) { - // anything || false ==> anything - hasFalse = true; - continue; - } - if (e.type === 1 /* True */) { - // anything || true ==> true - return [ContextKeyTrueExpr.INSTANCE]; - } - if (e.type === 9 /* Or */) { - expr = expr.concat(e.expr); - continue; - } - expr.push(e); - } - if (expr.length === 0 && hasFalse) { - return [ContextKeyFalseExpr.INSTANCE]; - } - expr.sort(cmp); - } - return expr; - } - serialize() { - return this.expr.map(e => e.serialize()).join(' || '); - } - keys() { - const result = []; - for (let expr of this.expr) { - result.push(...expr.keys()); - } - return result; - } - negate() { - let result = []; - for (let expr of this.expr) { - result.push(expr.negate()); - } - const terminals = (node) => { - if (node.type === 9 /* Or */) { - 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) { - const LEFT = result.shift(); - const RIGHT = result.shift(); - const all = []; - for (const left of terminals(LEFT)) { - for (const right of terminals(RIGHT)) { - all.push(ContextKeyExpr.and(left, right)); - } - } - result.unshift(ContextKeyExpr.or(...all)); - } - return result[0]; - } - } - exports.ContextKeyOrExpr = ContextKeyOrExpr; - class RawContextKey extends ContextKeyDefinedExpr { - constructor(key, defaultValue, metaOrHide) { - super(key); - this._defaultValue = defaultValue; - // collect all context keys into a central place - if (typeof metaOrHide === 'object') { - RawContextKey._info.push(Object.assign(Object.assign({}, metaOrHide), { key })); - } - else if (metaOrHide !== true) { - RawContextKey._info.push({ key, description: metaOrHide, type: defaultValue !== null && defaultValue !== undefined ? typeof defaultValue : undefined }); - } - } - static all() { - return RawContextKey._info.values(); - } - bindTo(target) { - return target.createKey(this.key, this._defaultValue); - } - getValue(target) { - return target.getContextKeyValue(this.key); - } - toNegated() { - return ContextKeyExpr.not(this.key); - } - isEqualTo(value) { - return ContextKeyExpr.equals(this.key, value); - } - } - exports.RawContextKey = RawContextKey; - RawContextKey._info = []; - exports.IContextKeyService = (0, instantiation_1.createDecorator)('contextKeyService'); - exports.SET_CONTEXT_COMMAND_ID = 'setContext'; - function cmp1(key1, key2) { - if (key1 < key2) { - return -1; - } - if (key1 > key2) { - return 1; - } - return 0; - } - function cmp2(key1, value1, key2, value2) { - if (key1 < key2) { - return -1; - } - if (key1 > key2) { - return 1; - } - if (value1 < value2) { - return -1; - } - if (value1 > value2) { - return 1; - } - return 0; - } -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[25/*vs/editor/common/editorContextKeys*/], __M([0/*require*/,1/*exports*/,466/*vs/nls!vs/editor/common/editorContextKeys*/,16/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, nls, contextkey_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.EditorContextKeys = void 0; - var EditorContextKeys; - (function (EditorContextKeys) { - EditorContextKeys.editorSimpleInput = new contextkey_1.RawContextKey('editorSimpleInput', false, true); - /** - * A context key that is set when the editor's text has focus (cursor is blinking). - * Is false when focus is in simple editor widgets (repl input, scm commit input). - */ - EditorContextKeys.editorTextFocus = new contextkey_1.RawContextKey('editorTextFocus', false, nls.localize(0, null)); - /** - * 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, nls.localize(1, null)); - /** - * A context key that is set when any editor input has focus (regular editor, repl input...). - */ - EditorContextKeys.textInputFocus = new contextkey_1.RawContextKey('textInputFocus', false, nls.localize(2, null)); - EditorContextKeys.readOnly = new contextkey_1.RawContextKey('editorReadonly', false, nls.localize(3, null)); - EditorContextKeys.inDiffEditor = new contextkey_1.RawContextKey('inDiffEditor', false, nls.localize(4, null)); - EditorContextKeys.columnSelection = new contextkey_1.RawContextKey('editorColumnSelection', false, nls.localize(5, null)); - EditorContextKeys.writable = EditorContextKeys.readOnly.toNegated(); - EditorContextKeys.hasNonEmptySelection = new contextkey_1.RawContextKey('editorHasSelection', false, nls.localize(6, null)); - EditorContextKeys.hasOnlyEmptySelection = EditorContextKeys.hasNonEmptySelection.toNegated(); - EditorContextKeys.hasMultipleSelections = new contextkey_1.RawContextKey('editorHasMultipleSelections', false, nls.localize(7, null)); - EditorContextKeys.hasSingleSelection = EditorContextKeys.hasMultipleSelections.toNegated(); - EditorContextKeys.tabMovesFocus = new contextkey_1.RawContextKey('editorTabMovesFocus', false, nls.localize(8, null)); - EditorContextKeys.tabDoesNotMoveFocus = EditorContextKeys.tabMovesFocus.toNegated(); - EditorContextKeys.isInWalkThroughSnippet = new contextkey_1.RawContextKey('isInEmbeddedEditor', false, true); - EditorContextKeys.canUndo = new contextkey_1.RawContextKey('canUndo', false, true); - EditorContextKeys.canRedo = new contextkey_1.RawContextKey('canRedo', false, true); - EditorContextKeys.hoverVisible = new contextkey_1.RawContextKey('editorHoverVisible', false, nls.localize(9, null)); - /** - * A context key that is set when an editor is part of a larger editor, like notebooks or - * (future) a diff editor - */ - EditorContextKeys.inCompositeEditor = new contextkey_1.RawContextKey('inCompositeEditor', undefined, nls.localize(10, null)); - EditorContextKeys.notInCompositeEditor = EditorContextKeys.inCompositeEditor.toNegated(); - // -- mode context keys - EditorContextKeys.languageId = new contextkey_1.RawContextKey('editorLangId', '', nls.localize(11, null)); - EditorContextKeys.hasCompletionItemProvider = new contextkey_1.RawContextKey('editorHasCompletionItemProvider', false, nls.localize(12, null)); - EditorContextKeys.hasCodeActionsProvider = new contextkey_1.RawContextKey('editorHasCodeActionsProvider', false, nls.localize(13, null)); - EditorContextKeys.hasCodeLensProvider = new contextkey_1.RawContextKey('editorHasCodeLensProvider', false, nls.localize(14, null)); - EditorContextKeys.hasDefinitionProvider = new contextkey_1.RawContextKey('editorHasDefinitionProvider', false, nls.localize(15, null)); - EditorContextKeys.hasDeclarationProvider = new contextkey_1.RawContextKey('editorHasDeclarationProvider', false, nls.localize(16, null)); - EditorContextKeys.hasImplementationProvider = new contextkey_1.RawContextKey('editorHasImplementationProvider', false, nls.localize(17, null)); - EditorContextKeys.hasTypeDefinitionProvider = new contextkey_1.RawContextKey('editorHasTypeDefinitionProvider', false, nls.localize(18, null)); - EditorContextKeys.hasHoverProvider = new contextkey_1.RawContextKey('editorHasHoverProvider', false, nls.localize(19, null)); - EditorContextKeys.hasDocumentHighlightProvider = new contextkey_1.RawContextKey('editorHasDocumentHighlightProvider', false, nls.localize(20, null)); - EditorContextKeys.hasDocumentSymbolProvider = new contextkey_1.RawContextKey('editorHasDocumentSymbolProvider', false, nls.localize(21, null)); - EditorContextKeys.hasReferenceProvider = new contextkey_1.RawContextKey('editorHasReferenceProvider', false, nls.localize(22, null)); - EditorContextKeys.hasRenameProvider = new contextkey_1.RawContextKey('editorHasRenameProvider', false, nls.localize(23, null)); - EditorContextKeys.hasSignatureHelpProvider = new contextkey_1.RawContextKey('editorHasSignatureHelpProvider', false, nls.localize(24, null)); - EditorContextKeys.hasInlayHintsProvider = new contextkey_1.RawContextKey('editorHasInlayHintsProvider', false, nls.localize(25, null)); - // -- mode context keys: formatting - EditorContextKeys.hasDocumentFormattingProvider = new contextkey_1.RawContextKey('editorHasDocumentFormattingProvider', false, nls.localize(26, null)); - EditorContextKeys.hasDocumentSelectionFormattingProvider = new contextkey_1.RawContextKey('editorHasDocumentSelectionFormattingProvider', false, nls.localize(27, null)); - EditorContextKeys.hasMultipleDocumentFormattingProvider = new contextkey_1.RawContextKey('editorHasMultipleDocumentFormattingProvider', false, nls.localize(28, null)); - EditorContextKeys.hasMultipleDocumentSelectionFormattingProvider = new contextkey_1.RawContextKey('editorHasMultipleDocumentSelectionFormattingProvider', false, nls.localize(29, null)); - })(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. - *--------------------------------------------------------------------------------------------*/ - - - - - - - - - -define(__m[188/*vs/editor/contrib/parameterHints/provideSignatureHelp*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,13/*vs/editor/common/core/position*/,18/*vs/editor/common/modes*/,16/*vs/platform/contextkey/common/contextkey*/,23/*vs/base/common/cancellation*/,26/*vs/platform/commands/common/commands*/,24/*vs/base/common/uri*/,20/*vs/base/common/types*/,68/*vs/editor/common/services/resolverService*/]), function (require, exports, errors_1, position_1, modes, contextkey_1, cancellation_1, commands_1, uri_1, types_1, resolverService_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.provideSignatureHelp = exports.Context = void 0; - exports.Context = { - Visible: new contextkey_1.RawContextKey('parameterHintsVisible', false), - MultipleSignatures: new contextkey_1.RawContextKey('parameterHintsMultipleSignatures', false), - }; - function provideSignatureHelp(model, position, context, token) { - return __awaiter(this, void 0, void 0, function* () { - const supports = modes.SignatureHelpProviderRegistry.ordered(model); - for (const support of supports) { - try { - const result = yield support.provideSignatureHelp(model, position, token, context); - if (result) { - return result; - } - } - catch (err) { - (0, errors_1.onUnexpectedExternalError)(err); - } - } - return undefined; - }); - } - exports.provideSignatureHelp = provideSignatureHelp; - commands_1.CommandsRegistry.registerCommand('_executeSignatureHelpProvider', (accessor, ...args) => __awaiter(void 0, void 0, void 0, function* () { - const [uri, position, triggerCharacter] = args; - (0, types_1.assertType)(uri_1.URI.isUri(uri)); - (0, types_1.assertType)(position_1.Position.isIPosition(position)); - (0, types_1.assertType)(typeof triggerCharacter === 'string' || !triggerCharacter); - const ref = yield accessor.get(resolverService_1.ITextModelService).createModelReference(uri); - try { - const result = yield provideSignatureHelp(ref.object.textEditorModel, position_1.Position.lift(position), { - triggerKind: modes.SignatureHelpTriggerKind.Invoke, - isRetrigger: false, - triggerCharacter, - }, cancellation_1.CancellationToken.None); - if (!result) { - return undefined; - } - setTimeout(() => result.dispose(), 0); - return result.value; - } - finally { - ref.dispose(); - } - })); -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - - - - - - - - - -define(__m[561/*vs/editor/contrib/parameterHints/parameterHintsModel*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,12/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,94/*vs/editor/common/core/characterClassifier*/,18/*vs/editor/common/modes*/,188/*vs/editor/contrib/parameterHints/provideSignatureHelp*/]), function (require, exports, async_1, errors_1, event_1, lifecycle_1, characterClassifier_1, modes, provideSignatureHelp_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ParameterHintsModel = void 0; - var ParameterHintState; - (function (ParameterHintState) { - ParameterHintState.Default = { type: 0 /* Default */ }; - class Pending { - constructor(request, previouslyActiveHints) { - this.request = request; - this.previouslyActiveHints = previouslyActiveHints; - this.type = 2 /* Pending */; - } - } - ParameterHintState.Pending = Pending; - class Active { - constructor(hints) { - this.hints = hints; - this.type = 1 /* Active */; - } - } - ParameterHintState.Active = Active; - })(ParameterHintState || (ParameterHintState = {})); - class ParameterHintsModel extends lifecycle_1.Disposable { - constructor(editor, delay = ParameterHintsModel.DEFAULT_DELAY) { - super(); - this._onChangedHints = this._register(new event_1.Emitter()); - this.onChangedHints = this._onChangedHints.event; - this.triggerOnType = false; - this._state = ParameterHintState.Default; - this._pendingTriggers = []; - this._lastSignatureHelpResult = this._register(new lifecycle_1.MutableDisposable()); - this.triggerChars = new characterClassifier_1.CharacterSet(); - this.retriggerChars = new characterClassifier_1.CharacterSet(); - this.triggerId = 0; - this.editor = editor; - this.throttledDelayer = new async_1.Delayer(delay); - this._register(this.editor.onDidBlurEditorWidget(() => this.cancel())); - this._register(this.editor.onDidChangeConfiguration(() => this.onEditorConfigurationChange())); - this._register(this.editor.onDidChangeModel(e => this.onModelChanged())); - this._register(this.editor.onDidChangeModelLanguage(_ => this.onModelChanged())); - this._register(this.editor.onDidChangeCursorSelection(e => this.onCursorChange(e))); - this._register(this.editor.onDidChangeModelContent(e => this.onModelContentChange())); - this._register(modes.SignatureHelpProviderRegistry.onDidChange(this.onModelChanged, this)); - this._register(this.editor.onDidType(text => this.onDidType(text))); - this.onEditorConfigurationChange(); - this.onModelChanged(); - } - get state() { return this._state; } - set state(value) { - if (this._state.type === 2 /* Pending */) { - this._state.request.cancel(); - } - this._state = value; - } - cancel(silent = false) { - this.state = ParameterHintState.Default; - this.throttledDelayer.cancel(); - if (!silent) { - this._onChangedHints.fire(undefined); - } - } - trigger(context, delay) { - const model = this.editor.getModel(); - if (!model || !modes.SignatureHelpProviderRegistry.has(model)) { - return; - } - const triggerId = ++this.triggerId; - this._pendingTriggers.push(context); - this.throttledDelayer.trigger(() => { - return this.doTrigger(triggerId); - }, delay) - .catch(errors_1.onUnexpectedError); - } - next() { - if (this.state.type !== 1 /* Active */) { - return; - } - const length = this.state.hints.signatures.length; - const activeSignature = this.state.hints.activeSignature; - const last = (activeSignature % length) === (length - 1); - const cycle = this.editor.getOption(74 /* parameterHints */).cycle; - // If there is only one signature, or we're on last signature of list - if ((length < 2 || last) && !cycle) { - this.cancel(); - return; - } - this.updateActiveSignature(last && cycle ? 0 : activeSignature + 1); - } - previous() { - if (this.state.type !== 1 /* Active */) { - return; - } - const length = this.state.hints.signatures.length; - const activeSignature = this.state.hints.activeSignature; - const first = activeSignature === 0; - const cycle = this.editor.getOption(74 /* parameterHints */).cycle; - // If there is only one signature, or we're on first signature of list - if ((length < 2 || first) && !cycle) { - this.cancel(); - return; - } - this.updateActiveSignature(first && cycle ? length - 1 : activeSignature - 1); - } - updateActiveSignature(activeSignature) { - if (this.state.type !== 1 /* Active */) { - return; - } - this.state = new ParameterHintState.Active(Object.assign(Object.assign({}, this.state.hints), { activeSignature })); - this._onChangedHints.fire(this.state.hints); - } - doTrigger(triggerId) { - return __awaiter(this, void 0, void 0, function* () { - const isRetrigger = this.state.type === 1 /* Active */ || this.state.type === 2 /* Pending */; - const activeSignatureHelp = this.getLastActiveHints(); - this.cancel(true); - if (this._pendingTriggers.length === 0) { - return false; - } - const context = this._pendingTriggers.reduce(mergeTriggerContexts); - this._pendingTriggers = []; - const triggerContext = { - triggerKind: context.triggerKind, - triggerCharacter: context.triggerCharacter, - isRetrigger: isRetrigger, - activeSignatureHelp: activeSignatureHelp - }; - if (!this.editor.hasModel()) { - return false; - } - const model = this.editor.getModel(); - const position = this.editor.getPosition(); - this.state = new ParameterHintState.Pending((0, async_1.createCancelablePromise)(token => (0, provideSignatureHelp_1.provideSignatureHelp)(model, position, triggerContext, token)), activeSignatureHelp); - try { - const result = yield this.state.request; - // Check that we are still resolving the correct signature help - if (triggerId !== this.triggerId) { - result === null || result === void 0 ? void 0 : result.dispose(); - return false; - } - if (!result || !result.value.signatures || result.value.signatures.length === 0) { - result === null || result === void 0 ? void 0 : result.dispose(); - this._lastSignatureHelpResult.clear(); - this.cancel(); - return false; - } - else { - this.state = new ParameterHintState.Active(result.value); - this._lastSignatureHelpResult.value = result; - this._onChangedHints.fire(this.state.hints); - return true; - } - } - catch (error) { - if (triggerId === this.triggerId) { - this.state = ParameterHintState.Default; - } - (0, errors_1.onUnexpectedError)(error); - return false; - } - }); - } - getLastActiveHints() { - switch (this.state.type) { - case 1 /* Active */: return this.state.hints; - case 2 /* Pending */: return this.state.previouslyActiveHints; - default: return undefined; - } - } - get isTriggered() { - return this.state.type === 1 /* Active */ - || this.state.type === 2 /* Pending */ - || this.throttledDelayer.isTriggered(); - } - onModelChanged() { - this.cancel(); - // Update trigger characters - this.triggerChars = new characterClassifier_1.CharacterSet(); - this.retriggerChars = new characterClassifier_1.CharacterSet(); - const model = this.editor.getModel(); - if (!model) { - return; - } - for (const support of modes.SignatureHelpProviderRegistry.ordered(model)) { - for (const ch of support.signatureHelpTriggerCharacters || []) { - this.triggerChars.add(ch.charCodeAt(0)); - // All trigger characters are also considered retrigger characters - this.retriggerChars.add(ch.charCodeAt(0)); - } - for (const ch of support.signatureHelpRetriggerCharacters || []) { - this.retriggerChars.add(ch.charCodeAt(0)); - } - } - } - onDidType(text) { - if (!this.triggerOnType) { - return; - } - const lastCharIndex = text.length - 1; - const triggerCharCode = text.charCodeAt(lastCharIndex); - if (this.triggerChars.has(triggerCharCode) || this.isTriggered && this.retriggerChars.has(triggerCharCode)) { - this.trigger({ - triggerKind: modes.SignatureHelpTriggerKind.TriggerCharacter, - triggerCharacter: text.charAt(lastCharIndex), - }); - } - } - onCursorChange(e) { - if (e.source === 'mouse') { - this.cancel(); - } - else if (this.isTriggered) { - this.trigger({ triggerKind: modes.SignatureHelpTriggerKind.ContentChange }); - } - } - onModelContentChange() { - if (this.isTriggered) { - this.trigger({ triggerKind: modes.SignatureHelpTriggerKind.ContentChange }); - } - } - onEditorConfigurationChange() { - this.triggerOnType = this.editor.getOption(74 /* parameterHints */).enabled; - if (!this.triggerOnType) { - this.cancel(); - } - } - dispose() { - this.cancel(true); - super.dispose(); - } - } - exports.ParameterHintsModel = ParameterHintsModel; - ParameterHintsModel.DEFAULT_DELAY = 120; // ms - function mergeTriggerContexts(previous, current) { - switch (current.triggerKind) { - case modes.SignatureHelpTriggerKind.Invoke: - // Invoke overrides previous triggers. - return current; - case modes.SignatureHelpTriggerKind.ContentChange: - // Ignore content changes triggers - return previous; - case modes.SignatureHelpTriggerKind.TriggerCharacter: - default: - return current; - } - } -}); - -/*--------------------------------------------------------------------------------------------- - * 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[562/*vs/editor/contrib/suggest/suggestAlternatives*/], __M([0/*require*/,1/*exports*/,16/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, contextkey_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.SuggestAlternatives = void 0; - let SuggestAlternatives = class SuggestAlternatives { - constructor(_editor, contextKeyService) { - this._editor = _editor; - this._index = 0; - this._ckOtherSuggestions = SuggestAlternatives.OtherSuggestions.bindTo(contextKeyService); - } - dispose() { - this.reset(); - } - reset() { - var _a; - this._ckOtherSuggestions.reset(); - (_a = this._listener) === null || _a === void 0 ? void 0 : _a.dispose(); - this._model = undefined; - this._acceptNext = undefined; - this._ignore = false; - } - set({ model, index }, acceptNext) { - // no suggestions -> nothing to do - if (model.items.length === 0) { - this.reset(); - return; - } - // no alternative suggestions -> nothing to do - let 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(() => { - if (!this._ignore) { - this.reset(); - } - }); - this._ckOtherSuggestions.set(true); - } - static _moveIndex(fwd, model, index) { - let 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; - } - next() { - this._move(true); - } - prev() { - this._move(false); - } - _move(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); - 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[563/*vs/editor/contrib/suggest/wordContextKey*/], __M([0/*require*/,1/*exports*/,16/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, contextkey_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.WordContextKey = void 0; - let WordContextKey = class WordContextKey { - constructor(_editor, contextKeyService) { - this._editor = _editor; - this._enabled = false; - this._ckAtEnd = WordContextKey.AtEnd.bindTo(contextKeyService); - this._configListener = this._editor.onDidChangeConfiguration(e => e.hasChanged(110 /* tabCompletion */) && this._update()); - this._update(); - } - dispose() { - var _a; - this._configListener.dispose(); - (_a = this._selectionListener) === null || _a === void 0 ? void 0 : _a.dispose(); - this._ckAtEnd.reset(); - } - _update() { - // only update this when tab completions are enabled - const enabled = this._editor.getOption(110 /* tabCompletion */) === 'on'; - if (this._enabled === enabled) { - return; - } - this._enabled = enabled; - if (this._enabled) { - const checkForWordEnd = () => { - if (!this._editor.hasModel()) { - this._ckAtEnd.set(false); - return; - } - const model = this._editor.getModel(); - const selection = this._editor.getSelection(); - const 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); - 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*/,9/*vs/platform/instantiation/common/instantiation*/,16/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, instantiation_1, contextkey_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CONTEXT_ACCESSIBILITY_MODE_ENABLED = exports.IAccessibilityService = void 0; - exports.IAccessibilityService = (0, 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. - *--------------------------------------------------------------------------------------------*/ -define(__m[253/*vs/platform/contextkey/common/contextkeys*/], __M([0/*require*/,1/*exports*/,535/*vs/nls!vs/platform/contextkey/common/contextkeys*/,16/*vs/platform/contextkey/common/contextkey*/,17/*vs/base/common/platform*/]), function (require, exports, nls_1, contextkey_1, platform_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.InputFocusedContextKey = exports.IsWindowsContext = void 0; - exports.IsWindowsContext = new contextkey_1.RawContextKey('isWindows', platform_1.isWindows, (0, nls_1.localize)(0, null)); - 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[69/*vs/platform/contextview/browser/contextView*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.IContextMenuService = exports.IContextViewService = void 0; - exports.IContextViewService = (0, instantiation_1.createDecorator)('contextViewService'); - exports.IContextMenuService = (0, instantiation_1.createDecorator)('contextMenuService'); -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[120/*vs/platform/dialogs/common/dialogs*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.IDialogService = void 0; - exports.IDialogService = (0, 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[143/*vs/platform/instantiation/common/serviceCollection*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ServiceCollection = void 0; - class ServiceCollection { - constructor(...entries) { - this._entries = new Map(); - for (let [id, service] of entries) { - this.set(id, service); - } - } - set(id, instanceOrDescriptor) { - const result = this._entries.get(id); - this._entries.set(id, instanceOrDescriptor); - return result; - } - has(id) { - return this._entries.has(id); - } - get(id) { - return this._entries.get(id); - } - } - 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. - *--------------------------------------------------------------------------------------------*/ -define(__m[564/*vs/platform/instantiation/common/instantiationService*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,547/*vs/platform/instantiation/common/graph*/,241/*vs/platform/instantiation/common/descriptors*/,9/*vs/platform/instantiation/common/instantiation*/,143/*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 }); - exports.InstantiationService = void 0; - // TRACING - const _enableTracing = false; - class CyclicDependencyError extends Error { - constructor(graph) { - var _a; - super('cyclic dependency between services'); - this.message = (_a = graph.findCycleSlow()) !== null && _a !== void 0 ? _a : `UNABLE to detect cycle, dumping graph: \n${graph.toString()}`; - } - } - class InstantiationService { - constructor(services = new serviceCollection_1.ServiceCollection(), strict = false, parent) { - this._activeInstantiations = new Set(); - this._services = services; - this._strict = strict; - this._parent = parent; - this._services.set(instantiation_1.IInstantiationService, this); - } - createChild(services) { - return new InstantiationService(services, this._strict, this); - } - invokeFunction(fn, ...args) { - let _trace = Trace.traceInvocation(fn); - let _done = false; - try { - const accessor = { - get: (id, isOptional) => { - if (_done) { - throw (0, errors_1.illegalState)('service accessor is only valid during the invocation of its target method'); - } - const result = this._getOrCreateServiceInstance(id, _trace); - if (!result && isOptional !== instantiation_1.optional) { - throw new Error(`[invokeFunction] unknown service '${id}'`); - } - return result; - } - }; - return fn(accessor, ...args); - } - finally { - _done = true; - _trace.stop(); - } - } - createInstance(ctorOrDescriptor, ...rest) { - let _trace; - let 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; - } - _createInstance(ctor, args = [], _trace) { - // arguments defined by service decorators - let serviceDependencies = instantiation_1._util.getServiceDependencies(ctor).sort((a, b) => a.index - b.index); - let serviceArgs = []; - for (const dependency of serviceDependencies) { - let 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); - } - let 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`); - let 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(...[...args, ...serviceArgs]); - } - _setServiceInstance(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'); - } - } - _getServiceInstanceOrDescriptor(id) { - let instanceOrDesc = this._services.get(id); - if (!instanceOrDesc && this._parent) { - return this._parent._getServiceInstanceOrDescriptor(id); - } - else { - return instanceOrDesc; - } - } - _getOrCreateServiceInstance(id, _trace) { - let thing = this._getServiceInstanceOrDescriptor(id); - if (thing instanceof descriptors_1.SyncDescriptor) { - return this._safeCreateAndCacheServiceInstance(id, thing, _trace.branch(id, true)); - } - else { - _trace.branch(id, false); - return thing; - } - } - _safeCreateAndCacheServiceInstance(id, desc, _trace) { - if (this._activeInstantiations.has(id)) { - throw new Error(`illegal state - RECURSIVELY instantiating service '${id}'`); - } - this._activeInstantiations.add(id); - try { - return this._createAndCacheServiceInstance(id, desc, _trace); - } - finally { - this._activeInstantiations.delete(id); - } - } - _createAndCacheServiceInstance(id, desc, _trace) { - const graph = new graph_1.Graph(data => data.id.toString()); - let cycleCount = 0; - const stack = [{ id, desc, _trace }]; - while (stack.length) { - const item = stack.pop(); - graph.lookupOrInsertNode(item); - // a weak but working heuristic for cycle checks - if (cycleCount++ > 1000) { - throw new CyclicDependencyError(graph); - } - // check all dependencies for existence and if they need to be created first - for (let dependency of instantiation_1._util.getServiceDependencies(item.desc.ctor)) { - let 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) { - const d = { id: dependency.id, desc: instanceOrDesc, _trace: item._trace.branch(dependency.id, true) }; - graph.insertEdge(item, d); - stack.push(d); - } - } - } - while (true) { - const 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 (const { data } of roots) { - // Repeat the check for this still being a service sync descriptor. That's because - // instantiating a dependency might have side-effect and recursively trigger instantiation - // so that some dependencies are now fullfilled already. - const instanceOrDesc = this._getServiceInstanceOrDescriptor(data.id); - if (instanceOrDesc instanceof descriptors_1.SyncDescriptor) { - // create instance and overwrite the service collections - const 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); - } - _createServiceInstanceWithOwner(id, ctor, args = [], supportsDelayedInstantiation, _trace) { - 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}`); - } - } - _createServiceInstance(ctor, args = [], _supportsDelayedInstantiation, _trace) { - if (!_supportsDelayedInstantiation) { - // eager instantiation - 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 - const idle = new async_1.IdleValue(() => this._createInstance(ctor, args, _trace)); - return new Proxy(Object.create(null), { - get(target, key) { - if (key in target) { - return target[key]; - } - let obj = idle.value; - let prop = obj[key]; - if (typeof prop !== 'function') { - return prop; - } - prop = prop.bind(obj); - target[key] = prop; - return prop; - }, - set(_target, p, value) { - idle.value[p] = value; - return true; - } - }); - } - } - } - exports.InstantiationService = InstantiationService; - class Trace { - constructor(type, name) { - this.type = type; - this.name = name; - this._start = Date.now(); - this._dep = []; - } - static traceInvocation(ctor) { - return !_enableTracing ? Trace._None : new Trace(1 /* Invocation */, ctor.name || ctor.toString().substring(0, 42).replace(/\n/g, '')); - } - static traceCreation(ctor) { - return !_enableTracing ? Trace._None : new Trace(0 /* Creation */, ctor.name); - } - branch(id, first) { - let child = new Trace(2 /* Branch */, id.toString()); - this._dep.push([id, first, child]); - return child; - } - stop() { - let dur = Date.now() - this._start; - Trace._totals += dur; - let causedCreation = false; - function printChild(n, trace) { - let res = []; - let prefix = new Array(n + 1).join('\t'); - for (const [id, first, child] of trace._dep) { - if (first && child) { - causedCreation = true; - res.push(`${prefix}CREATES -> ${id}`); - let nested = printChild(n + 1, child); - if (nested) { - res.push(nested); - } - } - else { - res.push(`${prefix}uses -> ${id}`); - } - } - return res.join('\n'); - } - let 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 extends Trace { - constructor() { super(-1, null); } - stop() { } - branch() { return this; } - }; - Trace._totals = 0; -}); -//#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[565/*vs/platform/keybinding/common/abstractKeybindingService*/], __M([0/*require*/,1/*exports*/,536/*vs/nls!vs/platform/keybinding/common/abstractKeybindingService*/,15/*vs/base/common/async*/,6/*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 }); - exports.AbstractKeybindingService = void 0; - class AbstractKeybindingService extends lifecycle_1.Disposable { - constructor(_contextKeyService, _commandService, _telemetryService, _notificationService, _logService) { - super(); - this._contextKeyService = _contextKeyService; - this._commandService = _commandService; - this._telemetryService = _telemetryService; - this._notificationService = _notificationService; - this._logService = _logService; - this._onDidUpdateKeybindings = this._register(new event_1.Emitter()); - this._currentChord = null; - this._currentChordChecker = new async_1.IntervalTimer(); - this._currentChordStatusMessage = null; - this._currentSingleModifier = null; - this._currentSingleModifierClearTimeout = new async_1.TimeoutTimer(); - this._logging = false; - } - get onDidUpdateKeybindings() { - return this._onDidUpdateKeybindings ? this._onDidUpdateKeybindings.event : event_1.Event.None; // Sinon stubbing walks properties on prototype - } - dispose() { - super.dispose(); - } - _log(str) { - if (this._logging) { - this._logService.info(`[KeybindingService]: ${str}`); - } - } - getKeybindings() { - return this._getResolver().getKeybindings(); - } - lookupKeybinding(commandId, context) { - const result = this._getResolver().lookupPrimaryKeybinding(commandId, context || this._contextKeyService); - if (!result) { - return undefined; - } - return result.resolvedKeybinding; - } - dispatchEvent(e, target) { - return this._dispatch(e, target); - } - softDispatch(e, target) { - const keybinding = this.resolveKeyboardEvent(e); - if (keybinding.isChord()) { - console.warn('Unexpected keyboard event mapped to a chord'); - return null; - } - const [firstPart,] = keybinding.getDispatchParts(); - if (firstPart === null) { - // cannot be dispatched, probably only modifier keys - return null; - } - const contextValue = this._contextKeyService.getContext(target); - const currentChord = this._currentChord ? this._currentChord.keypress : null; - return this._getResolver().resolve(contextValue, currentChord, firstPart); - } - _enterChordMode(firstPart, keypressLabel) { - this._currentChord = { - keypress: firstPart, - label: keypressLabel - }; - this._currentChordStatusMessage = this._notificationService.status(nls.localize(0, null, keypressLabel)); - const chordEnterTime = Date.now(); - this._currentChordChecker.cancelAndSet(() => { - 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); - } - _leaveChordMode() { - if (this._currentChordStatusMessage) { - this._currentChordStatusMessage.dispose(); - this._currentChordStatusMessage = null; - } - this._currentChordChecker.cancel(); - this._currentChord = null; - } - _dispatch(e, target) { - return this._doDispatch(this.resolveKeyboardEvent(e), target, /*isSingleModiferChord*/ false); - } - _singleModifierDispatch(e, target) { - const keybinding = this.resolveKeyboardEvent(e); - const [singleModifier,] = keybinding.getSingleModifierDispatchParts(); - if (singleModifier !== null && this._currentSingleModifier === null) { - // we have a valid `singleModifier`, store it for the next keyup, but clear it in 300ms - this._log(`+ Storing single modifier for possible chord ${singleModifier}.`); - this._currentSingleModifier = singleModifier; - this._currentSingleModifierClearTimeout.cancelAndSet(() => { - this._log(`+ Clearing single modifier due to 300ms elapsed.`); - this._currentSingleModifier = null; - }, 300); - return false; - } - if (singleModifier !== null && singleModifier === this._currentSingleModifier) { - // bingo! - this._log(`/ Dispatching single modifier chord ${singleModifier} ${singleModifier}`); - this._currentSingleModifierClearTimeout.cancel(); - this._currentSingleModifier = null; - return this._doDispatch(keybinding, target, /*isSingleModiferChord*/ true); - } - this._currentSingleModifierClearTimeout.cancel(); - this._currentSingleModifier = null; - return false; - } - _doDispatch(keybinding, target, isSingleModiferChord = false) { - let shouldPreventDefault = false; - if (keybinding.isChord()) { - console.warn('Unexpected keyboard event mapped to a chord'); - return false; - } - let firstPart = null; // the first keybinding i.e. Ctrl+K - let currentChord = null; // the "second" keybinding i.e. Ctrl+K "Ctrl+D" - if (isSingleModiferChord) { - const [dispatchKeyname,] = keybinding.getSingleModifierDispatchParts(); - firstPart = dispatchKeyname; - currentChord = dispatchKeyname; - } - else { - [firstPart,] = keybinding.getDispatchParts(); - currentChord = this._currentChord ? this._currentChord.keypress : null; - } - if (firstPart === null) { - this._log(`\\ Keyboard event cannot be dispatched in keydown phase.`); - // cannot be dispatched, probably only modifier keys - return shouldPreventDefault; - } - const contextValue = this._contextKeyService.getContext(target); - const keypressLabel = keybinding.getLabel(); - const resolveResult = this._getResolver().resolve(contextValue, currentChord, firstPart); - this._logService.trace('KeybindingService#dispatch', keypressLabel, resolveResult === null || resolveResult === void 0 ? void 0 : resolveResult.commandId); - 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, err => this._notificationService.warn(err)); - } - else { - this._commandService.executeCommand(resolveResult.commandId, resolveResult.commandArgs).then(undefined, err => this._notificationService.warn(err)); - } - this._telemetryService.publicLog2('workbenchActionExecuted', { id: resolveResult.commandId, from: 'keybinding' }); - } - return shouldPreventDefault; - } - mightProducePrintableCharacter(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; - } - } - 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[566/*vs/platform/keybinding/common/baseResolvedKeybinding*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,182/*vs/base/common/keybindingLabels*/,41/*vs/base/common/keyCodes*/]), function (require, exports, errors_1, keybindingLabels_1, keyCodes_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.BaseResolvedKeybinding = void 0; - class BaseResolvedKeybinding extends keyCodes_1.ResolvedKeybinding { - constructor(os, parts) { - super(); - if (parts.length === 0) { - throw (0, errors_1.illegalArgument)(`parts`); - } - this._os = os; - this._parts = parts; - } - getLabel() { - return keybindingLabels_1.UILabelProvider.toLabel(this._os, this._parts, (keybinding) => this._getLabel(keybinding)); - } - getAriaLabel() { - return keybindingLabels_1.AriaLabelProvider.toLabel(this._os, this._parts, (keybinding) => this._getAriaLabel(keybinding)); - } - isChord() { - return (this._parts.length > 1); - } - getParts() { - return this._parts.map((keybinding) => this._getPart(keybinding)); - } - _getPart(keybinding) { - return new keyCodes_1.ResolvedKeybindingPart(keybinding.ctrlKey, keybinding.shiftKey, keybinding.altKey, keybinding.metaKey, this._getLabel(keybinding), this._getAriaLabel(keybinding)); - } - getDispatchParts() { - return this._parts.map((keybinding) => this._getDispatchPart(keybinding)); - } - getSingleModifierDispatchParts() { - return this._parts.map((keybinding) => this._getSingleModifierDispatchPart(keybinding)); - } - } - 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[37/*vs/platform/keybinding/common/keybinding*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.IKeybindingService = void 0; - exports.IKeybindingService = (0, instantiation_1.createDecorator)('keybindingService'); -}); - -/*--------------------------------------------------------------------------------------------- - * 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/platform/keybinding/common/keybindingResolver*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.KeybindingResolver = void 0; - class KeybindingResolver { - constructor(defaultKeybindings, overrides, log) { - this._log = log; - this._defaultKeybindings = defaultKeybindings; - this._defaultBoundCommands = new Map(); - for (let i = 0, len = defaultKeybindings.length; i < len; i++) { - const 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 (let i = 0, len = this._keybindings.length; i < len; i++) { - let k = this._keybindings[i]; - if (k.keypressParts.length === 0) { - // unbound - continue; - } - if (k.when && k.when.type === 0 /* False */) { - // when condition is false - continue; - } - // TODO@chords - this._addKeyPress(k.keypressParts[0], k); - } - } - static _isTargetedForRemoval(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`. - */ - static combine(defaults, rawOverrides) { - defaults = defaults.slice(0); - let overrides = []; - for (const override of rawOverrides) { - if (!override.command || override.command.length === 0 || override.command.charAt(0) !== '-') { - overrides.push(override); - continue; - } - const command = override.command.substr(1); - // TODO@chords - const keypressFirstPart = override.keypressParts[0]; - const keypressChordPart = override.keypressParts[1]; - const when = override.when; - for (let j = defaults.length - 1; j >= 0; j--) { - if (this._isTargetedForRemoval(defaults[j], keypressFirstPart, keypressChordPart, command, when)) { - defaults.splice(j, 1); - } - } - } - return defaults.concat(overrides); - } - _addKeyPress(keypress, item) { - const 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 (let i = conflicts.length - 1; i >= 0; i--) { - let conflict = conflicts[i]; - if (conflict.command === item.command) { - continue; - } - const conflictIsChord = (conflict.keypressParts.length > 1); - const 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); - } - _addToLookupMap(item) { - if (!item.command) { - return; - } - let arr = this._lookupMap.get(item.command); - if (typeof arr === 'undefined') { - arr = [item]; - this._lookupMap.set(item.command, arr); - } - else { - arr.push(item); - } - } - _removeFromLookupMap(item) { - if (!item.command) { - return; - } - let arr = this._lookupMap.get(item.command); - if (typeof arr === 'undefined') { - return; - } - for (let 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`. - */ - static whenIsEntirelyIncluded(a, b) { - if (!b || b.type === 1 /* True */) { - return true; - } - if (!a || a.type === 1 /* True */) { - return false; - } - return this._implies(a, b); - } - /** - * Returns true if it is provable `p` implies `q`. - */ - static _implies(p, q) { - const notP = p.negate(); - const terminals = (node) => { - if (node.type === 9 /* Or */) { - return node.expr; - } - return [node]; - }; - let expr = terminals(notP).concat(terminals(q)); - for (let i = 0; i < expr.length; i++) { - const a = expr[i]; - const notA = a.negate(); - for (let j = i + 1; j < expr.length; j++) { - const b = expr[j]; - if (notA.equals(b)) { - return true; - } - } - } - return false; - } - getKeybindings() { - return this._keybindings; - } - lookupPrimaryKeybinding(commandId, context) { - const items = this._lookupMap.get(commandId); - if (typeof items === 'undefined' || items.length === 0) { - return null; - } - if (items.length === 1) { - return items[0]; - } - for (let i = items.length - 1; i >= 0; i--) { - const item = items[i]; - if (context.contextMatchesRules(item.when)) { - return item; - } - } - return items[items.length - 1]; - } - resolve(context, currentChord, keypress) { - this._log(`| Resolving ${keypress}${currentChord ? ` chorded from ${currentChord}` : ``}`); - let lookupMap = null; - if (currentChord !== null) { - // Fetch all chord bindings for `currentChord` - const candidates = this._map.get(currentChord); - if (typeof candidates === 'undefined') { - // No chords starting with `currentChord` - this._log(`\\ No keybinding entries.`); - return null; - } - lookupMap = []; - for (let i = 0, len = candidates.length; i < len; i++) { - let candidate = candidates[i]; - // TODO@chords - if (candidate.keypressParts[1] === keypress) { - lookupMap.push(candidate); - } - } - } - else { - const candidates = this._map.get(keypress); - if (typeof candidates === 'undefined') { - // No bindings with `keypress` - this._log(`\\ No keybinding entries.`); - return null; - } - lookupMap = candidates; - } - let result = this._findCommand(context, lookupMap); - if (!result) { - this._log(`\\ From ${lookupMap.length} keybinding entries, no when clauses matched the context.`); - return null; - } - // TODO@chords - if (currentChord === null && result.keypressParts.length > 1 && result.keypressParts[1] !== null) { - this._log(`\\ From ${lookupMap.length} keybinding entries, matched chord, when: ${printWhenExplanation(result.when)}, source: ${printSourceExplanation(result)}.`); - return { - enterChord: true, - leaveChord: false, - commandId: null, - commandArgs: null, - bubble: false - }; - } - this._log(`\\ From ${lookupMap.length} keybinding entries, matched ${result.command}, when: ${printWhenExplanation(result.when)}, source: ${printSourceExplanation(result)}.`); - return { - enterChord: false, - leaveChord: result.keypressParts.length > 1, - commandId: result.command, - commandArgs: result.commandArgs, - bubble: result.bubble - }; - } - _findCommand(context, matches) { - for (let i = matches.length - 1; i >= 0; i--) { - let k = matches[i]; - if (!KeybindingResolver.contextMatchesRules(context, k.when)) { - continue; - } - return k; - } - return null; - } - static contextMatchesRules(context, rules) { - if (!rules) { - return true; - } - return rules.evaluate(context); - } - } - exports.KeybindingResolver = KeybindingResolver; - function printWhenExplanation(when) { - if (!when) { - return `no when condition`; - } - return `${when.serialize()}`; - } - function printSourceExplanation(kb) { - return (kb.extensionId - ? (kb.isBuiltinExtension ? `built-in extension ${kb.extensionId}` : `user extension ${kb.extensionId}`) - : (kb.isDefault ? `built-in` : `user`)); - } -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[567/*vs/platform/keybinding/common/resolvedKeybindingItem*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.removeElementsAfterNulls = exports.ResolvedKeybindingItem = void 0; - class ResolvedKeybindingItem { - constructor(resolvedKeybinding, command, commandArgs, when, isDefault, extensionId, isBuiltinExtension) { - this._resolvedKeybindingItemBrand = undefined; - this.resolvedKeybinding = resolvedKeybinding; - this.keypressParts = resolvedKeybinding ? removeElementsAfterNulls(resolvedKeybinding.getDispatchParts()) : []; - if (resolvedKeybinding && this.keypressParts.length === 0) { - // handle possible single modifier chord keybindings - this.keypressParts = removeElementsAfterNulls(resolvedKeybinding.getSingleModifierDispatchParts()); - } - 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; - this.extensionId = extensionId; - this.isBuiltinExtension = isBuiltinExtension; - } - } - exports.ResolvedKeybindingItem = ResolvedKeybindingItem; - function removeElementsAfterNulls(arr) { - let result = []; - for (let i = 0, len = arr.length; i < len; i++) { - const 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[568/*vs/platform/keybinding/common/usLayoutResolvedKeybinding*/], __M([0/*require*/,1/*exports*/,41/*vs/base/common/keyCodes*/,566/*vs/platform/keybinding/common/baseResolvedKeybinding*/]), function (require, exports, keyCodes_1, baseResolvedKeybinding_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.USLayoutResolvedKeybinding = void 0; - /** - * Do not instantiate. Use KeybindingService to get a ResolvedKeybinding seeded with information about the current kb layout. - */ - class USLayoutResolvedKeybinding extends baseResolvedKeybinding_1.BaseResolvedKeybinding { - constructor(actual, os) { - super(os, actual.parts); - } - _keyCodeToUILabel(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); - } - _getLabel(keybinding) { - if (keybinding.isDuplicateModifierCase()) { - return ''; - } - return this._keyCodeToUILabel(keybinding.keyCode); - } - _getAriaLabel(keybinding) { - if (keybinding.isDuplicateModifierCase()) { - return ''; - } - return keyCodes_1.KeyCodeUtils.toString(keybinding.keyCode); - } - _getDispatchPart(keybinding) { - return USLayoutResolvedKeybinding.getDispatchStr(keybinding); - } - static getDispatchStr(keybinding) { - if (keybinding.isModifierKey()) { - return null; - } - let 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; - } - _getSingleModifierDispatchPart(keybinding) { - if (keybinding.keyCode === 5 /* Ctrl */ && !keybinding.shiftKey && !keybinding.altKey && !keybinding.metaKey) { - return 'ctrl'; - } - if (keybinding.keyCode === 4 /* Shift */ && !keybinding.ctrlKey && !keybinding.altKey && !keybinding.metaKey) { - return 'shift'; - } - if (keybinding.keyCode === 6 /* Alt */ && !keybinding.ctrlKey && !keybinding.shiftKey && !keybinding.metaKey) { - return 'alt'; - } - if (keybinding.keyCode === 57 /* Meta */ && !keybinding.ctrlKey && !keybinding.shiftKey && !keybinding.altKey) { - return 'meta'; - } - return null; - } - } - 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[121/*vs/platform/label/common/label*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ILabelService = void 0; - exports.ILabelService = (0, instantiation_1.createDecorator)('labelService'); -}); - -/*--------------------------------------------------------------------------------------------- - * 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/platform/layout/browser/layoutService*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ILayoutService = void 0; - exports.ILayoutService = (0, 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[569/*vs/platform/contextview/browser/contextViewService*/], __M([0/*require*/,1/*exports*/,207/*vs/base/browser/ui/contextview/contextview*/,2/*vs/base/common/lifecycle*/,144/*vs/platform/layout/browser/layoutService*/]), function (require, exports, contextview_1, lifecycle_1, layoutService_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ContextViewService = void 0; - let ContextViewService = class ContextViewService extends lifecycle_1.Disposable { - constructor(layoutService) { - super(); - this.layoutService = layoutService; - this.currentViewDisposable = lifecycle_1.Disposable.None; - this.container = layoutService.container; - this.contextView = this._register(new contextview_1.ContextView(this.container, 1 /* ABSOLUTE */)); - this.layout(); - this._register(layoutService.onDidLayout(() => this.layout())); - } - // ContextView - setContainer(container, domPosition) { - this.contextView.setContainer(container, domPosition || 1 /* ABSOLUTE */); - } - showContextView(delegate, container, shadowRoot) { - if (container) { - if (container !== this.container) { - this.container = container; - this.setContainer(container, shadowRoot ? 3 /* FIXED_SHADOW */ : 2 /* FIXED */); - } - } - else { - if (this.container !== this.layoutService.container) { - this.container = this.layoutService.container; - this.setContainer(this.container, 1 /* ABSOLUTE */); - } - } - this.contextView.show(delegate); - const disposable = (0, lifecycle_1.toDisposable)(() => { - if (this.currentViewDisposable === disposable) { - this.hideContextView(); - } - }); - this.currentViewDisposable = disposable; - return disposable; - } - getContextViewElement() { - return this.contextView.getViewElement(); - } - layout() { - this.contextView.layout(); - } - hideContextView(data) { - this.contextView.hide(data); - } - }; - ContextViewService = __decorate([ - __param(0, layoutService_1.ILayoutService) - ], ContextViewService); - 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[70/*vs/platform/log/common/log*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/,2/*vs/base/common/lifecycle*/,6/*vs/base/common/event*/]), function (require, exports, instantiation_1, lifecycle_1, event_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.LogService = exports.ConsoleLogger = exports.AbstractLogger = exports.DEFAULT_LOG_LEVEL = exports.LogLevel = exports.ILogService = void 0; - exports.ILogService = (0, 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 = {})); - exports.DEFAULT_LOG_LEVEL = LogLevel.Info; - class AbstractLogger extends lifecycle_1.Disposable { - constructor() { - super(...arguments); - this.level = exports.DEFAULT_LOG_LEVEL; - this._onDidChangeLogLevel = this._register(new event_1.Emitter()); - } - setLevel(level) { - if (this.level !== level) { - this.level = level; - this._onDidChangeLogLevel.fire(this.level); - } - } - getLevel() { - return this.level; - } - } - exports.AbstractLogger = AbstractLogger; - class ConsoleLogger extends AbstractLogger { - constructor(logLevel = exports.DEFAULT_LOG_LEVEL) { - super(); - this.setLevel(logLevel); - } - trace(message, ...args) { - if (this.getLevel() <= LogLevel.Trace) { - console.log('%cTRACE', 'color: #888', message, ...args); - } - } - debug(message, ...args) { - if (this.getLevel() <= LogLevel.Debug) { - console.log('%cDEBUG', 'background: #eee; color: #888', message, ...args); - } - } - info(message, ...args) { - if (this.getLevel() <= LogLevel.Info) { - console.log('%c INFO', 'color: #33f', message, ...args); - } - } - error(message, ...args) { - if (this.getLevel() <= LogLevel.Error) { - console.log('%c ERR', 'color: #f33', message, ...args); - } - } - dispose() { - // noop - } - } - exports.ConsoleLogger = ConsoleLogger; - class LogService extends lifecycle_1.Disposable { - constructor(logger) { - super(); - this.logger = logger; - this._register(logger); - } - getLevel() { - return this.logger.getLevel(); - } - trace(message, ...args) { - this.logger.trace(message, ...args); - } - debug(message, ...args) { - this.logger.debug(message, ...args); - } - info(message, ...args) { - this.logger.info(message, ...args); - } - error(message, ...args) { - this.logger.error(message, ...args); - } - } - exports.LogService = LogService; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - - - - - - - - - - - - - - - - - - -define(__m[255/*vs/editor/common/services/editorWorkerServiceImpl*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,204/*vs/base/common/worker/simpleWorker*/,301/*vs/base/worker/defaultWorkerFactory*/,3/*vs/editor/common/core/range*/,18/*vs/editor/common/modes*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/,397/*vs/editor/common/services/editorSimpleWorker*/,36/*vs/editor/common/services/modelService*/,142/*vs/editor/common/services/textResourceConfigurationService*/,8/*vs/base/common/strings*/,19/*vs/base/common/arrays*/,70/*vs/platform/log/common/log*/,81/*vs/base/common/stopwatch*/,12/*vs/base/common/errors*/]), 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, errors_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.EditorWorkerClient = exports.EditorWorkerHost = exports.EditorWorkerServiceImpl = void 0; - /** - * Stop syncing a model to the worker if it was not needed for 1 min. - */ - const STOP_SYNC_MODEL_DELTA_TIME_MS = 60 * 1000; - /** - * Stop the worker if it was not needed for 5 min. - */ - const STOP_WORKER_DELTA_TIME_MS = 5 * 60 * 1000; - function canSyncModel(modelService, resource) { - let model = modelService.getModel(resource); - if (!model) { - return false; - } - if (model.isTooLargeForSyncing()) { - return false; - } - return true; - } - let EditorWorkerServiceImpl = class EditorWorkerServiceImpl extends lifecycle_1.Disposable { - constructor(modelService, configurationService, logService) { - super(); - this._modelService = modelService; - this._workerManager = this._register(new WorkerManager(this._modelService)); - this._logService = logService; - // register default link-provider and default completions-provider - this._register(modes.LinkProviderRegistry.register('*', { - provideLinks: (model, token) => { - if (!canSyncModel(this._modelService, model.uri)) { - return Promise.resolve({ links: [] }); // File too large - } - return this._workerManager.withWorker().then(client => client.computeLinks(model.uri)).then(links => { - return links && { links }; - }); - } - })); - this._register(modes.CompletionProviderRegistry.register('*', new WordBasedCompletionItemProvider(this._workerManager, configurationService, this._modelService))); - } - dispose() { - super.dispose(); - } - canComputeDiff(original, modified) { - return (canSyncModel(this._modelService, original) && canSyncModel(this._modelService, modified)); - } - computeDiff(original, modified, ignoreTrimWhitespace, maxComputationTime) { - return this._workerManager.withWorker().then(client => client.computeDiff(original, modified, ignoreTrimWhitespace, maxComputationTime)); - } - computeMoreMinimalEdits(resource, edits) { - if ((0, arrays_1.isNonEmptyArray)(edits)) { - if (!canSyncModel(this._modelService, resource)) { - return Promise.resolve(edits); // File too large - } - const sw = stopwatch_1.StopWatch.create(true); - const result = this._workerManager.withWorker().then(client => client.computeMoreMinimalEdits(resource, edits)); - result.finally(() => this._logService.trace('FORMAT#computeMoreMinimalEdits', resource.toString(true), sw.elapsed())); - return Promise.race([result, (0, async_1.timeout)(1000).then(() => edits)]); - } - else { - return Promise.resolve(undefined); - } - } - canNavigateValueSet(resource) { - return (canSyncModel(this._modelService, resource)); - } - navigateValueSet(resource, range, up) { - return this._workerManager.withWorker().then(client => client.navigateValueSet(resource, range, up)); - } - canComputeWordRanges(resource) { - return canSyncModel(this._modelService, resource); - } - computeWordRanges(resource, range) { - return this._workerManager.withWorker().then(client => client.computeWordRanges(resource, range)); - } - }; - EditorWorkerServiceImpl = __decorate([ - __param(0, modelService_1.IModelService), - __param(1, textResourceConfigurationService_1.ITextResourceConfigurationService), - __param(2, log_1.ILogService) - ], EditorWorkerServiceImpl); - exports.EditorWorkerServiceImpl = EditorWorkerServiceImpl; - class WordBasedCompletionItemProvider { - constructor(workerManager, configurationService, modelService) { - this._debugDisplayName = 'wordbasedCompletions'; - this._workerManager = workerManager; - this._configurationService = configurationService; - this._modelService = modelService; - } - provideCompletionItems(model, position) { - return __awaiter(this, void 0, void 0, function* () { - const config = this._configurationService.getValue(model.uri, position, 'editor'); - if (!config.wordBasedSuggestions) { - return undefined; - } - const models = []; - if (config.wordBasedSuggestionsMode === 'currentDocument') { - // only current file and only if not too large - if (canSyncModel(this._modelService, model.uri)) { - models.push(model.uri); - } - } - else { - // either all files or files of same language - for (const candidate of this._modelService.getModels()) { - if (!canSyncModel(this._modelService, candidate.uri)) { - continue; - } - if (candidate === model) { - models.unshift(candidate.uri); - } - else if (config.wordBasedSuggestionsMode === 'allDocuments' || candidate.getLanguageIdentifier().id === model.getLanguageIdentifier().id) { - models.push(candidate.uri); - } - } - } - if (models.length === 0) { - return undefined; // File too large, no other files - } - const wordDefRegExp = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(model.getLanguageIdentifier().id); - const word = model.getWordAtPosition(position); - const replace = !word ? range_1.Range.fromPositions(position) : new range_1.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn); - const insert = replace.setEndPosition(position.lineNumber, position.column); - const client = yield this._workerManager.withWorker(); - const data = yield client.textualSuggest(models, word === null || word === void 0 ? void 0 : word.word, wordDefRegExp); - if (!data) { - return undefined; - } - return { - duration: data.duration, - suggestions: data.words.map((word) => { - return { - kind: 18 /* Text */, - label: word, - insertText: word, - range: { insert, replace } - }; - }), - }; - }); - } - } - class WorkerManager extends lifecycle_1.Disposable { - constructor(modelService) { - super(); - this._modelService = modelService; - this._editorWorkerClient = null; - this._lastWorkerUsedTime = (new Date()).getTime(); - let stopWorkerInterval = this._register(new async_1.IntervalTimer()); - stopWorkerInterval.cancelAndSet(() => this._checkStopIdleWorker(), Math.round(STOP_WORKER_DELTA_TIME_MS / 2)); - this._register(this._modelService.onModelRemoved(_ => this._checkStopEmptyWorker())); - } - dispose() { - if (this._editorWorkerClient) { - this._editorWorkerClient.dispose(); - this._editorWorkerClient = null; - } - super.dispose(); - } - /** - * Check if the model service has no more models and stop the worker if that is the case. - */ - _checkStopEmptyWorker() { - if (!this._editorWorkerClient) { - return; - } - let 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. - */ - _checkStopIdleWorker() { - if (!this._editorWorkerClient) { - return; - } - let timeSinceLastWorkerUsedTime = (new Date()).getTime() - this._lastWorkerUsedTime; - if (timeSinceLastWorkerUsedTime > STOP_WORKER_DELTA_TIME_MS) { - this._editorWorkerClient.dispose(); - this._editorWorkerClient = null; - } - } - withWorker() { - this._lastWorkerUsedTime = (new Date()).getTime(); - if (!this._editorWorkerClient) { - this._editorWorkerClient = new EditorWorkerClient(this._modelService, false, 'editorWorkerService'); - } - return Promise.resolve(this._editorWorkerClient); - } - } - class EditorModelManager extends lifecycle_1.Disposable { - constructor(proxy, modelService, keepIdleModels) { - super(); - this._syncedModels = Object.create(null); - this._syncedModelsLastUsedTime = Object.create(null); - this._proxy = proxy; - this._modelService = modelService; - if (!keepIdleModels) { - let timer = new async_1.IntervalTimer(); - timer.cancelAndSet(() => this._checkStopModelSync(), Math.round(STOP_SYNC_MODEL_DELTA_TIME_MS / 2)); - this._register(timer); - } - } - dispose() { - for (let modelUrl in this._syncedModels) { - (0, lifecycle_1.dispose)(this._syncedModels[modelUrl]); - } - this._syncedModels = Object.create(null); - this._syncedModelsLastUsedTime = Object.create(null); - super.dispose(); - } - ensureSyncedResources(resources) { - for (const resource of resources) { - let resourceStr = resource.toString(); - if (!this._syncedModels[resourceStr]) { - this._beginModelSync(resource); - } - if (this._syncedModels[resourceStr]) { - this._syncedModelsLastUsedTime[resourceStr] = (new Date()).getTime(); - } - } - } - _checkStopModelSync() { - let currentTime = (new Date()).getTime(); - let toRemove = []; - for (let modelUrl in this._syncedModelsLastUsedTime) { - let elapsedTime = currentTime - this._syncedModelsLastUsedTime[modelUrl]; - if (elapsedTime > STOP_SYNC_MODEL_DELTA_TIME_MS) { - toRemove.push(modelUrl); - } - } - for (const e of toRemove) { - this._stopModelSync(e); - } - } - _beginModelSync(resource) { - let model = this._modelService.getModel(resource); - if (!model) { - return; - } - if (model.isTooLargeForSyncing()) { - return; - } - let modelUrl = resource.toString(); - this._proxy.acceptNewModel({ - url: model.uri.toString(), - lines: model.getLinesContent(), - EOL: model.getEOL(), - versionId: model.getVersionId() - }); - const toDispose = new lifecycle_1.DisposableStore(); - toDispose.add(model.onDidChangeContent((e) => { - this._proxy.acceptModelChanged(modelUrl.toString(), e); - })); - toDispose.add(model.onWillDispose(() => { - this._stopModelSync(modelUrl); - })); - toDispose.add((0, lifecycle_1.toDisposable)(() => { - this._proxy.acceptRemovedModel(modelUrl); - })); - this._syncedModels[modelUrl] = toDispose; - } - _stopModelSync(modelUrl) { - let toDispose = this._syncedModels[modelUrl]; - delete this._syncedModels[modelUrl]; - delete this._syncedModelsLastUsedTime[modelUrl]; - (0, lifecycle_1.dispose)(toDispose); - } - } - class SynchronousWorkerClient { - constructor(instance) { - this._instance = instance; - this._proxyObj = Promise.resolve(this._instance); - } - dispose() { - this._instance.dispose(); - } - getProxyObject() { - return this._proxyObj; - } - } - class EditorWorkerHost { - constructor(workerClient) { - this._workerClient = workerClient; - } - // foreign host request - fhr(method, args) { - return this._workerClient.fhr(method, args); - } - } - exports.EditorWorkerHost = EditorWorkerHost; - class EditorWorkerClient extends lifecycle_1.Disposable { - constructor(modelService, keepIdleModels, label) { - super(); - this._disposed = false; - this._modelService = modelService; - this._keepIdleModels = keepIdleModels; - this._workerFactory = new defaultWorkerFactory_1.DefaultWorkerFactory(label); - this._worker = null; - this._modelManager = null; - } - // foreign host request - fhr(method, args) { - throw new Error(`Not implemented!`); - } - _getOrCreateWorker() { - if (!this._worker) { - try { - this._worker = this._register(new simpleWorker_1.SimpleWorkerClient(this._workerFactory, 'vs/editor/common/services/editorSimpleWorker', new EditorWorkerHost(this))); - } - catch (err) { - (0, simpleWorker_1.logOnceWebWorkerWarning)(err); - this._worker = new SynchronousWorkerClient(new editorSimpleWorker_1.EditorSimpleWorker(new EditorWorkerHost(this), null)); - } - } - return this._worker; - } - _getProxy() { - return this._getOrCreateWorker().getProxyObject().then(undefined, (err) => { - (0, simpleWorker_1.logOnceWebWorkerWarning)(err); - this._worker = new SynchronousWorkerClient(new editorSimpleWorker_1.EditorSimpleWorker(new EditorWorkerHost(this), null)); - return this._getOrCreateWorker().getProxyObject(); - }); - } - _getOrCreateModelManager(proxy) { - if (!this._modelManager) { - this._modelManager = this._register(new EditorModelManager(proxy, this._modelService, this._keepIdleModels)); - } - return this._modelManager; - } - _withSyncedResources(resources) { - if (this._disposed) { - return Promise.reject((0, errors_1.canceled)()); - } - return this._getProxy().then((proxy) => { - this._getOrCreateModelManager(proxy).ensureSyncedResources(resources); - return proxy; - }); - } - computeDiff(original, modified, ignoreTrimWhitespace, maxComputationTime) { - return this._withSyncedResources([original, modified]).then(proxy => { - return proxy.computeDiff(original.toString(), modified.toString(), ignoreTrimWhitespace, maxComputationTime); - }); - } - computeMoreMinimalEdits(resource, edits) { - return this._withSyncedResources([resource]).then(proxy => { - return proxy.computeMoreMinimalEdits(resource.toString(), edits); - }); - } - computeLinks(resource) { - return this._withSyncedResources([resource]).then(proxy => { - return proxy.computeLinks(resource.toString()); - }); - } - textualSuggest(resources, leadingWord, wordDefRegExp) { - return __awaiter(this, void 0, void 0, function* () { - const proxy = yield this._withSyncedResources(resources); - const wordDef = wordDefRegExp.source; - const wordDefFlags = (0, strings_1.regExpFlags)(wordDefRegExp); - return proxy.textualSuggest(resources.map(r => r.toString()), leadingWord, wordDef, wordDefFlags); - }); - } - computeWordRanges(resource, range) { - return this._withSyncedResources([resource]).then(proxy => { - let model = this._modelService.getModel(resource); - if (!model) { - return Promise.resolve(null); - } - let wordDefRegExp = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(model.getLanguageIdentifier().id); - let wordDef = wordDefRegExp.source; - let wordDefFlags = (0, strings_1.regExpFlags)(wordDefRegExp); - return proxy.computeWordRanges(resource.toString(), range, wordDef, wordDefFlags); - }); - } - navigateValueSet(resource, range, up) { - return this._withSyncedResources([resource]).then(proxy => { - let model = this._modelService.getModel(resource); - if (!model) { - return null; - } - let wordDefRegExp = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(model.getLanguageIdentifier().id); - let wordDef = wordDefRegExp.source; - let wordDefFlags = (0, strings_1.regExpFlags)(wordDefRegExp); - return proxy.navigateValueSet(resource.toString(), range, up, wordDef, wordDefFlags); - }); - } - dispose() { - super.dispose(); - this._disposed = true; - } - } - 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[256/*vs/editor/common/services/semanticTokensProviderStyling*/], __M([0/*require*/,1/*exports*/,18/*vs/editor/common/modes*/,70/*vs/platform/log/common/log*/,140/*vs/editor/common/model/tokensStore*/]), function (require, exports, modes_1, log_1, tokensStore_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.toMultilineTokens2 = exports.SemanticTokensProviderStyling = void 0; - class SemanticTokensProviderStyling { - constructor(_legend, _themeService, _logService) { - this._legend = _legend; - this._themeService = _themeService; - this._logService = _logService; - this._hashTable = new HashTable(); - this._hasWarnedOverlappingTokens = false; - } - getMetadata(tokenTypeIndex, tokenModifierSet, languageId) { - const entry = this._hashTable.get(tokenTypeIndex, tokenModifierSet, languageId.id); - let metadata; - if (entry) { - metadata = entry.metadata; - if (this._logService.getLevel() === log_1.LogLevel.Trace) { - this._logService.trace(`SemanticTokensProviderStyling [CACHED] ${tokenTypeIndex} / ${tokenModifierSet}: foreground ${modes_1.TokenMetadata.getForeground(metadata)}, fontStyle ${modes_1.TokenMetadata.getFontStyle(metadata).toString(2)}`); - } - } - else { - let tokenType = this._legend.tokenTypes[tokenTypeIndex]; - const tokenModifiers = []; - if (tokenType) { - let modifierSet = tokenModifierSet; - for (let modifierIndex = 0; modifierSet > 0 && modifierIndex < this._legend.tokenModifiers.length; modifierIndex++) { - if (modifierSet & 1) { - tokenModifiers.push(this._legend.tokenModifiers[modifierIndex]); - } - modifierSet = modifierSet >> 1; - } - if (modifierSet > 0 && this._logService.getLevel() === log_1.LogLevel.Trace) { - this._logService.trace(`SemanticTokensProviderStyling: unknown token modifier index: ${tokenModifierSet.toString(2)} for legend: ${JSON.stringify(this._legend.tokenModifiers)}`); - tokenModifiers.push('not-in-legend'); - } - const tokenStyle = this._themeService.getColorTheme().getTokenStyleMetadata(tokenType, tokenModifiers, languageId.language); - if (typeof tokenStyle === 'undefined') { - metadata = 2147483647 /* NO_STYLING */; - } - else { - metadata = 0; - if (typeof tokenStyle.italic !== 'undefined') { - const italicBit = (tokenStyle.italic ? 1 /* Italic */ : 0) << 11 /* FONT_STYLE_OFFSET */; - metadata |= italicBit | 1 /* SEMANTIC_USE_ITALIC */; - } - if (typeof tokenStyle.bold !== 'undefined') { - const boldBit = (tokenStyle.bold ? 2 /* Bold */ : 0) << 11 /* FONT_STYLE_OFFSET */; - metadata |= boldBit | 2 /* SEMANTIC_USE_BOLD */; - } - if (typeof tokenStyle.underline !== 'undefined') { - const underlineBit = (tokenStyle.underline ? 4 /* Underline */ : 0) << 11 /* FONT_STYLE_OFFSET */; - metadata |= underlineBit | 4 /* SEMANTIC_USE_UNDERLINE */; - } - if (tokenStyle.foreground) { - const foregroundBits = (tokenStyle.foreground) << 14 /* FOREGROUND_OFFSET */; - metadata |= foregroundBits | 8 /* SEMANTIC_USE_FOREGROUND */; - } - if (metadata === 0) { - // Nothing! - metadata = 2147483647 /* NO_STYLING */; - } - } - } - else { - if (this._logService.getLevel() === log_1.LogLevel.Trace) { - this._logService.trace(`SemanticTokensProviderStyling: unknown token type index: ${tokenTypeIndex} for legend: ${JSON.stringify(this._legend.tokenTypes)}`); - } - metadata = 2147483647 /* NO_STYLING */; - tokenType = 'not-in-legend'; - } - this._hashTable.add(tokenTypeIndex, tokenModifierSet, languageId.id, metadata); - if (this._logService.getLevel() === log_1.LogLevel.Trace) { - this._logService.trace(`SemanticTokensProviderStyling ${tokenTypeIndex} (${tokenType}) / ${tokenModifierSet} (${tokenModifiers.join(' ')}): foreground ${modes_1.TokenMetadata.getForeground(metadata)}, fontStyle ${modes_1.TokenMetadata.getFontStyle(metadata).toString(2)}`); - } - } - return metadata; - } - warnOverlappingSemanticTokens(lineNumber, startColumn) { - if (!this._hasWarnedOverlappingTokens) { - this._hasWarnedOverlappingTokens = true; - console.warn(`Overlapping semantic tokens detected at lineNumber ${lineNumber}, column ${startColumn}`); - } - } - } - exports.SemanticTokensProviderStyling = SemanticTokensProviderStyling; - function toMultilineTokens2(tokens, styling, languageId) { - const srcData = tokens.data; - const tokenCount = (tokens.data.length / 5) | 0; - const tokensPerArea = Math.max(Math.ceil(tokenCount / 1024 /* DesiredMaxAreas */), 400 /* DesiredTokensPerArea */); - const result = []; - let tokenIndex = 0; - let lastLineNumber = 1; - let lastStartCharacter = 0; - while (tokenIndex < tokenCount) { - const tokenStartIndex = tokenIndex; - let tokenEndIndex = Math.min(tokenStartIndex + tokensPerArea, tokenCount); - // Keep tokens on the same line in the same area... - if (tokenEndIndex < tokenCount) { - let smallTokenEndIndex = tokenEndIndex; - while (smallTokenEndIndex - 1 > tokenStartIndex && srcData[5 * smallTokenEndIndex] === 0) { - smallTokenEndIndex--; - } - if (smallTokenEndIndex - 1 === tokenStartIndex) { - // there are so many tokens on this line that our area would be empty, we must now go right - let bigTokenEndIndex = tokenEndIndex; - while (bigTokenEndIndex + 1 < tokenCount && srcData[5 * bigTokenEndIndex] === 0) { - bigTokenEndIndex++; - } - tokenEndIndex = bigTokenEndIndex; - } - else { - tokenEndIndex = smallTokenEndIndex; - } - } - let destData = new Uint32Array((tokenEndIndex - tokenStartIndex) * 4); - let destOffset = 0; - let areaLine = 0; - let prevLineNumber = 0; - let prevStartCharacter = 0; - let prevEndCharacter = 0; - while (tokenIndex < tokenEndIndex) { - const srcOffset = 5 * tokenIndex; - const deltaLine = srcData[srcOffset]; - const deltaCharacter = srcData[srcOffset + 1]; - const lineNumber = lastLineNumber + deltaLine; - const startCharacter = (deltaLine === 0 ? lastStartCharacter + deltaCharacter : deltaCharacter); - const length = srcData[srcOffset + 2]; - const tokenTypeIndex = srcData[srcOffset + 3]; - const tokenModifierSet = srcData[srcOffset + 4]; - const metadata = styling.getMetadata(tokenTypeIndex, tokenModifierSet, languageId); - if (metadata !== 2147483647 /* NO_STYLING */) { - if (areaLine === 0) { - areaLine = lineNumber; - } - if (prevLineNumber === lineNumber && prevEndCharacter > startCharacter) { - styling.warnOverlappingSemanticTokens(lineNumber, startCharacter + 1); - if (prevStartCharacter < startCharacter) { - // the previous token survives after the overlapping one - destData[destOffset - 4 + 2] = startCharacter; - } - else { - // the previous token is entirely covered by the overlapping one - destOffset -= 4; - } - } - destData[destOffset] = lineNumber - areaLine; - destData[destOffset + 1] = startCharacter; - destData[destOffset + 2] = startCharacter + length; - destData[destOffset + 3] = metadata; - destOffset += 4; - prevLineNumber = lineNumber; - prevStartCharacter = startCharacter; - prevEndCharacter = startCharacter + length; - } - lastLineNumber = lineNumber; - lastStartCharacter = startCharacter; - tokenIndex++; - } - if (destOffset !== destData.length) { - destData = destData.subarray(0, destOffset); - } - const tokens = new tokensStore_1.MultilineTokens2(areaLine, new tokensStore_1.SparseEncodedTokens(destData)); - result.push(tokens); - } - return result; - } - exports.toMultilineTokens2 = toMultilineTokens2; - class HashTableEntry { - constructor(tokenTypeIndex, tokenModifierSet, languageId, metadata) { - this.tokenTypeIndex = tokenTypeIndex; - this.tokenModifierSet = tokenModifierSet; - this.languageId = languageId; - this.metadata = metadata; - this.next = null; - } - } - class HashTable { - constructor() { - this._elementsCount = 0; - this._currentLengthIndex = 0; - this._currentLength = HashTable._SIZES[this._currentLengthIndex]; - this._growCount = Math.round(this._currentLengthIndex + 1 < HashTable._SIZES.length ? 2 / 3 * this._currentLength : 0); - this._elements = []; - HashTable._nullOutEntries(this._elements, this._currentLength); - } - static _nullOutEntries(entries, length) { - for (let i = 0; i < length; i++) { - entries[i] = null; - } - } - _hash2(n1, n2) { - return (((n1 << 5) - n1) + n2) | 0; // n1 * 31 + n2, keep as int32 - } - _hashFunc(tokenTypeIndex, tokenModifierSet, languageId) { - return this._hash2(this._hash2(tokenTypeIndex, tokenModifierSet), languageId) % this._currentLength; - } - get(tokenTypeIndex, tokenModifierSet, languageId) { - const hash = this._hashFunc(tokenTypeIndex, tokenModifierSet, languageId); - let p = this._elements[hash]; - while (p) { - if (p.tokenTypeIndex === tokenTypeIndex && p.tokenModifierSet === tokenModifierSet && p.languageId === languageId) { - return p; - } - p = p.next; - } - return null; - } - add(tokenTypeIndex, tokenModifierSet, languageId, metadata) { - this._elementsCount++; - if (this._growCount !== 0 && this._elementsCount >= this._growCount) { - // expand! - const oldElements = this._elements; - this._currentLengthIndex++; - this._currentLength = HashTable._SIZES[this._currentLengthIndex]; - this._growCount = Math.round(this._currentLengthIndex + 1 < HashTable._SIZES.length ? 2 / 3 * this._currentLength : 0); - this._elements = []; - HashTable._nullOutEntries(this._elements, this._currentLength); - for (const first of oldElements) { - let p = first; - while (p) { - const oldNext = p.next; - p.next = null; - this._add(p); - p = oldNext; - } - } - } - this._add(new HashTableEntry(tokenTypeIndex, tokenModifierSet, languageId, metadata)); - } - _add(element) { - const hash = this._hashFunc(element.tokenTypeIndex, element.tokenModifierSet, element.languageId); - element.next = this._elements[hash]; - this._elements[hash] = element; - } - } - HashTable._SIZES = [3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143]; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[570/*vs/editor/common/services/webWorker*/], __M([0/*require*/,1/*exports*/,255/*vs/editor/common/services/editorWorkerServiceImpl*/,20/*vs/base/common/types*/]), function (require, exports, editorWorkerServiceImpl_1, types) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.createWebWorker = void 0; - /** - * 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; - class MonacoWebWorkerImpl extends editorWorkerServiceImpl_1.EditorWorkerClient { - constructor(modelService, opts) { - super(modelService, opts.keepIdleModels || false, opts.label); - this._foreignModuleId = opts.moduleId; - this._foreignModuleCreateData = opts.createData || null; - this._foreignModuleHost = opts.host || null; - this._foreignProxy = null; - } - // foreign host request - fhr(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); - } - } - _getForeignProxy() { - if (!this._foreignProxy) { - this._foreignProxy = this._getProxy().then((proxy) => { - const foreignHostMethods = this._foreignModuleHost ? types.getAllMethodNames(this._foreignModuleHost) : []; - return proxy.loadForeignModule(this._foreignModuleId, this._foreignModuleCreateData, foreignHostMethods).then((foreignMethods) => { - this._foreignModuleCreateData = null; - const proxyMethodRequest = (method, args) => { - return proxy.fmr(method, args); - }; - const createProxyMethod = (method, proxyMethodRequest) => { - return function () { - const args = Array.prototype.slice.call(arguments, 0); - return proxyMethodRequest(method, args); - }; - }; - let foreignProxy = {}; - for (const foreignMethod of foreignMethods) { - foreignProxy[foreignMethod] = createProxyMethod(foreignMethod, proxyMethodRequest); - } - return foreignProxy; - }); - }); - } - return this._foreignProxy; - } - getProxy() { - return this._getForeignProxy(); - } - withSyncedResources(resources) { - return this._withSyncedResources(resources).then(_ => this.getProxy()); - } - } -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[87/*vs/platform/markers/common/markers*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/,538/*vs/nls!vs/platform/markers/common/markers*/,74/*vs/base/common/severity*/]), function (require, exports, instantiation_1, nls_1, severity_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.IMarkerService = exports.IMarkerData = exports.MarkerSeverity = void 0; - 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; - const _displayStrings = Object.create(null); - _displayStrings[MarkerSeverity.Error] = (0, nls_1.localize)(0, null); - _displayStrings[MarkerSeverity.Warning] = (0, nls_1.localize)(1, null); - _displayStrings[MarkerSeverity.Info] = (0, 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) { - const emptyString = ''; - function makeKey(markerData) { - return makeKeyOptionalMessage(markerData, true); - } - IMarkerData.makeKey = makeKey; - function makeKeyOptionalMessage(markerData, useMessage) { - let 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 = (0, 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[571/*vs/editor/contrib/gotoError/markerNavigationService*/], __M([0/*require*/,1/*exports*/,87/*vs/platform/markers/common/markers*/,24/*vs/base/common/uri*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,3/*vs/editor/common/core/range*/,8/*vs/base/common/strings*/,19/*vs/base/common/arrays*/,9/*vs/platform/instantiation/common/instantiation*/,75/*vs/platform/instantiation/common/extensions*/,72/*vs/base/common/linkedList*/]), function (require, exports, markers_1, uri_1, event_1, lifecycle_1, range_1, strings_1, arrays_1, instantiation_1, extensions_1, linkedList_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.IMarkerNavigationService = exports.MarkerList = exports.MarkerCoordinate = void 0; - class MarkerCoordinate { - constructor(marker, index, total) { - this.marker = marker; - this.index = index; - this.total = total; - } - } - exports.MarkerCoordinate = MarkerCoordinate; - let MarkerList = class MarkerList { - constructor(resourceFilter, _markerService) { - this._markerService = _markerService; - this._onDidChange = new event_1.Emitter(); - this.onDidChange = this._onDidChange.event; - this._dispoables = new lifecycle_1.DisposableStore(); - this._markers = []; - this._nextIdx = -1; - if (uri_1.URI.isUri(resourceFilter)) { - this._resourceFilter = uri => uri.toString() === resourceFilter.toString(); - } - else if (resourceFilter) { - this._resourceFilter = resourceFilter; - } - const updateMarker = () => { - this._markers = this._markerService.read({ - resource: uri_1.URI.isUri(resourceFilter) ? resourceFilter : undefined, - severities: markers_1.MarkerSeverity.Error | markers_1.MarkerSeverity.Warning | markers_1.MarkerSeverity.Info - }); - if (typeof resourceFilter === 'function') { - this._markers = this._markers.filter(m => this._resourceFilter(m.resource)); - } - this._markers.sort(MarkerList._compareMarker); - }; - updateMarker(); - this._dispoables.add(_markerService.onMarkerChanged(uris => { - if (!this._resourceFilter || uris.some(uri => this._resourceFilter(uri))) { - updateMarker(); - this._nextIdx = -1; - this._onDidChange.fire(); - } - })); - } - dispose() { - this._dispoables.dispose(); - this._onDidChange.dispose(); - } - matches(uri) { - if (!this._resourceFilter && !uri) { - return true; - } - if (!this._resourceFilter || !uri) { - return false; - } - return this._resourceFilter(uri); - } - get selected() { - const marker = this._markers[this._nextIdx]; - return marker && new MarkerCoordinate(marker, this._nextIdx + 1, this._markers.length); - } - _initIdx(model, position, fwd) { - let found = false; - let idx = this._markers.findIndex(marker => marker.resource.toString() === model.uri.toString()); - if (idx < 0) { - idx = (0, arrays_1.binarySearch)(this._markers, { resource: model.uri }, (a, b) => (0, strings_1.compare)(a.resource.toString(), b.resource.toString())); - if (idx < 0) { - idx = ~idx; - } - } - for (let i = idx; i < this._markers.length; i++) { - let range = range_1.Range.lift(this._markers[i]); - if (range.isEmpty()) { - const word = model.getWordAtPosition(range.getStartPosition()); - if (word) { - range = new range_1.Range(range.startLineNumber, word.startColumn, range.startLineNumber, word.endColumn); - } - } - if (position && (range.containsPosition(position) || position.isBeforeOrEqual(range.getStartPosition()))) { - this._nextIdx = i; - found = true; - break; - } - if (this._markers[i].resource.toString() !== model.uri.toString()) { - break; - } - } - if (!found) { - // after the last change - this._nextIdx = fwd ? 0 : this._markers.length - 1; - } - if (this._nextIdx < 0) { - this._nextIdx = this._markers.length - 1; - } - } - resetIndex() { - this._nextIdx = -1; - } - move(fwd, model, position) { - if (this._markers.length === 0) { - return false; - } - let oldIdx = this._nextIdx; - if (this._nextIdx === -1) { - this._initIdx(model, position, fwd); - } - else if (fwd) { - this._nextIdx = (this._nextIdx + 1) % this._markers.length; - } - else if (!fwd) { - this._nextIdx = (this._nextIdx - 1 + this._markers.length) % this._markers.length; - } - if (oldIdx !== this._nextIdx) { - return true; - } - return false; - } - find(uri, position) { - let idx = this._markers.findIndex(marker => marker.resource.toString() === uri.toString()); - if (idx < 0) { - return undefined; - } - for (; idx < this._markers.length; idx++) { - if (range_1.Range.containsPosition(this._markers[idx], position)) { - return new MarkerCoordinate(this._markers[idx], idx + 1, this._markers.length); - } - } - return undefined; - } - static _compareMarker(a, b) { - let res = (0, strings_1.compare)(a.resource.toString(), b.resource.toString()); - if (res === 0) { - res = markers_1.MarkerSeverity.compare(a.severity, b.severity); - } - if (res === 0) { - res = range_1.Range.compareRangesUsingStarts(a, b); - } - return res; - } - }; - MarkerList = __decorate([ - __param(1, markers_1.IMarkerService) - ], MarkerList); - exports.MarkerList = MarkerList; - exports.IMarkerNavigationService = (0, instantiation_1.createDecorator)('IMarkerNavigationService'); - let MarkerNavigationService = class MarkerNavigationService { - constructor(_markerService) { - this._markerService = _markerService; - this._provider = new linkedList_1.LinkedList(); - } - getMarkerList(resource) { - for (let provider of this._provider) { - const result = provider.getMarkerList(resource); - if (result) { - return result; - } - } - // default - return new MarkerList(resource, this._markerService); - } - }; - MarkerNavigationService = __decorate([ - __param(0, markers_1.IMarkerService) - ], MarkerNavigationService); - (0, extensions_1.registerSingleton)(exports.IMarkerNavigationService, MarkerNavigationService, 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[572/*vs/platform/markers/common/markerService*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,46/*vs/base/common/network*/,24/*vs/base/common/uri*/,6/*vs/base/common/event*/,87/*vs/platform/markers/common/markers*/,49/*vs/base/common/map*/,54/*vs/base/common/iterator*/]), function (require, exports, arrays_1, network_1, uri_1, event_1, markers_1, map_1, iterator_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MarkerService = void 0; - class DoubleResourceMap { - constructor() { - this._byResource = new map_1.ResourceMap(); - this._byOwner = new Map(); - } - set(resource, owner, value) { - let ownerMap = this._byResource.get(resource); - if (!ownerMap) { - ownerMap = new Map(); - this._byResource.set(resource, ownerMap); - } - ownerMap.set(owner, value); - let resourceMap = this._byOwner.get(owner); - if (!resourceMap) { - resourceMap = new map_1.ResourceMap(); - this._byOwner.set(owner, resourceMap); - } - resourceMap.set(resource, value); - } - get(resource, owner) { - let ownerMap = this._byResource.get(resource); - return ownerMap === null || ownerMap === void 0 ? void 0 : ownerMap.get(owner); - } - delete(resource, owner) { - let removedA = false; - let removedB = false; - let ownerMap = this._byResource.get(resource); - if (ownerMap) { - removedA = ownerMap.delete(owner); - } - let resourceMap = this._byOwner.get(owner); - if (resourceMap) { - removedB = resourceMap.delete(resource); - } - if (removedA !== removedB) { - throw new Error('illegal state'); - } - return removedA && removedB; - } - values(key) { - var _a, _b, _c, _d; - if (typeof key === 'string') { - return (_b = (_a = this._byOwner.get(key)) === null || _a === void 0 ? void 0 : _a.values()) !== null && _b !== void 0 ? _b : iterator_1.Iterable.empty(); - } - if (uri_1.URI.isUri(key)) { - return (_d = (_c = this._byResource.get(key)) === null || _c === void 0 ? void 0 : _c.values()) !== null && _d !== void 0 ? _d : iterator_1.Iterable.empty(); - } - return iterator_1.Iterable.map(iterator_1.Iterable.concat(...this._byOwner.values()), map => map[1]); - } - } - class MarkerStats { - constructor(service) { - this.errors = 0; - this.infos = 0; - this.warnings = 0; - this.unknowns = 0; - this._data = new map_1.ResourceMap(); - this._service = service; - this._subscription = service.onMarkerChanged(this._update, this); - } - dispose() { - this._subscription.dispose(); - } - _update(resources) { - for (const resource of resources) { - const oldStats = this._data.get(resource); - if (oldStats) { - this._substract(oldStats); - } - const newStats = this._resourceStats(resource); - this._add(newStats); - this._data.set(resource, newStats); - } - } - _resourceStats(resource) { - const 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 (const { severity } of this._service.read({ resource })) { - 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; - } - _substract(op) { - this.errors -= op.errors; - this.warnings -= op.warnings; - this.infos -= op.infos; - this.unknowns -= op.unknowns; - } - _add(op) { - this.errors += op.errors; - this.warnings += op.warnings; - this.infos += op.infos; - this.unknowns += op.unknowns; - } - } - class MarkerService { - constructor() { - this._onMarkerChanged = new event_1.DebounceEmitter({ - delay: 0, - merge: MarkerService._merge - }); - this.onMarkerChanged = this._onMarkerChanged.event; - this._data = new DoubleResourceMap(); - this._stats = new MarkerStats(this); - } - dispose() { - this._stats.dispose(); - this._onMarkerChanged.dispose(); - } - remove(owner, resources) { - for (const resource of resources || []) { - this.changeOne(owner, resource, []); - } - } - changeOne(owner, resource, markerData) { - if ((0, arrays_1.isFalsyOrEmpty)(markerData)) { - // remove marker for this (owner,resource)-tuple - const removed = this._data.delete(resource, owner); - if (removed) { - this._onMarkerChanged.fire([resource]); - } - } - else { - // insert marker for this (owner,resource)-tuple - const markers = []; - for (const data of markerData) { - const marker = MarkerService._toMarker(owner, resource, data); - if (marker) { - markers.push(marker); - } - } - this._data.set(resource, owner, markers); - this._onMarkerChanged.fire([resource]); - } - } - static _toMarker(owner, resource, data) { - let { code, severity, message, source, startLineNumber, startColumn, endLineNumber, endColumn, relatedInformation, tags, } = data; - 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, - owner, - code, - severity, - message, - source, - startLineNumber, - startColumn, - endLineNumber, - endColumn, - relatedInformation, - tags, - }; - } - read(filter = Object.create(null)) { - let { owner, resource, severities, take } = filter; - if (!take || take < 0) { - take = -1; - } - if (owner && resource) { - // exactly one owner AND resource - const data = this._data.get(resource, owner); - if (!data) { - return []; - } - else { - const result = []; - for (const marker of data) { - if (MarkerService._accept(marker, severities)) { - const newLen = result.push(marker); - if (take > 0 && newLen === take) { - break; - } - } - } - return result; - } - } - else if (!owner && !resource) { - // all - const result = []; - for (let markers of this._data.values()) { - for (let data of markers) { - if (MarkerService._accept(data, severities)) { - const newLen = result.push(data); - if (take > 0 && newLen === take) { - return result; - } - } - } - } - return result; - } - else { - // of one resource OR owner - const iterable = this._data.values(resource !== null && resource !== void 0 ? resource : owner); - const result = []; - for (const markers of iterable) { - for (const data of markers) { - if (MarkerService._accept(data, severities)) { - const newLen = result.push(data); - if (take > 0 && newLen === take) { - return result; - } - } - } - } - return result; - } - } - static _accept(marker, severities) { - return severities === undefined || (severities & marker.severity) === marker.severity; - } - // --- event debounce logic - static _merge(all) { - const set = new map_1.ResourceMap(); - for (let array of all) { - for (let item of array) { - set.set(item, true); - } - } - return Array.from(set.keys()); - } - } - 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[34/*vs/platform/notification/common/notification*/], __M([0/*require*/,1/*exports*/,74/*vs/base/common/severity*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, severity_1, instantiation_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.NoOpNotification = exports.INotificationService = exports.Severity = void 0; - exports.Severity = severity_1.default; - exports.INotificationService = (0, instantiation_1.createDecorator)('notificationService'); - class 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[58/*vs/platform/opener/common/opener*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,8/*vs/base/common/strings*/,24/*vs/base/common/uri*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, lifecycle_1, strings_1, uri_1, instantiation_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.matchesScheme = exports.NullOpenerService = exports.IOpenerService = void 0; - exports.IOpenerService = (0, instantiation_1.createDecorator)('openerService'); - exports.NullOpenerService = Object.freeze({ - _serviceBrand: undefined, - registerOpener() { return lifecycle_1.Disposable.None; }, - registerValidator() { return lifecycle_1.Disposable.None; }, - registerExternalUriResolver() { return lifecycle_1.Disposable.None; }, - setDefaultExternalOpener() { }, - registerExternalOpener() { return lifecycle_1.Disposable.None; }, - open() { - return __awaiter(this, void 0, void 0, function* () { return false; }); - }, - resolveExternalUri(uri) { - return __awaiter(this, void 0, void 0, function* () { return { resolved: uri, dispose() { } }; }); - }, - }); - function matchesScheme(target, scheme) { - if (uri_1.URI.isUri(target)) { - return (0, strings_1.equalsIgnoreCase)(target.scheme, scheme); - } - else { - return (0, 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. - *--------------------------------------------------------------------------------------------*/ - - - - - - - - - - - - - - - - - - -define(__m[145/*vs/editor/browser/core/markdownRenderer*/], __M([0/*require*/,1/*exports*/,298/*vs/base/browser/markdownRenderer*/,58/*vs/platform/opener/common/opener*/,57/*vs/editor/common/services/modeService*/,12/*vs/base/common/errors*/,246/*vs/editor/common/modes/textToHtmlTokenizer*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,18/*vs/editor/common/modes*/]), function (require, exports, markdownRenderer_1, opener_1, modeService_1, errors_1, textToHtmlTokenizer_1, event_1, lifecycle_1, modes_1) { - "use strict"; - var _a; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MarkdownRenderer = void 0; - /** - * Markdown renderer that can render codeblocks with the editor mechanics. This - * renderer should always be preferred. - */ - let MarkdownRenderer = class MarkdownRenderer { - constructor(_options, _modeService, _openerService) { - this._options = _options; - this._modeService = _modeService; - this._openerService = _openerService; - this._onDidRenderAsync = new event_1.Emitter(); - this.onDidRenderAsync = this._onDidRenderAsync.event; - } - dispose() { - this._onDidRenderAsync.dispose(); - } - render(markdown, options, markedOptions) { - const disposables = new lifecycle_1.DisposableStore(); - let element; - if (!markdown) { - element = document.createElement('span'); - } - else { - element = (0, markdownRenderer_1.renderMarkdown)(markdown, Object.assign(Object.assign({}, this._getRenderOptions(markdown, disposables)), options), markedOptions); - } - return { - element, - dispose: () => disposables.dispose() - }; - } - _getRenderOptions(markdown, disposeables) { - return { - baseUrl: this._options.baseUrl, - codeBlockRenderer: (languageAlias, value) => __awaiter(this, void 0, void 0, function* () { - var _a, _b, _c, _d; - // 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 - let modeId; - if (languageAlias) { - modeId = this._modeService.getModeIdForLanguageName(languageAlias); - } - else if (this._options.editor) { - modeId = (_a = this._options.editor.getModel()) === null || _a === void 0 ? void 0 : _a.getLanguageIdentifier().language; - } - if (!modeId) { - modeId = 'plaintext'; - } - this._modeService.triggerMode(modeId); - const tokenization = (_b = yield modes_1.TokenizationRegistry.getPromise(modeId)) !== null && _b !== void 0 ? _b : undefined; - const element = document.createElement('span'); - element.innerHTML = ((_d = (_c = MarkdownRenderer._ttpTokenizer) === null || _c === void 0 ? void 0 : _c.createHTML(value, tokenization)) !== null && _d !== void 0 ? _d : (0, textToHtmlTokenizer_1.tokenizeToString)(value, tokenization)); - // use "good" font - let fontFamily = this._options.codeBlockFontFamily; - if (this._options.editor) { - fontFamily = this._options.editor.getOption(41 /* fontInfo */).fontFamily; - } - if (fontFamily) { - element.style.fontFamily = fontFamily; - } - return element; - }), - asyncRenderCallback: () => this._onDidRenderAsync.fire(), - actionHandler: { - callback: (content) => this._openerService.open(content, { fromUserGesture: true, allowContributedOpeners: true, allowCommands: markdown.isTrusted }).catch(errors_1.onUnexpectedError), - disposeables - } - }; - } - }; - MarkdownRenderer._ttpTokenizer = (_a = window.trustedTypes) === null || _a === void 0 ? void 0 : _a.createPolicy('tokenizeToString', { - createHTML(value, tokenizer) { - return (0, textToHtmlTokenizer_1.tokenizeToString)(value, tokenizer); - } - }); - MarkdownRenderer = __decorate([ - __param(1, modeService_1.IModeService), - __param(2, opener_1.IOpenerService) - ], MarkdownRenderer); - 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[573/*vs/editor/browser/services/openerService*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,23/*vs/base/common/cancellation*/,72/*vs/base/common/linkedList*/,49/*vs/base/common/map*/,202/*vs/base/common/marshalling*/,46/*vs/base/common/network*/,43/*vs/base/common/resources*/,24/*vs/base/common/uri*/,28/*vs/editor/browser/services/codeEditorService*/,26/*vs/platform/commands/common/commands*/,545/*vs/platform/editor/common/editor*/,58/*vs/platform/opener/common/opener*/]), function (require, exports, dom, cancellation_1, linkedList_1, map_1, marshalling_1, network_1, resources_1, uri_1, codeEditorService_1, commands_1, editor_1, opener_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.OpenerService = void 0; - let CommandOpener = class CommandOpener { - constructor(_commandService) { - this._commandService = _commandService; - } - open(target, options) { - return __awaiter(this, void 0, void 0, function* () { - if (!(0, opener_1.matchesScheme)(target, network_1.Schemas.command)) { - return false; - } - if (!(options === null || options === void 0 ? void 0 : options.allowCommands)) { - // silently ignore commands when command-links are disabled, also - // surpress other openers by returning TRUE - return true; - } - // run command or bail out if command isn't known - if (typeof target === 'string') { - target = uri_1.URI.parse(target); - } - // execute as command - let args = []; - try { - args = (0, marshalling_1.parse)(decodeURIComponent(target.query)); - } - catch (_a) { - // ignore and retry - try { - args = (0, marshalling_1.parse)(target.query); - } - catch (_b) { - // ignore error - } - } - if (!Array.isArray(args)) { - args = [args]; - } - yield this._commandService.executeCommand(target.path, ...args); - return true; - }); - } - }; - CommandOpener = __decorate([ - __param(0, commands_1.ICommandService) - ], CommandOpener); - let EditorOpener = class EditorOpener { - constructor(_editorService) { - this._editorService = _editorService; - } - open(target, options) { - return __awaiter(this, void 0, void 0, function* () { - if (typeof target === 'string') { - target = uri_1.URI.parse(target); - } - let selection = undefined; - const 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 = (0, resources_1.normalizePath)(target); // workaround for non-normalized paths (https://github.com/microsoft/vscode/issues/12954) - } - yield this._editorService.openCodeEditor({ - resource: target, - options: Object.assign({ selection, context: (options === null || options === void 0 ? void 0 : options.fromUserGesture) ? editor_1.EditorOpenContext.USER : editor_1.EditorOpenContext.API }, options === null || options === void 0 ? void 0 : options.editorOptions) - }, this._editorService.getFocusedCodeEditor(), options === null || options === void 0 ? void 0 : options.openToSide); - return true; - }); - } - }; - EditorOpener = __decorate([ - __param(0, codeEditorService_1.ICodeEditorService) - ], EditorOpener); - let OpenerService = class OpenerService { - constructor(editorService, commandService) { - this._openers = new linkedList_1.LinkedList(); - this._validators = new linkedList_1.LinkedList(); - this._resolvers = new linkedList_1.LinkedList(); - this._resolvedUriTargets = new map_1.ResourceMap(uri => uri.with({ path: null, fragment: null, query: null }).toString()); - this._externalOpeners = new linkedList_1.LinkedList(); - // Default external opener is going through window.open() - this._defaultExternalOpener = { - openExternal: (href) => __awaiter(this, void 0, void 0, function* () { - // ensure to open HTTP/HTTPS links into new windows - // to not trigger a navigation. Any other link is - // safe to be set as HREF to prevent a blank window - // from opening. - if ((0, opener_1.matchesScheme)(href, network_1.Schemas.http) || (0, opener_1.matchesScheme)(href, network_1.Schemas.https)) { - dom.windowOpenNoOpener(href); - } - else { - window.location.href = href; - } - return true; - }) - }; - // Default opener: any external, maito, http(s), command, and catch-all-editors - this._openers.push({ - open: (target, options) => __awaiter(this, void 0, void 0, function* () { - if ((options === null || options === void 0 ? void 0 : options.openExternal) || (0, opener_1.matchesScheme)(target, network_1.Schemas.mailto) || (0, opener_1.matchesScheme)(target, network_1.Schemas.http) || (0, opener_1.matchesScheme)(target, network_1.Schemas.https)) { - // open externally - yield this._doOpenExternal(target, options); - return true; - } - return false; - }) - }); - this._openers.push(new CommandOpener(commandService)); - this._openers.push(new EditorOpener(editorService)); - } - registerOpener(opener) { - const remove = this._openers.unshift(opener); - return { dispose: remove }; - } - registerValidator(validator) { - const remove = this._validators.push(validator); - return { dispose: remove }; - } - registerExternalUriResolver(resolver) { - const remove = this._resolvers.push(resolver); - return { dispose: remove }; - } - setDefaultExternalOpener(externalOpener) { - this._defaultExternalOpener = externalOpener; - } - registerExternalOpener(opener) { - const remove = this._externalOpeners.push(opener); - return { dispose: remove }; - } - open(target, options) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - // check with contributed validators - const targetURI = typeof target === 'string' ? uri_1.URI.parse(target) : target; - // validate against the original URI that this URI resolves to, if one exists - const validationTarget = (_a = this._resolvedUriTargets.get(targetURI)) !== null && _a !== void 0 ? _a : target; - for (const validator of this._validators) { - if (!(yield validator.shouldOpen(validationTarget))) { - return false; - } - } - // check with contributed openers - for (const opener of this._openers) { - const handled = yield opener.open(target, options); - if (handled) { - return true; - } - } - return false; - }); - } - resolveExternalUri(resource, options) { - return __awaiter(this, void 0, void 0, function* () { - for (const resolver of this._resolvers) { - try { - const result = yield resolver.resolveExternalUri(resource, options); - if (result) { - if (!this._resolvedUriTargets.has(result.resolved)) { - this._resolvedUriTargets.set(result.resolved, resource); - } - return result; - } - } - catch (_a) { - // noop - } - } - throw new Error('Could not resolve external URI: ' + resource.toString()); - }); - } - _doOpenExternal(resource, options) { - return __awaiter(this, void 0, void 0, function* () { - //todo@jrieken IExternalUriResolver should support `uri: URI | string` - const uri = typeof resource === 'string' ? uri_1.URI.parse(resource) : resource; - let externalUri; - try { - externalUri = (yield this.resolveExternalUri(uri, options)).resolved; - } - catch (_a) { - externalUri = uri; - } - let href; - if (typeof resource === 'string' && uri.toString() === externalUri.toString()) { - // open the url-string AS IS - href = resource; - } - else { - // open URI using the toString(noEncode)+encodeURI-trick - href = encodeURI(externalUri.toString(true)); - } - if (options === null || options === void 0 ? void 0 : options.allowContributedOpeners) { - const preferredOpenerId = typeof (options === null || options === void 0 ? void 0 : options.allowContributedOpeners) === 'string' ? options === null || options === void 0 ? void 0 : options.allowContributedOpeners : undefined; - for (const opener of this._externalOpeners) { - const didOpen = yield opener.openExternal(href, { - sourceUri: uri, - preferredOpenerId, - }, cancellation_1.CancellationToken.None); - if (didOpen) { - return true; - } - } - } - return this._defaultExternalOpener.openExternal(href, { sourceUri: uri }, cancellation_1.CancellationToken.None); - }); - } - dispose() { - this._validators.clear(); - } - }; - OpenerService = __decorate([ - __param(0, codeEditorService_1.ICodeEditorService), - __param(1, commands_1.ICommandService) - ], 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[574/*vs/editor/contrib/hover/modesGlyphHover*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,82/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,230/*vs/editor/contrib/hover/hoverOperation*/,416/*vs/editor/contrib/hover/hoverWidgets*/,145/*vs/editor/browser/core/markdownRenderer*/,58/*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 }); - exports.ModesGlyphHoverWidget = void 0; - class MarginComputer { - constructor(editor) { - this._editor = editor; - this._lineNumber = -1; - this._result = []; - } - setLineNumber(lineNumber) { - this._lineNumber = lineNumber; - this._result = []; - } - clearResult() { - this._result = []; - } - computeSync() { - const toHoverMessage = (contents) => { - return { - value: contents - }; - }; - const lineDecorations = this._editor.getLineDecorations(this._lineNumber); - const result = []; - if (!lineDecorations) { - return result; - } - for (const d of lineDecorations) { - if (!d.options.glyphMarginClassName) { - continue; - } - const hoverMessage = d.options.glyphMarginHoverMessage; - if (!hoverMessage || (0, htmlContent_1.isEmptyMarkdownString)(hoverMessage)) { - continue; - } - result.push(...(0, arrays_1.asArray)(hoverMessage).map(toHoverMessage)); - } - return result; - } - onResult(result, isFromSynchronousComputation) { - this._result = this._result.concat(result); - } - getResult() { - return this._result; - } - getResultWithLoadingMessage() { - return this.getResult(); - } - } - class ModesGlyphHoverWidget extends hoverWidgets_1.GlyphHoverWidget { - constructor(editor, modeService, openerService = opener_1.NullOpenerService) { - super(ModesGlyphHoverWidget.ID, editor); - this._renderDisposeables = this._register(new lifecycle_1.DisposableStore()); - this._messages = []; - this._lastLineNumber = -1; - this._markdownRenderer = this._register(new markdownRenderer_1.MarkdownRenderer({ editor: this._editor }, modeService, openerService)); - this._computer = new MarginComputer(this._editor); - this._hoverOperation = new hoverOperation_1.HoverOperation(this._computer, (result) => this._withResult(result), undefined, (result) => this._withResult(result), 300); - } - dispose() { - this._hoverOperation.cancel(); - super.dispose(); - } - onModelDecorationsChanged() { - 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 */); - } - } - startShowingAt(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 */); - } - hide() { - this._lastLineNumber = -1; - this._hoverOperation.cancel(); - super.hide(); - } - _withResult(result) { - this._messages = result; - if (this._messages.length > 0) { - this._renderMessages(this._lastLineNumber, this._messages); - } - else { - this.hide(); - } - } - _renderMessages(lineNumber, messages) { - this._renderDisposeables.clear(); - const fragment = document.createDocumentFragment(); - for (const msg of messages) { - const renderedContents = this._markdownRenderer.render(msg.value); - this._renderDisposeables.add(renderedContents); - fragment.appendChild((0, dom_1.$)('div.hover-row', undefined, renderedContents.element)); - } - this.updateContents(fragment); - this.showAt(lineNumber); - } - } - exports.ModesGlyphHoverWidget = ModesGlyphHoverWidget; - ModesGlyphHoverWidget.ID = 'editor.contrib.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[257/*vs/editor/contrib/suggest/suggestWidgetDetails*/], __M([0/*require*/,1/*exports*/,523/*vs/nls!vs/editor/contrib/suggest/suggestWidgetDetails*/,2/*vs/base/common/lifecycle*/,7/*vs/base/browser/dom*/,61/*vs/base/browser/ui/scrollbar/scrollableElement*/,145/*vs/editor/browser/core/markdownRenderer*/,82/*vs/base/common/htmlContent*/,27/*vs/base/common/codicons*/,6/*vs/base/common/event*/,235/*vs/editor/contrib/suggest/resizable*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, nls, lifecycle_1, dom, scrollableElement_1, markdownRenderer_1, htmlContent_1, codicons_1, event_1, resizable_1, instantiation_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.SuggestDetailsOverlay = exports.SuggestDetailsWidget = exports.canExpandCompletionItem = void 0; - function canExpandCompletionItem(item) { - return !!item && Boolean(item.completion.documentation || item.completion.detail && item.completion.detail !== item.completion.label); - } - exports.canExpandCompletionItem = canExpandCompletionItem; - let SuggestDetailsWidget = class SuggestDetailsWidget { - constructor(_editor, instaService) { - this._editor = _editor; - this._onDidClose = new event_1.Emitter(); - this.onDidClose = this._onDidClose.event; - this._onDidChangeContents = new event_1.Emitter(); - this.onDidChangeContents = this._onDidChangeContents.event; - this._disposables = new lifecycle_1.DisposableStore(); - this._renderDisposeable = new lifecycle_1.DisposableStore(); - this._borderWidth = 1; - this._size = new dom.Dimension(330, 0); - this.domNode = dom.$('.suggest-details'); - this.domNode.classList.add('no-docs'); - this._markdownRenderer = instaService.createInstance(markdownRenderer_1.MarkdownRenderer, { editor: _editor }); - this._body = dom.$('.body'); - this._scrollbar = new scrollableElement_1.DomScrollableElement(this._body, {}); - dom.append(this.domNode, this._scrollbar.getDomNode()); - this._disposables.add(this._scrollbar); - this._header = dom.append(this._body, dom.$('.header')); - this._close = dom.append(this._header, dom.$('span' + codicons_1.Codicon.close.cssSelector)); - this._close.title = nls.localize(0, null); - this._type = dom.append(this._header, dom.$('p.type')); - this._docs = dom.append(this._body, dom.$('p.docs')); - this._configureFont(); - this._disposables.add(this._editor.onDidChangeConfiguration(e => { - if (e.hasChanged(41 /* fontInfo */)) { - this._configureFont(); - } - })); - } - dispose() { - this._disposables.dispose(); - this._renderDisposeable.dispose(); - } - _configureFont() { - const options = this._editor.getOptions(); - const fontInfo = options.get(41 /* fontInfo */); - const fontFamily = fontInfo.fontFamily; - const fontSize = options.get(106 /* suggestFontSize */) || fontInfo.fontSize; - const lineHeight = options.get(107 /* suggestLineHeight */) || fontInfo.lineHeight; - const fontWeight = fontInfo.fontWeight; - const fontSizePx = `${fontSize}px`; - const lineHeightPx = `${lineHeight}px`; - this.domNode.style.fontSize = fontSizePx; - this.domNode.style.lineHeight = lineHeightPx; - this.domNode.style.fontWeight = fontWeight; - this.domNode.style.fontFeatureSettings = fontInfo.fontFeatureSettings; - this._type.style.fontFamily = fontFamily; - this._close.style.height = lineHeightPx; - this._close.style.width = lineHeightPx; - } - getLayoutInfo() { - const lineHeight = this._editor.getOption(107 /* suggestLineHeight */) || this._editor.getOption(41 /* fontInfo */).lineHeight; - const borderWidth = this._borderWidth; - const borderHeight = borderWidth * 2; - return { - lineHeight, - borderWidth, - borderHeight, - verticalPadding: 22, - horizontalPadding: 14 - }; - } - renderLoading() { - this._type.textContent = nls.localize(1, null); - this._docs.textContent = ''; - this.domNode.classList.remove('no-docs', 'no-type'); - this.layout(this.size.width, this.getLayoutInfo().lineHeight * 2); - this._onDidChangeContents.fire(this); - } - renderItem(item, explainMode) { - var _a, _b; - this._renderDisposeable.clear(); - let { detail, documentation } = item.completion; - if (explainMode) { - let md = ''; - md += `score: ${item.score[0]}\n`; - md += `prefix: ${(_a = item.word) !== null && _a !== void 0 ? _a : '(no prefix)'}\n`; - md += `word: ${item.completion.filterText ? item.completion.filterText + ' (filterText)' : item.textLabel}\n`; - md += `distance: ${item.distance} (localityBonus-setting)\n`; - md += `index: ${item.idx}, based on ${item.completion.sortText && `sortText: "${item.completion.sortText}"` || 'label'}\n`; - md += `commit_chars: ${(_b = item.completion.commitCharacters) === null || _b === void 0 ? void 0 : _b.join('')}\n`; - documentation = new htmlContent_1.MarkdownString().appendCodeblock('empty', md); - detail = `Provider: ${item.provider._debugDisplayName}`; - } - if (!explainMode && !canExpandCompletionItem(item)) { - this.clearContents(); - return; - } - this.domNode.classList.remove('no-docs', 'no-type'); - // --- details - if (detail) { - const cappedDetail = detail.length > 100000 ? `${detail.substr(0, 100000)}…` : detail; - this._type.textContent = cappedDetail; - this._type.title = cappedDetail; - dom.show(this._type); - this._type.classList.toggle('auto-wrap', !/\r?\n^\s+/gmi.test(cappedDetail)); - } - else { - dom.clearNode(this._type); - this._type.title = ''; - dom.hide(this._type); - this.domNode.classList.add('no-type'); - } - // --- documentation - dom.clearNode(this._docs); - if (typeof documentation === 'string') { - this._docs.classList.remove('markdown-docs'); - this._docs.textContent = documentation; - } - else if (documentation) { - this._docs.classList.add('markdown-docs'); - dom.clearNode(this._docs); - const renderedContents = this._markdownRenderer.render(documentation); - this._docs.appendChild(renderedContents.element); - this._renderDisposeable.add(renderedContents); - this._renderDisposeable.add(this._markdownRenderer.onDidRenderAsync(() => { - this.layout(this._size.width, this._type.clientHeight + this._docs.clientHeight); - this._onDidChangeContents.fire(this); - })); - } - this.domNode.style.userSelect = 'text'; - this.domNode.tabIndex = -1; - this._close.onmousedown = e => { - e.preventDefault(); - e.stopPropagation(); - }; - this._close.onclick = e => { - e.preventDefault(); - e.stopPropagation(); - this._onDidClose.fire(); - }; - this._body.scrollTop = 0; - this.layout(this._size.width, this._type.clientHeight + this._docs.clientHeight); - this._onDidChangeContents.fire(this); - } - clearContents() { - this.domNode.classList.add('no-docs'); - this._type.textContent = ''; - this._docs.textContent = ''; - } - get size() { - return this._size; - } - layout(width, height) { - const newSize = new dom.Dimension(width, height); - if (!dom.Dimension.equals(newSize, this._size)) { - this._size = newSize; - dom.size(this.domNode, width, height); - } - this._scrollbar.scanDomNode(); - } - scrollDown(much = 8) { - this._body.scrollTop += much; - } - scrollUp(much = 8) { - this._body.scrollTop -= much; - } - scrollTop() { - this._body.scrollTop = 0; - } - scrollBottom() { - this._body.scrollTop = this._body.scrollHeight; - } - pageDown() { - this.scrollDown(80); - } - pageUp() { - this.scrollUp(80); - } - set borderWidth(width) { - this._borderWidth = width; - } - get borderWidth() { - return this._borderWidth; - } - }; - SuggestDetailsWidget = __decorate([ - __param(1, instantiation_1.IInstantiationService) - ], SuggestDetailsWidget); - exports.SuggestDetailsWidget = SuggestDetailsWidget; - class SuggestDetailsOverlay { - constructor(widget, _editor) { - this.widget = widget; - this._editor = _editor; - this._disposables = new lifecycle_1.DisposableStore(); - this._added = false; - this._resizable = new resizable_1.ResizableHTMLElement(); - this._resizable.domNode.classList.add('suggest-details-container'); - this._resizable.domNode.appendChild(widget.domNode); - this._resizable.enableSashes(false, true, true, false); - let topLeftNow; - let sizeNow; - let deltaTop = 0; - let deltaLeft = 0; - this._disposables.add(this._resizable.onDidWillResize(() => { - topLeftNow = this._topLeft; - sizeNow = this._resizable.size; - })); - this._disposables.add(this._resizable.onDidResize(e => { - if (topLeftNow && sizeNow) { - this.widget.layout(e.dimension.width, e.dimension.height); - let updateTopLeft = false; - if (e.west) { - deltaLeft = sizeNow.width - e.dimension.width; - updateTopLeft = true; - } - if (e.north) { - deltaTop = sizeNow.height - e.dimension.height; - updateTopLeft = true; - } - if (updateTopLeft) { - this._applyTopLeft({ - top: topLeftNow.top + deltaTop, - left: topLeftNow.left + deltaLeft, - }); - } - } - if (e.done) { - topLeftNow = undefined; - sizeNow = undefined; - deltaTop = 0; - deltaLeft = 0; - this._userSize = e.dimension; - } - })); - this._disposables.add(this.widget.onDidChangeContents(() => { - var _a; - if (this._anchorBox) { - this._placeAtAnchor(this._anchorBox, (_a = this._userSize) !== null && _a !== void 0 ? _a : this.widget.size); - } - })); - } - dispose() { - this._resizable.dispose(); - this._disposables.dispose(); - this.hide(); - } - getId() { - return 'suggest.details'; - } - getDomNode() { - return this._resizable.domNode; - } - getPosition() { - return null; - } - show() { - if (!this._added) { - this._editor.addOverlayWidget(this); - this.getDomNode().style.position = 'fixed'; - this._added = true; - } - } - hide(sessionEnded = false) { - this._resizable.clearSashHoverState(); - if (this._added) { - this._editor.removeOverlayWidget(this); - this._added = false; - this._anchorBox = undefined; - this._topLeft = undefined; - } - if (sessionEnded) { - this._userSize = undefined; - this.widget.clearContents(); - } - } - placeAtAnchor(anchor) { - var _a; - const anchorBox = dom.getDomNodePagePosition(anchor); - this._anchorBox = anchorBox; - this._placeAtAnchor(this._anchorBox, (_a = this._userSize) !== null && _a !== void 0 ? _a : this.widget.size); - } - _placeAtAnchor(anchorBox, size) { - const bodyBox = dom.getClientArea(document.body); - const info = this.widget.getLayoutInfo(); - let maxSizeTop; - let maxSizeBottom; - let minSize = new dom.Dimension(220, 2 * info.lineHeight); - let left = 0; - let top = anchorBox.top; - let bottom = anchorBox.top + anchorBox.height - info.borderHeight; - let alignAtTop; - let alignEast; - // position: EAST, west, south - let width = bodyBox.width - (anchorBox.left + anchorBox.width + info.borderWidth + info.horizontalPadding); - left = -info.borderWidth + anchorBox.left + anchorBox.width; - alignEast = true; - maxSizeTop = new dom.Dimension(width, bodyBox.height - anchorBox.top - info.borderHeight - info.verticalPadding); - maxSizeBottom = maxSizeTop.with(undefined, anchorBox.top + anchorBox.height - info.borderHeight - info.verticalPadding); - // find a better place if the widget is wider than there is space available - if (size.width > width) { - // position: east, WEST, south - if (anchorBox.left > width) { - // pos = SuggestDetailsPosition.West; - width = anchorBox.left - info.borderWidth - info.horizontalPadding; - alignEast = false; - left = Math.max(info.horizontalPadding, anchorBox.left - size.width - info.borderWidth); - maxSizeTop = maxSizeTop.with(width); - maxSizeBottom = maxSizeTop.with(undefined, maxSizeBottom.height); - } - // position: east, west, SOUTH - if (anchorBox.width > width * 1.3 && bodyBox.height - (anchorBox.top + anchorBox.height) > anchorBox.height) { - width = anchorBox.width; - left = anchorBox.left; - top = -info.borderWidth + anchorBox.top + anchorBox.height; - maxSizeTop = new dom.Dimension(anchorBox.width - info.borderHeight, bodyBox.height - anchorBox.top - anchorBox.height - info.verticalPadding); - maxSizeBottom = maxSizeTop.with(undefined, anchorBox.top - info.verticalPadding); - minSize = minSize.with(maxSizeTop.width); - } - } - // top/bottom placement - let height = size.height; - let maxHeight = Math.max(maxSizeTop.height, maxSizeBottom.height); - if (height > maxHeight) { - height = maxHeight; - } - let maxSize; - if (height <= maxSizeTop.height) { - alignAtTop = true; - maxSize = maxSizeTop; - } - else { - alignAtTop = false; - maxSize = maxSizeBottom; - } - this._applyTopLeft({ left, top: alignAtTop ? top : bottom - height }); - this.getDomNode().style.position = 'fixed'; - this._resizable.enableSashes(!alignAtTop, alignEast, alignAtTop, !alignEast); - this._resizable.minSize = minSize; - this._resizable.maxSize = maxSize; - this._resizable.layout(height, Math.min(maxSize.width, size.width)); - this.widget.layout(this._resizable.size.width, this._resizable.size.height); - } - _applyTopLeft(topLeft) { - this._topLeft = topLeft; - this.getDomNode().style.left = `${this._topLeft.left}px`; - this.getDomNode().style.top = `${this._topLeft.top}px`; - } - } - exports.SuggestDetailsOverlay = SuggestDetailsOverlay; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/platform/progress/common/progress*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.IEditorProgressService = exports.Progress = void 0; - class Progress { - constructor(callback) { - this.callback = callback; - } - report(item) { - this._value = item; - this.callback(this._value); - } - } - exports.Progress = Progress; - Progress.None = Object.freeze({ report() { } }); - exports.IEditorProgressService = (0, 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[575/*vs/platform/quickinput/browser/pickerQuickAccess*/], __M([0/*require*/,1/*exports*/,23/*vs/base/common/cancellation*/,2/*vs/base/common/lifecycle*/,15/*vs/base/common/async*/]), function (require, exports, cancellation_1, lifecycle_1, async_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.PickerQuickAccessProvider = exports.TriggerAction = void 0; - var TriggerAction; - (function (TriggerAction) { - /** - * Do nothing after the button was clicked. - */ - TriggerAction[TriggerAction["NO_ACTION"] = 0] = "NO_ACTION"; - /** - * Close the picker. - */ - TriggerAction[TriggerAction["CLOSE_PICKER"] = 1] = "CLOSE_PICKER"; - /** - * Update the results of the picker. - */ - TriggerAction[TriggerAction["REFRESH_PICKER"] = 2] = "REFRESH_PICKER"; - /** - * Remove the item from the picker. - */ - TriggerAction[TriggerAction["REMOVE_ITEM"] = 3] = "REMOVE_ITEM"; - })(TriggerAction = exports.TriggerAction || (exports.TriggerAction = {})); - function isPicksWithActive(obj) { - const candidate = obj; - return Array.isArray(candidate.items); - } - function isFastAndSlowPicks(obj) { - const candidate = obj; - return !!candidate.picks && candidate.additionalPicks instanceof Promise; - } - class PickerQuickAccessProvider extends lifecycle_1.Disposable { - constructor(prefix, options) { - super(); - this.prefix = prefix; - this.options = options; - } - provide(picker, token) { - var _a; - const disposables = new lifecycle_1.DisposableStore(); - // Apply options if any - picker.canAcceptInBackground = !!((_a = this.options) === null || _a === void 0 ? void 0 : _a.canAcceptInBackground); - // Disable filtering & sorting, we control the results - picker.matchOnLabel = picker.matchOnDescription = picker.matchOnDetail = picker.sortByLabel = false; - // Set initial picks and update on type - let picksCts = undefined; - const picksDisposable = disposables.add(new lifecycle_1.MutableDisposable()); - const updatePickerItems = () => __awaiter(this, void 0, void 0, function* () { - const picksDisposables = picksDisposable.value = new lifecycle_1.DisposableStore(); - // Cancel any previous ask for picks and busy - picksCts === null || picksCts === void 0 ? void 0 : picksCts.dispose(true); - picker.busy = false; - // Create new cancellation source for this run - picksCts = new cancellation_1.CancellationTokenSource(token); - // Collect picks and support both long running and short or combined - const picksToken = picksCts.token; - const picksFilter = picker.value.substr(this.prefix.length).trim(); - const providedPicks = this._getPicks(picksFilter, picksDisposables, picksToken); - const applyPicks = (picks, skipEmpty) => { - var _a; - let items; - let activeItem = undefined; - if (isPicksWithActive(picks)) { - items = picks.items; - activeItem = picks.active; - } - else { - items = picks; - } - if (items.length === 0) { - if (skipEmpty) { - return false; - } - if (picksFilter.length > 0 && ((_a = this.options) === null || _a === void 0 ? void 0 : _a.noResultsPick)) { - items = [this.options.noResultsPick]; - } - } - picker.items = items; - if (activeItem) { - picker.activeItems = [activeItem]; - } - return true; - }; - // No Picks - if (providedPicks === null) { - // Ignore - } - // Fast and Slow Picks - else if (isFastAndSlowPicks(providedPicks)) { - let fastPicksApplied = false; - let slowPicksApplied = false; - yield Promise.all([ - // Fast Picks: to reduce amount of flicker, we race against - // the slow picks over 500ms and then set the fast picks. - // If the slow picks are faster, we reduce the flicker by - // only setting the items once. - (() => __awaiter(this, void 0, void 0, function* () { - yield (0, async_1.timeout)(PickerQuickAccessProvider.FAST_PICKS_RACE_DELAY); - if (picksToken.isCancellationRequested) { - return; - } - if (!slowPicksApplied) { - fastPicksApplied = applyPicks(providedPicks.picks, true /* skip over empty to reduce flicker */); - } - }))(), - // Slow Picks: we await the slow picks and then set them at - // once together with the fast picks, but only if we actually - // have additional results. - (() => __awaiter(this, void 0, void 0, function* () { - picker.busy = true; - try { - const awaitedAdditionalPicks = yield providedPicks.additionalPicks; - if (picksToken.isCancellationRequested) { - return; - } - let picks; - let activePick = undefined; - if (isPicksWithActive(providedPicks.picks)) { - picks = providedPicks.picks.items; - activePick = providedPicks.picks.active; - } - else { - picks = providedPicks.picks; - } - let additionalPicks; - let additionalActivePick = undefined; - if (isPicksWithActive(awaitedAdditionalPicks)) { - additionalPicks = awaitedAdditionalPicks.items; - additionalActivePick = awaitedAdditionalPicks.active; - } - else { - additionalPicks = awaitedAdditionalPicks; - } - if (additionalPicks.length > 0 || !fastPicksApplied) { - // If we do not have any activePick or additionalActivePick - // we try to preserve the currently active pick from the - // fast results. This fixes an issue where the user might - // have made a pick active before the additional results - // kick in. - // See https://github.com/microsoft/vscode/issues/102480 - let fallbackActivePick = undefined; - if (!activePick && !additionalActivePick) { - const fallbackActivePickCandidate = picker.activeItems[0]; - if (fallbackActivePickCandidate && picks.indexOf(fallbackActivePickCandidate) !== -1) { - fallbackActivePick = fallbackActivePickCandidate; - } - } - applyPicks({ - items: [...picks, ...additionalPicks], - active: activePick || additionalActivePick || fallbackActivePick - }); - } - } - finally { - if (!picksToken.isCancellationRequested) { - picker.busy = false; - } - slowPicksApplied = true; - } - }))() - ]); - } - // Fast Picks - else if (!(providedPicks instanceof Promise)) { - applyPicks(providedPicks); - } - // Slow Picks - else { - picker.busy = true; - try { - const awaitedPicks = yield providedPicks; - if (picksToken.isCancellationRequested) { - return; - } - applyPicks(awaitedPicks); - } - finally { - if (!picksToken.isCancellationRequested) { - picker.busy = false; - } - } - } - }); - disposables.add(picker.onDidChangeValue(() => updatePickerItems())); - updatePickerItems(); - // Accept the pick on accept and hide picker - disposables.add(picker.onDidAccept(event => { - const [item] = picker.selectedItems; - if (typeof (item === null || item === void 0 ? void 0 : item.accept) === 'function') { - if (!event.inBackground) { - picker.hide(); // hide picker unless we accept in background - } - item.accept(picker.keyMods, event); - } - })); - // Trigger the pick with button index if button triggered - disposables.add(picker.onDidTriggerItemButton(({ button, item }) => __awaiter(this, void 0, void 0, function* () { - var _b, _c; - if (typeof item.trigger === 'function') { - const buttonIndex = (_c = (_b = item.buttons) === null || _b === void 0 ? void 0 : _b.indexOf(button)) !== null && _c !== void 0 ? _c : -1; - if (buttonIndex >= 0) { - const result = item.trigger(buttonIndex, picker.keyMods); - const action = (typeof result === 'number') ? result : yield result; - if (token.isCancellationRequested) { - return; - } - switch (action) { - case TriggerAction.NO_ACTION: - break; - case TriggerAction.CLOSE_PICKER: - picker.hide(); - break; - case TriggerAction.REFRESH_PICKER: - updatePickerItems(); - break; - case TriggerAction.REMOVE_ITEM: - const index = picker.items.indexOf(item); - if (index !== -1) { - const items = picker.items.slice(); - items.splice(index, 1); - picker.items = items; - } - break; - } - } - } - }))); - return disposables; - } - } - exports.PickerQuickAccessProvider = PickerQuickAccessProvider; - PickerQuickAccessProvider.FAST_PICKS_RACE_DELAY = 200; // timeout before we accept fast results before slow results are present -}); - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -define(__m[78/*vs/platform/quickinput/common/quickInput*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/,205/*vs/base/parts/quickinput/common/quickInput*/]), function (require, exports, instantiation_1, quickInput_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.IQuickInputService = void 0; - __exportStar(quickInput_1, exports); - exports.IQuickInputService = (0, instantiation_1.createDecorator)('quickInputService'); -}); - -/*--------------------------------------------------------------------------------------------- - * 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/platform/registry/common/platform*/], __M([0/*require*/,1/*exports*/,20/*vs/base/common/types*/,198/*vs/base/common/assert*/]), function (require, exports, Types, Assert) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Registry = void 0; - class RegistryImpl { - constructor() { - this.data = new Map(); - } - add(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); - } - as(id) { - return this.data.get(id) || null; - } - } - 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[146/*vs/editor/common/modes/modesRegistry*/], __M([0/*require*/,1/*exports*/,468/*vs/nls!vs/editor/common/modes/modesRegistry*/,6/*vs/base/common/event*/,18/*vs/editor/common/modes*/,45/*vs/editor/common/modes/languageConfigurationRegistry*/,32/*vs/platform/registry/common/platform*/,106/*vs/base/common/mime*/]), function (require, exports, nls, event_1, modes_1, languageConfigurationRegistry_1, platform_1, mime_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.PLAINTEXT_LANGUAGE_IDENTIFIER = exports.PLAINTEXT_EXTENSION = exports.PLAINTEXT_MODE_ID = exports.ModesRegistry = exports.EditorModesRegistry = exports.Extensions = void 0; - // Define extension point ids - exports.Extensions = { - ModesRegistry: 'editor.modesRegistry' - }; - class EditorModesRegistry { - constructor() { - this._onDidChangeLanguages = new event_1.Emitter(); - this.onDidChangeLanguages = this._onDidChangeLanguages.event; - this._languages = []; - this._dynamicLanguages = []; - } - // --- languages - registerLanguage(def) { - this._languages.push(def); - this._onDidChangeLanguages.fire(undefined); - return { - dispose: () => { - for (let i = 0, len = this._languages.length; i < len; i++) { - if (this._languages[i] === def) { - this._languages.splice(i, 1); - return; - } - } - } - }; - } - getLanguages() { - return [].concat(this._languages).concat(this._dynamicLanguages); - } - } - exports.EditorModesRegistry = EditorModesRegistry; - exports.ModesRegistry = new EditorModesRegistry(); - platform_1.Registry.add(exports.Extensions.ModesRegistry, exports.ModesRegistry); - exports.PLAINTEXT_MODE_ID = 'plaintext'; - exports.PLAINTEXT_EXTENSION = '.txt'; - exports.PLAINTEXT_LANGUAGE_IDENTIFIER = new modes_1.LanguageIdentifier(exports.PLAINTEXT_MODE_ID, 1 /* PlainText */); - exports.ModesRegistry.registerLanguage({ - id: exports.PLAINTEXT_MODE_ID, - extensions: [exports.PLAINTEXT_EXTENSION], - aliases: [nls.localize(0, null), 'text'], - mimetypes: [mime_1.Mimes.text] - }); - 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 - } - }, 0); -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[576/*vs/editor/common/services/getIconClasses*/], __M([0/*require*/,1/*exports*/,46/*vs/base/common/network*/,43/*vs/base/common/resources*/,146/*vs/editor/common/modes/modesRegistry*/,240/*vs/platform/files/common/files*/]), function (require, exports, network_1, resources_1, modesRegistry_1, files_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.cssEscape = exports.detectModeId = exports.getIconClasses = void 0; - function getIconClasses(modelService, modeService, resource, fileKind) { - // we always set these base classes even if we do not have a path - const 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 - let name; - if (resource.scheme === network_1.Schemas.data) { - const metadata = resources_1.DataUri.parseMetaData(resource); - name = metadata.get(resources_1.DataUri.META_DATA_LABEL); - } - else { - name = cssEscape((0, resources_1.basenameOrAuthority)(resource).toLowerCase()); - } - // Folders - if (fileKind === files_1.FileKind.FOLDER) { - classes.push(`${name}-name-folder-icon`); - } - // Files - else { - // Name & Extension(s) - if (name) { - classes.push(`${name}-name-file-icon`); - // Avoid doing an explosive combination of extensions for very long filenames - // (most file systems do not allow files > 255 length) with lots of `.` characters - // https://github.com/microsoft/vscode/issues/116199 - if (name.length <= 255) { - const dotSegments = name.split('.'); - for (let 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 - const 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 - } - let modeId = null; - // Data URI: check for encoded metadata - if (resource.scheme === network_1.Schemas.data) { - const metadata = resources_1.DataUri.parseMetaData(resource); - const mime = metadata.get(resources_1.DataUri.META_DATA_MIME); - if (mime) { - modeId = modeService.getModeId(mime); - } - } - // Any other URI: check for model if existing - else { - const 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(str) { - return str.replace(/[\11\12\14\15\40]/g, '/'); // HTML class names can not contain certain whitespace characters, use / instead, which doesn't exist in file names. - } - 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[189/*vs/platform/jsonschemas/common/jsonContributionRegistry*/], __M([0/*require*/,1/*exports*/,32/*vs/platform/registry/common/platform*/,6/*vs/base/common/event*/]), function (require, exports, platform, event_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Extensions = void 0; - 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; - } - class JSONContributionRegistry { - constructor() { - this._onDidChangeSchema = new event_1.Emitter(); - this.schemasById = {}; - } - registerSchema(uri, unresolvedSchemaContent) { - this.schemasById[normalizeId(uri)] = unresolvedSchemaContent; - this._onDidChangeSchema.fire(uri); - } - notifySchemaChanged(uri) { - this._onDidChangeSchema.fire(uri); - } - } - const 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[98/*vs/platform/configuration/common/configurationRegistry*/], __M([0/*require*/,1/*exports*/,533/*vs/nls!vs/platform/configuration/common/configurationRegistry*/,6/*vs/base/common/event*/,32/*vs/platform/registry/common/platform*/,20/*vs/base/common/types*/,189/*vs/platform/jsonschemas/common/jsonContributionRegistry*/]), function (require, exports, nls, event_1, platform_1, types, jsonContributionRegistry_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateProperty = exports.getDefaultValue = exports.overrideIdentifierFromKey = exports.OVERRIDE_PROPERTY_PATTERN = exports.resourceLanguageSettingsSchemaId = exports.resourceSettings = exports.windowSettings = exports.machineOverridableSettings = exports.machineSettings = exports.applicationSettings = exports.allSettings = exports.Extensions = void 0; - 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'; - const contributionRegistry = platform_1.Registry.as(jsonContributionRegistry_1.Extensions.JSONContribution); - class ConfigurationRegistry { - constructor() { - this.overrideIdentifiers = new Set(); - this._onDidSchemaChange = new event_1.Emitter(); - this._onDidUpdateConfiguration = new event_1.Emitter(); - this.defaultValues = {}; - this.defaultLanguageConfigurationOverridesNode = { - id: 'defaultOverrides', - title: nls.localize(0, null), - properties: {} - }; - this.configurationContributors = [this.defaultLanguageConfigurationOverridesNode]; - 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); - } - registerConfiguration(configuration, validate = true) { - this.registerConfigurations([configuration], validate); - } - registerConfigurations(configurations, validate = true) { - const properties = []; - configurations.forEach(configuration => { - properties.push(...this.validateAndRegisterProperties(configuration, validate, configuration.extensionInfo)); // fills in defaults - this.configurationContributors.push(configuration); - this.registerJSONConfiguration(configuration); - }); - contributionRegistry.registerSchema(exports.resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema); - this._onDidSchemaChange.fire(); - this._onDidUpdateConfiguration.fire(properties); - } - registerOverrideIdentifiers(overrideIdentifiers) { - for (const overrideIdentifier of overrideIdentifiers) { - this.overrideIdentifiers.add(overrideIdentifier); - } - this.updateOverridePropertyPatternKey(); - } - validateAndRegisterProperties(configuration, validate = true, extensionInfo, scope = 3 /* WINDOW */) { - var _a; - scope = types.isUndefinedOrNull(configuration.scope) ? scope : configuration.scope; - let propertyKeys = []; - let properties = configuration.properties; - if (properties) { - for (let key in properties) { - if (validate && validateProperty(key)) { - delete properties[key]; - continue; - } - const property = properties[key]; - // update default value - this.updatePropertyDefaultValue(key, property); - // update scope - 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; - property.restricted = types.isUndefinedOrNull(property.restricted) ? !!((_a = extensionInfo === null || extensionInfo === void 0 ? void 0 : extensionInfo.restrictedConfigurations) === null || _a === void 0 ? void 0 : _a.includes(key)) : property.restricted; - } - // 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]; - } - if (!properties[key].deprecationMessage && properties[key].markdownDeprecationMessage) { - // If not set, default deprecationMessage to the markdown source - properties[key].deprecationMessage = properties[key].markdownDeprecationMessage; - } - propertyKeys.push(key); - } - } - let subNodes = configuration.allOf; - if (subNodes) { - for (let node of subNodes) { - propertyKeys.push(...this.validateAndRegisterProperties(node, validate, extensionInfo, scope)); - } - } - return propertyKeys; - } - getConfigurationProperties() { - return this.configurationProperties; - } - registerJSONConfiguration(configuration) { - const register = (configuration) => { - let properties = configuration.properties; - if (properties) { - for (const key in properties) { - this.updateSchema(key, properties[key]); - } - } - let subNodes = configuration.allOf; - if (subNodes) { - subNodes.forEach(register); - } - }; - register(configuration); - } - updateSchema(key, property) { - exports.allSettings.properties[key] = property; - switch (property.scope) { - case 1 /* APPLICATION */: - exports.applicationSettings.properties[key] = property; - break; - case 2 /* MACHINE */: - exports.machineSettings.properties[key] = property; - break; - case 6 /* MACHINE_OVERRIDABLE */: - exports.machineOverridableSettings.properties[key] = property; - break; - case 3 /* WINDOW */: - exports.windowSettings.properties[key] = property; - break; - case 4 /* RESOURCE */: - exports.resourceSettings.properties[key] = property; - break; - case 5 /* LANGUAGE_OVERRIDABLE */: - exports.resourceSettings.properties[key] = property; - this.resourceLanguageSettingsSchema.properties[key] = property; - break; - } - } - updateOverridePropertyPatternKey() { - for (const overrideIdentifier of this.overrideIdentifiers.values()) { - const overrideIdentifierProperty = `[${overrideIdentifier}]`; - const resourceLanguagePropertiesSchema = { - type: 'object', - description: nls.localize(1, null), - errorMessage: nls.localize(2, null), - $ref: exports.resourceLanguageSettingsSchemaId, - }; - this.updatePropertyDefaultValue(overrideIdentifierProperty, resourceLanguagePropertiesSchema); - 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(); - } - updatePropertyDefaultValue(key, property) { - let defaultValue = this.defaultValues[key]; - if (types.isUndefined(defaultValue)) { - defaultValue = property.default; - } - if (types.isUndefined(defaultValue)) { - defaultValue = getDefaultValue(property.type); - } - property.default = defaultValue; - } - } - const OVERRIDE_PROPERTY = '\\[.*\\]$'; - exports.OVERRIDE_PROPERTY_PATTERN = new RegExp(OVERRIDE_PROPERTY); - function overrideIdentifierFromKey(key) { - return key.substring(1, key.length - 1); - } - exports.overrideIdentifierFromKey = overrideIdentifierFromKey; - function getDefaultValue(type) { - const 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; - const configurationRegistry = new ConfigurationRegistry(); - platform_1.Registry.add(exports.Extensions.Configuration, configurationRegistry); - function validateProperty(property) { - if (!property.trim()) { - return nls.localize(3, null); - } - if (exports.OVERRIDE_PROPERTY_PATTERN.test(property)) { - return nls.localize(4, null, property); - } - if (configurationRegistry.getConfigurationProperties()[property] !== undefined) { - return nls.localize(5, 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[190/*vs/editor/common/config/commonEditorConfig*/], __M([0/*require*/,1/*exports*/,463/*vs/nls!vs/editor/common/config/commonEditorConfig*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,42/*vs/base/common/objects*/,19/*vs/base/common/arrays*/,35/*vs/editor/common/config/editorOptions*/,133/*vs/editor/common/config/editorZoom*/,168/*vs/editor/common/config/fontInfo*/,98/*vs/platform/configuration/common/configurationRegistry*/,32/*vs/platform/registry/common/platform*/,199/*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.isDiffEditorConfigurationKey = exports.isEditorConfigurationKey = exports.editorConfigurationBaseNode = exports.CommonEditorConfiguration = exports.ComputedEditorOptions = exports.TabFocus = void 0; - exports.TabFocus = new class { - constructor() { - this._tabFocus = false; - this._onDidChangeTabFocus = new event_1.Emitter(); - this.onDidChangeTabFocus = this._onDidChangeTabFocus.event; - } - getTabFocusMode() { - return this._tabFocus; - } - setTabFocusMode(tabFocusMode) { - if (this._tabFocus === tabFocusMode) { - return; - } - this._tabFocus = tabFocusMode; - this._onDidChangeTabFocus.fire(this._tabFocus); - } - }; - const hasOwnProperty = Object.hasOwnProperty; - class ComputedEditorOptions { - constructor() { - this._values = []; - } - _read(id) { - return this._values[id]; - } - get(id) { - return this._values[id]; - } - _write(id, value) { - this._values[id] = value; - } - } - exports.ComputedEditorOptions = ComputedEditorOptions; - class RawEditorOptions { - constructor() { - this._values = []; - } - _read(id) { - return this._values[id]; - } - _write(id, value) { - this._values[id] = value; - } - } - class EditorConfiguration2 { - static readOptions(_options) { - const options = _options; - const result = new RawEditorOptions(); - for (const editorOption of editorOptions_1.editorOptionsRegistry) { - const value = (editorOption.name === '_never_' ? undefined : options[editorOption.name]); - result._write(editorOption.id, value); - } - return result; - } - static validateOptions(options) { - const result = new editorOptions_1.ValidatedEditorOptions(); - for (const editorOption of editorOptions_1.editorOptionsRegistry) { - result._write(editorOption.id, editorOption.validate(options._read(editorOption.id))); - } - return result; - } - static computeOptions(options, env) { - const result = new ComputedEditorOptions(); - for (const editorOption of editorOptions_1.editorOptionsRegistry) { - result._write(editorOption.id, editorOption.compute(env, result, options._read(editorOption.id))); - } - return result; - } - static _deepEquals(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 (let key in a) { - if (!EditorConfiguration2._deepEquals(a[key], b[key])) { - return false; - } - } - return true; - } - static checkEquals(a, b) { - const result = []; - let somethingChanged = false; - for (const editorOption of editorOptions_1.editorOptionsRegistry) { - const 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); - } - } - /** - * Compatibility with old options - */ - function migrateOptions(options) { - const wordWrap = options.wordWrap; - if (wordWrap === true) { - options.wordWrap = 'on'; - } - else if (wordWrap === false) { - options.wordWrap = 'off'; - } - const lineNumbers = options.lineNumbers; - if (lineNumbers === true) { - options.lineNumbers = 'on'; - } - else if (lineNumbers === false) { - options.lineNumbers = 'off'; - } - const autoClosingBrackets = options.autoClosingBrackets; - if (autoClosingBrackets === false) { - options.autoClosingBrackets = 'never'; - options.autoClosingQuotes = 'never'; - options.autoSurround = 'never'; - } - const cursorBlinking = options.cursorBlinking; - if (cursorBlinking === 'visible') { - options.cursorBlinking = 'solid'; - } - const renderWhitespace = options.renderWhitespace; - if (renderWhitespace === true) { - options.renderWhitespace = 'boundary'; - } - else if (renderWhitespace === false) { - options.renderWhitespace = 'none'; - } - const renderLineHighlight = options.renderLineHighlight; - if (renderLineHighlight === true) { - options.renderLineHighlight = 'line'; - } - else if (renderLineHighlight === false) { - options.renderLineHighlight = 'none'; - } - const acceptSuggestionOnEnter = options.acceptSuggestionOnEnter; - if (acceptSuggestionOnEnter === true) { - options.acceptSuggestionOnEnter = 'on'; - } - else if (acceptSuggestionOnEnter === false) { - options.acceptSuggestionOnEnter = 'off'; - } - const tabCompletion = options.tabCompletion; - if (tabCompletion === false) { - options.tabCompletion = 'off'; - } - else if (tabCompletion === true) { - options.tabCompletion = 'onlySnippets'; - } - const suggest = options.suggest; - if (suggest && typeof suggest.filteredTypes === 'object' && suggest.filteredTypes) { - const mapping = {}; - mapping['method'] = 'showMethods'; - mapping['function'] = 'showFunctions'; - mapping['constructor'] = 'showConstructors'; - mapping['deprecated'] = 'showDeprecated'; - 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'; - (0, collections_1.forEach)(mapping, entry => { - const value = suggest.filteredTypes[entry.key]; - if (value === false) { - suggest[entry.value] = value; - } - }); - // delete (suggest).filteredTypes; - } - const hover = options.hover; - if (hover === true) { - options.hover = { - enabled: true - }; - } - else if (hover === false) { - options.hover = { - enabled: false - }; - } - const parameterHints = options.parameterHints; - if (parameterHints === true) { - options.parameterHints = { - enabled: true - }; - } - else if (parameterHints === false) { - options.parameterHints = { - enabled: false - }; - } - const autoIndent = options.autoIndent; - if (autoIndent === true) { - options.autoIndent = 'full'; - } - else if (autoIndent === false) { - options.autoIndent = 'advanced'; - } - const matchBrackets = options.matchBrackets; - if (matchBrackets === true) { - options.matchBrackets = 'always'; - } - else if (matchBrackets === false) { - options.matchBrackets = 'never'; - } - } - function deepCloneAndMigrateOptions(_options) { - const options = objects.deepClone(_options); - migrateOptions(options); - return options; - } - class CommonEditorConfiguration extends lifecycle_1.Disposable { - constructor(isSimpleWidget, _options) { - super(); - this._onDidChange = this._register(new event_1.Emitter()); - this.onDidChange = this._onDidChange.event; - this._onDidChangeFast = this._register(new event_1.Emitter()); - this.onDidChangeFast = this._onDidChangeFast.event; - this.isSimpleWidget = isSimpleWidget; - this._isDominatedByLongLines = false; - this._computeOptionsMemory = new editorOptions_1.ComputeOptionsMemory(); - this._viewLineCount = 1; - 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(_ => this._recomputeOptions())); - this._register(exports.TabFocus.onDidChangeTabFocus(_ => this._recomputeOptions())); - } - observeReferenceElement(dimension) { - } - updatePixelRatio() { - } - _recomputeOptions() { - const oldOptions = this.options; - const newOptions = this._computeInternalOptions(); - if (!oldOptions) { - this.options = newOptions; - } - else { - const changeEvent = EditorConfiguration2.checkEquals(oldOptions, newOptions); - if (changeEvent === null) { - // nothing changed! - return; - } - this.options = newOptions; - this._onDidChangeFast.fire(changeEvent); - this._onDidChange.fire(changeEvent); - } - } - getRawOptions() { - return this._rawOptions; - } - _computeInternalOptions() { - const partialEnv = this._getEnvConfiguration(); - const bareFontInfo = fontInfo_1.BareFontInfo.createFromValidatedSettings(this._validatedOptions, partialEnv.zoomLevel, partialEnv.pixelRatio, this.isSimpleWidget); - const env = { - memory: this._computeOptionsMemory, - outerWidth: partialEnv.outerWidth, - outerHeight: partialEnv.outerHeight, - fontInfo: this.readConfiguration(bareFontInfo), - extraEditorClassName: partialEnv.extraEditorClassName, - isDominatedByLongLines: this._isDominatedByLongLines, - viewLineCount: this._viewLineCount, - lineNumbersDigitCount: this._lineNumbersDigitCount, - emptySelectionClipboard: partialEnv.emptySelectionClipboard, - pixelRatio: partialEnv.pixelRatio, - tabFocusMode: exports.TabFocus.getTabFocusMode(), - accessibilitySupport: partialEnv.accessibilitySupport - }; - return EditorConfiguration2.computeOptions(this._validatedOptions, env); - } - static _subsetEquals(base, subset) { - for (const key in subset) { - if (hasOwnProperty.call(subset, key)) { - const subsetValue = subset[key]; - const baseValue = base[key]; - if (baseValue === subsetValue) { - continue; - } - if (Array.isArray(baseValue) && Array.isArray(subsetValue)) { - if (!arrays.equals(baseValue, subsetValue)) { - return false; - } - continue; - } - if (baseValue && typeof baseValue === 'object' && subsetValue && typeof subsetValue === 'object') { - if (!this._subsetEquals(baseValue, subsetValue)) { - return false; - } - continue; - } - return false; - } - } - return true; - } - updateOptions(_newOptions) { - if (typeof _newOptions === 'undefined') { - return; - } - const 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(); - } - setIsDominatedByLongLines(isDominatedByLongLines) { - this._isDominatedByLongLines = isDominatedByLongLines; - this._recomputeOptions(); - } - setMaxLineNumber(maxLineNumber) { - const lineNumbersDigitCount = CommonEditorConfiguration._digitCount(maxLineNumber); - if (this._lineNumbersDigitCount === lineNumbersDigitCount) { - return; - } - this._lineNumbersDigitCount = lineNumbersDigitCount; - this._recomputeOptions(); - } - setViewLineCount(viewLineCount) { - if (this._viewLineCount === viewLineCount) { - return; - } - this._viewLineCount = viewLineCount; - this._recomputeOptions(); - } - static _digitCount(n) { - let r = 0; - while (n) { - n = Math.floor(n / 10); - r++; - } - return r ? r : 1; - } - } - exports.CommonEditorConfiguration = CommonEditorConfiguration; - exports.editorConfigurationBaseNode = Object.freeze({ - id: 'editor', - order: 5, - type: 'object', - title: nls.localize(0, null), - scope: 5 /* LANGUAGE_OVERRIDABLE */, - }); - const configurationRegistry = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration); - const editorConfiguration = Object.assign(Object.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.wordBasedSuggestionsMode': { - enum: ['currentDocument', 'matchingDocuments', 'allDocuments'], - default: 'matchingDocuments', - enumDescriptions: [ - nls.localize(7, null), - nls.localize(8, null), - nls.localize(9, null) - ], - description: nls.localize(10, null) - }, - 'editor.semanticHighlighting.enabled': { - enum: [true, false, 'configuredByTheme'], - enumDescriptions: [ - nls.localize(11, null), - nls.localize(12, null), - nls.localize(13, null) - ], - default: 'configuredByTheme', - description: nls.localize(14, null) - }, - 'editor.stablePeek': { - type: 'boolean', - default: false, - markdownDescription: nls.localize(15, null) - }, - 'editor.maxTokenizationLineLength': { - type: 'integer', - default: 20000, - description: nls.localize(16, null) - }, - 'diffEditor.maxComputationTime': { - type: 'number', - default: 5000, - description: nls.localize(17, null) - }, - 'diffEditor.renderSideBySide': { - type: 'boolean', - default: true, - description: nls.localize(18, null) - }, - 'diffEditor.ignoreTrimWhitespace': { - type: 'boolean', - default: true, - description: nls.localize(19, null) - }, - 'diffEditor.renderIndicators': { - type: 'boolean', - default: true, - description: nls.localize(20, null) - }, - 'diffEditor.codeLens': { - type: 'boolean', - default: false, - description: nls.localize(21, null) - }, - 'diffEditor.wordWrap': { - type: 'string', - enum: ['off', 'on', 'inherit'], - default: 'inherit', - markdownEnumDescriptions: [ - nls.localize(22, null), - nls.localize(23, null), - nls.localize(24, null), - ] - } - } }); - function isConfigurationPropertySchema(x) { - return (typeof x.type !== 'undefined' || typeof x.anyOf !== 'undefined'); - } - // Add properties from the Editor Option Registry - for (const editorOption of editorOptions_1.editorOptionsRegistry) { - const schema = editorOption.schema; - if (typeof schema !== 'undefined') { - if (isConfigurationPropertySchema(schema)) { - // This is a single schema contribution - editorConfiguration.properties[`editor.${editorOption.name}`] = schema; - } - else { - for (let key in schema) { - if (hasOwnProperty.call(schema, key)) { - editorConfiguration.properties[key] = schema[key]; - } - } - } - } - } - let cachedEditorConfigurationKeys = null; - function getEditorConfigurationKeys() { - if (cachedEditorConfigurationKeys === null) { - cachedEditorConfigurationKeys = Object.create(null); - Object.keys(editorConfiguration.properties).forEach((prop) => { - cachedEditorConfigurationKeys[prop] = true; - }); - } - return cachedEditorConfigurationKeys; - } - function isEditorConfigurationKey(key) { - const editorConfigurationKeys = getEditorConfigurationKeys(); - return (editorConfigurationKeys[`editor.${key}`] || false); - } - exports.isEditorConfigurationKey = isEditorConfigurationKey; - function isDiffEditorConfigurationKey(key) { - const 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[65/*vs/editor/browser/config/configuration*/], __M([0/*require*/,1/*exports*/,39/*vs/base/browser/browser*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,370/*vs/editor/browser/config/charWidthReader*/,214/*vs/editor/browser/config/elementSizeObserver*/,190/*vs/editor/common/config/commonEditorConfig*/,35/*vs/editor/common/config/editorOptions*/,168/*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 }); - exports.Configuration = exports.clearAllFontInfos = void 0; - class CSSBasedConfigurationCache { - constructor() { - this._keys = Object.create(null); - this._values = Object.create(null); - } - has(item) { - const itemId = item.getId(); - return !!this._values[itemId]; - } - get(item) { - const itemId = item.getId(); - return this._values[itemId]; - } - put(item, value) { - const itemId = item.getId(); - this._keys[itemId] = item; - this._values[itemId] = value; - } - remove(item) { - const itemId = item.getId(); - delete this._keys[itemId]; - delete this._values[itemId]; - } - getValues() { - return Object.keys(this._keys).map(id => this._values[id]); - } - } - function clearAllFontInfos() { - CSSBasedConfiguration.INSTANCE.clearCache(); - } - exports.clearAllFontInfos = clearAllFontInfos; - class CSSBasedConfiguration extends lifecycle_1.Disposable { - constructor() { - super(); - this._onDidChange = this._register(new event_1.Emitter()); - this.onDidChange = this._onDidChange.event; - this._cache = new CSSBasedConfigurationCache(); - this._evictUntrustedReadingsTimeout = -1; - } - dispose() { - if (this._evictUntrustedReadingsTimeout !== -1) { - clearTimeout(this._evictUntrustedReadingsTimeout); - this._evictUntrustedReadingsTimeout = -1; - } - super.dispose(); - } - clearCache() { - this._cache = new CSSBasedConfigurationCache(); - this._onDidChange.fire(); - } - _writeToCache(item, value) { - this._cache.put(item, value); - if (!value.isTrusted && this._evictUntrustedReadingsTimeout === -1) { - // Try reading again after some time - this._evictUntrustedReadingsTimeout = setTimeout(() => { - this._evictUntrustedReadingsTimeout = -1; - this._evictUntrustedReadings(); - }, 5000); - } - } - _evictUntrustedReadings() { - const values = this._cache.getValues(); - let somethingRemoved = false; - for (const item of values) { - if (!item.isTrusted) { - somethingRemoved = true; - this._cache.remove(item); - } - } - if (somethingRemoved) { - this._onDidChange.fire(); - } - } - readConfiguration(bareFontInfo) { - if (!this._cache.has(bareFontInfo)) { - let 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(), - pixelRatio: browser.getPixelRatio(), - 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), - wsmiddotWidth: Math.max(readConfig.wsmiddotWidth, 5), - maxDigitWidth: Math.max(readConfig.maxDigitWidth, 5), - }, false); - } - this._writeToCache(bareFontInfo, readConfig); - } - return this._cache.get(bareFontInfo); - } - static createRequest(chr, type, all, monospace) { - const result = new charWidthReader_1.CharWidthRequest(chr, type); - all.push(result); - if (monospace) { - monospace.push(result); - } - return result; - } - static _actualReadConfiguration(bareFontInfo) { - const all = []; - const monospace = []; - const typicalHalfwidthCharacter = this.createRequest('n', 0 /* Regular */, all, monospace); - const typicalFullwidthCharacter = this.createRequest('\uff4d', 0 /* Regular */, all, null); - const space = this.createRequest(' ', 0 /* Regular */, all, monospace); - const digit0 = this.createRequest('0', 0 /* Regular */, all, monospace); - const digit1 = this.createRequest('1', 0 /* Regular */, all, monospace); - const digit2 = this.createRequest('2', 0 /* Regular */, all, monospace); - const digit3 = this.createRequest('3', 0 /* Regular */, all, monospace); - const digit4 = this.createRequest('4', 0 /* Regular */, all, monospace); - const digit5 = this.createRequest('5', 0 /* Regular */, all, monospace); - const digit6 = this.createRequest('6', 0 /* Regular */, all, monospace); - const digit7 = this.createRequest('7', 0 /* Regular */, all, monospace); - const digit8 = this.createRequest('8', 0 /* Regular */, all, monospace); - const digit9 = this.createRequest('9', 0 /* Regular */, all, monospace); - // monospace test: used for whitespace rendering - const rightwardsArrow = this.createRequest('→', 0 /* Regular */, all, monospace); - const halfwidthRightwardsArrow = this.createRequest('→', 0 /* Regular */, all, null); - // U+00B7 - MIDDLE DOT - const middot = this.createRequest('·', 0 /* Regular */, all, monospace); - // U+2E31 - WORD SEPARATOR MIDDLE DOT - const wsmiddotWidth = this.createRequest(String.fromCharCode(0x2E31), 0 /* Regular */, all, null); - // 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); - (0, charWidthReader_1.readCharWidths)(bareFontInfo, all); - const maxDigitWidth = Math.max(digit0.width, digit1.width, digit2.width, digit3.width, digit4.width, digit5.width, digit6.width, digit7.width, digit8.width, digit9.width); - let isMonospace = (bareFontInfo.fontFeatureSettings === editorOptions_1.EditorFontLigatures.OFF); - const referenceWidth = monospace[0].width; - for (let i = 1, len = monospace.length; isMonospace && i < len; i++) { - const diff = referenceWidth - monospace[i].width; - if (diff < -0.001 || diff > 0.001) { - isMonospace = false; - break; - } - } - let 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. - const canTrustBrowserZoomLevel = (browser.getTimeSinceLastZoomLevelChanged() > 2000); - return new fontInfo_1.FontInfo({ - zoomLevel: browser.getZoomLevel(), - pixelRatio: browser.getPixelRatio(), - 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, - wsmiddotWidth: wsmiddotWidth.width, - maxDigitWidth: maxDigitWidth - }, canTrustBrowserZoomLevel); - } - } - CSSBasedConfiguration.INSTANCE = new CSSBasedConfiguration(); - class Configuration extends commonEditorConfig_1.CommonEditorConfiguration { - constructor(isSimpleWidget, options, referenceDomElement = null, accessibilityService) { - super(isSimpleWidget, options); - this.accessibilityService = accessibilityService; - this._elementSizeObserver = this._register(new elementSizeObserver_1.ElementSizeObserver(referenceDomElement, options.dimension, () => this._recomputeOptions())); - this._register(CSSBasedConfiguration.INSTANCE.onDidChange(() => this._recomputeOptions())); - if (this._validatedOptions.get(10 /* automaticLayout */)) { - this._elementSizeObserver.startObserving(); - } - this._register(browser.onDidChangeZoomLevel(_ => this._recomputeOptions())); - this._register(this.accessibilityService.onDidChangeScreenReaderOptimized(() => this._recomputeOptions())); - this._recomputeOptions(); - } - static applyFontInfoSlow(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'; - } - static applyFontInfo(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); - } - observeReferenceElement(dimension) { - this._elementSizeObserver.observe(dimension); - } - updatePixelRatio() { - this._recomputeOptions(); - } - static _getExtraEditorClassName() { - let extra = ''; - if (!browser.isSafari && !browser.isWebkitWebView) { - // Use user-select: none in all browsers except Safari and native macOS WebView - extra += 'no-user-select '; - } - if (browser.isSafari) { - // See https://github.com/microsoft/vscode/issues/108822 - extra += 'no-minimap-shadow '; - } - if (platform.isMacintosh) { - extra += 'mac '; - } - return extra; - } - _getEnvConfiguration() { - return { - extraEditorClassName: Configuration._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()) - }; - } - readConfiguration(bareFontInfo) { - return CSSBasedConfiguration.INSTANCE.readConfiguration(bareFontInfo); - } - } - 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[577/*vs/editor/browser/view/domLineBreaksComputer*/], __M([0/*require*/,1/*exports*/,83/*vs/editor/common/core/stringBuilder*/,8/*vs/base/common/strings*/,65/*vs/editor/browser/config/configuration*/,62/*vs/editor/common/viewModel/viewModel*/,96/*vs/editor/common/model/textModelEvents*/]), function (require, exports, stringBuilder_1, strings, configuration_1, viewModel_1, textModelEvents_1) { - "use strict"; - var _a; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DOMLineBreaksComputerFactory = void 0; - const ttPolicy = (_a = window.trustedTypes) === null || _a === void 0 ? void 0 : _a.createPolicy('domLineBreaksComputer', { createHTML: value => value }); - class DOMLineBreaksComputerFactory { - static create() { - return new DOMLineBreaksComputerFactory(); - } - constructor() { - } - createLineBreaksComputer(fontInfo, tabSize, wrappingColumn, wrappingIndent) { - tabSize = tabSize | 0; //@perf - wrappingColumn = +wrappingColumn; //@perf - let requests = []; - let injectedTexts = []; - return { - addRequest: (lineText, injectedText, previousLineBreakData) => { - requests.push(lineText); - injectedTexts.push(injectedText); - }, - finalize: () => { - return createLineBreaks(requests, fontInfo, tabSize, wrappingColumn, wrappingIndent, injectedTexts); - } - }; - } - } - exports.DOMLineBreaksComputerFactory = DOMLineBreaksComputerFactory; - function createLineBreaks(requests, fontInfo, tabSize, firstLineBreakColumn, wrappingIndent, injectedTextsPerLine) { - var _a; - function createEmptyLineBreakWithPossiblyInjectedText(requestIdx) { - const injectedTexts = injectedTextsPerLine[requestIdx]; - if (injectedTexts) { - const lineText = textModelEvents_1.LineInjectedText.applyInjectedText(requests[requestIdx], injectedTexts); - const injectionOptions = injectedTexts.map(t => t.options); - const injectionOffsets = injectedTexts.map(text => text.column - 1); - // creating a `LineBreakData` with an invalid `breakOffsetsVisibleColumn` is OK - // because `breakOffsetsVisibleColumn` will never be used because it contains injected text - return new viewModel_1.LineBreakData([lineText.length], [], 0, injectionOffsets, injectionOptions); - } - else { - return null; - } - } - if (firstLineBreakColumn === -1) { - const result = []; - for (let i = 0, len = requests.length; i < len; i++) { - result[i] = createEmptyLineBreakWithPossiblyInjectedText(i); - } - return result; - } - const 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 */; - } - const containerDomNode = document.createElement('div'); - configuration_1.Configuration.applyFontInfoSlow(containerDomNode, fontInfo); - const sb = (0, stringBuilder_1.createStringBuilder)(10000); - const firstNonWhitespaceIndices = []; - const wrappedTextIndentLengths = []; - const renderLineContents = []; - const allCharOffsets = []; - const allVisibleColumns = []; - for (let i = 0; i < requests.length; i++) { - const lineContent = textModelEvents_1.LineInjectedText.applyInjectedText(requests[i], injectedTextsPerLine[i]); - let firstNonWhitespaceIndex = 0; - let wrappedTextIndentLength = 0; - let width = overallWidth; - if (wrappingIndent !== 0 /* None */) { - firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent); - if (firstNonWhitespaceIndex === -1) { - // all whitespace line - firstNonWhitespaceIndex = 0; - } - else { - // Track existing indent - for (let i = 0; i < firstNonWhitespaceIndex; i++) { - const charWidth = (lineContent.charCodeAt(i) === 9 /* Tab */ - ? (tabSize - (wrappedTextIndentLength % tabSize)) - : 1); - wrappedTextIndentLength += charWidth; - } - const 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; - } - } - } - const renderLineContent = lineContent.substr(firstNonWhitespaceIndex); - const tmp = renderLine(renderLineContent, wrappedTextIndentLength, tabSize, width, sb); - firstNonWhitespaceIndices[i] = firstNonWhitespaceIndex; - wrappedTextIndentLengths[i] = wrappedTextIndentLength; - renderLineContents[i] = renderLineContent; - allCharOffsets[i] = tmp[0]; - allVisibleColumns[i] = tmp[1]; - } - const html = sb.build(); - const trustedhtml = (_a = ttPolicy === null || ttPolicy === void 0 ? void 0 : ttPolicy.createHTML(html)) !== null && _a !== void 0 ? _a : html; - containerDomNode.innerHTML = trustedhtml; - containerDomNode.style.position = 'absolute'; - containerDomNode.style.top = '10000'; - containerDomNode.style.wordWrap = 'break-word'; - document.body.appendChild(containerDomNode); - let range = document.createRange(); - const lineDomNodes = Array.prototype.slice.call(containerDomNode.children, 0); - let result = []; - for (let i = 0; i < requests.length; i++) { - const lineDomNode = lineDomNodes[i]; - const breakOffsets = readLineBreaks(range, lineDomNode, renderLineContents[i], allCharOffsets[i]); - if (breakOffsets === null) { - result[i] = createEmptyLineBreakWithPossiblyInjectedText(i); - continue; - } - const firstNonWhitespaceIndex = firstNonWhitespaceIndices[i]; - const wrappedTextIndentLength = wrappedTextIndentLengths[i]; - const visibleColumns = allVisibleColumns[i]; - const breakOffsetsVisibleColumn = []; - for (let 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 (let j = 0, len = breakOffsets.length; j < len; j++) { - breakOffsets[j] += firstNonWhitespaceIndex; - } - } - let injectionOptions; - let injectionOffsets; - const curInjectedTexts = injectedTextsPerLine[i]; - if (curInjectedTexts) { - injectionOptions = curInjectedTexts.map(t => t.options); - injectionOffsets = curInjectedTexts.map(text => text.column - 1); - } - else { - injectionOptions = null; - injectionOffsets = null; - } - result[i] = new viewModel_1.LineBreakData(breakOffsets, breakOffsetsVisibleColumn, wrappedTextIndentLength, injectionOffsets, injectionOptions); - } - document.body.removeChild(containerDomNode); - return result; - } - function renderLine(lineContent, initialVisibleColumn, tabSize, width, sb) { - sb.appendASCIIString('
    '); - // if (containsRTL) { - // sb.appendASCIIString('" dir="ltr'); - // } - const len = lineContent.length; - let visibleColumn = initialVisibleColumn; - let charOffset = 0; - let charOffsets = []; - let visibleColumns = []; - let nextCharCode = (0 < len ? lineContent.charCodeAt(0) : 0 /* Null */); - sb.appendASCIIString(''); - for (let charIndex = 0; charIndex < len; charIndex++) { - if (charIndex !== 0 && charIndex % 16384 /* SPAN_MODULO_LIMIT */ === 0) { - sb.appendASCIIString(''); - } - charOffsets[charIndex] = charOffset; - visibleColumns[charIndex] = visibleColumn; - const charCode = nextCharCode; - nextCharCode = (charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : 0 /* Null */); - let producedCharacters = 1; - let charWidth = 1; - switch (charCode) { - case 9 /* Tab */: - producedCharacters = (tabSize - (visibleColumn % tabSize)); - charWidth = producedCharacters; - for (let 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 */: - case 8233 /* PARAGRAPH_SEPARATOR */: - case 133 /* NEXT_LINE */: - sb.write1(0xFFFD); - break; - default: - if (strings.isFullWidthCharacter(charCode)) { - charWidth++; - } - if (charCode < 32) { - sb.write1(9216 + charCode); - } - else { - sb.write1(charCode); - } - } - charOffset += producedCharacters; - visibleColumn += charWidth; - } - sb.appendASCIIString(''); - 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; - } - const spans = Array.prototype.slice.call(lineDomNode.children, 0); - const breakOffsets = []; - try { - discoverBreaks(range, spans, charOffsets, 0, null, lineContent.length - 1, null, breakOffsets); - } - catch (err) { - console.log(err); - return null; - } - if (breakOffsets.length === 0) { - return null; - } - breakOffsets.push(lineContent.length); - return breakOffsets; - } - function discoverBreaks(range, spans, charOffsets, low, lowRects, high, highRects, result) { - if (low === high) { - return; - } - lowRects = lowRects || readClientRect(range, spans, charOffsets[low], charOffsets[low + 1]); - highRects = highRects || readClientRect(range, spans, 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; - } - const mid = low + ((high - low) / 2) | 0; - const midRects = readClientRect(range, spans, charOffsets[mid], charOffsets[mid + 1]); - discoverBreaks(range, spans, charOffsets, low, lowRects, mid, midRects, result); - discoverBreaks(range, spans, charOffsets, mid, midRects, high, highRects, result); - } - function readClientRect(range, spans, startOffset, endOffset) { - range.setStart(spans[(startOffset / 16384 /* SPAN_MODULO_LIMIT */) | 0].firstChild, startOffset % 16384 /* SPAN_MODULO_LIMIT */); - range.setEnd(spans[(endOffset / 16384 /* SPAN_MODULO_LIMIT */) | 0].firstChild, endOffset % 16384 /* SPAN_MODULO_LIMIT */); - 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[578/*vs/editor/browser/view/viewOverlays*/], __M([0/*require*/,1/*exports*/,30/*vs/base/browser/fastDomNode*/,65/*vs/editor/browser/config/configuration*/,170/*vs/editor/browser/view/viewLayer*/,47/*vs/editor/browser/view/viewPart*/]), function (require, exports, fastDomNode_1, configuration_1, viewLayer_1, viewPart_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MarginViewOverlays = exports.ContentViewOverlays = exports.ViewOverlayLine = exports.ViewOverlays = void 0; - class ViewOverlays extends viewPart_1.ViewPart { - constructor(context) { - super(context); - this._visibleLines = new viewLayer_1.VisibleLinesCollection(this); - this.domNode = this._visibleLines.domNode; - this._dynamicOverlays = []; - this._isFocused = false; - this.domNode.setClassName('view-overlays'); - } - shouldRender() { - if (super.shouldRender()) { - return true; - } - for (let i = 0, len = this._dynamicOverlays.length; i < len; i++) { - const dynamicOverlay = this._dynamicOverlays[i]; - if (dynamicOverlay.shouldRender()) { - return true; - } - } - return false; - } - dispose() { - super.dispose(); - for (let i = 0, len = this._dynamicOverlays.length; i < len; i++) { - const dynamicOverlay = this._dynamicOverlays[i]; - dynamicOverlay.dispose(); - } - this._dynamicOverlays = []; - } - getDomNode() { - return this.domNode; - } - // ---- begin IVisibleLinesHost - createVisibleLine() { - return new ViewOverlayLine(this._context.configuration, this._dynamicOverlays); - } - // ---- end IVisibleLinesHost - addDynamicOverlay(overlay) { - this._dynamicOverlays.push(overlay); - } - // ----- event handlers - onConfigurationChanged(e) { - this._visibleLines.onConfigurationChanged(e); - const startLineNumber = this._visibleLines.getStartLineNumber(); - const endLineNumber = this._visibleLines.getEndLineNumber(); - for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { - const line = this._visibleLines.getVisibleLine(lineNumber); - line.onConfigurationChanged(e); - } - return true; - } - onFlushed(e) { - return this._visibleLines.onFlushed(e); - } - onFocusChanged(e) { - this._isFocused = e.isFocused; - return true; - } - onLinesChanged(e) { - return this._visibleLines.onLinesChanged(e); - } - onLinesDeleted(e) { - return this._visibleLines.onLinesDeleted(e); - } - onLinesInserted(e) { - return this._visibleLines.onLinesInserted(e); - } - onScrollChanged(e) { - return this._visibleLines.onScrollChanged(e) || true; - } - onTokensChanged(e) { - return this._visibleLines.onTokensChanged(e); - } - onZonesChanged(e) { - return this._visibleLines.onZonesChanged(e); - } - // ----- end event handlers - prepareRender(ctx) { - const toRender = this._dynamicOverlays.filter(overlay => overlay.shouldRender()); - for (let i = 0, len = toRender.length; i < len; i++) { - const dynamicOverlay = toRender[i]; - dynamicOverlay.prepareRender(ctx); - dynamicOverlay.onDidRender(); - } - } - render(ctx) { - // Overwriting to bypass `shouldRender` flag - this._viewOverlaysRender(ctx); - this.domNode.toggleClassName('focused', this._isFocused); - } - _viewOverlaysRender(ctx) { - this._visibleLines.renderLines(ctx.viewportData); - } - } - exports.ViewOverlays = ViewOverlays; - class ViewOverlayLine { - constructor(configuration, dynamicOverlays) { - this._configuration = configuration; - this._lineHeight = this._configuration.options.get(57 /* lineHeight */); - this._dynamicOverlays = dynamicOverlays; - this._domNode = null; - this._renderedContent = null; - } - getDomNode() { - if (!this._domNode) { - return null; - } - return this._domNode.domNode; - } - setDomNode(domNode) { - this._domNode = (0, fastDomNode_1.createFastDomNode)(domNode); - } - onContentChanged() { - // Nothing - } - onTokensChanged() { - // Nothing - } - onConfigurationChanged(e) { - this._lineHeight = this._configuration.options.get(57 /* lineHeight */); - } - renderLine(lineNumber, deltaTop, viewportData, sb) { - let result = ''; - for (let i = 0, len = this._dynamicOverlays.length; i < len; i++) { - const dynamicOverlay = this._dynamicOverlays[i]; - result += dynamicOverlay.render(viewportData.startLineNumber, lineNumber); - } - if (this._renderedContent === result) { - // No rendering needed - return false; - } - this._renderedContent = result; - sb.appendASCIIString('
    '); - sb.appendASCIIString(result); - sb.appendASCIIString('
    '); - return true; - } - layoutLine(lineNumber, deltaTop) { - if (this._domNode) { - this._domNode.setTop(deltaTop); - this._domNode.setHeight(this._lineHeight); - } - } - } - exports.ViewOverlayLine = ViewOverlayLine; - class ContentViewOverlays extends ViewOverlays { - constructor(context) { - super(context); - const options = this._context.configuration.options; - const layoutInfo = options.get(129 /* layoutInfo */); - this._contentWidth = layoutInfo.contentWidth; - this.domNode.setHeight(0); - } - // --- begin event handlers - onConfigurationChanged(e) { - const options = this._context.configuration.options; - const layoutInfo = options.get(129 /* layoutInfo */); - this._contentWidth = layoutInfo.contentWidth; - return super.onConfigurationChanged(e) || true; - } - onScrollChanged(e) { - return super.onScrollChanged(e) || e.scrollWidthChanged; - } - // --- end event handlers - _viewOverlaysRender(ctx) { - super._viewOverlaysRender(ctx); - this.domNode.setWidth(Math.max(ctx.scrollWidth, this._contentWidth)); - } - } - exports.ContentViewOverlays = ContentViewOverlays; - class MarginViewOverlays extends ViewOverlays { - constructor(context) { - super(context); - const options = this._context.configuration.options; - const layoutInfo = options.get(129 /* layoutInfo */); - this._contentLeft = layoutInfo.contentLeft; - this.domNode.setClassName('margin-view-overlays'); - this.domNode.setWidth(1); - configuration_1.Configuration.applyFontInfo(this.domNode, options.get(41 /* fontInfo */)); - } - onConfigurationChanged(e) { - const options = this._context.configuration.options; - configuration_1.Configuration.applyFontInfo(this.domNode, options.get(41 /* fontInfo */)); - const layoutInfo = options.get(129 /* layoutInfo */); - this._contentLeft = layoutInfo.contentLeft; - return super.onConfigurationChanged(e) || true; - } - onScrollChanged(e) { - return super.onScrollChanged(e) || e.scrollHeightChanged; - } - _viewOverlaysRender(ctx) { - super._viewOverlaysRender(ctx); - const height = Math.min(ctx.scrollHeight, 1000000); - this.domNode.setHeight(height); - this.domNode.setWidth(this._contentLeft); - } - } - exports.MarginViewOverlays = MarginViewOverlays; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[579/*vs/editor/browser/viewParts/viewCursors/viewCursor*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,30/*vs/base/browser/fastDomNode*/,8/*vs/base/common/strings*/,65/*vs/editor/browser/config/configuration*/,35/*vs/editor/common/config/editorOptions*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,131/*vs/base/browser/ui/mouseCursor/mouseCursor*/]), function (require, exports, dom, fastDomNode_1, strings, configuration_1, editorOptions_1, position_1, range_1, mouseCursor_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ViewCursor = void 0; - class ViewCursorRenderData { - constructor(top, left, width, height, textContent, textContentClassName) { - this.top = top; - this.left = left; - this.width = width; - this.height = height; - this.textContent = textContent; - this.textContentClassName = textContentClassName; - } - } - class ViewCursor { - constructor(context) { - this._context = context; - const options = this._context.configuration.options; - const fontInfo = options.get(41 /* fontInfo */); - this._cursorStyle = options.get(22 /* cursorStyle */); - this._lineHeight = options.get(57 /* lineHeight */); - this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth; - this._lineCursorWidth = Math.min(options.get(25 /* cursorWidth */), this._typicalHalfwidthCharacterWidth); - this._isVisible = true; - // Create the dom node - this._domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div')); - this._domNode.setClassName(`cursor ${mouseCursor_1.MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`); - this._domNode.setHeight(this._lineHeight); - this._domNode.setTop(0); - this._domNode.setLeft(0); - configuration_1.Configuration.applyFontInfo(this._domNode, fontInfo); - this._domNode.setDisplay('none'); - this._position = new position_1.Position(1, 1); - this._lastRenderedContent = ''; - this._renderData = null; - } - getDomNode() { - return this._domNode; - } - getPosition() { - return this._position; - } - show() { - if (!this._isVisible) { - this._domNode.setVisibility('inherit'); - this._isVisible = true; - } - } - hide() { - if (this._isVisible) { - this._domNode.setVisibility('hidden'); - this._isVisible = false; - } - } - onConfigurationChanged(e) { - const options = this._context.configuration.options; - const fontInfo = options.get(41 /* fontInfo */); - this._cursorStyle = options.get(22 /* cursorStyle */); - this._lineHeight = options.get(57 /* lineHeight */); - this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth; - this._lineCursorWidth = Math.min(options.get(25 /* cursorWidth */), this._typicalHalfwidthCharacterWidth); - configuration_1.Configuration.applyFontInfo(this._domNode, fontInfo); - return true; - } - onCursorPositionChanged(position) { - this._position = position; - return true; - } - _prepareRender(ctx) { - let textContent = ''; - if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Line || this._cursorStyle === editorOptions_1.TextEditorCursorStyle.LineThin) { - const visibleRange = ctx.visibleRangeForPosition(this._position); - if (!visibleRange || visibleRange.outsideRenderedLine) { - // Outside viewport - return null; - } - let width; - if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Line) { - width = dom.computeScreenAwareSize(this._lineCursorWidth > 0 ? this._lineCursorWidth : 2); - if (width > 2) { - const lineContent = this._context.model.getLineContent(this._position.lineNumber); - const nextCharLength = strings.nextCharLength(lineContent, this._position.column - 1); - textContent = lineContent.substr(this._position.column - 1, nextCharLength); - } - } - else { - width = dom.computeScreenAwareSize(1); - } - let left = visibleRange.left; - if (width >= 2 && left >= 1) { - // try to center cursor - left -= 1; - } - const top = ctx.getVerticalOffsetForLineNumber(this._position.lineNumber) - ctx.bigNumbersDelta; - return new ViewCursorRenderData(top, left, width, this._lineHeight, textContent, ''); - } - const lineContent = this._context.model.getLineContent(this._position.lineNumber); - const nextCharLength = strings.nextCharLength(lineContent, this._position.column - 1); - const visibleRangeForCharacter = ctx.linesVisibleRangesForRange(new range_1.Range(this._position.lineNumber, this._position.column, this._position.lineNumber, this._position.column + nextCharLength), false); - if (!visibleRangeForCharacter || visibleRangeForCharacter.length === 0) { - // Outside viewport - return null; - } - const firstVisibleRangeForCharacter = visibleRangeForCharacter[0]; - if (firstVisibleRangeForCharacter.outsideRenderedLine || firstVisibleRangeForCharacter.ranges.length === 0) { - // Outside viewport - return null; - } - const range = firstVisibleRangeForCharacter.ranges[0]; - const width = range.width < 1 ? this._typicalHalfwidthCharacterWidth : range.width; - let textContentClassName = ''; - if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Block) { - const lineData = this._context.model.getViewLineData(this._position.lineNumber); - textContent = lineContent.substr(this._position.column - 1, nextCharLength); - const tokenIndex = lineData.tokens.findTokenIndexAtOffset(this._position.column - 1); - textContentClassName = lineData.tokens.getClassName(tokenIndex); - } - let top = ctx.getVerticalOffsetForLineNumber(this._position.lineNumber) - ctx.bigNumbersDelta; - let height = this._lineHeight; - // Underline might interfere with clicking - if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Underline || this._cursorStyle === editorOptions_1.TextEditorCursorStyle.UnderlineThin) { - top += this._lineHeight - 2; - height = 2; - } - return new ViewCursorRenderData(top, range.left, width, height, textContent, textContentClassName); - } - prepareRender(ctx) { - this._renderData = this._prepareRender(ctx); - } - render(ctx) { - if (!this._renderData) { - this._domNode.setDisplay('none'); - return null; - } - if (this._lastRenderedContent !== this._renderData.textContent) { - this._lastRenderedContent = this._renderData.textContent; - this._domNode.domNode.textContent = this._lastRenderedContent; - } - this._domNode.setClassName(`cursor ${mouseCursor_1.MOUSE_CURSOR_TEXT_CSS_CLASS_NAME} ${this._renderData.textContentClassName}`); - this._domNode.setDisplay('block'); - this._domNode.setTop(this._renderData.top); - this._domNode.setLeft(this._renderData.left); - this._domNode.setWidth(this._renderData.width); - this._domNode.setLineHeight(this._renderData.height); - this._domNode.setHeight(this._renderData.height); - return { - domNode: this._domNode.domNode, - position: this._position, - contentLeft: this._renderData.left, - height: this._renderData.height, - width: 2 - }; - } - } - exports.ViewCursor = ViewCursor; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[580/*vs/editor/common/services/languagesRegistry*/], __M([0/*require*/,1/*exports*/,12/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,106/*vs/base/common/mime*/,8/*vs/base/common/strings*/,18/*vs/editor/common/modes*/,146/*vs/editor/common/modes/modesRegistry*/,77/*vs/editor/common/modes/nullMode*/,98/*vs/platform/configuration/common/configurationRegistry*/,32/*vs/platform/registry/common/platform*/]), function (require, exports, errors_1, event_1, lifecycle_1, mime, strings, modes_1, modesRegistry_1, nullMode_1, configurationRegistry_1, platform_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.LanguagesRegistry = void 0; - const hasOwnProperty = Object.prototype.hasOwnProperty; - class LanguagesRegistry extends lifecycle_1.Disposable { - constructor(useModesRegistry = true, warnOnOverwrite = false) { - super(); - this._onDidChange = this._register(new event_1.Emitter()); - this.onDidChange = this._onDidChange.event; - this._warnOnOverwrite = warnOnOverwrite; - this._nextLanguageId2 = 1; - this._languageIdToLanguage = []; - this._languageToLanguageId = Object.create(null); - this._languages = {}; - this._mimeTypesMap = {}; - this._nameMap = {}; - this._lowercaseNameMap = {}; - if (useModesRegistry) { - this._initializeFromRegistry(); - this._register(modesRegistry_1.ModesRegistry.onDidChangeLanguages((m) => this._initializeFromRegistry())); - } - } - _initializeFromRegistry() { - this._languages = {}; - this._mimeTypesMap = {}; - this._nameMap = {}; - this._lowercaseNameMap = {}; - const desc = modesRegistry_1.ModesRegistry.getLanguages(); - this._registerLanguages(desc); - } - _registerLanguages(desc) { - for (const d of desc) { - this._registerLanguage(d); - } - // Rebuild fast path maps - this._mimeTypesMap = {}; - this._nameMap = {}; - this._lowercaseNameMap = {}; - Object.keys(this._languages).forEach((langId) => { - let language = this._languages[langId]; - if (language.name) { - this._nameMap[language.name] = language.identifier; - } - language.aliases.forEach((alias) => { - this._lowercaseNameMap[alias.toLowerCase()] = language.identifier; - }); - language.mimetypes.forEach((mimetype) => { - this._mimeTypesMap[mimetype] = language.identifier; - }); - }); - platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).registerOverrideIdentifiers(modesRegistry_1.ModesRegistry.getLanguages().map(language => language.id)); - this._onDidChange.fire(); - } - _getLanguageId(language) { - if (this._languageToLanguageId[language]) { - return this._languageToLanguageId[language]; - } - const languageId = this._nextLanguageId2++; - this._languageIdToLanguage[languageId] = language; - this._languageToLanguageId[language] = languageId; - return languageId; - } - _registerLanguage(lang) { - const langId = lang.id; - let resolvedLanguage; - if (hasOwnProperty.call(this._languages, langId)) { - resolvedLanguage = this._languages[langId]; - } - else { - const languageId = this._getLanguageId(langId); - resolvedLanguage = { - identifier: new modes_1.LanguageIdentifier(langId, languageId), - name: null, - mimetypes: [], - aliases: [], - extensions: [], - filenames: [], - configurationFiles: [] - }; - this._languages[langId] = resolvedLanguage; - } - this._mergeLanguage(resolvedLanguage, lang); - } - _mergeLanguage(resolvedLanguage, lang) { - const langId = lang.id; - let primaryMime = null; - if (Array.isArray(lang.mimetypes) && lang.mimetypes.length > 0) { - resolvedLanguage.mimetypes.push(...lang.mimetypes); - primaryMime = lang.mimetypes[0]; - } - if (!primaryMime) { - primaryMime = `text/x-${langId}`; - resolvedLanguage.mimetypes.push(primaryMime); - } - if (Array.isArray(lang.extensions)) { - if (lang.configuration) { - // insert first as this appears to be the 'primary' language definition - resolvedLanguage.extensions = lang.extensions.concat(resolvedLanguage.extensions); - } - else { - resolvedLanguage.extensions = resolvedLanguage.extensions.concat(lang.extensions); - } - for (let extension of lang.extensions) { - mime.registerTextMime({ id: langId, mime: primaryMime, extension: extension }, this._warnOnOverwrite); - } - } - if (Array.isArray(lang.filenames)) { - for (let filename of lang.filenames) { - mime.registerTextMime({ id: langId, mime: primaryMime, filename: filename }, this._warnOnOverwrite); - resolvedLanguage.filenames.push(filename); - } - } - if (Array.isArray(lang.filenamePatterns)) { - for (let filenamePattern of lang.filenamePatterns) { - mime.registerTextMime({ id: langId, mime: primaryMime, filepattern: filenamePattern }, this._warnOnOverwrite); - } - } - if (typeof lang.firstLine === 'string' && lang.firstLine.length > 0) { - let firstLineRegexStr = lang.firstLine; - if (firstLineRegexStr.charAt(0) !== '^') { - firstLineRegexStr = '^' + firstLineRegexStr; - } - try { - let firstLineRegex = new RegExp(firstLineRegexStr); - if (!strings.regExpLeadsToEndlessLoop(firstLineRegex)) { - mime.registerTextMime({ id: langId, mime: primaryMime, firstline: firstLineRegex }, this._warnOnOverwrite); - } - } - catch (err) { - // Most likely, the regex was bad - (0, errors_1.onUnexpectedError)(err); - } - } - resolvedLanguage.aliases.push(langId); - let langAliases = null; - if (typeof lang.aliases !== 'undefined' && Array.isArray(lang.aliases)) { - if (lang.aliases.length === 0) { - // signal that this language should not get a name - langAliases = [null]; - } - else { - langAliases = lang.aliases; - } - } - if (langAliases !== null) { - for (const langAlias of langAliases) { - if (!langAlias || langAlias.length === 0) { - continue; - } - resolvedLanguage.aliases.push(langAlias); - } - } - let containsAliases = (langAliases !== null && langAliases.length > 0); - if (containsAliases && langAliases[0] === null) { - // signal that this language should not get a name - } - else { - let bestName = (containsAliases ? langAliases[0] : null) || langId; - if (containsAliases || !resolvedLanguage.name) { - resolvedLanguage.name = bestName; - } - } - if (lang.configuration) { - resolvedLanguage.configurationFiles.push(lang.configuration); - } - } - isRegisteredMode(mimetypeOrModeId) { - // Is this a known mime type ? - if (hasOwnProperty.call(this._mimeTypesMap, mimetypeOrModeId)) { - return true; - } - // Is this a known mode id ? - return hasOwnProperty.call(this._languages, mimetypeOrModeId); - } - getModeIdForLanguageNameLowercase(languageNameLower) { - if (!hasOwnProperty.call(this._lowercaseNameMap, languageNameLower)) { - return null; - } - return this._lowercaseNameMap[languageNameLower].language; - } - extractModeIds(commaSeparatedMimetypesOrCommaSeparatedIds) { - if (!commaSeparatedMimetypesOrCommaSeparatedIds) { - return []; - } - return (commaSeparatedMimetypesOrCommaSeparatedIds. - split(','). - map((mimeTypeOrId) => mimeTypeOrId.trim()). - map((mimeTypeOrId) => { - if (hasOwnProperty.call(this._mimeTypesMap, mimeTypeOrId)) { - return this._mimeTypesMap[mimeTypeOrId].language; - } - return mimeTypeOrId; - }). - filter((modeId) => { - return hasOwnProperty.call(this._languages, modeId); - })); - } - getLanguageIdentifier(_modeId) { - if (_modeId === nullMode_1.NULL_MODE_ID || _modeId === 0 /* Null */) { - return nullMode_1.NULL_LANGUAGE_IDENTIFIER; - } - let modeId; - if (typeof _modeId === 'string') { - modeId = _modeId; - } - else { - modeId = this._languageIdToLanguage[_modeId]; - if (!modeId) { - return null; - } - } - if (!hasOwnProperty.call(this._languages, modeId)) { - return null; - } - return this._languages[modeId].identifier; - } - getModeIdsFromFilepathOrFirstLine(resource, firstLine) { - if (!resource && !firstLine) { - return []; - } - let mimeTypes = mime.guessMimeTypes(resource, firstLine); - return this.extractModeIds(mimeTypes.join(',')); - } - } - exports.LanguagesRegistry = LanguagesRegistry; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[581/*vs/editor/common/services/modeServiceImpl*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,381/*vs/editor/common/modes/abstractMode*/,77/*vs/editor/common/modes/nullMode*/,580/*vs/editor/common/services/languagesRegistry*/,19/*vs/base/common/arrays*/]), function (require, exports, event_1, lifecycle_1, abstractMode_1, nullMode_1, languagesRegistry_1, arrays_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ModeServiceImpl = void 0; - class LanguageSelection { - constructor(onLanguagesMaybeChanged, selector) { - this._selector = selector; - this.languageIdentifier = this._selector(); - let listener; - this._onDidChange = new event_1.Emitter({ - onFirstListenerAdd: () => { - listener = onLanguagesMaybeChanged(() => this._evaluate()); - }, - onLastListenerRemove: () => { - listener.dispose(); - } - }); - this.onDidChange = this._onDidChange.event; - } - _evaluate() { - let languageIdentifier = this._selector(); - if (languageIdentifier.id === this.languageIdentifier.id) { - // no change - return; - } - this.languageIdentifier = languageIdentifier; - this._onDidChange.fire(this.languageIdentifier); - } - } - class ModeServiceImpl extends lifecycle_1.Disposable { - constructor(warnOnOverwrite = false) { - super(); - this._onDidCreateMode = this._register(new event_1.Emitter()); - this.onDidCreateMode = this._onDidCreateMode.event; - this._onLanguagesMaybeChanged = this._register(new event_1.Emitter({ leakWarningThreshold: 200 /* https://github.com/microsoft/vscode/issues/119968 */ })); - this.onLanguagesMaybeChanged = this._onLanguagesMaybeChanged.event; - this._instantiatedModes = {}; - this._registry = this._register(new languagesRegistry_1.LanguagesRegistry(true, warnOnOverwrite)); - this._register(this._registry.onDidChange(() => this._onLanguagesMaybeChanged.fire())); - } - isRegisteredMode(mimetypeOrModeId) { - return this._registry.isRegisteredMode(mimetypeOrModeId); - } - getModeIdForLanguageName(alias) { - return this._registry.getModeIdForLanguageNameLowercase(alias); - } - getModeIdByFilepathOrFirstLine(resource, firstLine) { - const modeIds = this._registry.getModeIdsFromFilepathOrFirstLine(resource, firstLine); - return (0, arrays_1.firstOrDefault)(modeIds, null); - } - getModeId(commaSeparatedMimetypesOrCommaSeparatedIds) { - const modeIds = this._registry.extractModeIds(commaSeparatedMimetypesOrCommaSeparatedIds); - return (0, arrays_1.firstOrDefault)(modeIds, null); - } - getLanguageIdentifier(modeId) { - return this._registry.getLanguageIdentifier(modeId); - } - // --- instantiation - create(commaSeparatedMimetypesOrCommaSeparatedIds) { - return new LanguageSelection(this.onLanguagesMaybeChanged, () => { - const modeId = this.getModeId(commaSeparatedMimetypesOrCommaSeparatedIds); - return this._createModeAndGetLanguageIdentifier(modeId); - }); - } - createByFilepathOrFirstLine(resource, firstLine) { - return new LanguageSelection(this.onLanguagesMaybeChanged, () => { - const modeId = this.getModeIdByFilepathOrFirstLine(resource, firstLine); - return this._createModeAndGetLanguageIdentifier(modeId); - }); - } - _createModeAndGetLanguageIdentifier(modeId) { - // Fall back to plain text if no mode was found - const languageIdentifier = this.getLanguageIdentifier(modeId || 'plaintext') || nullMode_1.NULL_LANGUAGE_IDENTIFIER; - this._getOrCreateMode(languageIdentifier.language); - return languageIdentifier; - } - triggerMode(commaSeparatedMimetypesOrCommaSeparatedIds) { - const modeId = this.getModeId(commaSeparatedMimetypesOrCommaSeparatedIds); - // Fall back to plain text if no mode was found - this._getOrCreateMode(modeId || 'plaintext'); - } - _getOrCreateMode(modeId) { - if (!this._instantiatedModes.hasOwnProperty(modeId)) { - let languageIdentifier = this.getLanguageIdentifier(modeId) || nullMode_1.NULL_LANGUAGE_IDENTIFIER; - this._instantiatedModes[modeId] = new abstractMode_1.FrankensteinMode(languageIdentifier); - this._onDidCreateMode.fire(this._instantiatedModes[modeId]); - } - return this._instantiatedModes[modeId]; - } - } - exports.ModeServiceImpl = ModeServiceImpl; -}); - -define(__m[38/*vs/platform/configuration/common/configuration*/], __M([0/*require*/,1/*exports*/,32/*vs/platform/registry/common/platform*/,9/*vs/platform/instantiation/common/instantiation*/,98/*vs/platform/configuration/common/configurationRegistry*/]), function (require, exports, platform_1, instantiation_1, configurationRegistry_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getDefaultValues = exports.getConfigurationKeys = exports.getConfigurationValue = exports.removeFromValueTree = exports.addToValueTree = exports.toValuesTree = exports.IConfigurationService = void 0; - exports.IConfigurationService = (0, instantiation_1.createDecorator)('configurationService'); - function toValuesTree(properties, conflictReporter) { - const root = Object.create(null); - for (let key in properties) { - addToValueTree(root, key, properties[key], conflictReporter); - } - return root; - } - exports.toValuesTree = toValuesTree; - function addToValueTree(settingsTreeRoot, key, value, conflictReporter) { - const segments = key.split('.'); - const last = segments.pop(); - let curr = settingsTreeRoot; - for (let i = 0; i < segments.length; i++) { - let s = segments[i]; - let obj = curr[s]; - switch (typeof obj) { - case 'undefined': - obj = curr[s] = Object.create(null); - break; - case 'object': - break; - default: - conflictReporter(`Ignoring ${key} as ${segments.slice(0, i + 1).join('.')} is ${JSON.stringify(obj)}`); - return; - } - curr = obj; - } - if (typeof curr === 'object' && curr !== null) { - try { - curr[last] = value; // workaround https://github.com/microsoft/vscode/issues/13606 - } - catch (e) { - conflictReporter(`Ignoring ${key} as ${segments.join('.')} is ${JSON.stringify(curr)}`); - } - } - else { - conflictReporter(`Ignoring ${key} as ${segments.join('.')} is ${JSON.stringify(curr)}`); - } - } - exports.addToValueTree = addToValueTree; - function removeFromValueTree(valueTree, key) { - const segments = key.split('.'); - doRemoveFromValueTree(valueTree, segments); - } - exports.removeFromValueTree = removeFromValueTree; - function doRemoveFromValueTree(valueTree, segments) { - const first = segments.shift(); - if (segments.length === 0) { - // Reached last segment - delete valueTree[first]; - return; - } - if (Object.keys(valueTree).indexOf(first) !== -1) { - const value = valueTree[first]; - if (typeof value === 'object' && !Array.isArray(value)) { - doRemoveFromValueTree(value, segments); - if (Object.keys(value).length === 0) { - delete valueTree[first]; - } - } - } - } - /** - * A helper function to get the configuration value with a specific settings path (e.g. config.some.setting) - */ - function getConfigurationValue(config, settingPath, defaultValue) { - function accessSetting(config, path) { - let current = config; - for (const component of path) { - if (typeof current !== 'object' || current === null) { - return undefined; - } - current = current[component]; - } - return current; - } - const path = settingPath.split('.'); - const result = accessSetting(config, path); - return typeof result === 'undefined' ? defaultValue : result; - } - exports.getConfigurationValue = getConfigurationValue; - function getConfigurationKeys() { - const properties = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).getConfigurationProperties(); - return Object.keys(properties); - } - exports.getConfigurationKeys = getConfigurationKeys; - function getDefaultValues() { - const valueTreeRoot = Object.create(null); - const properties = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).getConfigurationProperties(); - for (let key in properties) { - let value = properties[key].default; - addToValueTree(valueTreeRoot, key, value, message => console.error(`Conflict in default settings: ${message}`)); - } - return valueTreeRoot; - } - exports.getDefaultValues = getDefaultValues; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - - - - - - - - - -define(__m[582/*vs/platform/accessibility/common/accessibilityService*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,64/*vs/platform/accessibility/common/accessibility*/,6/*vs/base/common/event*/,16/*vs/platform/contextkey/common/contextkey*/,38/*vs/platform/configuration/common/configuration*/]), function (require, exports, lifecycle_1, accessibility_1, event_1, contextkey_1, configuration_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.AccessibilityService = void 0; - let AccessibilityService = class AccessibilityService extends lifecycle_1.Disposable { - constructor(_contextKeyService, _configurationService) { - super(); - this._contextKeyService = _contextKeyService; - this._configurationService = _configurationService; - this._accessibilitySupport = 0 /* Unknown */; - this._onDidChangeScreenReaderOptimized = new event_1.Emitter(); - this._accessibilityModeEnabledContext = accessibility_1.CONTEXT_ACCESSIBILITY_MODE_ENABLED.bindTo(this._contextKeyService); - const updateContextKey = () => this._accessibilityModeEnabledContext.set(this.isScreenReaderOptimized()); - this._register(this._configurationService.onDidChangeConfiguration(e => { - if (e.affectsConfiguration('editor.accessibilitySupport')) { - updateContextKey(); - this._onDidChangeScreenReaderOptimized.fire(); - } - })); - updateContextKey(); - this.onDidChangeScreenReaderOptimized(() => updateContextKey()); - } - get onDidChangeScreenReaderOptimized() { - return this._onDidChangeScreenReaderOptimized.event; - } - isScreenReaderOptimized() { - const config = this._configurationService.getValue('editor.accessibilitySupport'); - return config === 'on' || (config === 'auto' && this._accessibilitySupport === 2 /* Enabled */); - } - getAccessibilitySupport() { - return this._accessibilitySupport; - } - }; - AccessibilityService = __decorate([ - __param(0, contextkey_1.IContextKeyService), - __param(1, configuration_1.IConfigurationService) - ], AccessibilityService); - exports.AccessibilityService = AccessibilityService; -}); - -define(__m[583/*vs/platform/configuration/common/configurationModels*/], __M([0/*require*/,1/*exports*/,49/*vs/base/common/map*/,19/*vs/base/common/arrays*/,20/*vs/base/common/types*/,42/*vs/base/common/objects*/,24/*vs/base/common/uri*/,98/*vs/platform/configuration/common/configurationRegistry*/,38/*vs/platform/configuration/common/configuration*/]), function (require, exports, map_1, arrays, types, objects, uri_1, configurationRegistry_1, configuration_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ConfigurationChangeEvent = exports.Configuration = exports.DefaultConfigurationModel = exports.ConfigurationModel = void 0; - class ConfigurationModel { - constructor(_contents = {}, _keys = [], _overrides = []) { - this._contents = _contents; - this._keys = _keys; - this._overrides = _overrides; - this.isFrozen = false; - } - get contents() { - return this.checkAndFreeze(this._contents); - } - get overrides() { - return this.checkAndFreeze(this._overrides); - } - get keys() { - return this.checkAndFreeze(this._keys); - } - isEmpty() { - return this._keys.length === 0 && Object.keys(this._contents).length === 0 && this._overrides.length === 0; - } - getValue(section) { - return section ? (0, configuration_1.getConfigurationValue)(this.contents, section) : this.contents; - } - override(identifier) { - const overrideContents = this.getContentsForOverrideIdentifer(identifier); - if (!overrideContents || typeof overrideContents !== 'object' || !Object.keys(overrideContents).length) { - // If there are no valid overrides, return self - return this; - } - let contents = {}; - for (const key of arrays.distinct([...Object.keys(this.contents), ...Object.keys(overrideContents)])) { - let contentsForKey = this.contents[key]; - let overrideContentsForKey = overrideContents[key]; - // If there are override contents for the key, clone and merge otherwise use base contents - if (overrideContentsForKey) { - // Clone and merge only if base contents and override contents are of type object otherwise just override - if (typeof contentsForKey === 'object' && typeof overrideContentsForKey === 'object') { - contentsForKey = objects.deepClone(contentsForKey); - this.mergeContents(contentsForKey, overrideContentsForKey); - } - else { - contentsForKey = overrideContentsForKey; - } - } - contents[key] = contentsForKey; - } - return new ConfigurationModel(contents, this.keys, this.overrides); - } - merge(...others) { - const contents = objects.deepClone(this.contents); - const overrides = objects.deepClone(this.overrides); - const keys = [...this.keys]; - for (const other of others) { - this.mergeContents(contents, other.contents); - for (const otherOverride of other.overrides) { - const [override] = overrides.filter(o => arrays.equals(o.identifiers, otherOverride.identifiers)); - if (override) { - this.mergeContents(override.contents, otherOverride.contents); - } - else { - overrides.push(objects.deepClone(otherOverride)); - } - } - for (const key of other.keys) { - if (keys.indexOf(key) === -1) { - keys.push(key); - } - } - } - return new ConfigurationModel(contents, keys, overrides); - } - freeze() { - this.isFrozen = true; - return this; - } - mergeContents(source, target) { - for (const key of Object.keys(target)) { - if (key in source) { - if (types.isObject(source[key]) && types.isObject(target[key])) { - this.mergeContents(source[key], target[key]); - continue; - } - } - source[key] = objects.deepClone(target[key]); - } - } - checkAndFreeze(data) { - if (this.isFrozen && !Object.isFrozen(data)) { - return objects.deepFreeze(data); - } - return data; - } - getContentsForOverrideIdentifer(identifier) { - for (const override of this.overrides) { - if (override.identifiers.indexOf(identifier) !== -1) { - return override.contents; - } - } - return null; - } - toJSON() { - return { - contents: this.contents, - overrides: this.overrides, - keys: this.keys - }; - } - // Update methods - setValue(key, value) { - this.addKey(key); - (0, configuration_1.addToValueTree)(this.contents, key, value, e => { throw new Error(e); }); - } - removeValue(key) { - if (this.removeKey(key)) { - (0, configuration_1.removeFromValueTree)(this.contents, key); - } - } - addKey(key) { - let index = this.keys.length; - for (let i = 0; i < index; i++) { - if (key.indexOf(this.keys[i]) === 0) { - index = i; - } - } - this.keys.splice(index, 1, key); - } - removeKey(key) { - let index = this.keys.indexOf(key); - if (index !== -1) { - this.keys.splice(index, 1); - return true; - } - return false; - } - } - exports.ConfigurationModel = ConfigurationModel; - class DefaultConfigurationModel extends ConfigurationModel { - constructor() { - const contents = (0, configuration_1.getDefaultValues)(); - const keys = (0, configuration_1.getConfigurationKeys)(); - const overrides = []; - for (const key of Object.keys(contents)) { - if (configurationRegistry_1.OVERRIDE_PROPERTY_PATTERN.test(key)) { - overrides.push({ - identifiers: [(0, configurationRegistry_1.overrideIdentifierFromKey)(key).trim()], - keys: Object.keys(contents[key]), - contents: (0, configuration_1.toValuesTree)(contents[key], message => console.error(`Conflict in default settings file: ${message}`)), - }); - } - } - super(contents, keys, overrides); - } - } - exports.DefaultConfigurationModel = DefaultConfigurationModel; - class Configuration { - constructor(_defaultConfiguration, _localUserConfiguration, _remoteUserConfiguration = new ConfigurationModel(), _workspaceConfiguration = new ConfigurationModel(), _folderConfigurations = new map_1.ResourceMap(), _memoryConfiguration = new ConfigurationModel(), _memoryConfigurationByResource = new map_1.ResourceMap(), _freeze = true) { - this._defaultConfiguration = _defaultConfiguration; - this._localUserConfiguration = _localUserConfiguration; - this._remoteUserConfiguration = _remoteUserConfiguration; - this._workspaceConfiguration = _workspaceConfiguration; - this._folderConfigurations = _folderConfigurations; - this._memoryConfiguration = _memoryConfiguration; - this._memoryConfigurationByResource = _memoryConfigurationByResource; - this._freeze = _freeze; - this._workspaceConsolidatedConfiguration = null; - this._foldersConsolidatedConfigurations = new map_1.ResourceMap(); - this._userConfiguration = null; - } - getValue(section, overrides, workspace) { - const consolidateConfigurationModel = this.getConsolidateConfigurationModel(overrides, workspace); - return consolidateConfigurationModel.getValue(section); - } - updateValue(key, value, overrides = {}) { - let memoryConfiguration; - if (overrides.resource) { - memoryConfiguration = this._memoryConfigurationByResource.get(overrides.resource); - if (!memoryConfiguration) { - memoryConfiguration = new ConfigurationModel(); - this._memoryConfigurationByResource.set(overrides.resource, memoryConfiguration); - } - } - else { - memoryConfiguration = this._memoryConfiguration; - } - if (value === undefined) { - memoryConfiguration.removeValue(key); - } - else { - memoryConfiguration.setValue(key, value); - } - if (!overrides.resource) { - this._workspaceConsolidatedConfiguration = null; - } - } - get userConfiguration() { - if (!this._userConfiguration) { - this._userConfiguration = this._remoteUserConfiguration.isEmpty() ? this._localUserConfiguration : this._localUserConfiguration.merge(this._remoteUserConfiguration); - if (this._freeze) { - this._userConfiguration.freeze(); - } - } - return this._userConfiguration; - } - getConsolidateConfigurationModel(overrides, workspace) { - let configurationModel = this.getConsolidatedConfigurationModelForResource(overrides, workspace); - return overrides.overrideIdentifier ? configurationModel.override(overrides.overrideIdentifier) : configurationModel; - } - getConsolidatedConfigurationModelForResource({ resource }, workspace) { - let consolidateConfiguration = this.getWorkspaceConsolidatedConfiguration(); - if (workspace && resource) { - const root = workspace.getFolder(resource); - if (root) { - consolidateConfiguration = this.getFolderConsolidatedConfiguration(root.uri) || consolidateConfiguration; - } - const memoryConfigurationForResource = this._memoryConfigurationByResource.get(resource); - if (memoryConfigurationForResource) { - consolidateConfiguration = consolidateConfiguration.merge(memoryConfigurationForResource); - } - } - return consolidateConfiguration; - } - getWorkspaceConsolidatedConfiguration() { - if (!this._workspaceConsolidatedConfiguration) { - this._workspaceConsolidatedConfiguration = this._defaultConfiguration.merge(this.userConfiguration, this._workspaceConfiguration, this._memoryConfiguration); - if (this._freeze) { - this._workspaceConfiguration = this._workspaceConfiguration.freeze(); - } - } - return this._workspaceConsolidatedConfiguration; - } - getFolderConsolidatedConfiguration(folder) { - let folderConsolidatedConfiguration = this._foldersConsolidatedConfigurations.get(folder); - if (!folderConsolidatedConfiguration) { - const workspaceConsolidateConfiguration = this.getWorkspaceConsolidatedConfiguration(); - const folderConfiguration = this._folderConfigurations.get(folder); - if (folderConfiguration) { - folderConsolidatedConfiguration = workspaceConsolidateConfiguration.merge(folderConfiguration); - if (this._freeze) { - folderConsolidatedConfiguration = folderConsolidatedConfiguration.freeze(); - } - this._foldersConsolidatedConfigurations.set(folder, folderConsolidatedConfiguration); - } - else { - folderConsolidatedConfiguration = workspaceConsolidateConfiguration; - } - } - return folderConsolidatedConfiguration; - } - toData() { - return { - defaults: { - contents: this._defaultConfiguration.contents, - overrides: this._defaultConfiguration.overrides, - keys: this._defaultConfiguration.keys - }, - user: { - contents: this.userConfiguration.contents, - overrides: this.userConfiguration.overrides, - keys: this.userConfiguration.keys - }, - workspace: { - contents: this._workspaceConfiguration.contents, - overrides: this._workspaceConfiguration.overrides, - keys: this._workspaceConfiguration.keys - }, - folders: [...this._folderConfigurations.keys()].reduce((result, folder) => { - const { contents, overrides, keys } = this._folderConfigurations.get(folder); - result.push([folder, { contents, overrides, keys }]); - return result; - }, []) - }; - } - static parse(data) { - const defaultConfiguration = this.parseConfigurationModel(data.defaults); - const userConfiguration = this.parseConfigurationModel(data.user); - const workspaceConfiguration = this.parseConfigurationModel(data.workspace); - const folders = data.folders.reduce((result, value) => { - result.set(uri_1.URI.revive(value[0]), this.parseConfigurationModel(value[1])); - return result; - }, new map_1.ResourceMap()); - return new Configuration(defaultConfiguration, userConfiguration, new ConfigurationModel(), workspaceConfiguration, folders, new ConfigurationModel(), new map_1.ResourceMap(), false); - } - static parseConfigurationModel(model) { - return new ConfigurationModel(model.contents, model.keys, model.overrides).freeze(); - } - } - exports.Configuration = Configuration; - class ConfigurationChangeEvent { - constructor(change, previous, currentConfiguraiton, currentWorkspace) { - this.change = change; - this.previous = previous; - this.currentConfiguraiton = currentConfiguraiton; - this.currentWorkspace = currentWorkspace; - this._previousConfiguration = undefined; - const keysSet = new Set(); - change.keys.forEach(key => keysSet.add(key)); - change.overrides.forEach(([, keys]) => keys.forEach(key => keysSet.add(key))); - this.affectedKeys = [...keysSet.values()]; - const configurationModel = new ConfigurationModel(); - this.affectedKeys.forEach(key => configurationModel.setValue(key, {})); - this.affectedKeysTree = configurationModel.contents; - } - get previousConfiguration() { - if (!this._previousConfiguration && this.previous) { - this._previousConfiguration = Configuration.parse(this.previous.data); - } - return this._previousConfiguration; - } - affectsConfiguration(section, overrides) { - var _a; - if (this.doesAffectedKeysTreeContains(this.affectedKeysTree, section)) { - if (overrides) { - const value1 = this.previousConfiguration ? this.previousConfiguration.getValue(section, overrides, (_a = this.previous) === null || _a === void 0 ? void 0 : _a.workspace) : undefined; - const value2 = this.currentConfiguraiton.getValue(section, overrides, this.currentWorkspace); - return !objects.equals(value1, value2); - } - return true; - } - return false; - } - doesAffectedKeysTreeContains(affectedKeysTree, section) { - let requestedTree = (0, configuration_1.toValuesTree)({ [section]: true }, () => { }); - let key; - while (typeof requestedTree === 'object' && (key = Object.keys(requestedTree)[0])) { // Only one key should present, since we added only one property - affectedKeysTree = affectedKeysTree[key]; - if (!affectedKeysTree) { - return false; // Requested tree is not found - } - requestedTree = requestedTree[key]; - } - return true; - } - } - exports.ConfigurationChangeEvent = ConfigurationChangeEvent; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - - - - - - - - - -define(__m[584/*vs/platform/contextkey/browser/contextKeyService*/], __M([0/*require*/,1/*exports*/,6/*vs/base/common/event*/,54/*vs/base/common/iterator*/,2/*vs/base/common/lifecycle*/,49/*vs/base/common/map*/,534/*vs/nls!vs/platform/contextkey/browser/contextKeyService*/,26/*vs/platform/commands/common/commands*/,38/*vs/platform/configuration/common/configuration*/,16/*vs/platform/contextkey/common/contextkey*/,254/*vs/platform/keybinding/common/keybindingResolver*/]), function (require, exports, event_1, iterator_1, lifecycle_1, map_1, nls_1, commands_1, configuration_1, contextkey_1, keybindingResolver_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ContextKeyService = exports.AbstractContextKeyService = exports.Context = void 0; - const KEYBINDING_CONTEXT_ATTR = 'data-keybinding-context'; - class Context { - constructor(id, parent) { - this._id = id; - this._parent = parent; - this._value = Object.create(null); - this._value['_contextId'] = id; - } - setValue(key, value) { - // console.log('SET ' + key + ' = ' + value + ' ON ' + this._id); - if (this._value[key] !== value) { - this._value[key] = value; - return true; - } - return false; - } - removeValue(key) { - // console.log('REMOVE ' + key + ' FROM ' + this._id); - if (key in this._value) { - delete this._value[key]; - return true; - } - return false; - } - getValue(key) { - const ret = this._value[key]; - if (typeof ret === 'undefined' && this._parent) { - return this._parent.getValue(key); - } - return ret; - } - } - exports.Context = Context; - class NullContext extends Context { - constructor() { - super(-1, null); - } - setValue(key, value) { - return false; - } - removeValue(key) { - return false; - } - getValue(key) { - return undefined; - } - } - NullContext.INSTANCE = new NullContext(); - class ConfigAwareContextValuesContainer extends Context { - constructor(id, _configurationService, emitter) { - super(id, null); - this._configurationService = _configurationService; - this._values = map_1.TernarySearchTree.forConfigKeys(); - this._listener = this._configurationService.onDidChangeConfiguration(event => { - if (event.source === 6 /* DEFAULT */) { - // new setting, reset everything - const allKeys = Array.from(iterator_1.Iterable.map(this._values, ([k]) => k)); - this._values.clear(); - emitter.fire(new ArrayContextKeyChangeEvent(allKeys)); - } - else { - const changedKeys = []; - for (const configKey of event.affectedKeys) { - const contextKey = `config.${configKey}`; - const cachedItems = this._values.findSuperstr(contextKey); - if (cachedItems !== undefined) { - changedKeys.push(...iterator_1.Iterable.map(cachedItems, ([key]) => key)); - this._values.deleteSuperstr(contextKey); - } - if (this._values.has(contextKey)) { - changedKeys.push(contextKey); - this._values.delete(contextKey); - } - } - emitter.fire(new ArrayContextKeyChangeEvent(changedKeys)); - } - }); - } - dispose() { - this._listener.dispose(); - } - getValue(key) { - if (key.indexOf(ConfigAwareContextValuesContainer._keyPrefix) !== 0) { - return super.getValue(key); - } - if (this._values.has(key)) { - return this._values.get(key); - } - const configKey = key.substr(ConfigAwareContextValuesContainer._keyPrefix.length); - const configValue = this._configurationService.getValue(configKey); - let value = undefined; - switch (typeof configValue) { - case 'number': - case 'boolean': - case 'string': - value = configValue; - break; - default: - if (Array.isArray(configValue)) { - value = JSON.stringify(configValue); - } - else { - value = configValue; - } - } - this._values.set(key, value); - return value; - } - setValue(key, value) { - return super.setValue(key, value); - } - removeValue(key) { - return super.removeValue(key); - } - } - ConfigAwareContextValuesContainer._keyPrefix = 'config.'; - class ContextKey { - constructor(service, key, defaultValue) { - this._service = service; - this._key = key; - this._defaultValue = defaultValue; - this.reset(); - } - set(value) { - this._service.setContext(this._key, value); - } - reset() { - if (typeof this._defaultValue === 'undefined') { - this._service.removeContext(this._key); - } - else { - this._service.setContext(this._key, this._defaultValue); - } - } - get() { - return this._service.getContextKeyValue(this._key); - } - } - class SimpleContextKeyChangeEvent { - constructor(key) { - this.key = key; - } - affectsSome(keys) { - return keys.has(this.key); - } - } - class ArrayContextKeyChangeEvent { - constructor(keys) { - this.keys = keys; - } - affectsSome(keys) { - for (const key of this.keys) { - if (keys.has(key)) { - return true; - } - } - return false; - } - } - class CompositeContextKeyChangeEvent { - constructor(events) { - this.events = events; - } - affectsSome(keys) { - for (const e of this.events) { - if (e.affectsSome(keys)) { - return true; - } - } - return false; - } - } - class AbstractContextKeyService { - constructor(myContextId) { - this._onDidChangeContext = new event_1.PauseableEmitter({ merge: input => new CompositeContextKeyChangeEvent(input) }); - this.onDidChangeContext = this._onDidChangeContext.event; - this._isDisposed = false; - this._myContextId = myContextId; - } - createKey(key, defaultValue) { - if (this._isDisposed) { - throw new Error(`AbstractContextKeyService has been disposed`); - } - return new ContextKey(this, key, defaultValue); - } - bufferChangeEvents(callback) { - this._onDidChangeContext.pause(); - try { - callback(); - } - finally { - this._onDidChangeContext.resume(); - } - } - createScoped(domNode) { - if (this._isDisposed) { - throw new Error(`AbstractContextKeyService has been disposed`); - } - return new ScopedContextKeyService(this, domNode); - } - contextMatchesRules(rules) { - if (this._isDisposed) { - throw new Error(`AbstractContextKeyService has been disposed`); - } - const context = this.getContextValuesContainer(this._myContextId); - const result = keybindingResolver_1.KeybindingResolver.contextMatchesRules(context, rules); - // console.group(rules.serialize() + ' -> ' + result); - // rules.keys().forEach(key => { console.log(key, ctx[key]); }); - // console.groupEnd(); - return result; - } - getContextKeyValue(key) { - if (this._isDisposed) { - return undefined; - } - return this.getContextValuesContainer(this._myContextId).getValue(key); - } - setContext(key, value) { - if (this._isDisposed) { - return; - } - const myContext = this.getContextValuesContainer(this._myContextId); - if (!myContext) { - return; - } - if (myContext.setValue(key, value)) { - this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key)); - } - } - removeContext(key) { - if (this._isDisposed) { - return; - } - if (this.getContextValuesContainer(this._myContextId).removeValue(key)) { - this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key)); - } - } - getContext(target) { - if (this._isDisposed) { - return NullContext.INSTANCE; - } - return this.getContextValuesContainer(findContextAttr(target)); - } - } - exports.AbstractContextKeyService = AbstractContextKeyService; - let ContextKeyService = class ContextKeyService extends AbstractContextKeyService { - constructor(configurationService) { - super(0); - this._contexts = new Map(); - this._toDispose = new lifecycle_1.DisposableStore(); - this._lastContextId = 0; - const myContext = new ConfigAwareContextValuesContainer(this._myContextId, configurationService, this._onDidChangeContext); - this._contexts.set(this._myContextId, myContext); - this._toDispose.add(myContext); - // Uncomment this to see the contexts continuously logged - // let lastLoggedValue: string | null = null; - // setInterval(() => { - // let values = Object.keys(this._contexts).map((key) => this._contexts[key]); - // let logValue = values.map(v => JSON.stringify(v._value, null, '\t')).join('\n'); - // if (lastLoggedValue !== logValue) { - // lastLoggedValue = logValue; - // console.log(lastLoggedValue); - // } - // }, 2000); - } - dispose() { - this._onDidChangeContext.dispose(); - this._isDisposed = true; - this._toDispose.dispose(); - } - getContextValuesContainer(contextId) { - if (this._isDisposed) { - return NullContext.INSTANCE; - } - return this._contexts.get(contextId) || NullContext.INSTANCE; - } - createChildContext(parentContextId = this._myContextId) { - if (this._isDisposed) { - throw new Error(`ContextKeyService has been disposed`); - } - let id = (++this._lastContextId); - this._contexts.set(id, new Context(id, this.getContextValuesContainer(parentContextId))); - return id; - } - disposeContext(contextId) { - if (!this._isDisposed) { - this._contexts.delete(contextId); - } - } - }; - ContextKeyService = __decorate([ - __param(0, configuration_1.IConfigurationService) - ], ContextKeyService); - exports.ContextKeyService = ContextKeyService; - class ScopedContextKeyService extends AbstractContextKeyService { - constructor(parent, domNode) { - super(parent.createChildContext()); - this._parentChangeListener = new lifecycle_1.MutableDisposable(); - this._parent = parent; - this._updateParentChangeListener(); - this._domNode = domNode; - if (this._domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) { - let extraInfo = ''; - if (this._domNode.classList) { - extraInfo = Array.from(this._domNode.classList.values()).join(', '); - } - console.error(`Element already has context attribute${extraInfo ? ': ' + extraInfo : ''}`); - } - this._domNode.setAttribute(KEYBINDING_CONTEXT_ATTR, String(this._myContextId)); - } - _updateParentChangeListener() { - // Forward parent events to this listener. Parent will change. - this._parentChangeListener.value = this._parent.onDidChangeContext(this._onDidChangeContext.fire, this._onDidChangeContext); - } - dispose() { - if (this._isDisposed) { - return; - } - this._onDidChangeContext.dispose(); - this._parent.disposeContext(this._myContextId); - this._parentChangeListener.dispose(); - this._domNode.removeAttribute(KEYBINDING_CONTEXT_ATTR); - this._isDisposed = true; - } - getContextValuesContainer(contextId) { - if (this._isDisposed) { - return NullContext.INSTANCE; - } - return this._parent.getContextValuesContainer(contextId); - } - createChildContext(parentContextId = this._myContextId) { - if (this._isDisposed) { - throw new Error(`ScopedContextKeyService has been disposed`); - } - return this._parent.createChildContext(parentContextId); - } - disposeContext(contextId) { - if (this._isDisposed) { - return; - } - this._parent.disposeContext(contextId); - } - } - function findContextAttr(domNode) { - while (domNode) { - if (domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) { - const attr = domNode.getAttribute(KEYBINDING_CONTEXT_ATTR); - if (attr) { - return parseInt(attr, 10); - } - return NaN; - } - domNode = domNode.parentElement; - } - return 0; - } - commands_1.CommandsRegistry.registerCommand(contextkey_1.SET_CONTEXT_COMMAND_ID, function (accessor, contextKey, contextValue) { - accessor.get(contextkey_1.IContextKeyService).createKey(String(contextKey), contextValue); - }); - commands_1.CommandsRegistry.registerCommand({ - id: 'getContextKeyInfo', - handler() { - return [...contextkey_1.RawContextKey.all()].sort((a, b) => a.key.localeCompare(b.key)); - }, - description: { - description: (0, nls_1.localize)(0, null), - args: [] - } - }); - commands_1.CommandsRegistry.registerCommand('_generateContextKeyInfo', function () { - const result = []; - const seen = new Set(); - for (let info of contextkey_1.RawContextKey.all()) { - if (!seen.has(info.key)) { - seen.add(info.key); - result.push(info); - } - } - result.sort((a, b) => a.key.localeCompare(b.key)); - console.log(JSON.stringify(result, undefined, 2)); - }); -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[88/*vs/platform/keybinding/common/keybindingsRegistry*/], __M([0/*require*/,1/*exports*/,41/*vs/base/common/keyCodes*/,17/*vs/base/common/platform*/,26/*vs/platform/commands/common/commands*/,32/*vs/platform/registry/common/platform*/]), function (require, exports, keyCodes_1, platform_1, commands_1, platform_2) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Extensions = exports.KeybindingsRegistry = void 0; - class KeybindingsRegistryImpl { - constructor() { - this._coreKeybindings = []; - this._extensionKeybindings = []; - this._cachedMergedKeybindings = null; - } - /** - * Take current platform into account and reduce to primary & secondary. - */ - static bindToCurrentPlatform(kb) { - if (platform_1.OS === 1 /* Windows */) { - if (kb && kb.win) { - return kb.win; - } - } - else if (platform_1.OS === 2 /* Macintosh */) { - if (kb && kb.mac) { - return kb.mac; - } - } - else { - if (kb && kb.linux) { - return kb.linux; - } - } - return kb; - } - registerKeybindingRule(rule) { - const actualKb = KeybindingsRegistryImpl.bindToCurrentPlatform(rule); - if (actualKb && actualKb.primary) { - const kk = (0, keyCodes_1.createKeybinding)(actualKb.primary, platform_1.OS); - if (kk) { - this._registerDefaultKeybinding(kk, rule.id, rule.args, rule.weight, 0, rule.when); - } - } - if (actualKb && Array.isArray(actualKb.secondary)) { - for (let i = 0, len = actualKb.secondary.length; i < len; i++) { - const k = actualKb.secondary[i]; - const kk = (0, keyCodes_1.createKeybinding)(k, platform_1.OS); - if (kk) { - this._registerDefaultKeybinding(kk, rule.id, rule.args, rule.weight, -i - 1, rule.when); - } - } - } - } - registerCommandAndKeybindingRule(desc) { - this.registerKeybindingRule(desc); - commands_1.CommandsRegistry.registerCommand(desc); - } - static _mightProduceChar(keyCode) { - if (keyCode >= 21 /* KEY_0 */ && keyCode <= 30 /* KEY_9 */) { - return true; - } - if (keyCode >= 31 /* KEY_A */ && keyCode <= 56 /* KEY_Z */) { - return true; - } - return (keyCode === 80 /* US_SEMICOLON */ - || keyCode === 81 /* US_EQUAL */ - || keyCode === 82 /* US_COMMA */ - || keyCode === 83 /* US_MINUS */ - || keyCode === 84 /* US_DOT */ - || keyCode === 85 /* US_SLASH */ - || keyCode === 86 /* US_BACKTICK */ - || keyCode === 110 /* ABNT_C1 */ - || keyCode === 111 /* ABNT_C2 */ - || keyCode === 87 /* US_OPEN_SQUARE_BRACKET */ - || keyCode === 88 /* US_BACKSLASH */ - || keyCode === 89 /* US_CLOSE_SQUARE_BRACKET */ - || keyCode === 90 /* US_QUOTE */ - || keyCode === 91 /* OEM_8 */ - || keyCode === 92 /* OEM_102 */); - } - _assertNoCtrlAlt(keybinding, commandId) { - if (keybinding.ctrlKey && keybinding.altKey && !keybinding.metaKey) { - if (KeybindingsRegistryImpl._mightProduceChar(keybinding.keyCode)) { - console.warn('Ctrl+Alt+ keybindings should not be used by default under Windows. Offender: ', keybinding, ' for ', commandId); - } - } - } - _registerDefaultKeybinding(keybinding, commandId, commandArgs, weight1, weight2, when) { - if (platform_1.OS === 1 /* Windows */) { - this._assertNoCtrlAlt(keybinding.parts[0], commandId); - } - this._coreKeybindings.push({ - keybinding: keybinding, - command: commandId, - commandArgs: commandArgs, - when: when, - weight1: weight1, - weight2: weight2, - extensionId: null, - isBuiltinExtension: false - }); - this._cachedMergedKeybindings = null; - } - getDefaultKeybindings() { - if (!this._cachedMergedKeybindings) { - this._cachedMergedKeybindings = [].concat(this._coreKeybindings).concat(this._extensionKeybindings); - this._cachedMergedKeybindings.sort(sorter); - } - return this._cachedMergedKeybindings.slice(0); - } - } - exports.KeybindingsRegistry = new KeybindingsRegistryImpl(); - // Define extension point ids - exports.Extensions = { - EditorModes: 'platform.keybindingsRegistry' - }; - platform_2.Registry.add(exports.Extensions.EditorModes, exports.KeybindingsRegistry); - function sorter(a, b) { - if (a.weight1 !== b.weight1) { - return a.weight1 - b.weight1; - } - if (a.command < b.command) { - return -1; - } - if (a.command > b.command) { - return 1; - } - return a.weight2 - b.weight2; - } -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - - - - - - - - - -define(__m[585/*vs/platform/browser/contextScopedHistoryWidget*/], __M([0/*require*/,1/*exports*/,16/*vs/platform/contextkey/common/contextkey*/,442/*vs/base/browser/ui/findinput/findInput*/,88/*vs/platform/keybinding/common/keybindingsRegistry*/,443/*vs/base/browser/ui/findinput/replaceInput*/]), function (require, exports, contextkey_1, findInput_1, keybindingsRegistry_1, replaceInput_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ContextScopedReplaceInput = exports.ContextScopedFindInput = exports.createAndBindHistoryNavigationWidgetScopedContextKeyService = exports.HistoryNavigationEnablementContext = exports.HistoryNavigationWidgetContext = void 0; - exports.HistoryNavigationWidgetContext = 'historyNavigationWidget'; - exports.HistoryNavigationEnablementContext = 'historyNavigationEnabled'; - function bindContextScopedWidget(contextKeyService, widget, contextKey) { - new contextkey_1.RawContextKey(contextKey, widget).bindTo(contextKeyService); - } - function createWidgetScopedContextKeyService(contextKeyService, widget) { - return contextKeyService.createScoped(widget.target); - } - function getContextScopedWidget(contextKeyService, contextKey) { - return contextKeyService.getContext(document.activeElement).getValue(contextKey); - } - function createAndBindHistoryNavigationWidgetScopedContextKeyService(contextKeyService, widget) { - const scopedContextKeyService = createWidgetScopedContextKeyService(contextKeyService, widget); - bindContextScopedWidget(scopedContextKeyService, widget, exports.HistoryNavigationWidgetContext); - const historyNavigationEnablement = new contextkey_1.RawContextKey(exports.HistoryNavigationEnablementContext, true).bindTo(scopedContextKeyService); - return { scopedContextKeyService, historyNavigationEnablement }; - } - exports.createAndBindHistoryNavigationWidgetScopedContextKeyService = createAndBindHistoryNavigationWidgetScopedContextKeyService; - let ContextScopedFindInput = class ContextScopedFindInput extends findInput_1.FindInput { - constructor(container, contextViewProvider, options, contextKeyService, showFindOptions = false) { - super(container, contextViewProvider, showFindOptions, options); - this._register(createAndBindHistoryNavigationWidgetScopedContextKeyService(contextKeyService, { target: this.inputBox.element, historyNavigator: this.inputBox }).scopedContextKeyService); - } - }; - ContextScopedFindInput = __decorate([ - __param(3, contextkey_1.IContextKeyService) - ], ContextScopedFindInput); - exports.ContextScopedFindInput = ContextScopedFindInput; - let ContextScopedReplaceInput = class ContextScopedReplaceInput extends replaceInput_1.ReplaceInput { - constructor(container, contextViewProvider, options, contextKeyService, showReplaceOptions = false) { - super(container, contextViewProvider, showReplaceOptions, options); - this._register(createAndBindHistoryNavigationWidgetScopedContextKeyService(contextKeyService, { target: this.inputBox.element, historyNavigator: this.inputBox }).scopedContextKeyService); - } - }; - ContextScopedReplaceInput = __decorate([ - __param(3, contextkey_1.IContextKeyService) - ], ContextScopedReplaceInput); - exports.ContextScopedReplaceInput = ContextScopedReplaceInput; - keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({ - id: 'history.showPrevious', - weight: 200 /* WorkbenchContrib */, - when: contextkey_1.ContextKeyExpr.and(contextkey_1.ContextKeyExpr.has(exports.HistoryNavigationWidgetContext), contextkey_1.ContextKeyExpr.equals(exports.HistoryNavigationEnablementContext, true)), - primary: 16 /* UpArrow */, - secondary: [512 /* Alt */ | 16 /* UpArrow */], - handler: (accessor, arg2) => { - const widget = getContextScopedWidget(accessor.get(contextkey_1.IContextKeyService), exports.HistoryNavigationWidgetContext); - if (widget) { - const historyInputBox = widget.historyNavigator; - historyInputBox.showPreviousValue(); - } - } - }); - keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({ - id: 'history.showNext', - weight: 200 /* WorkbenchContrib */, - when: contextkey_1.ContextKeyExpr.and(contextkey_1.ContextKeyExpr.has(exports.HistoryNavigationWidgetContext), contextkey_1.ContextKeyExpr.equals(exports.HistoryNavigationEnablementContext, true)), - primary: 18 /* DownArrow */, - secondary: [512 /* Alt */ | 18 /* DownArrow */], - handler: (accessor, arg2) => { - const widget = getContextScopedWidget(accessor.get(contextkey_1.IContextKeyService), exports.HistoryNavigationWidgetContext); - if (widget) { - const historyInputBox = widget.historyNavigator; - historyInputBox.showNextValue(); - } - } - }); -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[99/*vs/platform/quickinput/common/quickAccess*/], __M([0/*require*/,1/*exports*/,32/*vs/platform/registry/common/platform*/,19/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/]), function (require, exports, platform_1, arrays_1, lifecycle_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.QuickAccessRegistry = exports.Extensions = exports.DefaultQuickAccessFilterValue = void 0; - var DefaultQuickAccessFilterValue; - (function (DefaultQuickAccessFilterValue) { - /** - * Keep the value as it is given to quick access. - */ - DefaultQuickAccessFilterValue[DefaultQuickAccessFilterValue["PRESERVE"] = 0] = "PRESERVE"; - /** - * Use the value that was used last time something was accepted from the picker. - */ - DefaultQuickAccessFilterValue[DefaultQuickAccessFilterValue["LAST"] = 1] = "LAST"; - })(DefaultQuickAccessFilterValue = exports.DefaultQuickAccessFilterValue || (exports.DefaultQuickAccessFilterValue = {})); - exports.Extensions = { - Quickaccess: 'workbench.contributions.quickaccess' - }; - class QuickAccessRegistry { - constructor() { - this.providers = []; - this.defaultProvider = undefined; - } - registerQuickAccessProvider(provider) { - // Extract the default provider when no prefix is present - if (provider.prefix.length === 0) { - this.defaultProvider = provider; - } - else { - this.providers.push(provider); - } - // sort the providers by decreasing prefix length, such that longer - // prefixes take priority: 'ext' vs 'ext install' - the latter should win - this.providers.sort((providerA, providerB) => providerB.prefix.length - providerA.prefix.length); - return (0, lifecycle_1.toDisposable)(() => { - this.providers.splice(this.providers.indexOf(provider), 1); - if (this.defaultProvider === provider) { - this.defaultProvider = undefined; - } - }); - } - getQuickAccessProviders() { - return (0, arrays_1.coalesce)([this.defaultProvider, ...this.providers]); - } - getQuickAccessProvider(prefix) { - const result = prefix ? (this.providers.find(provider => prefix.startsWith(provider.prefix)) || undefined) : undefined; - return result || this.defaultProvider; - } - } - exports.QuickAccessRegistry = QuickAccessRegistry; - platform_1.Registry.add(exports.Extensions.Quickaccess, new QuickAccessRegistry()); -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - - - - - - - - - -define(__m[586/*vs/platform/quickinput/browser/helpQuickAccess*/], __M([0/*require*/,1/*exports*/,78/*vs/platform/quickinput/common/quickInput*/,99/*vs/platform/quickinput/common/quickAccess*/,32/*vs/platform/registry/common/platform*/,540/*vs/nls!vs/platform/quickinput/browser/helpQuickAccess*/,2/*vs/base/common/lifecycle*/]), function (require, exports, quickInput_1, quickAccess_1, platform_1, nls_1, lifecycle_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.HelpQuickAccessProvider = void 0; - let HelpQuickAccessProvider = class HelpQuickAccessProvider { - constructor(quickInputService) { - this.quickInputService = quickInputService; - this.registry = platform_1.Registry.as(quickAccess_1.Extensions.Quickaccess); - } - provide(picker) { - const disposables = new lifecycle_1.DisposableStore(); - // Open a picker with the selected value if picked - disposables.add(picker.onDidAccept(() => { - const [item] = picker.selectedItems; - if (item) { - this.quickInputService.quickAccess.show(item.prefix, { preserveValue: true }); - } - })); - // Also open a picker when we detect the user typed the exact - // name of a provider (e.g. `?term` for terminals) - disposables.add(picker.onDidChangeValue(value => { - const providerDescriptor = this.registry.getQuickAccessProvider(value.substr(HelpQuickAccessProvider.PREFIX.length)); - if (providerDescriptor && providerDescriptor.prefix && providerDescriptor.prefix !== HelpQuickAccessProvider.PREFIX) { - this.quickInputService.quickAccess.show(providerDescriptor.prefix, { preserveValue: true }); - } - })); - // Fill in all providers separated by editor/global scope - const { editorProviders, globalProviders } = this.getQuickAccessProviders(); - picker.items = editorProviders.length === 0 || globalProviders.length === 0 ? - // Without groups - [ - ...(editorProviders.length === 0 ? globalProviders : editorProviders) - ] : - // With groups - [ - { label: (0, nls_1.localize)(0, null), type: 'separator' }, - ...globalProviders, - { label: (0, nls_1.localize)(1, null), type: 'separator' }, - ...editorProviders - ]; - return disposables; - } - getQuickAccessProviders() { - const globalProviders = []; - const editorProviders = []; - for (const provider of this.registry.getQuickAccessProviders().sort((providerA, providerB) => providerA.prefix.localeCompare(providerB.prefix))) { - if (provider.prefix === HelpQuickAccessProvider.PREFIX) { - continue; // exclude help which is already active - } - for (const helpEntry of provider.helpEntries) { - const prefix = helpEntry.prefix || provider.prefix; - const label = prefix || '\u2026' /* ... */; - (helpEntry.needsEditor ? editorProviders : globalProviders).push({ - prefix, - label, - ariaLabel: (0, nls_1.localize)(2, null, label, helpEntry.description), - description: helpEntry.description - }); - } - } - return { editorProviders, globalProviders }; - } - }; - HelpQuickAccessProvider.PREFIX = '?'; - HelpQuickAccessProvider = __decorate([ - __param(0, quickInput_1.IQuickInputService) - ], HelpQuickAccessProvider); - exports.HelpQuickAccessProvider = HelpQuickAccessProvider; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[587/*vs/editor/standalone/browser/quickAccess/standaloneHelpQuickAccess*/], __M([0/*require*/,1/*exports*/,32/*vs/platform/registry/common/platform*/,99/*vs/platform/quickinput/common/quickAccess*/,63/*vs/editor/common/standaloneStrings*/,586/*vs/platform/quickinput/browser/helpQuickAccess*/]), function (require, exports, platform_1, quickAccess_1, standaloneStrings_1, helpQuickAccess_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - platform_1.Registry.as(quickAccess_1.Extensions.Quickaccess).registerQuickAccessProvider({ - ctor: helpQuickAccess_1.HelpQuickAccessProvider, - prefix: '', - helpEntries: [{ description: standaloneStrings_1.QuickHelpNLS.helpQuickAccessActionLabel, needsEditor: 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[588/*vs/platform/quickinput/browser/quickAccess*/], __M([0/*require*/,1/*exports*/,78/*vs/platform/quickinput/common/quickInput*/,2/*vs/base/common/lifecycle*/,99/*vs/platform/quickinput/common/quickAccess*/,32/*vs/platform/registry/common/platform*/,23/*vs/base/common/cancellation*/,9/*vs/platform/instantiation/common/instantiation*/,80/*vs/base/common/functional*/]), function (require, exports, quickInput_1, lifecycle_1, quickAccess_1, platform_1, cancellation_1, instantiation_1, functional_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.QuickAccessController = void 0; - let QuickAccessController = class QuickAccessController extends lifecycle_1.Disposable { - constructor(quickInputService, instantiationService) { - super(); - this.quickInputService = quickInputService; - this.instantiationService = instantiationService; - this.registry = platform_1.Registry.as(quickAccess_1.Extensions.Quickaccess); - this.mapProviderToDescriptor = new Map(); - this.lastAcceptedPickerValues = new Map(); - this.visibleQuickAccess = undefined; - } - show(value = '', options) { - this.doShowOrPick(value, false, options); - } - doShowOrPick(value, pick, options) { - var _a; - // Find provider for the value to show - const [provider, descriptor] = this.getOrInstantiateProvider(value); - // Return early if quick access is already showing on that same prefix - const visibleQuickAccess = this.visibleQuickAccess; - const visibleDescriptor = visibleQuickAccess === null || visibleQuickAccess === void 0 ? void 0 : visibleQuickAccess.descriptor; - if (visibleQuickAccess && descriptor && visibleDescriptor === descriptor) { - // Apply value only if it is more specific than the prefix - // from the provider and we are not instructed to preserve - if (value !== descriptor.prefix && !(options === null || options === void 0 ? void 0 : options.preserveValue)) { - visibleQuickAccess.picker.value = value; - } - // Always adjust selection - this.adjustValueSelection(visibleQuickAccess.picker, descriptor, options); - return; - } - // Rewrite the filter value based on certain rules unless disabled - if (descriptor && !(options === null || options === void 0 ? void 0 : options.preserveValue)) { - let newValue = undefined; - // If we have a visible provider with a value, take it's filter value but - // rewrite to new provider prefix in case they differ - if (visibleQuickAccess && visibleDescriptor && visibleDescriptor !== descriptor) { - const newValueCandidateWithoutPrefix = visibleQuickAccess.value.substr(visibleDescriptor.prefix.length); - if (newValueCandidateWithoutPrefix) { - newValue = `${descriptor.prefix}${newValueCandidateWithoutPrefix}`; - } - } - // Otherwise, take a default value as instructed - if (!newValue) { - const defaultFilterValue = provider === null || provider === void 0 ? void 0 : provider.defaultFilterValue; - if (defaultFilterValue === quickAccess_1.DefaultQuickAccessFilterValue.LAST) { - newValue = this.lastAcceptedPickerValues.get(descriptor); - } - else if (typeof defaultFilterValue === 'string') { - newValue = `${descriptor.prefix}${defaultFilterValue}`; - } - } - if (typeof newValue === 'string') { - value = newValue; - } - } - // Create a picker for the provider to use with the initial value - // and adjust the filtering to exclude the prefix from filtering - const disposables = new lifecycle_1.DisposableStore(); - const picker = disposables.add(this.quickInputService.createQuickPick()); - picker.value = value; - this.adjustValueSelection(picker, descriptor, options); - picker.placeholder = descriptor === null || descriptor === void 0 ? void 0 : descriptor.placeholder; - picker.quickNavigate = options === null || options === void 0 ? void 0 : options.quickNavigateConfiguration; - picker.hideInput = !!picker.quickNavigate && !visibleQuickAccess; // only hide input if there was no picker opened already - if (typeof (options === null || options === void 0 ? void 0 : options.itemActivation) === 'number' || (options === null || options === void 0 ? void 0 : options.quickNavigateConfiguration)) { - picker.itemActivation = (_a = options === null || options === void 0 ? void 0 : options.itemActivation) !== null && _a !== void 0 ? _a : quickInput_1.ItemActivation.SECOND /* quick nav is always second */; - } - picker.contextKey = descriptor === null || descriptor === void 0 ? void 0 : descriptor.contextKey; - picker.filterValue = (value) => value.substring(descriptor ? descriptor.prefix.length : 0); - if (descriptor === null || descriptor === void 0 ? void 0 : descriptor.placeholder) { - picker.ariaLabel = descriptor === null || descriptor === void 0 ? void 0 : descriptor.placeholder; - } - // Pick mode: setup a promise that can be resolved - // with the selected items and prevent execution - let pickPromise = undefined; - let pickResolve = undefined; - if (pick) { - pickPromise = new Promise(resolve => pickResolve = resolve); - disposables.add((0, functional_1.once)(picker.onWillAccept)(e => { - e.veto(); - picker.hide(); - })); - } - // Register listeners - disposables.add(this.registerPickerListeners(picker, provider, descriptor, value)); - // Ask provider to fill the picker as needed if we have one - // and pass over a cancellation token that will indicate when - // the picker is hiding without a pick being made. - const cts = disposables.add(new cancellation_1.CancellationTokenSource()); - if (provider) { - disposables.add(provider.provide(picker, cts.token)); - } - // Finally, trigger disposal and cancellation when the picker - // hides depending on items selected or not. - (0, functional_1.once)(picker.onDidHide)(() => { - if (picker.selectedItems.length === 0) { - cts.cancel(); - } - // Start to dispose once picker hides - disposables.dispose(); - // Resolve pick promise with selected items - pickResolve === null || pickResolve === void 0 ? void 0 : pickResolve(picker.selectedItems); - }); - // Finally, show the picker. This is important because a provider - // may not call this and then our disposables would leak that rely - // on the onDidHide event. - picker.show(); - // Pick mode: return with promise - if (pick) { - return pickPromise; - } - } - adjustValueSelection(picker, descriptor, options) { - var _a; - let valueSelection; - // Preserve: just always put the cursor at the end - if (options === null || options === void 0 ? void 0 : options.preserveValue) { - valueSelection = [picker.value.length, picker.value.length]; - } - // Otherwise: select the value up until the prefix - else { - valueSelection = [(_a = descriptor === null || descriptor === void 0 ? void 0 : descriptor.prefix.length) !== null && _a !== void 0 ? _a : 0, picker.value.length]; - } - picker.valueSelection = valueSelection; - } - registerPickerListeners(picker, provider, descriptor, value) { - const disposables = new lifecycle_1.DisposableStore(); - // Remember as last visible picker and clean up once picker get's disposed - const visibleQuickAccess = this.visibleQuickAccess = { picker, descriptor, value }; - disposables.add((0, lifecycle_1.toDisposable)(() => { - if (visibleQuickAccess === this.visibleQuickAccess) { - this.visibleQuickAccess = undefined; - } - })); - // Whenever the value changes, check if the provider has - // changed and if so - re-create the picker from the beginning - disposables.add(picker.onDidChangeValue(value => { - const [providerForValue] = this.getOrInstantiateProvider(value); - if (providerForValue !== provider) { - this.show(value, { preserveValue: true } /* do not rewrite value from user typing! */); - } - else { - visibleQuickAccess.value = value; // remember the value in our visible one - } - })); - // Remember picker input for future use when accepting - if (descriptor) { - disposables.add(picker.onDidAccept(() => { - this.lastAcceptedPickerValues.set(descriptor, picker.value); - })); - } - return disposables; - } - getOrInstantiateProvider(value) { - const providerDescriptor = this.registry.getQuickAccessProvider(value); - if (!providerDescriptor) { - return [undefined, undefined]; - } - let provider = this.mapProviderToDescriptor.get(providerDescriptor); - if (!provider) { - provider = this.instantiationService.createInstance(providerDescriptor.ctor); - this.mapProviderToDescriptor.set(providerDescriptor, provider); - } - return [provider, providerDescriptor]; - } - }; - QuickAccessController = __decorate([ - __param(0, quickInput_1.IQuickInputService), - __param(1, instantiation_1.IInstantiationService) - ], QuickAccessController); - exports.QuickAccessController = QuickAccessController; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/platform/storage/common/storage*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,20/*vs/base/common/types*/,300/*vs/base/parts/storage/common/storage*/]), function (require, exports, instantiation_1, event_1, lifecycle_1, types_1, storage_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.InMemoryStorageService = exports.AbstractStorageService = exports.WillSaveStateReason = exports.IStorageService = void 0; - const TARGET_KEY = '__$__targetStorageMarker'; - exports.IStorageService = (0, instantiation_1.createDecorator)('storageService'); - var WillSaveStateReason; - (function (WillSaveStateReason) { - /** - * No specific reason to save state. - */ - WillSaveStateReason[WillSaveStateReason["NONE"] = 0] = "NONE"; - /** - * A hint that the workbench is about to shutdown. - */ - WillSaveStateReason[WillSaveStateReason["SHUTDOWN"] = 1] = "SHUTDOWN"; - })(WillSaveStateReason = exports.WillSaveStateReason || (exports.WillSaveStateReason = {})); - class AbstractStorageService extends lifecycle_1.Disposable { - constructor(options = { flushInterval: AbstractStorageService.DEFAULT_FLUSH_INTERVAL }) { - super(); - this.options = options; - this._onDidChangeValue = this._register(new event_1.PauseableEmitter()); - this._onDidChangeTarget = this._register(new event_1.PauseableEmitter()); - this._onWillSaveState = this._register(new event_1.Emitter()); - this.onWillSaveState = this._onWillSaveState.event; - this._workspaceKeyTargets = undefined; - this._globalKeyTargets = undefined; - } - emitDidChangeValue(scope, key) { - // Specially handle `TARGET_KEY` - if (key === TARGET_KEY) { - // Clear our cached version which is now out of date - if (scope === 0 /* GLOBAL */) { - this._globalKeyTargets = undefined; - } - else if (scope === 1 /* WORKSPACE */) { - this._workspaceKeyTargets = undefined; - } - // Emit as `didChangeTarget` event - this._onDidChangeTarget.fire({ scope }); - } - // Emit any other key to outside - else { - this._onDidChangeValue.fire({ scope, key, target: this.getKeyTargets(scope)[key] }); - } - } - get(key, scope, fallbackValue) { - var _a; - return (_a = this.getStorage(scope)) === null || _a === void 0 ? void 0 : _a.get(key, fallbackValue); - } - getBoolean(key, scope, fallbackValue) { - var _a; - return (_a = this.getStorage(scope)) === null || _a === void 0 ? void 0 : _a.getBoolean(key, fallbackValue); - } - getNumber(key, scope, fallbackValue) { - var _a; - return (_a = this.getStorage(scope)) === null || _a === void 0 ? void 0 : _a.getNumber(key, fallbackValue); - } - store(key, value, scope, target) { - // We remove the key for undefined/null values - if ((0, types_1.isUndefinedOrNull)(value)) { - this.remove(key, scope); - return; - } - // Update our datastructures but send events only after - this.withPausedEmitters(() => { - var _a; - // Update key-target map - this.updateKeyTarget(key, scope, target); - // Store actual value - (_a = this.getStorage(scope)) === null || _a === void 0 ? void 0 : _a.set(key, value); - }); - } - remove(key, scope) { - // Update our datastructures but send events only after - this.withPausedEmitters(() => { - var _a; - // Update key-target map - this.updateKeyTarget(key, scope, undefined); - // Remove actual key - (_a = this.getStorage(scope)) === null || _a === void 0 ? void 0 : _a.delete(key); - }); - } - withPausedEmitters(fn) { - // Pause emitters - this._onDidChangeValue.pause(); - this._onDidChangeTarget.pause(); - try { - fn(); - } - finally { - // Resume emitters - this._onDidChangeValue.resume(); - this._onDidChangeTarget.resume(); - } - } - updateKeyTarget(key, scope, target) { - var _a, _b; - // Add - const keyTargets = this.getKeyTargets(scope); - if (typeof target === 'number') { - if (keyTargets[key] !== target) { - keyTargets[key] = target; - (_a = this.getStorage(scope)) === null || _a === void 0 ? void 0 : _a.set(TARGET_KEY, JSON.stringify(keyTargets)); - } - } - // Remove - else { - if (typeof keyTargets[key] === 'number') { - delete keyTargets[key]; - (_b = this.getStorage(scope)) === null || _b === void 0 ? void 0 : _b.set(TARGET_KEY, JSON.stringify(keyTargets)); - } - } - } - get workspaceKeyTargets() { - if (!this._workspaceKeyTargets) { - this._workspaceKeyTargets = this.loadKeyTargets(1 /* WORKSPACE */); - } - return this._workspaceKeyTargets; - } - get globalKeyTargets() { - if (!this._globalKeyTargets) { - this._globalKeyTargets = this.loadKeyTargets(0 /* GLOBAL */); - } - return this._globalKeyTargets; - } - getKeyTargets(scope) { - return scope === 0 /* GLOBAL */ ? this.globalKeyTargets : this.workspaceKeyTargets; - } - loadKeyTargets(scope) { - const keysRaw = this.get(TARGET_KEY, scope); - if (keysRaw) { - try { - return JSON.parse(keysRaw); - } - catch (error) { - // Fail gracefully - } - } - return Object.create(null); - } - } - exports.AbstractStorageService = AbstractStorageService; - AbstractStorageService.DEFAULT_FLUSH_INTERVAL = 60 * 1000; // every minute - class InMemoryStorageService extends AbstractStorageService { - constructor() { - super(); - this.globalStorage = this._register(new storage_1.Storage(new storage_1.InMemoryStorageDatabase())); - this.workspaceStorage = this._register(new storage_1.Storage(new storage_1.InMemoryStorageDatabase())); - this._register(this.workspaceStorage.onDidChangeStorage(key => this.emitDidChangeValue(1 /* WORKSPACE */, key))); - this._register(this.globalStorage.onDidChangeStorage(key => this.emitDidChangeValue(0 /* GLOBAL */, key))); - } - getStorage(scope) { - return scope === 0 /* GLOBAL */ ? this.globalStorage : this.workspaceStorage; - } - } - exports.InMemoryStorageService = InMemoryStorageService; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - - - - - - - - - -define(__m[589/*vs/editor/contrib/codelens/codeLensCache*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/,75/*vs/platform/instantiation/common/extensions*/,251/*vs/editor/contrib/codelens/codelens*/,49/*vs/base/common/map*/,71/*vs/platform/storage/common/storage*/,3/*vs/editor/common/core/range*/,15/*vs/base/common/async*/,80/*vs/base/common/functional*/]), function (require, exports, instantiation_1, extensions_1, codelens_1, map_1, storage_1, range_1, async_1, functional_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CodeLensCache = exports.ICodeLensCache = void 0; - exports.ICodeLensCache = (0, instantiation_1.createDecorator)('ICodeLensCache'); - class CacheItem { - constructor(lineCount, data) { - this.lineCount = lineCount; - this.data = data; - } - } - let CodeLensCache = class CodeLensCache { - constructor(storageService) { - this._fakeProvider = new class { - provideCodeLenses() { - throw new Error('not supported'); - } - }; - this._cache = new map_1.LRUCache(20, 0.75); - // remove old data - const oldkey = 'codelens/cache'; - (0, async_1.runWhenIdle)(() => storageService.remove(oldkey, 1 /* WORKSPACE */)); - // restore lens data on start - const key = 'codelens/cache2'; - const raw = storageService.get(key, 1 /* WORKSPACE */, '{}'); - this._deserialize(raw); - // store lens data on shutdown - (0, functional_1.once)(storageService.onWillSaveState)(e => { - if (e.reason === storage_1.WillSaveStateReason.SHUTDOWN) { - storageService.store(key, this._serialize(), 1 /* WORKSPACE */, 1 /* MACHINE */); - } - }); - } - put(model, data) { - // create a copy of the model that is without command-ids - // but with comand-labels - const copyItems = data.lenses.map(item => { - var _a; - return { - range: item.symbol.range, - command: item.symbol.command && { id: '', title: (_a = item.symbol.command) === null || _a === void 0 ? void 0 : _a.title }, - }; - }); - const copyModel = new codelens_1.CodeLensModel(); - copyModel.add({ lenses: copyItems, dispose: () => { } }, this._fakeProvider); - const item = new CacheItem(model.getLineCount(), copyModel); - this._cache.set(model.uri.toString(), item); - } - get(model) { - const item = this._cache.get(model.uri.toString()); - return item && item.lineCount === model.getLineCount() ? item.data : undefined; - } - delete(model) { - this._cache.delete(model.uri.toString()); - } - // --- persistence - _serialize() { - const data = Object.create(null); - for (const [key, value] of this._cache) { - const lines = new Set(); - for (const d of value.data.lenses) { - lines.add(d.symbol.range.startLineNumber); - } - data[key] = { - lineCount: value.lineCount, - lines: [...lines.values()] - }; - } - return JSON.stringify(data); - } - _deserialize(raw) { - try { - const data = JSON.parse(raw); - for (const key in data) { - const element = data[key]; - const lenses = []; - for (const line of element.lines) { - lenses.push({ range: new range_1.Range(line, 1, line, 11) }); - } - const model = new codelens_1.CodeLensModel(); - model.add({ lenses, dispose() { } }, this._fakeProvider); - this._cache.set(key, new CacheItem(element.lineCount, model)); - } - } - catch (_a) { - // ignore... - } - } - }; - CodeLensCache = __decorate([ - __param(0, storage_1.IStorageService) - ], CodeLensCache); - exports.CodeLensCache = CodeLensCache; - (0, extensions_1.registerSingleton)(exports.ICodeLensCache, CodeLensCache); -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - - - - - - - - - -define(__m[590/*vs/editor/contrib/suggest/suggestMemory*/], __M([0/*require*/,1/*exports*/,49/*vs/base/common/map*/,71/*vs/platform/storage/common/storage*/,18/*vs/editor/common/modes*/,2/*vs/base/common/lifecycle*/,15/*vs/base/common/async*/,9/*vs/platform/instantiation/common/instantiation*/,38/*vs/platform/configuration/common/configuration*/,75/*vs/platform/instantiation/common/extensions*/,57/*vs/editor/common/services/modeService*/]), function (require, exports, map_1, storage_1, modes_1, lifecycle_1, async_1, instantiation_1, configuration_1, extensions_1, modeService_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ISuggestMemoryService = exports.SuggestMemoryService = exports.PrefixMemory = exports.LRUMemory = exports.NoMemory = exports.Memory = void 0; - class Memory { - constructor(name) { - this.name = name; - } - select(model, pos, items) { - if (items.length === 0) { - return 0; - } - let topScore = items[0].score[0]; - for (let i = 0; i < items.length; i++) { - const { score, completion: suggestion } = items[i]; - if (score[0] !== topScore) { - // stop when leaving the group of top matches - break; - } - if (suggestion.preselect) { - // stop when seeing an auto-select-item - return i; - } - } - return 0; - } - } - exports.Memory = Memory; - class NoMemory extends Memory { - constructor() { - super('first'); - } - memorize(model, pos, item) { - // no-op - } - toJSON() { - return undefined; - } - fromJSON() { - // - } - } - exports.NoMemory = NoMemory; - class LRUMemory extends Memory { - constructor() { - super('recentlyUsed'); - this._cache = new map_1.LRUCache(300, 0.66); - this._seq = 0; - } - memorize(model, pos, item) { - const key = `${model.getLanguageIdentifier().language}/${item.textLabel}`; - this._cache.set(key, { - touch: this._seq++, - type: item.completion.kind, - insertText: item.completion.insertText - }); - } - select(model, pos, items) { - if (items.length === 0) { - return 0; - } - const lineSuffix = model.getLineContent(pos.lineNumber).substr(pos.column - 10, pos.column - 1); - if (/\s$/.test(lineSuffix)) { - return super.select(model, pos, items); - } - let topScore = items[0].score[0]; - let indexPreselect = -1; - let indexRecency = -1; - let seq = -1; - for (let i = 0; i < items.length; i++) { - if (items[i].score[0] !== topScore) { - // consider only top items - break; - } - const key = `${model.getLanguageIdentifier().language}/${items[i].textLabel}`; - const item = this._cache.peek(key); - if (item && item.touch > seq && item.type === items[i].completion.kind && item.insertText === items[i].completion.insertText) { - seq = item.touch; - indexRecency = i; - } - if (items[i].completion.preselect && indexPreselect === -1) { - // stop when seeing an auto-select-item - return indexPreselect = i; - } - } - if (indexRecency !== -1) { - return indexRecency; - } - else if (indexPreselect !== -1) { - return indexPreselect; - } - else { - return 0; - } - } - toJSON() { - return this._cache.toJSON(); - } - fromJSON(data) { - this._cache.clear(); - let seq = 0; - for (const [key, value] of data) { - value.touch = seq; - value.type = typeof value.type === 'number' ? value.type : (0, modes_1.completionKindFromString)(value.type); - this._cache.set(key, value); - } - this._seq = this._cache.size; - } - } - exports.LRUMemory = LRUMemory; - class PrefixMemory extends Memory { - constructor() { - super('recentlyUsedByPrefix'); - this._trie = map_1.TernarySearchTree.forStrings(); - this._seq = 0; - } - memorize(model, pos, item) { - const { word } = model.getWordUntilPosition(pos); - const key = `${model.getLanguageIdentifier().language}/${word}`; - this._trie.set(key, { - type: item.completion.kind, - insertText: item.completion.insertText, - touch: this._seq++ - }); - } - select(model, pos, items) { - let { word } = model.getWordUntilPosition(pos); - if (!word) { - return super.select(model, pos, items); - } - let key = `${model.getLanguageIdentifier().language}/${word}`; - let item = this._trie.get(key); - if (!item) { - item = this._trie.findSubstr(key); - } - if (item) { - for (let i = 0; i < items.length; i++) { - let { kind, insertText } = items[i].completion; - if (kind === item.type && insertText === item.insertText) { - return i; - } - } - } - return super.select(model, pos, items); - } - toJSON() { - let entries = []; - this._trie.forEach((value, key) => entries.push([key, value])); - // sort by last recently used (touch), then - // take the top 200 item and normalize their - // touch - entries - .sort((a, b) => -(a[1].touch - b[1].touch)) - .forEach((value, i) => value[1].touch = i); - return entries.slice(0, 200); - } - fromJSON(data) { - this._trie.clear(); - if (data.length > 0) { - this._seq = data[0][1].touch + 1; - for (const [key, value] of data) { - value.type = typeof value.type === 'number' ? value.type : (0, modes_1.completionKindFromString)(value.type); - this._trie.set(key, value); - } - } - } - } - exports.PrefixMemory = PrefixMemory; - let SuggestMemoryService = class SuggestMemoryService { - constructor(_storageService, _modeService, _configService) { - this._storageService = _storageService; - this._modeService = _modeService; - this._configService = _configService; - this._disposables = new lifecycle_1.DisposableStore(); - this._persistSoon = new async_1.RunOnceScheduler(() => this._saveState(), 500); - this._disposables.add(_storageService.onWillSaveState(e => { - if (e.reason === storage_1.WillSaveStateReason.SHUTDOWN) { - this._saveState(); - } - })); - } - dispose() { - this._disposables.dispose(); - this._persistSoon.dispose(); - } - memorize(model, pos, item) { - this._withStrategy(model, pos).memorize(model, pos, item); - this._persistSoon.schedule(); - } - select(model, pos, items) { - return this._withStrategy(model, pos).select(model, pos, items); - } - _withStrategy(model, pos) { - var _a, _b; - const mode = this._configService.getValue('editor.suggestSelection', { - overrideIdentifier: (_a = this._modeService.getLanguageIdentifier(model.getLanguageIdAtPosition(pos.lineNumber, pos.column))) === null || _a === void 0 ? void 0 : _a.language, - resource: model.uri - }); - if (((_b = this._strategy) === null || _b === void 0 ? void 0 : _b.name) !== mode) { - this._saveState(); - const ctor = SuggestMemoryService._strategyCtors.get(mode) || NoMemory; - this._strategy = new ctor(); - try { - const share = this._configService.getValue('editor.suggest.shareSuggestSelections'); - const scope = share ? 0 /* GLOBAL */ : 1 /* WORKSPACE */; - const raw = this._storageService.get(`${SuggestMemoryService._storagePrefix}/${mode}`, scope); - if (raw) { - this._strategy.fromJSON(JSON.parse(raw)); - } - } - catch (e) { - // things can go wrong with JSON... - } - } - return this._strategy; - } - _saveState() { - if (this._strategy) { - const share = this._configService.getValue('editor.suggest.shareSuggestSelections'); - const scope = share ? 0 /* GLOBAL */ : 1 /* WORKSPACE */; - const raw = JSON.stringify(this._strategy); - this._storageService.store(`${SuggestMemoryService._storagePrefix}/${this._strategy.name}`, raw, scope, 1 /* MACHINE */); - } - } - }; - SuggestMemoryService._strategyCtors = new Map([ - ['recentlyUsedByPrefix', PrefixMemory], - ['recentlyUsed', LRUMemory], - ['first', NoMemory] - ]); - SuggestMemoryService._storagePrefix = 'suggest/memories'; - SuggestMemoryService = __decorate([ - __param(0, storage_1.IStorageService), - __param(1, modeService_1.IModeService), - __param(2, configuration_1.IConfigurationService) - ], SuggestMemoryService); - exports.SuggestMemoryService = SuggestMemoryService; - exports.ISuggestMemoryService = (0, instantiation_1.createDecorator)('ISuggestMemories'); - (0, extensions_1.registerSingleton)(exports.ISuggestMemoryService, SuggestMemoryService, 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[89/*vs/platform/telemetry/common/telemetry*/], __M([0/*require*/,1/*exports*/,9/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ITelemetryService = void 0; - exports.ITelemetryService = (0, instantiation_1.createDecorator)('telemetryService'); -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - - - - - - - - - - - - - - - - - - -define(__m[591/*vs/platform/quickinput/browser/commandsQuickAccess*/], __M([0/*require*/,1/*exports*/,539/*vs/nls!vs/platform/quickinput/browser/commandsQuickAccess*/,575/*vs/platform/quickinput/browser/pickerQuickAccess*/,2/*vs/base/common/lifecycle*/,67/*vs/base/common/filters*/,20/*vs/base/common/types*/,49/*vs/base/common/map*/,71/*vs/platform/storage/common/storage*/,38/*vs/platform/configuration/common/configuration*/,9/*vs/platform/instantiation/common/instantiation*/,37/*vs/platform/keybinding/common/keybinding*/,26/*vs/platform/commands/common/commands*/,89/*vs/platform/telemetry/common/telemetry*/,12/*vs/base/common/errors*/,120/*vs/platform/dialogs/common/dialogs*/,74/*vs/base/common/severity*/,447/*vs/base/common/errorMessage*/]), function (require, exports, nls_1, pickerQuickAccess_1, lifecycle_1, filters_1, types_1, map_1, storage_1, configuration_1, instantiation_1, keybinding_1, commands_1, telemetry_1, errors_1, dialogs_1, severity_1, errorMessage_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CommandsHistory = exports.AbstractCommandsQuickAccessProvider = void 0; - let AbstractCommandsQuickAccessProvider = class AbstractCommandsQuickAccessProvider extends pickerQuickAccess_1.PickerQuickAccessProvider { - constructor(options, instantiationService, keybindingService, commandService, telemetryService, dialogService) { - super(AbstractCommandsQuickAccessProvider.PREFIX, options); - this.instantiationService = instantiationService; - this.keybindingService = keybindingService; - this.commandService = commandService; - this.telemetryService = telemetryService; - this.dialogService = dialogService; - this.commandsHistory = this._register(this.instantiationService.createInstance(CommandsHistory)); - this.options = options; - } - _getPicks(filter, disposables, token) { - return __awaiter(this, void 0, void 0, function* () { - // Ask subclass for all command picks - const allCommandPicks = yield this.getCommandPicks(disposables, token); - if (token.isCancellationRequested) { - return []; - } - // Filter - const filteredCommandPicks = []; - for (const commandPick of allCommandPicks) { - const labelHighlights = (0, types_1.withNullAsUndefined)(AbstractCommandsQuickAccessProvider.WORD_FILTER(filter, commandPick.label)); - const aliasHighlights = commandPick.commandAlias ? (0, types_1.withNullAsUndefined)(AbstractCommandsQuickAccessProvider.WORD_FILTER(filter, commandPick.commandAlias)) : undefined; - // Add if matching in label or alias - if (labelHighlights || aliasHighlights) { - commandPick.highlights = { - label: labelHighlights, - detail: this.options.showAlias ? aliasHighlights : undefined - }; - filteredCommandPicks.push(commandPick); - } - // Also add if we have a 100% command ID match - else if (filter === commandPick.commandId) { - filteredCommandPicks.push(commandPick); - } - } - // Add description to commands that have duplicate labels - const mapLabelToCommand = new Map(); - for (const commandPick of filteredCommandPicks) { - const existingCommandForLabel = mapLabelToCommand.get(commandPick.label); - if (existingCommandForLabel) { - commandPick.description = commandPick.commandId; - existingCommandForLabel.description = existingCommandForLabel.commandId; - } - else { - mapLabelToCommand.set(commandPick.label, commandPick); - } - } - // Sort by MRU order and fallback to name otherwise - filteredCommandPicks.sort((commandPickA, commandPickB) => { - const commandACounter = this.commandsHistory.peek(commandPickA.commandId); - const commandBCounter = this.commandsHistory.peek(commandPickB.commandId); - if (commandACounter && commandBCounter) { - return commandACounter > commandBCounter ? -1 : 1; // use more recently used command before older - } - if (commandACounter) { - return -1; // first command was used, so it wins over the non used one - } - if (commandBCounter) { - return 1; // other command was used so it wins over the command - } - // both commands were never used, so we sort by name - return commandPickA.label.localeCompare(commandPickB.label); - }); - const commandPicks = []; - let addSeparator = false; - for (let i = 0; i < filteredCommandPicks.length; i++) { - const commandPick = filteredCommandPicks[i]; - const keybinding = this.keybindingService.lookupKeybinding(commandPick.commandId); - const ariaLabel = keybinding ? - (0, nls_1.localize)(0, null, commandPick.label, keybinding.getAriaLabel()) : - commandPick.label; - // Separator: recently used - if (i === 0 && this.commandsHistory.peek(commandPick.commandId)) { - commandPicks.push({ type: 'separator', label: (0, nls_1.localize)(1, null) }); - addSeparator = true; - } - // Separator: other commands - if (i !== 0 && addSeparator && !this.commandsHistory.peek(commandPick.commandId)) { - commandPicks.push({ type: 'separator', label: (0, nls_1.localize)(2, null) }); - addSeparator = false; // only once - } - // Command - commandPicks.push(Object.assign(Object.assign({}, commandPick), { ariaLabel, detail: this.options.showAlias && commandPick.commandAlias !== commandPick.label ? commandPick.commandAlias : undefined, keybinding, accept: () => __awaiter(this, void 0, void 0, function* () { - // Add to history - this.commandsHistory.push(commandPick.commandId); - // Telementry - this.telemetryService.publicLog2('workbenchActionExecuted', { - id: commandPick.commandId, - from: 'quick open' - }); - // Run - try { - yield this.commandService.executeCommand(commandPick.commandId); - } - catch (error) { - if (!(0, errors_1.isPromiseCanceledError)(error)) { - this.dialogService.show(severity_1.default.Error, (0, nls_1.localize)(3, null, commandPick.label, (0, errorMessage_1.toErrorMessage)(error))); - } - } - }) })); - } - return commandPicks; - }); - } - }; - AbstractCommandsQuickAccessProvider.PREFIX = '>'; - AbstractCommandsQuickAccessProvider.WORD_FILTER = (0, filters_1.or)(filters_1.matchesPrefix, filters_1.matchesWords, filters_1.matchesContiguousSubString); - AbstractCommandsQuickAccessProvider = __decorate([ - __param(1, instantiation_1.IInstantiationService), - __param(2, keybinding_1.IKeybindingService), - __param(3, commands_1.ICommandService), - __param(4, telemetry_1.ITelemetryService), - __param(5, dialogs_1.IDialogService) - ], AbstractCommandsQuickAccessProvider); - exports.AbstractCommandsQuickAccessProvider = AbstractCommandsQuickAccessProvider; - let CommandsHistory = class CommandsHistory extends lifecycle_1.Disposable { - constructor(storageService, configurationService) { - super(); - this.storageService = storageService; - this.configurationService = configurationService; - this.configuredCommandsHistoryLength = 0; - this.updateConfiguration(); - this.load(); - this.registerListeners(); - } - registerListeners() { - this._register(this.configurationService.onDidChangeConfiguration(() => this.updateConfiguration())); - } - updateConfiguration() { - this.configuredCommandsHistoryLength = CommandsHistory.getConfiguredCommandHistoryLength(this.configurationService); - if (CommandsHistory.cache && CommandsHistory.cache.limit !== this.configuredCommandsHistoryLength) { - CommandsHistory.cache.limit = this.configuredCommandsHistoryLength; - CommandsHistory.saveState(this.storageService); - } - } - load() { - const raw = this.storageService.get(CommandsHistory.PREF_KEY_CACHE, 0 /* GLOBAL */); - let serializedCache; - if (raw) { - try { - serializedCache = JSON.parse(raw); - } - catch (error) { - // invalid data - } - } - const cache = CommandsHistory.cache = new map_1.LRUCache(this.configuredCommandsHistoryLength, 1); - if (serializedCache) { - let entries; - if (serializedCache.usesLRU) { - entries = serializedCache.entries; - } - else { - entries = serializedCache.entries.sort((a, b) => a.value - b.value); - } - entries.forEach(entry => cache.set(entry.key, entry.value)); - } - CommandsHistory.counter = this.storageService.getNumber(CommandsHistory.PREF_KEY_COUNTER, 0 /* GLOBAL */, CommandsHistory.counter); - } - push(commandId) { - if (!CommandsHistory.cache) { - return; - } - CommandsHistory.cache.set(commandId, CommandsHistory.counter++); // set counter to command - CommandsHistory.saveState(this.storageService); - } - peek(commandId) { - var _a; - return (_a = CommandsHistory.cache) === null || _a === void 0 ? void 0 : _a.peek(commandId); - } - static saveState(storageService) { - if (!CommandsHistory.cache) { - return; - } - const serializedCache = { usesLRU: true, entries: [] }; - CommandsHistory.cache.forEach((value, key) => serializedCache.entries.push({ key, value })); - storageService.store(CommandsHistory.PREF_KEY_CACHE, JSON.stringify(serializedCache), 0 /* GLOBAL */, 0 /* USER */); - storageService.store(CommandsHistory.PREF_KEY_COUNTER, CommandsHistory.counter, 0 /* GLOBAL */, 0 /* USER */); - } - static getConfiguredCommandHistoryLength(configurationService) { - var _a, _b; - const config = configurationService.getValue(); - const configuredCommandHistoryLength = (_b = (_a = config.workbench) === null || _a === void 0 ? void 0 : _a.commandPalette) === null || _b === void 0 ? void 0 : _b.history; - if (typeof configuredCommandHistoryLength === 'number') { - return configuredCommandHistoryLength; - } - return CommandsHistory.DEFAULT_COMMANDS_HISTORY_LENGTH; - } - }; - CommandsHistory.DEFAULT_COMMANDS_HISTORY_LENGTH = 50; - CommandsHistory.PREF_KEY_CACHE = 'commandPalette.mru.cache'; - CommandsHistory.PREF_KEY_COUNTER = 'commandPalette.mru.counter'; - CommandsHistory.counter = 1; - CommandsHistory = __decorate([ - __param(0, storage_1.IStorageService), - __param(1, configuration_1.IConfigurationService) - ], CommandsHistory); - exports.CommandsHistory = CommandsHistory; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[592/*vs/editor/contrib/quickAccess/commandsQuickAccess*/], __M([0/*require*/,1/*exports*/,591/*vs/platform/quickinput/browser/commandsQuickAccess*/,104/*vs/base/common/iconLabels*/]), function (require, exports, commandsQuickAccess_1, iconLabels_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.AbstractEditorCommandsQuickAccessProvider = void 0; - class AbstractEditorCommandsQuickAccessProvider extends commandsQuickAccess_1.AbstractCommandsQuickAccessProvider { - constructor(options, instantiationService, keybindingService, commandService, telemetryService, dialogService) { - super(options, instantiationService, keybindingService, commandService, telemetryService, dialogService); - } - getCodeEditorCommandPicks() { - const activeTextEditorControl = this.activeTextEditorControl; - if (!activeTextEditorControl) { - return []; - } - const editorCommandPicks = []; - for (const editorAction of activeTextEditorControl.getSupportedActions()) { - editorCommandPicks.push({ - commandId: editorAction.id, - commandAlias: editorAction.alias, - label: (0, iconLabels_1.stripIcons)(editorAction.label) || editorAction.id, - }); - } - return editorCommandPicks; - } - } - exports.AbstractEditorCommandsQuickAccessProvider = AbstractEditorCommandsQuickAccessProvider; -}); - -/*--------------------------------------------------------------------------------------------- - * 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/platform/theme/common/colorRegistry*/], __M([0/*require*/,1/*exports*/,32/*vs/platform/registry/common/platform*/,29/*vs/base/common/color*/,6/*vs/base/common/event*/,541/*vs/nls!vs/platform/theme/common/colorRegistry*/,189/*vs/platform/jsonschemas/common/jsonContributionRegistry*/,15/*vs/base/common/async*/,20/*vs/base/common/types*/]), function (require, exports, platform, color_1, event_1, nls, jsonContributionRegistry_1, async_1, types_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.workbenchColorsSchemaId = exports.resolveColorValue = exports.ifDefinedThenElse = exports.oneOf = exports.transparent = exports.lighten = exports.darken = exports.executeTransform = exports.problemsInfoIconForeground = exports.problemsWarningIconForeground = exports.problemsErrorIconForeground = exports.minimapSliderActiveBackground = exports.minimapSliderHoverBackground = exports.minimapSliderBackground = exports.minimapBackground = exports.minimapWarning = exports.minimapError = exports.minimapSelection = exports.minimapFindMatch = exports.overviewRulerSelectionHighlightForeground = exports.overviewRulerFindMatchForeground = exports.snippetFinalTabstopHighlightBorder = exports.snippetFinalTabstopHighlightBackground = exports.snippetTabstopHighlightBorder = exports.snippetTabstopHighlightBackground = exports.menuSeparatorBackground = exports.menuSelectionBorder = exports.menuSelectionBackground = exports.menuSelectionForeground = exports.menuBackground = exports.menuForeground = exports.menuBorder = exports.quickInputListFocusBackground = exports.quickInputListFocusIconForeground = exports.quickInputListFocusForeground = exports._deprecatedQuickInputListFocusBackground = exports.tableColumnsBorder = exports.treeIndentGuidesStroke = exports.listFilterWidgetNoMatchesOutline = exports.listFilterWidgetOutline = exports.listFilterWidgetBackground = exports.listFocusHighlightForeground = exports.listHighlightForeground = exports.listDropBackground = exports.listHoverForeground = exports.listHoverBackground = exports.listInactiveFocusOutline = exports.listInactiveFocusBackground = exports.listInactiveSelectionIconForeground = exports.listInactiveSelectionForeground = exports.listInactiveSelectionBackground = exports.listActiveSelectionIconForeground = exports.listActiveSelectionForeground = exports.listActiveSelectionBackground = exports.listFocusOutline = exports.listFocusForeground = exports.listFocusBackground = exports.diffDiagonalFill = exports.diffBorder = exports.diffRemovedOutline = exports.diffInsertedOutline = exports.diffRemoved = exports.diffInserted = exports.defaultRemoveColor = exports.defaultInsertColor = exports.editorLightBulbAutoFixForeground = exports.editorLightBulbForeground = exports.editorInlayHintBackground = exports.editorInlayHintForeground = exports.editorActiveLinkForeground = exports.editorHoverStatusBarBackground = exports.editorHoverBorder = exports.editorHoverForeground = exports.editorHoverBackground = exports.editorHoverHighlight = exports.editorFindRangeHighlightBorder = exports.editorFindMatchHighlightBorder = exports.editorFindMatchBorder = exports.editorFindRangeHighlight = exports.editorFindMatchHighlight = exports.editorFindMatch = exports.editorSelectionHighlightBorder = exports.editorSelectionHighlight = exports.editorInactiveSelection = exports.editorSelectionForeground = exports.editorSelectionBackground = exports.keybindingLabelBottomBorder = exports.keybindingLabelBorder = exports.keybindingLabelForeground = exports.keybindingLabelBackground = exports.pickerGroupBorder = exports.pickerGroupForeground = exports.quickInputTitleBackground = exports.quickInputForeground = exports.quickInputBackground = exports.editorWidgetResizeBorder = exports.editorWidgetBorder = exports.editorWidgetForeground = exports.editorWidgetBackground = exports.editorForeground = exports.editorBackground = exports.editorHintBorder = exports.editorHintForeground = exports.editorInfoBorder = exports.editorInfoForeground = exports.editorInfoBackground = exports.editorWarningBorder = exports.editorWarningForeground = exports.editorWarningBackground = exports.editorErrorBorder = exports.editorErrorForeground = exports.editorErrorBackground = exports.progressBarBackground = exports.scrollbarSliderActiveBackground = exports.scrollbarSliderHoverBackground = exports.scrollbarSliderBackground = exports.scrollbarShadow = exports.badgeForeground = exports.badgeBackground = exports.buttonHoverBackground = exports.buttonBackground = exports.buttonForeground = exports.selectForeground = exports.selectBackground = exports.inputValidationErrorBorder = exports.inputValidationErrorForeground = exports.inputValidationErrorBackground = exports.inputValidationWarningBorder = exports.inputValidationWarningForeground = exports.inputValidationWarningBackground = exports.inputValidationInfoBorder = exports.inputValidationInfoForeground = exports.inputValidationInfoBackground = exports.inputActiveOptionForeground = exports.inputActiveOptionBackground = exports.inputActiveOptionBorder = exports.inputBorder = exports.inputForeground = exports.inputBackground = exports.widgetShadow = exports.textCodeBlockBackground = exports.textLinkActiveForeground = exports.textLinkForeground = exports.activeContrastBorder = exports.contrastBorder = exports.focusBorder = exports.iconForeground = exports.errorForeground = exports.foreground = exports.registerColor = exports.Extensions = void 0; - // color registry - exports.Extensions = { - ColorContribution: 'base.contributions.colors' - }; - class ColorRegistry { - constructor() { - this._onDidChangeSchema = new event_1.Emitter(); - this.onDidChangeSchema = this._onDidChangeSchema.event; - this.colorSchema = { type: 'object', properties: {} }; - this.colorReferenceSchema = { type: 'string', enum: [], enumDescriptions: [] }; - this.colorsById = {}; - } - registerColor(id, defaults, description, needsTransparency = false, deprecationMessage) { - let colorContribution = { id, description, defaults, needsTransparency, deprecationMessage }; - this.colorsById[id] = colorContribution; - let propertySchema = { type: 'string', description, format: 'color-hex', defaultSnippets: [{ body: '${1:#ff0000}' }] }; - if (deprecationMessage) { - propertySchema.deprecationMessage = deprecationMessage; - } - this.colorSchema.properties[id] = propertySchema; - this.colorReferenceSchema.enum.push(id); - this.colorReferenceSchema.enumDescriptions.push(description); - this._onDidChangeSchema.fire(); - return id; - } - resolveDefaultColor(id, theme) { - const colorDesc = this.colorsById[id]; - if (colorDesc && colorDesc.defaults) { - const colorValue = colorDesc.defaults[theme.type]; - return resolveColorValue(colorValue, theme); - } - return undefined; - } - getColorSchema() { - return this.colorSchema; - } - toString() { - let sorter = (a, b) => { - let cat1 = a.indexOf('.') === -1 ? 0 : 1; - let cat2 = b.indexOf('.') === -1 ? 0 : 1; - if (cat1 !== cat2) { - return cat1 - cat2; - } - return a.localeCompare(b); - }; - return Object.keys(this.colorsById).sort(sorter).map(k => `- \`${k}\`: ${this.colorsById[k].description}`).join('\n'); - } - } - const colorRegistry = new ColorRegistry(); - platform.Registry.add(exports.Extensions.ColorContribution, colorRegistry); - function registerColor(id, defaults, description, needsTransparency, deprecationMessage) { - return colorRegistry.registerColor(id, defaults, description, needsTransparency, deprecationMessage); - } - exports.registerColor = registerColor; - // ----- base colors - exports.foreground = registerColor('foreground', { dark: '#CCCCCC', light: '#616161', hc: '#FFFFFF' }, nls.localize(0, null)); - exports.errorForeground = registerColor('errorForeground', { dark: '#F48771', light: '#A1260D', hc: '#F48771' }, nls.localize(1, null)); - exports.iconForeground = registerColor('icon.foreground', { dark: '#C5C5C5', light: '#424242', hc: '#FFFFFF' }, nls.localize(2, null)); - exports.focusBorder = registerColor('focusBorder', { dark: '#007FD4', light: '#0090F1', hc: '#F38518' }, nls.localize(3, null)); - exports.contrastBorder = registerColor('contrastBorder', { light: null, dark: null, hc: '#6FC3DF' }, nls.localize(4, null)); - exports.activeContrastBorder = registerColor('contrastActiveBorder', { light: null, dark: null, hc: exports.focusBorder }, nls.localize(5, null)); - exports.textLinkForeground = registerColor('textLink.foreground', { light: '#006AB1', dark: '#3794FF', hc: '#3794FF' }, nls.localize(6, null)); - exports.textLinkActiveForeground = registerColor('textLink.activeForeground', { light: '#006AB1', dark: '#3794FF', hc: '#3794FF' }, nls.localize(7, null)); - exports.textCodeBlockBackground = registerColor('textCodeBlock.background', { light: '#dcdcdc66', dark: '#0a0a0a66', hc: color_1.Color.black }, nls.localize(8, null)); - // ----- widgets - exports.widgetShadow = registerColor('widget.shadow', { dark: transparent(color_1.Color.black, .36), light: transparent(color_1.Color.black, .16), hc: null }, nls.localize(9, null)); - exports.inputBackground = registerColor('input.background', { dark: '#3C3C3C', light: color_1.Color.white, hc: color_1.Color.black }, nls.localize(10, null)); - exports.inputForeground = registerColor('input.foreground', { dark: exports.foreground, light: exports.foreground, hc: exports.foreground }, nls.localize(11, null)); - exports.inputBorder = registerColor('input.border', { dark: null, light: null, hc: exports.contrastBorder }, nls.localize(12, null)); - exports.inputActiveOptionBorder = registerColor('inputOption.activeBorder', { dark: '#007ACC00', light: '#007ACC00', hc: exports.contrastBorder }, nls.localize(13, null)); - exports.inputActiveOptionBackground = registerColor('inputOption.activeBackground', { dark: transparent(exports.focusBorder, 0.4), light: transparent(exports.focusBorder, 0.2), hc: color_1.Color.transparent }, nls.localize(14, null)); - exports.inputActiveOptionForeground = registerColor('inputOption.activeForeground', { dark: color_1.Color.white, light: color_1.Color.black, hc: null }, nls.localize(15, null)); - exports.inputValidationInfoBackground = registerColor('inputValidation.infoBackground', { dark: '#063B49', light: '#D6ECF2', hc: color_1.Color.black }, nls.localize(16, null)); - exports.inputValidationInfoForeground = registerColor('inputValidation.infoForeground', { dark: null, light: null, hc: null }, nls.localize(17, null)); - exports.inputValidationInfoBorder = registerColor('inputValidation.infoBorder', { dark: '#007acc', light: '#007acc', hc: exports.contrastBorder }, nls.localize(18, null)); - exports.inputValidationWarningBackground = registerColor('inputValidation.warningBackground', { dark: '#352A05', light: '#F6F5D2', hc: color_1.Color.black }, nls.localize(19, null)); - exports.inputValidationWarningForeground = registerColor('inputValidation.warningForeground', { dark: null, light: null, hc: null }, nls.localize(20, null)); - exports.inputValidationWarningBorder = registerColor('inputValidation.warningBorder', { dark: '#B89500', light: '#B89500', hc: exports.contrastBorder }, nls.localize(21, null)); - exports.inputValidationErrorBackground = registerColor('inputValidation.errorBackground', { dark: '#5A1D1D', light: '#F2DEDE', hc: color_1.Color.black }, nls.localize(22, null)); - exports.inputValidationErrorForeground = registerColor('inputValidation.errorForeground', { dark: null, light: null, hc: null }, nls.localize(23, null)); - exports.inputValidationErrorBorder = registerColor('inputValidation.errorBorder', { dark: '#BE1100', light: '#BE1100', hc: exports.contrastBorder }, nls.localize(24, null)); - exports.selectBackground = registerColor('dropdown.background', { dark: '#3C3C3C', light: color_1.Color.white, hc: color_1.Color.black }, nls.localize(25, null)); - exports.selectForeground = registerColor('dropdown.foreground', { dark: '#F0F0F0', light: null, hc: color_1.Color.white }, nls.localize(26, null)); - exports.buttonForeground = registerColor('button.foreground', { dark: color_1.Color.white, light: color_1.Color.white, hc: color_1.Color.white }, nls.localize(27, null)); - exports.buttonBackground = registerColor('button.background', { dark: '#0E639C', light: '#007ACC', hc: null }, nls.localize(28, null)); - exports.buttonHoverBackground = registerColor('button.hoverBackground', { dark: lighten(exports.buttonBackground, 0.2), light: darken(exports.buttonBackground, 0.2), hc: null }, nls.localize(29, null)); - exports.badgeBackground = registerColor('badge.background', { dark: '#4D4D4D', light: '#C4C4C4', hc: color_1.Color.black }, nls.localize(30, null)); - exports.badgeForeground = registerColor('badge.foreground', { dark: color_1.Color.white, light: '#333', hc: color_1.Color.white }, nls.localize(31, null)); - exports.scrollbarShadow = registerColor('scrollbar.shadow', { dark: '#000000', light: '#DDDDDD', hc: null }, nls.localize(32, null)); - exports.scrollbarSliderBackground = registerColor('scrollbarSlider.background', { dark: color_1.Color.fromHex('#797979').transparent(0.4), light: color_1.Color.fromHex('#646464').transparent(0.4), hc: transparent(exports.contrastBorder, 0.6) }, nls.localize(33, null)); - exports.scrollbarSliderHoverBackground = registerColor('scrollbarSlider.hoverBackground', { dark: color_1.Color.fromHex('#646464').transparent(0.7), light: color_1.Color.fromHex('#646464').transparent(0.7), hc: transparent(exports.contrastBorder, 0.8) }, nls.localize(34, null)); - exports.scrollbarSliderActiveBackground = registerColor('scrollbarSlider.activeBackground', { dark: color_1.Color.fromHex('#BFBFBF').transparent(0.4), light: color_1.Color.fromHex('#000000').transparent(0.6), hc: exports.contrastBorder }, nls.localize(35, null)); - exports.progressBarBackground = registerColor('progressBar.background', { dark: color_1.Color.fromHex('#0E70C0'), light: color_1.Color.fromHex('#0E70C0'), hc: exports.contrastBorder }, nls.localize(36, null)); - exports.editorErrorBackground = registerColor('editorError.background', { dark: null, light: null, hc: null }, nls.localize(37, null), true); - exports.editorErrorForeground = registerColor('editorError.foreground', { dark: '#F48771', light: '#E51400', hc: null }, nls.localize(38, null)); - exports.editorErrorBorder = registerColor('editorError.border', { dark: null, light: null, hc: color_1.Color.fromHex('#E47777').transparent(0.8) }, nls.localize(39, null)); - exports.editorWarningBackground = registerColor('editorWarning.background', { dark: null, light: null, hc: null }, nls.localize(40, null), true); - exports.editorWarningForeground = registerColor('editorWarning.foreground', { dark: '#CCA700', light: '#BF8803', hc: null }, nls.localize(41, null)); - exports.editorWarningBorder = registerColor('editorWarning.border', { dark: null, light: null, hc: color_1.Color.fromHex('#FFCC00').transparent(0.8) }, nls.localize(42, null)); - exports.editorInfoBackground = registerColor('editorInfo.background', { dark: null, light: null, hc: null }, nls.localize(43, null), true); - exports.editorInfoForeground = registerColor('editorInfo.foreground', { dark: '#75BEFF', light: '#75BEFF', hc: null }, nls.localize(44, null)); - exports.editorInfoBorder = registerColor('editorInfo.border', { dark: null, light: null, hc: color_1.Color.fromHex('#75BEFF').transparent(0.8) }, nls.localize(45, null)); - exports.editorHintForeground = registerColor('editorHint.foreground', { dark: color_1.Color.fromHex('#eeeeee').transparent(0.7), light: '#6c6c6c', hc: null }, nls.localize(46, null)); - exports.editorHintBorder = registerColor('editorHint.border', { dark: null, light: null, hc: color_1.Color.fromHex('#eeeeee').transparent(0.8) }, nls.localize(47, null)); - /** - * Editor background color. - * Because of bug https://monacotools.visualstudio.com/DefaultCollection/Monaco/_workitems/edit/13254 - * we are *not* using the color white (or #ffffff, rgba(255,255,255)) but something very close to white. - */ - exports.editorBackground = registerColor('editor.background', { light: '#fffffe', dark: '#1E1E1E', hc: color_1.Color.black }, nls.localize(48, null)); - /** - * Editor foreground color. - */ - exports.editorForeground = registerColor('editor.foreground', { light: '#333333', dark: '#BBBBBB', hc: color_1.Color.white }, nls.localize(49, null)); - /** - * Editor widgets - */ - exports.editorWidgetBackground = registerColor('editorWidget.background', { dark: '#252526', light: '#F3F3F3', hc: '#0C141F' }, nls.localize(50, null)); - exports.editorWidgetForeground = registerColor('editorWidget.foreground', { dark: exports.foreground, light: exports.foreground, hc: exports.foreground }, nls.localize(51, null)); - exports.editorWidgetBorder = registerColor('editorWidget.border', { dark: '#454545', light: '#C8C8C8', hc: exports.contrastBorder }, nls.localize(52, null)); - exports.editorWidgetResizeBorder = registerColor('editorWidget.resizeBorder', { light: null, dark: null, hc: null }, nls.localize(53, null)); - /** - * Quick pick widget - */ - exports.quickInputBackground = registerColor('quickInput.background', { dark: exports.editorWidgetBackground, light: exports.editorWidgetBackground, hc: exports.editorWidgetBackground }, nls.localize(54, null)); - exports.quickInputForeground = registerColor('quickInput.foreground', { dark: exports.editorWidgetForeground, light: exports.editorWidgetForeground, hc: exports.editorWidgetForeground }, nls.localize(55, null)); - exports.quickInputTitleBackground = registerColor('quickInputTitle.background', { dark: new color_1.Color(new color_1.RGBA(255, 255, 255, 0.105)), light: new color_1.Color(new color_1.RGBA(0, 0, 0, 0.06)), hc: '#000000' }, nls.localize(56, null)); - exports.pickerGroupForeground = registerColor('pickerGroup.foreground', { dark: '#3794FF', light: '#0066BF', hc: color_1.Color.white }, nls.localize(57, null)); - exports.pickerGroupBorder = registerColor('pickerGroup.border', { dark: '#3F3F46', light: '#CCCEDB', hc: color_1.Color.white }, nls.localize(58, null)); - /** - * Keybinding label - */ - exports.keybindingLabelBackground = registerColor('keybindingLabel.background', { dark: new color_1.Color(new color_1.RGBA(128, 128, 128, 0.17)), light: new color_1.Color(new color_1.RGBA(221, 221, 221, 0.4)), hc: color_1.Color.transparent }, nls.localize(59, null)); - exports.keybindingLabelForeground = registerColor('keybindingLabel.foreground', { dark: color_1.Color.fromHex('#CCCCCC'), light: color_1.Color.fromHex('#555555'), hc: color_1.Color.white }, nls.localize(60, null)); - exports.keybindingLabelBorder = registerColor('keybindingLabel.border', { dark: new color_1.Color(new color_1.RGBA(51, 51, 51, 0.6)), light: new color_1.Color(new color_1.RGBA(204, 204, 204, 0.4)), hc: new color_1.Color(new color_1.RGBA(111, 195, 223)) }, nls.localize(61, null)); - exports.keybindingLabelBottomBorder = registerColor('keybindingLabel.bottomBorder', { dark: new color_1.Color(new color_1.RGBA(68, 68, 68, 0.6)), light: new color_1.Color(new color_1.RGBA(187, 187, 187, 0.4)), hc: new color_1.Color(new color_1.RGBA(111, 195, 223)) }, nls.localize(62, null)); - /** - * Editor selection colors. - */ - exports.editorSelectionBackground = registerColor('editor.selectionBackground', { light: '#ADD6FF', dark: '#264F78', hc: '#f3f518' }, nls.localize(63, null)); - exports.editorSelectionForeground = registerColor('editor.selectionForeground', { light: null, dark: null, hc: '#000000' }, nls.localize(64, null)); - exports.editorInactiveSelection = registerColor('editor.inactiveSelectionBackground', { light: transparent(exports.editorSelectionBackground, 0.5), dark: transparent(exports.editorSelectionBackground, 0.5), hc: transparent(exports.editorSelectionBackground, 0.5) }, nls.localize(65, null), true); - exports.editorSelectionHighlight = registerColor('editor.selectionHighlightBackground', { light: lessProminent(exports.editorSelectionBackground, exports.editorBackground, 0.3, 0.6), dark: lessProminent(exports.editorSelectionBackground, exports.editorBackground, 0.3, 0.6), hc: null }, nls.localize(66, null), true); - exports.editorSelectionHighlightBorder = registerColor('editor.selectionHighlightBorder', { light: null, dark: null, hc: exports.activeContrastBorder }, nls.localize(67, null)); - /** - * Editor find match colors. - */ - exports.editorFindMatch = registerColor('editor.findMatchBackground', { light: '#A8AC94', dark: '#515C6A', hc: null }, nls.localize(68, null)); - exports.editorFindMatchHighlight = registerColor('editor.findMatchHighlightBackground', { light: '#EA5C0055', dark: '#EA5C0055', hc: null }, nls.localize(69, null), true); - exports.editorFindRangeHighlight = registerColor('editor.findRangeHighlightBackground', { dark: '#3a3d4166', light: '#b4b4b44d', hc: null }, nls.localize(70, null), true); - exports.editorFindMatchBorder = registerColor('editor.findMatchBorder', { light: null, dark: null, hc: exports.activeContrastBorder }, nls.localize(71, null)); - exports.editorFindMatchHighlightBorder = registerColor('editor.findMatchHighlightBorder', { light: null, dark: null, hc: exports.activeContrastBorder }, nls.localize(72, null)); - exports.editorFindRangeHighlightBorder = registerColor('editor.findRangeHighlightBorder', { dark: null, light: null, hc: transparent(exports.activeContrastBorder, 0.4) }, nls.localize(73, null), true); - /** - * Editor hover - */ - exports.editorHoverHighlight = registerColor('editor.hoverHighlightBackground', { light: '#ADD6FF26', dark: '#264f7840', hc: '#ADD6FF26' }, nls.localize(74, null), true); - exports.editorHoverBackground = registerColor('editorHoverWidget.background', { light: exports.editorWidgetBackground, dark: exports.editorWidgetBackground, hc: exports.editorWidgetBackground }, nls.localize(75, null)); - exports.editorHoverForeground = registerColor('editorHoverWidget.foreground', { light: exports.editorWidgetForeground, dark: exports.editorWidgetForeground, hc: exports.editorWidgetForeground }, nls.localize(76, null)); - exports.editorHoverBorder = registerColor('editorHoverWidget.border', { light: exports.editorWidgetBorder, dark: exports.editorWidgetBorder, hc: exports.editorWidgetBorder }, nls.localize(77, null)); - exports.editorHoverStatusBarBackground = registerColor('editorHoverWidget.statusBarBackground', { dark: lighten(exports.editorHoverBackground, 0.2), light: darken(exports.editorHoverBackground, 0.05), hc: exports.editorWidgetBackground }, nls.localize(78, null)); - /** - * Editor link colors - */ - exports.editorActiveLinkForeground = registerColor('editorLink.activeForeground', { dark: '#4E94CE', light: color_1.Color.blue, hc: color_1.Color.cyan }, nls.localize(79, null)); - /** - * Inline hints - */ - exports.editorInlayHintForeground = registerColor('editorInlayHint.foreground', { dark: transparent(exports.badgeForeground, .8), light: transparent(exports.badgeForeground, .8), hc: exports.badgeForeground }, nls.localize(80, null)); - exports.editorInlayHintBackground = registerColor('editorInlayHint.background', { dark: transparent(exports.badgeBackground, .6), light: transparent(exports.badgeBackground, .3), hc: exports.badgeBackground }, nls.localize(81, null)); - /** - * Editor lighbulb icon colors - */ - exports.editorLightBulbForeground = registerColor('editorLightBulb.foreground', { dark: '#FFCC00', light: '#DDB100', hc: '#FFCC00' }, nls.localize(82, null)); - exports.editorLightBulbAutoFixForeground = registerColor('editorLightBulbAutoFix.foreground', { dark: '#75BEFF', light: '#007ACC', hc: '#75BEFF' }, nls.localize(83, null)); - /** - * Diff Editor Colors - */ - exports.defaultInsertColor = new color_1.Color(new color_1.RGBA(155, 185, 85, 0.2)); - exports.defaultRemoveColor = new color_1.Color(new color_1.RGBA(255, 0, 0, 0.2)); - exports.diffInserted = registerColor('diffEditor.insertedTextBackground', { dark: exports.defaultInsertColor, light: exports.defaultInsertColor, hc: null }, nls.localize(84, null), true); - exports.diffRemoved = registerColor('diffEditor.removedTextBackground', { dark: exports.defaultRemoveColor, light: exports.defaultRemoveColor, hc: null }, nls.localize(85, null), true); - exports.diffInsertedOutline = registerColor('diffEditor.insertedTextBorder', { dark: null, light: null, hc: '#33ff2eff' }, nls.localize(86, null)); - exports.diffRemovedOutline = registerColor('diffEditor.removedTextBorder', { dark: null, light: null, hc: '#FF008F' }, nls.localize(87, null)); - exports.diffBorder = registerColor('diffEditor.border', { dark: null, light: null, hc: exports.contrastBorder }, nls.localize(88, null)); - exports.diffDiagonalFill = registerColor('diffEditor.diagonalFill', { dark: '#cccccc33', light: '#22222233', hc: null }, nls.localize(89, null)); - /** - * List and tree colors - */ - exports.listFocusBackground = registerColor('list.focusBackground', { dark: null, light: null, hc: null }, nls.localize(90, null)); - exports.listFocusForeground = registerColor('list.focusForeground', { dark: null, light: null, hc: null }, nls.localize(91, null)); - exports.listFocusOutline = registerColor('list.focusOutline', { dark: exports.focusBorder, light: exports.focusBorder, hc: exports.activeContrastBorder }, nls.localize(92, null)); - exports.listActiveSelectionBackground = registerColor('list.activeSelectionBackground', { dark: '#094771', light: '#0060C0', hc: null }, nls.localize(93, null)); - exports.listActiveSelectionForeground = registerColor('list.activeSelectionForeground', { dark: color_1.Color.white, light: color_1.Color.white, hc: null }, nls.localize(94, null)); - exports.listActiveSelectionIconForeground = registerColor('list.activeSelectionIconForeground', { dark: null, light: null, hc: null }, nls.localize(95, null)); - exports.listInactiveSelectionBackground = registerColor('list.inactiveSelectionBackground', { dark: '#37373D', light: '#E4E6F1', hc: null }, nls.localize(96, null)); - exports.listInactiveSelectionForeground = registerColor('list.inactiveSelectionForeground', { dark: null, light: null, hc: null }, nls.localize(97, null)); - exports.listInactiveSelectionIconForeground = registerColor('list.inactiveSelectionIconForeground', { dark: null, light: null, hc: null }, nls.localize(98, null)); - exports.listInactiveFocusBackground = registerColor('list.inactiveFocusBackground', { dark: null, light: null, hc: null }, nls.localize(99, null)); - exports.listInactiveFocusOutline = registerColor('list.inactiveFocusOutline', { dark: null, light: null, hc: null }, nls.localize(100, null)); - exports.listHoverBackground = registerColor('list.hoverBackground', { dark: '#2A2D2E', light: '#F0F0F0', hc: null }, nls.localize(101, null)); - exports.listHoverForeground = registerColor('list.hoverForeground', { dark: null, light: null, hc: null }, nls.localize(102, null)); - exports.listDropBackground = registerColor('list.dropBackground', { dark: '#062F4A', light: '#D6EBFF', hc: null }, nls.localize(103, null)); - exports.listHighlightForeground = registerColor('list.highlightForeground', { dark: '#18A3FF', light: '#0066BF', hc: exports.focusBorder }, nls.localize(104, null)); - exports.listFocusHighlightForeground = registerColor('list.focusHighlightForeground', { dark: exports.listHighlightForeground, light: ifDefinedThenElse(exports.listActiveSelectionBackground, exports.listHighlightForeground, '#9DDDFF'), hc: exports.listHighlightForeground }, nls.localize(105, null)); - exports.listFilterWidgetBackground = registerColor('listFilterWidget.background', { light: '#efc1ad', dark: '#653723', hc: color_1.Color.black }, nls.localize(106, null)); - exports.listFilterWidgetOutline = registerColor('listFilterWidget.outline', { dark: color_1.Color.transparent, light: color_1.Color.transparent, hc: '#f38518' }, nls.localize(107, null)); - exports.listFilterWidgetNoMatchesOutline = registerColor('listFilterWidget.noMatchesOutline', { dark: '#BE1100', light: '#BE1100', hc: exports.contrastBorder }, nls.localize(108, null)); - exports.treeIndentGuidesStroke = registerColor('tree.indentGuidesStroke', { dark: '#585858', light: '#a9a9a9', hc: '#a9a9a9' }, nls.localize(109, null)); - exports.tableColumnsBorder = registerColor('tree.tableColumnsBorder', { dark: '#CCCCCC20', light: '#61616120', hc: null }, nls.localize(110, null)); - /** - * Quick pick widget (dependent on List and tree colors) - */ - exports._deprecatedQuickInputListFocusBackground = registerColor('quickInput.list.focusBackground', { dark: null, light: null, hc: null }, '', undefined, nls.localize(111, null)); - exports.quickInputListFocusForeground = registerColor('quickInputList.focusForeground', { dark: exports.listActiveSelectionForeground, light: exports.listActiveSelectionForeground, hc: exports.listActiveSelectionForeground }, nls.localize(112, null)); - exports.quickInputListFocusIconForeground = registerColor('quickInputList.focusIconForeground', { dark: exports.listActiveSelectionIconForeground, light: exports.listActiveSelectionIconForeground, hc: exports.listActiveSelectionIconForeground }, nls.localize(113, null)); - exports.quickInputListFocusBackground = registerColor('quickInputList.focusBackground', { dark: oneOf(exports._deprecatedQuickInputListFocusBackground, exports.listActiveSelectionBackground), light: oneOf(exports._deprecatedQuickInputListFocusBackground, exports.listActiveSelectionBackground), hc: null }, nls.localize(114, null)); - /** - * Menu colors - */ - exports.menuBorder = registerColor('menu.border', { dark: null, light: null, hc: exports.contrastBorder }, nls.localize(115, null)); - exports.menuForeground = registerColor('menu.foreground', { dark: exports.selectForeground, light: exports.foreground, hc: exports.selectForeground }, nls.localize(116, null)); - exports.menuBackground = registerColor('menu.background', { dark: exports.selectBackground, light: exports.selectBackground, hc: exports.selectBackground }, nls.localize(117, null)); - exports.menuSelectionForeground = registerColor('menu.selectionForeground', { dark: exports.listActiveSelectionForeground, light: exports.listActiveSelectionForeground, hc: exports.listActiveSelectionForeground }, nls.localize(118, null)); - exports.menuSelectionBackground = registerColor('menu.selectionBackground', { dark: exports.listActiveSelectionBackground, light: exports.listActiveSelectionBackground, hc: exports.listActiveSelectionBackground }, nls.localize(119, null)); - exports.menuSelectionBorder = registerColor('menu.selectionBorder', { dark: null, light: null, hc: exports.activeContrastBorder }, nls.localize(120, null)); - exports.menuSeparatorBackground = registerColor('menu.separatorBackground', { dark: '#BBBBBB', light: '#888888', hc: exports.contrastBorder }, nls.localize(121, null)); - /** - * Snippet placeholder colors - */ - exports.snippetTabstopHighlightBackground = registerColor('editor.snippetTabstopHighlightBackground', { dark: new color_1.Color(new color_1.RGBA(124, 124, 124, 0.3)), light: new color_1.Color(new color_1.RGBA(10, 50, 100, 0.2)), hc: new color_1.Color(new color_1.RGBA(124, 124, 124, 0.3)) }, nls.localize(122, null)); - exports.snippetTabstopHighlightBorder = registerColor('editor.snippetTabstopHighlightBorder', { dark: null, light: null, hc: null }, nls.localize(123, null)); - exports.snippetFinalTabstopHighlightBackground = registerColor('editor.snippetFinalTabstopHighlightBackground', { dark: null, light: null, hc: null }, nls.localize(124, null)); - exports.snippetFinalTabstopHighlightBorder = registerColor('editor.snippetFinalTabstopHighlightBorder', { dark: '#525252', light: new color_1.Color(new color_1.RGBA(10, 50, 100, 0.5)), hc: '#525252' }, nls.localize(125, null)); - exports.overviewRulerFindMatchForeground = registerColor('editorOverviewRuler.findMatchForeground', { dark: '#d186167e', light: '#d186167e', hc: '#AB5A00' }, nls.localize(126, null), true); - exports.overviewRulerSelectionHighlightForeground = registerColor('editorOverviewRuler.selectionHighlightForeground', { dark: '#A0A0A0CC', light: '#A0A0A0CC', hc: '#A0A0A0CC' }, nls.localize(127, null), true); - exports.minimapFindMatch = registerColor('minimap.findMatchHighlight', { light: '#d18616', dark: '#d18616', hc: '#AB5A00' }, nls.localize(128, null), true); - exports.minimapSelection = registerColor('minimap.selectionHighlight', { light: '#ADD6FF', dark: '#264F78', hc: '#ffffff' }, nls.localize(129, null), true); - exports.minimapError = registerColor('minimap.errorHighlight', { dark: new color_1.Color(new color_1.RGBA(255, 18, 18, 0.7)), light: new color_1.Color(new color_1.RGBA(255, 18, 18, 0.7)), hc: new color_1.Color(new color_1.RGBA(255, 50, 50, 1)) }, nls.localize(130, null)); - exports.minimapWarning = registerColor('minimap.warningHighlight', { dark: exports.editorWarningForeground, light: exports.editorWarningForeground, hc: exports.editorWarningBorder }, nls.localize(131, null)); - exports.minimapBackground = registerColor('minimap.background', { dark: null, light: null, hc: null }, nls.localize(132, null)); - exports.minimapSliderBackground = registerColor('minimapSlider.background', { light: transparent(exports.scrollbarSliderBackground, 0.5), dark: transparent(exports.scrollbarSliderBackground, 0.5), hc: transparent(exports.scrollbarSliderBackground, 0.5) }, nls.localize(133, null)); - exports.minimapSliderHoverBackground = registerColor('minimapSlider.hoverBackground', { light: transparent(exports.scrollbarSliderHoverBackground, 0.5), dark: transparent(exports.scrollbarSliderHoverBackground, 0.5), hc: transparent(exports.scrollbarSliderHoverBackground, 0.5) }, nls.localize(134, null)); - exports.minimapSliderActiveBackground = registerColor('minimapSlider.activeBackground', { light: transparent(exports.scrollbarSliderActiveBackground, 0.5), dark: transparent(exports.scrollbarSliderActiveBackground, 0.5), hc: transparent(exports.scrollbarSliderActiveBackground, 0.5) }, nls.localize(135, null)); - exports.problemsErrorIconForeground = registerColor('problemsErrorIcon.foreground', { dark: exports.editorErrorForeground, light: exports.editorErrorForeground, hc: exports.editorErrorForeground }, nls.localize(136, null)); - exports.problemsWarningIconForeground = registerColor('problemsWarningIcon.foreground', { dark: exports.editorWarningForeground, light: exports.editorWarningForeground, hc: exports.editorWarningForeground }, nls.localize(137, null)); - exports.problemsInfoIconForeground = registerColor('problemsInfoIcon.foreground', { dark: exports.editorInfoForeground, light: exports.editorInfoForeground, hc: exports.editorInfoForeground }, nls.localize(138, null)); - // ----- color functions - function executeTransform(transform, theme) { - var _a, _b, _c; - switch (transform.op) { - case 0 /* Darken */: - return (_a = resolveColorValue(transform.value, theme)) === null || _a === void 0 ? void 0 : _a.darken(transform.factor); - case 1 /* Lighten */: - return (_b = resolveColorValue(transform.value, theme)) === null || _b === void 0 ? void 0 : _b.lighten(transform.factor); - case 2 /* Transparent */: - return (_c = resolveColorValue(transform.value, theme)) === null || _c === void 0 ? void 0 : _c.transparent(transform.factor); - case 3 /* OneOf */: - for (const candidate of transform.values) { - const color = resolveColorValue(candidate, theme); - if (color) { - return color; - } - } - return undefined; - case 5 /* IfDefinedThenElse */: - return resolveColorValue(theme.defines(transform.if) ? transform.then : transform.else, theme); - case 4 /* LessProminent */: - const from = resolveColorValue(transform.value, theme); - if (!from) { - return undefined; - } - const backgroundColor = resolveColorValue(transform.background, theme); - if (!backgroundColor) { - return from.transparent(transform.factor * transform.transparency); - } - return from.isDarkerThan(backgroundColor) - ? color_1.Color.getLighterColor(from, backgroundColor, transform.factor).transparent(transform.transparency) - : color_1.Color.getDarkerColor(from, backgroundColor, transform.factor).transparent(transform.transparency); - default: - throw (0, types_1.assertNever)(transform); - } - } - exports.executeTransform = executeTransform; - function darken(colorValue, factor) { - return { op: 0 /* Darken */, value: colorValue, factor }; - } - exports.darken = darken; - function lighten(colorValue, factor) { - return { op: 1 /* Lighten */, value: colorValue, factor }; - } - exports.lighten = lighten; - function transparent(colorValue, factor) { - return { op: 2 /* Transparent */, value: colorValue, factor }; - } - exports.transparent = transparent; - function oneOf(...colorValues) { - return { op: 3 /* OneOf */, values: colorValues }; - } - exports.oneOf = oneOf; - function ifDefinedThenElse(ifArg, thenArg, elseArg) { - return { op: 5 /* IfDefinedThenElse */, if: ifArg, then: thenArg, else: elseArg }; - } - exports.ifDefinedThenElse = ifDefinedThenElse; - function lessProminent(colorValue, backgroundColorValue, factor, transparency) { - return { op: 4 /* LessProminent */, value: colorValue, background: backgroundColorValue, factor, transparency }; - } - // ----- implementation - /** - * @param colorValue Resolve a color value in the context of a theme - */ - function resolveColorValue(colorValue, theme) { - if (colorValue === null) { - return undefined; - } - else if (typeof colorValue === 'string') { - if (colorValue[0] === '#') { - return color_1.Color.fromHex(colorValue); - } - return theme.getColor(colorValue); - } - else if (colorValue instanceof color_1.Color) { - return colorValue; - } - else if (typeof colorValue === 'object') { - return executeTransform(colorValue, theme); - } - return undefined; - } - exports.resolveColorValue = resolveColorValue; - exports.workbenchColorsSchemaId = 'vscode://schemas/workbench-colors'; - let schemaRegistry = platform.Registry.as(jsonContributionRegistry_1.Extensions.JSONContribution); - schemaRegistry.registerSchema(exports.workbenchColorsSchemaId, colorRegistry.getColorSchema()); - const delayer = new async_1.RunOnceScheduler(() => schemaRegistry.notifySchemaChanged(exports.workbenchColorsSchemaId), 200); - colorRegistry.onDidChangeSchema(() => { - if (!delayer.isScheduled()) { - delayer.schedule(); - } - }); -}); -// setTimeout(_ => console.log(colorRegistry.toString()), 5000); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[122/*vs/platform/theme/common/styler*/], __M([0/*require*/,1/*exports*/,22/*vs/platform/theme/common/colorRegistry*/]), function (require, exports, colorRegistry_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.attachMenuStyler = exports.defaultMenuStyles = exports.defaultListStyles = exports.attachListStyler = exports.attachBadgeStyler = exports.attachStyler = exports.computeStyles = void 0; - function computeStyles(theme, styleMap) { - const styles = Object.create(null); - for (let key in styleMap) { - const value = styleMap[key]; - if (value) { - styles[key] = (0, colorRegistry_1.resolveColorValue)(value, theme); - } - } - return styles; - } - exports.computeStyles = computeStyles; - function attachStyler(themeService, styleMap, widgetOrCallback) { - function applyStyles() { - const styles = computeStyles(themeService.getColorTheme(), styleMap); - if (typeof widgetOrCallback === 'function') { - widgetOrCallback(styles); - } - else { - widgetOrCallback.style(styles); - } - } - applyStyles(); - return themeService.onDidColorThemeChange(applyStyles); - } - exports.attachStyler = attachStyler; - function attachBadgeStyler(widget, themeService, style) { - return attachStyler(themeService, { - badgeBackground: (style === null || style === void 0 ? void 0 : style.badgeBackground) || colorRegistry_1.badgeBackground, - badgeForeground: (style === null || style === void 0 ? void 0 : style.badgeForeground) || colorRegistry_1.badgeForeground, - badgeBorder: colorRegistry_1.contrastBorder - }, widget); - } - exports.attachBadgeStyler = attachBadgeStyler; - function attachListStyler(widget, themeService, overrides) { - return attachStyler(themeService, Object.assign(Object.assign({}, exports.defaultListStyles), (overrides || {})), widget); - } - exports.attachListStyler = attachListStyler; - exports.defaultListStyles = { - listFocusBackground: colorRegistry_1.listFocusBackground, - listFocusForeground: colorRegistry_1.listFocusForeground, - listFocusOutline: colorRegistry_1.listFocusOutline, - listActiveSelectionBackground: colorRegistry_1.listActiveSelectionBackground, - listActiveSelectionForeground: colorRegistry_1.listActiveSelectionForeground, - listActiveSelectionIconForeground: colorRegistry_1.listActiveSelectionIconForeground, - listFocusAndSelectionBackground: colorRegistry_1.listActiveSelectionBackground, - listFocusAndSelectionForeground: colorRegistry_1.listActiveSelectionForeground, - listInactiveSelectionBackground: colorRegistry_1.listInactiveSelectionBackground, - listInactiveSelectionIconForeground: colorRegistry_1.listInactiveSelectionIconForeground, - listInactiveSelectionForeground: colorRegistry_1.listInactiveSelectionForeground, - listInactiveFocusBackground: colorRegistry_1.listInactiveFocusBackground, - listInactiveFocusOutline: colorRegistry_1.listInactiveFocusOutline, - listHoverBackground: colorRegistry_1.listHoverBackground, - listHoverForeground: colorRegistry_1.listHoverForeground, - listDropBackground: colorRegistry_1.listDropBackground, - listSelectionOutline: colorRegistry_1.activeContrastBorder, - listHoverOutline: colorRegistry_1.activeContrastBorder, - listFilterWidgetBackground: colorRegistry_1.listFilterWidgetBackground, - listFilterWidgetOutline: colorRegistry_1.listFilterWidgetOutline, - listFilterWidgetNoMatchesOutline: colorRegistry_1.listFilterWidgetNoMatchesOutline, - listMatchesShadow: colorRegistry_1.widgetShadow, - treeIndentGuidesStroke: colorRegistry_1.treeIndentGuidesStroke, - tableColumnsBorder: colorRegistry_1.tableColumnsBorder - }; - exports.defaultMenuStyles = { - shadowColor: colorRegistry_1.widgetShadow, - borderColor: colorRegistry_1.menuBorder, - foregroundColor: colorRegistry_1.menuForeground, - backgroundColor: colorRegistry_1.menuBackground, - selectionForegroundColor: colorRegistry_1.menuSelectionForeground, - selectionBackgroundColor: colorRegistry_1.menuSelectionBackground, - selectionBorderColor: colorRegistry_1.menuSelectionBorder, - separatorColor: colorRegistry_1.menuSeparatorBackground - }; - function attachMenuStyler(widget, themeService, style) { - return attachStyler(themeService, Object.assign(Object.assign({}, exports.defaultMenuStyles), style), widget); - } - exports.attachMenuStyler = attachMenuStyler; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[593/*vs/platform/contextview/browser/contextMenuHandler*/], __M([0/*require*/,1/*exports*/,50/*vs/base/common/actions*/,2/*vs/base/common/lifecycle*/,444/*vs/base/browser/ui/menu/menu*/,7/*vs/base/browser/dom*/,122/*vs/platform/theme/common/styler*/,55/*vs/base/browser/mouseEvent*/,12/*vs/base/common/errors*/,369/*vs/css!vs/platform/contextview/browser/contextMenuHandler*/]), function (require, exports, actions_1, lifecycle_1, menu_1, dom_1, styler_1, mouseEvent_1, errors_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ContextMenuHandler = void 0; - class ContextMenuHandler { - constructor(contextViewService, telemetryService, notificationService, keybindingService, themeService) { - this.contextViewService = contextViewService; - this.telemetryService = telemetryService; - this.notificationService = notificationService; - this.keybindingService = keybindingService; - this.themeService = themeService; - this.focusToReturn = null; - this.block = null; - this.options = { blockMouse: true }; - } - configure(options) { - this.options = options; - } - showContextMenu(delegate) { - const actions = delegate.getActions(); - if (!actions.length) { - return; // Don't render an empty context menu - } - this.focusToReturn = document.activeElement; - let menu; - let shadowRootElement = (0, dom_1.isHTMLElement)(delegate.domForShadowRoot) ? delegate.domForShadowRoot : undefined; - this.contextViewService.showContextView({ - getAnchor: () => delegate.getAnchor(), - canRelayout: false, - anchorAlignment: delegate.anchorAlignment, - anchorAxisAlignment: delegate.anchorAxisAlignment, - render: (container) => { - let className = delegate.getMenuClassName ? delegate.getMenuClassName() : ''; - if (className) { - container.className += ' ' + className; - } - // Render invisible div to block mouse interaction in the rest of the UI - if (this.options.blockMouse) { - this.block = container.appendChild((0, dom_1.$)('.context-view-block')); - this.block.style.position = 'fixed'; - this.block.style.cursor = 'initial'; - this.block.style.left = '0'; - this.block.style.top = '0'; - this.block.style.width = '100%'; - this.block.style.height = '100%'; - this.block.style.zIndex = '-1'; - // TODO@Steven: this is never getting disposed - (0, dom_1.addDisposableListener)(this.block, dom_1.EventType.MOUSE_DOWN, e => e.stopPropagation()); - } - const menuDisposables = new lifecycle_1.DisposableStore(); - const actionRunner = delegate.actionRunner || new actions_1.ActionRunner(); - actionRunner.onBeforeRun(this.onActionRun, this, menuDisposables); - actionRunner.onDidRun(this.onDidActionRun, this, menuDisposables); - menu = new menu_1.Menu(container, actions, { - actionViewItemProvider: delegate.getActionViewItem, - context: delegate.getActionsContext ? delegate.getActionsContext() : null, - actionRunner, - getKeyBinding: delegate.getKeyBinding ? delegate.getKeyBinding : action => this.keybindingService.lookupKeybinding(action.id) - }); - menuDisposables.add((0, styler_1.attachMenuStyler)(menu, this.themeService)); - menu.onDidCancel(() => this.contextViewService.hideContextView(true), null, menuDisposables); - menu.onDidBlur(() => this.contextViewService.hideContextView(true), null, menuDisposables); - menuDisposables.add((0, dom_1.addDisposableListener)(window, dom_1.EventType.BLUR, () => this.contextViewService.hideContextView(true))); - menuDisposables.add((0, dom_1.addDisposableListener)(window, dom_1.EventType.MOUSE_DOWN, (e) => { - if (e.defaultPrevented) { - return; - } - let event = new mouseEvent_1.StandardMouseEvent(e); - let element = event.target; - // Don't do anything as we are likely creating a context menu - if (event.rightButton) { - return; - } - while (element) { - if (element === container) { - return; - } - element = element.parentElement; - } - this.contextViewService.hideContextView(true); - })); - return (0, lifecycle_1.combinedDisposable)(menuDisposables, menu); - }, - focus: () => { - if (menu) { - menu.focus(!!delegate.autoSelectFirstItem); - } - }, - onHide: (didCancel) => { - if (delegate.onHide) { - delegate.onHide(!!didCancel); - } - if (this.block) { - this.block.remove(); - this.block = null; - } - if (this.focusToReturn) { - this.focusToReturn.focus(); - } - } - }, shadowRootElement, !!shadowRootElement); - } - onActionRun(e) { - this.telemetryService.publicLog2('workbenchActionExecuted', { id: e.action.id, from: 'contextMenu' }); - this.contextViewService.hideContextView(false); - // Restore focus here - if (this.focusToReturn) { - this.focusToReturn.focus(); - } - } - onDidActionRun(e) { - if (e.error && !(0, errors_1.isPromiseCanceledError)(e.error)) { - this.notificationService.error(e.error); - } - } - } - exports.ContextMenuHandler = ContextMenuHandler; -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[100/*vs/platform/theme/common/theme*/], __M([0/*require*/,1/*exports*/]), function (require, exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ColorScheme = void 0; - /** - * Color scheme used by the OS and by color themes. - */ - var ColorScheme; - (function (ColorScheme) { - ColorScheme["DARK"] = "dark"; - ColorScheme["LIGHT"] = "light"; - ColorScheme["HIGH_CONTRAST"] = "hc"; - })(ColorScheme = exports.ColorScheme || (exports.ColorScheme = {})); -}); - -/*--------------------------------------------------------------------------------------------- - * 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/editor/browser/viewParts/lines/viewLine*/], __M([0/*require*/,1/*exports*/,39/*vs/base/browser/browser*/,30/*vs/base/browser/fastDomNode*/,17/*vs/base/common/platform*/,392/*vs/editor/browser/viewParts/lines/rangeUtil*/,113/*vs/editor/common/view/renderingContext*/,136/*vs/editor/common/viewLayout/lineDecorations*/,114/*vs/editor/common/viewLayout/viewLineRenderer*/,100/*vs/platform/theme/common/theme*/,35/*vs/editor/common/config/editorOptions*/]), function (require, exports, browser, fastDomNode_1, platform, rangeUtil_1, renderingContext_1, lineDecorations_1, viewLineRenderer_1, theme_1, editorOptions_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ViewLine = exports.ViewLineOptions = exports.DomReadingContext = void 0; - const canUseFastRenderedViewLine = (function () { - if (platform.isNative) { - // In VSCode we know very well when the zoom level changes - return true; - } - if (platform.isLinux || browser.isFirefox || browser.isSafari) { - // On Linux, it appears that zooming affects char widths (in pixels), which is unexpected. - // -- - // Even though we read character widths correctly, having read them at a specific zoom level - // does not mean they are the same at the current zoom level. - // -- - // This could be improved if we ever figure out how to get an event when browsers zoom, - // but until then we have to stick with reading client rects. - // -- - // The same has been observed with Firefox on Windows7 - // -- - // The same has been oversved with Safari - return false; - } - return true; - })(); - let monospaceAssumptionsAreValid = true; - class DomReadingContext { - constructor(domNode, endNode) { - this._domNode = domNode; - this._clientRectDeltaLeft = 0; - this._clientRectDeltaLeftRead = false; - this.endNode = endNode; - } - get clientRectDeltaLeft() { - if (!this._clientRectDeltaLeftRead) { - this._clientRectDeltaLeftRead = true; - this._clientRectDeltaLeft = this._domNode.getBoundingClientRect().left; - } - return this._clientRectDeltaLeft; - } - } - exports.DomReadingContext = DomReadingContext; - class ViewLineOptions { - constructor(config, themeType) { - this.themeType = themeType; - const options = config.options; - const fontInfo = options.get(41 /* fontInfo */); - this.renderWhitespace = options.get(87 /* renderWhitespace */); - this.renderControlCharacters = options.get(81 /* renderControlCharacters */); - this.spaceWidth = fontInfo.spaceWidth; - this.middotWidth = fontInfo.middotWidth; - this.wsmiddotWidth = fontInfo.wsmiddotWidth; - this.useMonospaceOptimizations = (fontInfo.isMonospace - && !options.get(27 /* disableMonospaceOptimizations */)); - this.canUseHalfwidthRightwardsArrow = fontInfo.canUseHalfwidthRightwardsArrow; - this.lineHeight = options.get(57 /* lineHeight */); - this.stopRenderingLineAfter = options.get(104 /* stopRenderingLineAfter */); - this.fontLigatures = options.get(42 /* fontLigatures */); - } - equals(other) { - return (this.themeType === other.themeType - && this.renderWhitespace === other.renderWhitespace - && this.renderControlCharacters === other.renderControlCharacters - && this.spaceWidth === other.spaceWidth - && this.middotWidth === other.middotWidth - && this.wsmiddotWidth === other.wsmiddotWidth - && this.useMonospaceOptimizations === other.useMonospaceOptimizations - && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow - && this.lineHeight === other.lineHeight - && this.stopRenderingLineAfter === other.stopRenderingLineAfter - && this.fontLigatures === other.fontLigatures); - } - } - exports.ViewLineOptions = ViewLineOptions; - class ViewLine { - constructor(options) { - this._options = options; - this._isMaybeInvalid = true; - this._renderedViewLine = null; - } - // --- begin IVisibleLineData - getDomNode() { - if (this._renderedViewLine && this._renderedViewLine.domNode) { - return this._renderedViewLine.domNode.domNode; - } - return null; - } - setDomNode(domNode) { - if (this._renderedViewLine) { - this._renderedViewLine.domNode = (0, fastDomNode_1.createFastDomNode)(domNode); - } - else { - throw new Error('I have no rendered view line to set the dom node to...'); - } - } - onContentChanged() { - this._isMaybeInvalid = true; - } - onTokensChanged() { - this._isMaybeInvalid = true; - } - onDecorationsChanged() { - this._isMaybeInvalid = true; - } - onOptionsChanged(newOptions) { - this._isMaybeInvalid = true; - this._options = newOptions; - } - onSelectionChanged() { - if (this._options.themeType === theme_1.ColorScheme.HIGH_CONTRAST || this._options.renderWhitespace === 'selection') { - this._isMaybeInvalid = true; - return true; - } - return false; - } - renderLine(lineNumber, deltaTop, viewportData, sb) { - if (this._isMaybeInvalid === false) { - // it appears that nothing relevant has changed - return false; - } - this._isMaybeInvalid = false; - const lineData = viewportData.getViewLineRenderingData(lineNumber); - const options = this._options; - const actualInlineDecorations = lineDecorations_1.LineDecoration.filter(lineData.inlineDecorations, lineNumber, lineData.minColumn, lineData.maxColumn); - // Only send selection information when needed for rendering whitespace - let selectionsOnLine = null; - if (options.themeType === theme_1.ColorScheme.HIGH_CONTRAST || this._options.renderWhitespace === 'selection') { - const selections = viewportData.selections; - for (const selection of selections) { - if (selection.endLineNumber < lineNumber || selection.startLineNumber > lineNumber) { - // Selection does not intersect line - continue; - } - const startColumn = (selection.startLineNumber === lineNumber ? selection.startColumn : lineData.minColumn); - const endColumn = (selection.endLineNumber === lineNumber ? selection.endColumn : lineData.maxColumn); - if (startColumn < endColumn) { - if (options.themeType === theme_1.ColorScheme.HIGH_CONTRAST || this._options.renderWhitespace !== 'selection') { - actualInlineDecorations.push(new lineDecorations_1.LineDecoration(startColumn, endColumn, 'inline-selected-text', 0 /* Regular */)); - } - else { - if (!selectionsOnLine) { - selectionsOnLine = []; - } - selectionsOnLine.push(new viewLineRenderer_1.LineRange(startColumn - 1, endColumn - 1)); - } - } - } - } - const renderLineInput = new viewLineRenderer_1.RenderLineInput(options.useMonospaceOptimizations, options.canUseHalfwidthRightwardsArrow, lineData.content, lineData.continuesWithWrappedLine, lineData.isBasicASCII, lineData.containsRTL, lineData.minColumn - 1, lineData.tokens, actualInlineDecorations, lineData.tabSize, lineData.startVisibleColumn, options.spaceWidth, options.middotWidth, options.wsmiddotWidth, options.stopRenderingLineAfter, options.renderWhitespace, options.renderControlCharacters, options.fontLigatures !== editorOptions_1.EditorFontLigatures.OFF, selectionsOnLine); - if (this._renderedViewLine && this._renderedViewLine.input.equals(renderLineInput)) { - // no need to do anything, we have the same render input - return false; - } - sb.appendASCIIString('
    '); - const output = (0, viewLineRenderer_1.renderViewLine)(renderLineInput, sb); - sb.appendASCIIString('
    '); - let renderedViewLine = null; - if (monospaceAssumptionsAreValid && canUseFastRenderedViewLine && lineData.isBasicASCII && options.useMonospaceOptimizations && output.containsForeignElements === 0 /* None */) { - if (lineData.content.length < 300 && renderLineInput.lineTokens.getCount() < 100) { - // Browser rounding errors have been observed in Chrome and IE, so using the fast - // view line only for short lines. Please test before removing the length check... - // --- - // Another rounding error has been observed on Linux in VSCode, where width - // rounding errors add up to an observable large number... - // --- - // Also see another example of rounding errors on Windows in - // https://github.com/microsoft/vscode/issues/33178 - renderedViewLine = new FastRenderedViewLine(this._renderedViewLine ? this._renderedViewLine.domNode : null, renderLineInput, output.characterMapping); - } - } - if (!renderedViewLine) { - renderedViewLine = createRenderedLine(this._renderedViewLine ? this._renderedViewLine.domNode : null, renderLineInput, output.characterMapping, output.containsRTL, output.containsForeignElements); - } - this._renderedViewLine = renderedViewLine; - return true; - } - layoutLine(lineNumber, deltaTop) { - if (this._renderedViewLine && this._renderedViewLine.domNode) { - this._renderedViewLine.domNode.setTop(deltaTop); - this._renderedViewLine.domNode.setHeight(this._options.lineHeight); - } - } - // --- end IVisibleLineData - getWidth() { - if (!this._renderedViewLine) { - return 0; - } - return this._renderedViewLine.getWidth(); - } - getWidthIsFast() { - if (!this._renderedViewLine) { - return true; - } - return this._renderedViewLine.getWidthIsFast(); - } - needsMonospaceFontCheck() { - if (!this._renderedViewLine) { - return false; - } - return (this._renderedViewLine instanceof FastRenderedViewLine); - } - monospaceAssumptionsAreValid() { - if (!this._renderedViewLine) { - return monospaceAssumptionsAreValid; - } - if (this._renderedViewLine instanceof FastRenderedViewLine) { - return this._renderedViewLine.monospaceAssumptionsAreValid(); - } - return monospaceAssumptionsAreValid; - } - onMonospaceAssumptionsInvalidated() { - if (this._renderedViewLine && this._renderedViewLine instanceof FastRenderedViewLine) { - this._renderedViewLine = this._renderedViewLine.toSlowRenderedLine(); - } - } - getVisibleRangesForRange(startColumn, endColumn, context) { - if (!this._renderedViewLine) { - return null; - } - startColumn = startColumn | 0; // @perf - endColumn = endColumn | 0; // @perf - startColumn = Math.min(this._renderedViewLine.input.lineContent.length + 1, Math.max(1, startColumn)); - endColumn = Math.min(this._renderedViewLine.input.lineContent.length + 1, Math.max(1, endColumn)); - const stopRenderingLineAfter = this._renderedViewLine.input.stopRenderingLineAfter | 0; // @perf - let outsideRenderedLine = false; - if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter + 1 && endColumn > stopRenderingLineAfter + 1) { - // This range is obviously not visible - outsideRenderedLine = true; - } - if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter + 1) { - startColumn = stopRenderingLineAfter + 1; - } - if (stopRenderingLineAfter !== -1 && endColumn > stopRenderingLineAfter + 1) { - endColumn = stopRenderingLineAfter + 1; - } - const horizontalRanges = this._renderedViewLine.getVisibleRangesForRange(startColumn, endColumn, context); - if (horizontalRanges && horizontalRanges.length > 0) { - return new renderingContext_1.VisibleRanges(outsideRenderedLine, horizontalRanges); - } - return null; - } - getColumnOfNodeOffset(lineNumber, spanNode, offset) { - if (!this._renderedViewLine) { - return 1; - } - return this._renderedViewLine.getColumnOfNodeOffset(lineNumber, spanNode, offset); - } - } - exports.ViewLine = ViewLine; - ViewLine.CLASS_NAME = 'view-line'; - /** - * A rendered line which is guaranteed to contain only regular ASCII and is rendered with a monospace font. - */ - class FastRenderedViewLine { - constructor(domNode, renderLineInput, characterMapping) { - this.domNode = domNode; - this.input = renderLineInput; - this._characterMapping = characterMapping; - this._charWidth = renderLineInput.spaceWidth; - } - getWidth() { - return this._getCharPosition(this._characterMapping.length); - } - getWidthIsFast() { - return true; - } - monospaceAssumptionsAreValid() { - if (!this.domNode) { - return monospaceAssumptionsAreValid; - } - const expectedWidth = this.getWidth(); - const actualWidth = this.domNode.domNode.firstChild.offsetWidth; - if (Math.abs(expectedWidth - actualWidth) >= 2) { - // more than 2px off - console.warn(`monospace assumptions have been violated, therefore disabling monospace optimizations!`); - monospaceAssumptionsAreValid = false; - } - return monospaceAssumptionsAreValid; - } - toSlowRenderedLine() { - return createRenderedLine(this.domNode, this.input, this._characterMapping, false, 0 /* None */); - } - getVisibleRangesForRange(startColumn, endColumn, context) { - const startPosition = this._getCharPosition(startColumn); - const endPosition = this._getCharPosition(endColumn); - return [new renderingContext_1.HorizontalRange(startPosition, endPosition - startPosition)]; - } - _getCharPosition(column) { - const charOffset = this._characterMapping.getAbsoluteOffset(column); - return Math.round(this._charWidth * charOffset); - } - getColumnOfNodeOffset(lineNumber, spanNode, offset) { - const spanNodeTextContentLength = spanNode.textContent.length; - let spanIndex = -1; - while (spanNode) { - spanNode = spanNode.previousSibling; - spanIndex++; - } - return this._characterMapping.getColumn(new viewLineRenderer_1.DomPosition(spanIndex, offset), spanNodeTextContentLength); - } - } - /** - * Every time we render a line, we save what we have rendered in an instance of this class. - */ - class RenderedViewLine { - constructor(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements) { - this.domNode = domNode; - this.input = renderLineInput; - this._characterMapping = characterMapping; - this._isWhitespaceOnly = /^\s*$/.test(renderLineInput.lineContent); - this._containsForeignElements = containsForeignElements; - this._cachedWidth = -1; - this._pixelOffsetCache = null; - if (!containsRTL || this._characterMapping.length === 0 /* the line is empty */) { - this._pixelOffsetCache = new Int32Array(Math.max(2, this._characterMapping.length + 1)); - for (let column = 0, len = this._characterMapping.length; column <= len; column++) { - this._pixelOffsetCache[column] = -1; - } - } - } - // --- Reading from the DOM methods - _getReadingTarget(myDomNode) { - return myDomNode.domNode.firstChild; - } - /** - * Width of the line in pixels - */ - getWidth() { - if (!this.domNode) { - return 0; - } - if (this._cachedWidth === -1) { - this._cachedWidth = this._getReadingTarget(this.domNode).offsetWidth; - } - return this._cachedWidth; - } - getWidthIsFast() { - if (this._cachedWidth === -1) { - return false; - } - return true; - } - /** - * Visible ranges for a model range - */ - getVisibleRangesForRange(startColumn, endColumn, context) { - if (!this.domNode) { - return null; - } - if (this._pixelOffsetCache !== null) { - // the text is LTR - const startOffset = this._readPixelOffset(this.domNode, startColumn, context); - if (startOffset === -1) { - return null; - } - const endOffset = this._readPixelOffset(this.domNode, endColumn, context); - if (endOffset === -1) { - return null; - } - return [new renderingContext_1.HorizontalRange(startOffset, endOffset - startOffset)]; - } - return this._readVisibleRangesForRange(this.domNode, startColumn, endColumn, context); - } - _readVisibleRangesForRange(domNode, startColumn, endColumn, context) { - if (startColumn === endColumn) { - const pixelOffset = this._readPixelOffset(domNode, startColumn, context); - if (pixelOffset === -1) { - return null; - } - else { - return [new renderingContext_1.HorizontalRange(pixelOffset, 0)]; - } - } - else { - return this._readRawVisibleRangesForRange(domNode, startColumn, endColumn, context); - } - } - _readPixelOffset(domNode, column, context) { - if (this._characterMapping.length === 0) { - // This line has no content - if (this._containsForeignElements === 0 /* None */) { - // We can assume the line is really empty - return 0; - } - if (this._containsForeignElements === 2 /* After */) { - // We have foreign elements after the (empty) line - return 0; - } - if (this._containsForeignElements === 1 /* Before */) { - // We have foreign elements before the (empty) line - return this.getWidth(); - } - // We have foreign elements before & after the (empty) line - const readingTarget = this._getReadingTarget(domNode); - if (readingTarget.firstChild) { - return readingTarget.firstChild.offsetWidth; - } - else { - return 0; - } - } - if (this._pixelOffsetCache !== null) { - // the text is LTR - const cachedPixelOffset = this._pixelOffsetCache[column]; - if (cachedPixelOffset !== -1) { - return cachedPixelOffset; - } - const result = this._actualReadPixelOffset(domNode, column, context); - this._pixelOffsetCache[column] = result; - return result; - } - return this._actualReadPixelOffset(domNode, column, context); - } - _actualReadPixelOffset(domNode, column, context) { - if (this._characterMapping.length === 0) { - // This line has no content - const r = rangeUtil_1.RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), 0, 0, 0, 0, context.clientRectDeltaLeft, context.endNode); - if (!r || r.length === 0) { - return -1; - } - return r[0].left; - } - if (column === this._characterMapping.length && this._isWhitespaceOnly && this._containsForeignElements === 0 /* None */) { - // This branch helps in the case of whitespace only lines which have a width set - return this.getWidth(); - } - const domPosition = this._characterMapping.getDomPosition(column); - const r = rangeUtil_1.RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), domPosition.partIndex, domPosition.charIndex, domPosition.partIndex, domPosition.charIndex, context.clientRectDeltaLeft, context.endNode); - if (!r || r.length === 0) { - return -1; - } - const result = r[0].left; - if (this.input.isBasicASCII) { - const charOffset = this._characterMapping.getAbsoluteOffset(column); - const expectedResult = Math.round(this.input.spaceWidth * charOffset); - if (Math.abs(expectedResult - result) <= 1) { - return expectedResult; - } - } - return result; - } - _readRawVisibleRangesForRange(domNode, startColumn, endColumn, context) { - if (startColumn === 1 && endColumn === this._characterMapping.length) { - // This branch helps IE with bidi text & gives a performance boost to other browsers when reading visible ranges for an entire line - return [new renderingContext_1.HorizontalRange(0, this.getWidth())]; - } - const startDomPosition = this._characterMapping.getDomPosition(startColumn); - const endDomPosition = this._characterMapping.getDomPosition(endColumn); - return rangeUtil_1.RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), startDomPosition.partIndex, startDomPosition.charIndex, endDomPosition.partIndex, endDomPosition.charIndex, context.clientRectDeltaLeft, context.endNode); - } - /** - * Returns the column for the text found at a specific offset inside a rendered dom node - */ - getColumnOfNodeOffset(lineNumber, spanNode, offset) { - const spanNodeTextContentLength = spanNode.textContent.length; - let spanIndex = -1; - while (spanNode) { - spanNode = spanNode.previousSibling; - spanIndex++; - } - return this._characterMapping.getColumn(new viewLineRenderer_1.DomPosition(spanIndex, offset), spanNodeTextContentLength); - } - } - class WebKitRenderedViewLine extends RenderedViewLine { - _readVisibleRangesForRange(domNode, startColumn, endColumn, context) { - const output = super._readVisibleRangesForRange(domNode, startColumn, endColumn, context); - if (!output || output.length === 0 || startColumn === endColumn || (startColumn === 1 && endColumn === this._characterMapping.length)) { - return output; - } - // WebKit is buggy and returns an expanded range (to contain words in some cases) - // The last client rect is enlarged (I think) - if (!this.input.containsRTL) { - // This is an attempt to patch things up - // Find position of last column - const endPixelOffset = this._readPixelOffset(domNode, endColumn, context); - if (endPixelOffset !== -1) { - const lastRange = output[output.length - 1]; - if (lastRange.left < endPixelOffset) { - // Trim down the width of the last visible range to not go after the last column's position - lastRange.width = endPixelOffset - lastRange.left; - } - } - } - return output; - } - } - const createRenderedLine = (function () { - if (browser.isWebKit) { - return createWebKitRenderedLine; - } - return createNormalRenderedLine; - })(); - function createWebKitRenderedLine(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements) { - return new WebKitRenderedViewLine(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements); - } - function createNormalRenderedLine(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements) { - return new RenderedViewLine(domNode, renderLineInput, 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[191/*vs/editor/browser/controller/mouseTarget*/], __M([0/*require*/,1/*exports*/,167/*vs/editor/browser/editorDom*/,47/*vs/editor/browser/view/viewPart*/,258/*vs/editor/browser/viewParts/lines/viewLine*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,40/*vs/editor/common/controller/cursorCommon*/,7/*vs/base/browser/dom*/,243/*vs/editor/common/controller/cursorAtomicMoveOperations*/]), function (require, exports, editorDom_1, viewPart_1, viewLine_1, position_1, range_1, cursorCommon_1, dom, cursorAtomicMoveOperations_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.shadowCaretRangeFromPoint = exports.MouseTargetFactory = exports.HitTestContext = exports.MouseTarget = exports.PointerHandlerLastRenderData = void 0; - class UnknownHitTestResult { - constructor(hitTarget = null) { - this.hitTarget = hitTarget; - this.type = 0 /* Unknown */; - } - } - class ContentHitTestResult { - constructor(position, spanNode, injectedText) { - this.position = position; - this.spanNode = spanNode; - this.injectedText = injectedText; - this.type = 1 /* Content */; - } - } - var HitTestResult; - (function (HitTestResult) { - function createFromDOMInfo(ctx, spanNode, offset) { - const position = ctx.getPositionFromDOMInfo(spanNode, offset); - if (position) { - return new ContentHitTestResult(position, spanNode, null); - } - return new UnknownHitTestResult(spanNode); - } - HitTestResult.createFromDOMInfo = createFromDOMInfo; - })(HitTestResult || (HitTestResult = {})); - class PointerHandlerLastRenderData { - constructor(lastViewCursorsRenderData, lastTextareaPosition) { - this.lastViewCursorsRenderData = lastViewCursorsRenderData; - this.lastTextareaPosition = lastTextareaPosition; - } - } - exports.PointerHandlerLastRenderData = PointerHandlerLastRenderData; - class MouseTarget { - constructor(element, type, mouseColumn = 0, position = null, range = null, detail = null) { - this.element = element; - this.type = type; - this.mouseColumn = mouseColumn; - this.position = position; - if (!range && position) { - range = new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column); - } - this.range = range; - this.detail = detail; - } - static _typeToString(type) { - if (type === 1 /* TEXTAREA */) { - return 'TEXTAREA'; - } - if (type === 2 /* GUTTER_GLYPH_MARGIN */) { - return 'GUTTER_GLYPH_MARGIN'; - } - if (type === 3 /* GUTTER_LINE_NUMBERS */) { - return 'GUTTER_LINE_NUMBERS'; - } - if (type === 4 /* GUTTER_LINE_DECORATIONS */) { - return 'GUTTER_LINE_DECORATIONS'; - } - if (type === 5 /* GUTTER_VIEW_ZONE */) { - return 'GUTTER_VIEW_ZONE'; - } - if (type === 6 /* CONTENT_TEXT */) { - return 'CONTENT_TEXT'; - } - if (type === 7 /* CONTENT_EMPTY */) { - return 'CONTENT_EMPTY'; - } - if (type === 8 /* CONTENT_VIEW_ZONE */) { - return 'CONTENT_VIEW_ZONE'; - } - if (type === 9 /* CONTENT_WIDGET */) { - return 'CONTENT_WIDGET'; - } - if (type === 10 /* OVERVIEW_RULER */) { - return 'OVERVIEW_RULER'; - } - if (type === 11 /* SCROLLBAR */) { - return 'SCROLLBAR'; - } - if (type === 12 /* OVERLAY_WIDGET */) { - return 'OVERLAY_WIDGET'; - } - return 'UNKNOWN'; - } - static toString(target) { - return this._typeToString(target.type) + ': ' + target.position + ' - ' + target.range + ' - ' + target.detail; - } - toString() { - return MouseTarget.toString(this); - } - } - exports.MouseTarget = MouseTarget; - class ElementPath { - static isTextArea(path) { - return (path.length === 2 - && path[0] === 3 /* OverflowGuard */ - && path[1] === 6 /* TextArea */); - } - static isChildOfViewLines(path) { - return (path.length >= 4 - && path[0] === 3 /* OverflowGuard */ - && path[3] === 7 /* ViewLines */); - } - static isStrictChildOfViewLines(path) { - return (path.length > 4 - && path[0] === 3 /* OverflowGuard */ - && path[3] === 7 /* ViewLines */); - } - static isChildOfScrollableElement(path) { - return (path.length >= 2 - && path[0] === 3 /* OverflowGuard */ - && path[1] === 5 /* ScrollableElement */); - } - static isChildOfMinimap(path) { - return (path.length >= 2 - && path[0] === 3 /* OverflowGuard */ - && path[1] === 8 /* Minimap */); - } - static isChildOfContentWidgets(path) { - return (path.length >= 4 - && path[0] === 3 /* OverflowGuard */ - && path[3] === 1 /* ContentWidgets */); - } - static isChildOfOverflowingContentWidgets(path) { - return (path.length >= 1 - && path[0] === 2 /* OverflowingContentWidgets */); - } - static isChildOfOverlayWidgets(path) { - return (path.length >= 2 - && path[0] === 3 /* OverflowGuard */ - && path[1] === 4 /* OverlayWidgets */); - } - } - class HitTestContext { - constructor(context, viewHelper, lastRenderData) { - this.model = context.model; - const options = context.configuration.options; - this.layoutInfo = options.get(129 /* layoutInfo */); - this.viewDomNode = viewHelper.viewDomNode; - this.lineHeight = options.get(57 /* lineHeight */); - this.stickyTabStops = options.get(103 /* stickyTabStops */); - this.typicalHalfwidthCharacterWidth = options.get(41 /* fontInfo */).typicalHalfwidthCharacterWidth; - this.lastRenderData = lastRenderData; - this._context = context; - this._viewHelper = viewHelper; - } - getZoneAtCoord(mouseVerticalOffset) { - return HitTestContext.getZoneAtCoord(this._context, mouseVerticalOffset); - } - static getZoneAtCoord(context, mouseVerticalOffset) { - // The target is either a view zone or the empty space after the last view-line - const viewZoneWhitespace = context.viewLayout.getWhitespaceAtVerticalOffset(mouseVerticalOffset); - if (viewZoneWhitespace) { - const viewZoneMiddle = viewZoneWhitespace.verticalOffset + viewZoneWhitespace.height / 2; - const lineCount = context.model.getLineCount(); - let positionBefore = null; - let position; - let positionAfter = null; - if (viewZoneWhitespace.afterLineNumber !== lineCount) { - // There are more lines after this view zone - positionAfter = new position_1.Position(viewZoneWhitespace.afterLineNumber + 1, 1); - } - if (viewZoneWhitespace.afterLineNumber > 0) { - // There are more lines above this view zone - positionBefore = new position_1.Position(viewZoneWhitespace.afterLineNumber, context.model.getLineMaxColumn(viewZoneWhitespace.afterLineNumber)); - } - if (positionAfter === null) { - position = positionBefore; - } - else if (positionBefore === null) { - position = positionAfter; - } - else if (mouseVerticalOffset < viewZoneMiddle) { - position = positionBefore; - } - else { - position = positionAfter; - } - return { - viewZoneId: viewZoneWhitespace.id, - afterLineNumber: viewZoneWhitespace.afterLineNumber, - positionBefore: positionBefore, - positionAfter: positionAfter, - position: position - }; - } - return null; - } - getFullLineRangeAtCoord(mouseVerticalOffset) { - if (this._context.viewLayout.isAfterLines(mouseVerticalOffset)) { - // Below the last line - const lineNumber = this._context.model.getLineCount(); - const maxLineColumn = this._context.model.getLineMaxColumn(lineNumber); - return { - range: new range_1.Range(lineNumber, maxLineColumn, lineNumber, maxLineColumn), - isAfterLines: true - }; - } - const lineNumber = this._context.viewLayout.getLineNumberAtVerticalOffset(mouseVerticalOffset); - const maxLineColumn = this._context.model.getLineMaxColumn(lineNumber); - return { - range: new range_1.Range(lineNumber, 1, lineNumber, maxLineColumn), - isAfterLines: false - }; - } - getLineNumberAtVerticalOffset(mouseVerticalOffset) { - return this._context.viewLayout.getLineNumberAtVerticalOffset(mouseVerticalOffset); - } - isAfterLines(mouseVerticalOffset) { - return this._context.viewLayout.isAfterLines(mouseVerticalOffset); - } - isInTopPadding(mouseVerticalOffset) { - return this._context.viewLayout.isInTopPadding(mouseVerticalOffset); - } - isInBottomPadding(mouseVerticalOffset) { - return this._context.viewLayout.isInBottomPadding(mouseVerticalOffset); - } - getVerticalOffsetForLineNumber(lineNumber) { - return this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber); - } - findAttribute(element, attr) { - return HitTestContext._findAttribute(element, attr, this._viewHelper.viewDomNode); - } - static _findAttribute(element, attr, stopAt) { - while (element && element !== document.body) { - if (element.hasAttribute && element.hasAttribute(attr)) { - return element.getAttribute(attr); - } - if (element === stopAt) { - return null; - } - element = element.parentNode; - } - return null; - } - getLineWidth(lineNumber) { - return this._viewHelper.getLineWidth(lineNumber); - } - visibleRangeForPosition(lineNumber, column) { - return this._viewHelper.visibleRangeForPosition(lineNumber, column); - } - getPositionFromDOMInfo(spanNode, offset) { - return this._viewHelper.getPositionFromDOMInfo(spanNode, offset); - } - getCurrentScrollTop() { - return this._context.viewLayout.getCurrentScrollTop(); - } - getCurrentScrollLeft() { - return this._context.viewLayout.getCurrentScrollLeft(); - } - } - exports.HitTestContext = HitTestContext; - class BareHitTestRequest { - constructor(ctx, editorPos, pos) { - this.editorPos = editorPos; - this.pos = pos; - this.mouseVerticalOffset = Math.max(0, ctx.getCurrentScrollTop() + pos.y - editorPos.y); - this.mouseContentHorizontalOffset = ctx.getCurrentScrollLeft() + pos.x - editorPos.x - ctx.layoutInfo.contentLeft; - this.isInMarginArea = (pos.x - editorPos.x < ctx.layoutInfo.contentLeft && pos.x - editorPos.x >= ctx.layoutInfo.glyphMarginLeft); - this.isInContentArea = !this.isInMarginArea; - this.mouseColumn = Math.max(0, MouseTargetFactory._getMouseColumn(this.mouseContentHorizontalOffset, ctx.typicalHalfwidthCharacterWidth)); - } - } - class HitTestRequest extends BareHitTestRequest { - constructor(ctx, editorPos, pos, target) { - super(ctx, editorPos, pos); - this._ctx = ctx; - if (target) { - this.target = target; - this.targetPath = viewPart_1.PartFingerprints.collect(target, ctx.viewDomNode); - } - else { - this.target = null; - this.targetPath = new Uint8Array(0); - } - } - toString() { - return `pos(${this.pos.x},${this.pos.y}), editorPos(${this.editorPos.x},${this.editorPos.y}), mouseVerticalOffset: ${this.mouseVerticalOffset}, mouseContentHorizontalOffset: ${this.mouseContentHorizontalOffset}\n\ttarget: ${this.target ? this.target.outerHTML : null}`; - } - // public fulfill(type: MouseTargetType.OVERVIEW_RULER, position?: Position | null, range?: EditorRange | null, detail?: any): MouseTarget; - // public fulfill(type: MouseTargetType.OUTSIDE_EDITOR, position?: Position | null, range?: EditorRange | null, detail?: any): MouseTarget; - fulfill(type, position = null, range = null, detail = null) { - let mouseColumn = this.mouseColumn; - if (position && position.column < this._ctx.model.getLineMaxColumn(position.lineNumber)) { - // Most likely, the line contains foreign decorations... - mouseColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(this._ctx.model.getLineContent(position.lineNumber), position.column, this._ctx.model.getTextModelOptions().tabSize) + 1; - } - return new MouseTarget(this.target, type, mouseColumn, position, range, detail); - } - withTarget(target) { - return new HitTestRequest(this._ctx, this.editorPos, this.pos, target); - } - } - const EMPTY_CONTENT_AFTER_LINES = { isAfterLines: true }; - function createEmptyContentDataInLines(horizontalDistanceToText) { - return { - isAfterLines: false, - horizontalDistanceToText: horizontalDistanceToText - }; - } - class MouseTargetFactory { - constructor(context, viewHelper) { - this._context = context; - this._viewHelper = viewHelper; - } - mouseTargetIsWidget(e) { - const t = e.target; - const path = viewPart_1.PartFingerprints.collect(t, this._viewHelper.viewDomNode); - // Is it a content widget? - if (ElementPath.isChildOfContentWidgets(path) || ElementPath.isChildOfOverflowingContentWidgets(path)) { - return true; - } - // Is it an overlay widget? - if (ElementPath.isChildOfOverlayWidgets(path)) { - return true; - } - return false; - } - createMouseTarget(lastRenderData, editorPos, pos, target) { - const ctx = new HitTestContext(this._context, this._viewHelper, lastRenderData); - const request = new HitTestRequest(ctx, editorPos, pos, target); - try { - const r = MouseTargetFactory._createMouseTarget(ctx, request, false); - // console.log(r.toString()); - return r; - } - catch (err) { - // console.log(err); - return request.fulfill(0 /* UNKNOWN */); - } - } - static _createMouseTarget(ctx, request, domHitTestExecuted) { - // console.log(`${domHitTestExecuted ? '=>' : ''}CAME IN REQUEST: ${request}`); - // First ensure the request has a target - if (request.target === null) { - if (domHitTestExecuted) { - // Still no target... and we have already executed hit test... - return request.fulfill(0 /* UNKNOWN */); - } - const hitTestResult = MouseTargetFactory._doHitTest(ctx, request); - if (hitTestResult.type === 1 /* Content */) { - return MouseTargetFactory.createMouseTargetFromHitTestPosition(ctx, request, hitTestResult.spanNode, hitTestResult.position, hitTestResult.injectedText); - } - return this._createMouseTarget(ctx, request.withTarget(hitTestResult.hitTarget), true); - } - // we know for a fact that request.target is not null - const resolvedRequest = request; - let result = null; - result = result || MouseTargetFactory._hitTestContentWidget(ctx, resolvedRequest); - result = result || MouseTargetFactory._hitTestOverlayWidget(ctx, resolvedRequest); - result = result || MouseTargetFactory._hitTestMinimap(ctx, resolvedRequest); - result = result || MouseTargetFactory._hitTestScrollbarSlider(ctx, resolvedRequest); - result = result || MouseTargetFactory._hitTestViewZone(ctx, resolvedRequest); - result = result || MouseTargetFactory._hitTestMargin(ctx, resolvedRequest); - result = result || MouseTargetFactory._hitTestViewCursor(ctx, resolvedRequest); - result = result || MouseTargetFactory._hitTestTextArea(ctx, resolvedRequest); - result = result || MouseTargetFactory._hitTestViewLines(ctx, resolvedRequest, domHitTestExecuted); - result = result || MouseTargetFactory._hitTestScrollbar(ctx, resolvedRequest); - return (result || request.fulfill(0 /* UNKNOWN */)); - } - static _hitTestContentWidget(ctx, request) { - // Is it a content widget? - if (ElementPath.isChildOfContentWidgets(request.targetPath) || ElementPath.isChildOfOverflowingContentWidgets(request.targetPath)) { - const widgetId = ctx.findAttribute(request.target, 'widgetId'); - if (widgetId) { - return request.fulfill(9 /* CONTENT_WIDGET */, null, null, widgetId); - } - else { - return request.fulfill(0 /* UNKNOWN */); - } - } - return null; - } - static _hitTestOverlayWidget(ctx, request) { - // Is it an overlay widget? - if (ElementPath.isChildOfOverlayWidgets(request.targetPath)) { - const widgetId = ctx.findAttribute(request.target, 'widgetId'); - if (widgetId) { - return request.fulfill(12 /* OVERLAY_WIDGET */, null, null, widgetId); - } - else { - return request.fulfill(0 /* UNKNOWN */); - } - } - return null; - } - static _hitTestViewCursor(ctx, request) { - if (request.target) { - // Check if we've hit a painted cursor - const lastViewCursorsRenderData = ctx.lastRenderData.lastViewCursorsRenderData; - for (const d of lastViewCursorsRenderData) { - if (request.target === d.domNode) { - return request.fulfill(6 /* CONTENT_TEXT */, d.position, null, { mightBeForeignElement: false }); - } - } - } - if (request.isInContentArea) { - // Edge has a bug when hit-testing the exact position of a cursor, - // instead of returning the correct dom node, it returns the - // first or last rendered view line dom node, therefore help it out - // and first check if we are on top of a cursor - const lastViewCursorsRenderData = ctx.lastRenderData.lastViewCursorsRenderData; - const mouseContentHorizontalOffset = request.mouseContentHorizontalOffset; - const mouseVerticalOffset = request.mouseVerticalOffset; - for (const d of lastViewCursorsRenderData) { - if (mouseContentHorizontalOffset < d.contentLeft) { - // mouse position is to the left of the cursor - continue; - } - if (mouseContentHorizontalOffset > d.contentLeft + d.width) { - // mouse position is to the right of the cursor - continue; - } - const cursorVerticalOffset = ctx.getVerticalOffsetForLineNumber(d.position.lineNumber); - if (cursorVerticalOffset <= mouseVerticalOffset - && mouseVerticalOffset <= cursorVerticalOffset + d.height) { - return request.fulfill(6 /* CONTENT_TEXT */, d.position, null, { mightBeForeignElement: false }); - } - } - } - return null; - } - static _hitTestViewZone(ctx, request) { - const viewZoneData = ctx.getZoneAtCoord(request.mouseVerticalOffset); - if (viewZoneData) { - const mouseTargetType = (request.isInContentArea ? 8 /* CONTENT_VIEW_ZONE */ : 5 /* GUTTER_VIEW_ZONE */); - return request.fulfill(mouseTargetType, viewZoneData.position, null, viewZoneData); - } - return null; - } - static _hitTestTextArea(ctx, request) { - // Is it the textarea? - if (ElementPath.isTextArea(request.targetPath)) { - if (ctx.lastRenderData.lastTextareaPosition) { - return request.fulfill(6 /* CONTENT_TEXT */, ctx.lastRenderData.lastTextareaPosition, null, { mightBeForeignElement: false }); - } - return request.fulfill(1 /* TEXTAREA */, ctx.lastRenderData.lastTextareaPosition); - } - return null; - } - static _hitTestMargin(ctx, request) { - if (request.isInMarginArea) { - const res = ctx.getFullLineRangeAtCoord(request.mouseVerticalOffset); - const pos = res.range.getStartPosition(); - let offset = Math.abs(request.pos.x - request.editorPos.x); - const detail = { - isAfterLines: res.isAfterLines, - glyphMarginLeft: ctx.layoutInfo.glyphMarginLeft, - glyphMarginWidth: ctx.layoutInfo.glyphMarginWidth, - lineNumbersWidth: ctx.layoutInfo.lineNumbersWidth, - offsetX: offset - }; - offset -= ctx.layoutInfo.glyphMarginLeft; - if (offset <= ctx.layoutInfo.glyphMarginWidth) { - // On the glyph margin - return request.fulfill(2 /* GUTTER_GLYPH_MARGIN */, pos, res.range, detail); - } - offset -= ctx.layoutInfo.glyphMarginWidth; - if (offset <= ctx.layoutInfo.lineNumbersWidth) { - // On the line numbers - return request.fulfill(3 /* GUTTER_LINE_NUMBERS */, pos, res.range, detail); - } - offset -= ctx.layoutInfo.lineNumbersWidth; - // On the line decorations - return request.fulfill(4 /* GUTTER_LINE_DECORATIONS */, pos, res.range, detail); - } - return null; - } - static _hitTestViewLines(ctx, request, domHitTestExecuted) { - if (!ElementPath.isChildOfViewLines(request.targetPath)) { - return null; - } - if (ctx.isInTopPadding(request.mouseVerticalOffset)) { - return request.fulfill(7 /* CONTENT_EMPTY */, new position_1.Position(1, 1), null, EMPTY_CONTENT_AFTER_LINES); - } - // Check if it is below any lines and any view zones - if (ctx.isAfterLines(request.mouseVerticalOffset) || ctx.isInBottomPadding(request.mouseVerticalOffset)) { - // This most likely indicates it happened after the last view-line - const lineCount = ctx.model.getLineCount(); - const maxLineColumn = ctx.model.getLineMaxColumn(lineCount); - return request.fulfill(7 /* CONTENT_EMPTY */, new position_1.Position(lineCount, maxLineColumn), null, EMPTY_CONTENT_AFTER_LINES); - } - if (domHitTestExecuted) { - // Check if we are hitting a view-line (can happen in the case of inline decorations on empty lines) - // See https://github.com/microsoft/vscode/issues/46942 - if (ElementPath.isStrictChildOfViewLines(request.targetPath)) { - const lineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset); - if (ctx.model.getLineLength(lineNumber) === 0) { - const lineWidth = ctx.getLineWidth(lineNumber); - const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth); - return request.fulfill(7 /* CONTENT_EMPTY */, new position_1.Position(lineNumber, 1), null, detail); - } - const lineWidth = ctx.getLineWidth(lineNumber); - if (request.mouseContentHorizontalOffset >= lineWidth) { - const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth); - const pos = new position_1.Position(lineNumber, ctx.model.getLineMaxColumn(lineNumber)); - return request.fulfill(7 /* CONTENT_EMPTY */, pos, null, detail); - } - } - // We have already executed hit test... - return request.fulfill(0 /* UNKNOWN */); - } - const hitTestResult = MouseTargetFactory._doHitTest(ctx, request); - if (hitTestResult.type === 1 /* Content */) { - return MouseTargetFactory.createMouseTargetFromHitTestPosition(ctx, request, hitTestResult.spanNode, hitTestResult.position, hitTestResult.injectedText); - } - return this._createMouseTarget(ctx, request.withTarget(hitTestResult.hitTarget), true); - } - static _hitTestMinimap(ctx, request) { - if (ElementPath.isChildOfMinimap(request.targetPath)) { - const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset); - const maxColumn = ctx.model.getLineMaxColumn(possibleLineNumber); - return request.fulfill(11 /* SCROLLBAR */, new position_1.Position(possibleLineNumber, maxColumn)); - } - return null; - } - static _hitTestScrollbarSlider(ctx, request) { - if (ElementPath.isChildOfScrollableElement(request.targetPath)) { - if (request.target && request.target.nodeType === 1) { - const className = request.target.className; - if (className && /\b(slider|scrollbar)\b/.test(className)) { - const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset); - const maxColumn = ctx.model.getLineMaxColumn(possibleLineNumber); - return request.fulfill(11 /* SCROLLBAR */, new position_1.Position(possibleLineNumber, maxColumn)); - } - } - } - return null; - } - static _hitTestScrollbar(ctx, request) { - // Is it the overview ruler? - // Is it a child of the scrollable element? - if (ElementPath.isChildOfScrollableElement(request.targetPath)) { - const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset); - const maxColumn = ctx.model.getLineMaxColumn(possibleLineNumber); - return request.fulfill(11 /* SCROLLBAR */, new position_1.Position(possibleLineNumber, maxColumn)); - } - return null; - } - getMouseColumn(editorPos, pos) { - const options = this._context.configuration.options; - const layoutInfo = options.get(129 /* layoutInfo */); - const mouseContentHorizontalOffset = this._context.viewLayout.getCurrentScrollLeft() + pos.x - editorPos.x - layoutInfo.contentLeft; - return MouseTargetFactory._getMouseColumn(mouseContentHorizontalOffset, options.get(41 /* fontInfo */).typicalHalfwidthCharacterWidth); - } - static _getMouseColumn(mouseContentHorizontalOffset, typicalHalfwidthCharacterWidth) { - if (mouseContentHorizontalOffset < 0) { - return 1; - } - const chars = Math.round(mouseContentHorizontalOffset / typicalHalfwidthCharacterWidth); - return (chars + 1); - } - static createMouseTargetFromHitTestPosition(ctx, request, spanNode, pos, injectedText) { - const lineNumber = pos.lineNumber; - const column = pos.column; - const lineWidth = ctx.getLineWidth(lineNumber); - if (request.mouseContentHorizontalOffset > lineWidth) { - const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth); - return request.fulfill(7 /* CONTENT_EMPTY */, pos, null, detail); - } - const visibleRange = ctx.visibleRangeForPosition(lineNumber, column); - if (!visibleRange) { - return request.fulfill(0 /* UNKNOWN */, pos); - } - const columnHorizontalOffset = visibleRange.left; - if (request.mouseContentHorizontalOffset === columnHorizontalOffset) { - return request.fulfill(6 /* CONTENT_TEXT */, pos, null, { mightBeForeignElement: !!injectedText }); - } - const points = []; - points.push({ offset: visibleRange.left, column: column }); - if (column > 1) { - const visibleRange = ctx.visibleRangeForPosition(lineNumber, column - 1); - if (visibleRange) { - points.push({ offset: visibleRange.left, column: column - 1 }); - } - } - const lineMaxColumn = ctx.model.getLineMaxColumn(lineNumber); - if (column < lineMaxColumn) { - const visibleRange = ctx.visibleRangeForPosition(lineNumber, column + 1); - if (visibleRange) { - points.push({ offset: visibleRange.left, column: column + 1 }); - } - } - points.sort((a, b) => a.offset - b.offset); - const mouseCoordinates = request.pos.toClientCoordinates(); - const spanNodeClientRect = spanNode.getBoundingClientRect(); - const mouseIsOverSpanNode = (spanNodeClientRect.left <= mouseCoordinates.clientX && mouseCoordinates.clientX <= spanNodeClientRect.right); - for (let i = 1; i < points.length; i++) { - const prev = points[i - 1]; - const curr = points[i]; - if (prev.offset <= request.mouseContentHorizontalOffset && request.mouseContentHorizontalOffset <= curr.offset) { - const rng = new range_1.Range(lineNumber, prev.column, lineNumber, curr.column); - return request.fulfill(6 /* CONTENT_TEXT */, pos, rng, { mightBeForeignElement: !mouseIsOverSpanNode || !!injectedText }); - } - } - return request.fulfill(6 /* CONTENT_TEXT */, pos, null, { mightBeForeignElement: !mouseIsOverSpanNode || !!injectedText }); - } - /** - * Most probably WebKit browsers and Edge - */ - static _doHitTestWithCaretRangeFromPoint(ctx, request) { - // In Chrome, especially on Linux it is possible to click between lines, - // so try to adjust the `hity` below so that it lands in the center of a line - const lineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset); - const lineVerticalOffset = ctx.getVerticalOffsetForLineNumber(lineNumber); - const lineCenteredVerticalOffset = lineVerticalOffset + Math.floor(ctx.lineHeight / 2); - let adjustedPageY = request.pos.y + (lineCenteredVerticalOffset - request.mouseVerticalOffset); - if (adjustedPageY <= request.editorPos.y) { - adjustedPageY = request.editorPos.y + 1; - } - if (adjustedPageY >= request.editorPos.y + ctx.layoutInfo.height) { - adjustedPageY = request.editorPos.y + ctx.layoutInfo.height - 1; - } - const adjustedPage = new editorDom_1.PageCoordinates(request.pos.x, adjustedPageY); - const r = this._actualDoHitTestWithCaretRangeFromPoint(ctx, adjustedPage.toClientCoordinates()); - if (r.type === 1 /* Content */) { - return r; - } - // Also try to hit test without the adjustment (for the edge cases that we are near the top or bottom) - return this._actualDoHitTestWithCaretRangeFromPoint(ctx, request.pos.toClientCoordinates()); - } - static _actualDoHitTestWithCaretRangeFromPoint(ctx, coords) { - const shadowRoot = dom.getShadowRoot(ctx.viewDomNode); - let range; - if (shadowRoot) { - if (typeof shadowRoot.caretRangeFromPoint === 'undefined') { - range = shadowCaretRangeFromPoint(shadowRoot, coords.clientX, coords.clientY); - } - else { - range = shadowRoot.caretRangeFromPoint(coords.clientX, coords.clientY); - } - } - else { - range = document.caretRangeFromPoint(coords.clientX, coords.clientY); - } - if (!range || !range.startContainer) { - return new UnknownHitTestResult(); - } - // Chrome always hits a TEXT_NODE, while Edge sometimes hits a token span - const startContainer = range.startContainer; - if (startContainer.nodeType === startContainer.TEXT_NODE) { - // startContainer is expected to be the token text - const parent1 = startContainer.parentNode; // expected to be the token span - const parent2 = parent1 ? parent1.parentNode : null; // expected to be the view line container span - const parent3 = parent2 ? parent2.parentNode : null; // expected to be the view line div - const parent3ClassName = parent3 && parent3.nodeType === parent3.ELEMENT_NODE ? parent3.className : null; - if (parent3ClassName === viewLine_1.ViewLine.CLASS_NAME) { - return HitTestResult.createFromDOMInfo(ctx, parent1, range.startOffset); - } - else { - return new UnknownHitTestResult(startContainer.parentNode); - } - } - else if (startContainer.nodeType === startContainer.ELEMENT_NODE) { - // startContainer is expected to be the token span - const parent1 = startContainer.parentNode; // expected to be the view line container span - const parent2 = parent1 ? parent1.parentNode : null; // expected to be the view line div - const parent2ClassName = parent2 && parent2.nodeType === parent2.ELEMENT_NODE ? parent2.className : null; - if (parent2ClassName === viewLine_1.ViewLine.CLASS_NAME) { - return HitTestResult.createFromDOMInfo(ctx, startContainer, startContainer.textContent.length); - } - else { - return new UnknownHitTestResult(startContainer); - } - } - return new UnknownHitTestResult(); - } - /** - * Most probably Gecko - */ - static _doHitTestWithCaretPositionFromPoint(ctx, coords) { - const hitResult = document.caretPositionFromPoint(coords.clientX, coords.clientY); - if (hitResult.offsetNode.nodeType === hitResult.offsetNode.TEXT_NODE) { - // offsetNode is expected to be the token text - const parent1 = hitResult.offsetNode.parentNode; // expected to be the token span - const parent2 = parent1 ? parent1.parentNode : null; // expected to be the view line container span - const parent3 = parent2 ? parent2.parentNode : null; // expected to be the view line div - const parent3ClassName = parent3 && parent3.nodeType === parent3.ELEMENT_NODE ? parent3.className : null; - if (parent3ClassName === viewLine_1.ViewLine.CLASS_NAME) { - return HitTestResult.createFromDOMInfo(ctx, hitResult.offsetNode.parentNode, hitResult.offset); - } - else { - return new UnknownHitTestResult(hitResult.offsetNode.parentNode); - } - } - // For inline decorations, Gecko sometimes returns the `` of the line and the offset is the `` with the inline decoration - // Some other times, it returns the `` with the inline decoration - if (hitResult.offsetNode.nodeType === hitResult.offsetNode.ELEMENT_NODE) { - const parent1 = hitResult.offsetNode.parentNode; - const parent1ClassName = parent1 && parent1.nodeType === parent1.ELEMENT_NODE ? parent1.className : null; - const parent2 = parent1 ? parent1.parentNode : null; - const parent2ClassName = parent2 && parent2.nodeType === parent2.ELEMENT_NODE ? parent2.className : null; - if (parent1ClassName === viewLine_1.ViewLine.CLASS_NAME) { - // it returned the `` of the line and the offset is the `` with the inline decoration - const tokenSpan = hitResult.offsetNode.childNodes[Math.min(hitResult.offset, hitResult.offsetNode.childNodes.length - 1)]; - if (tokenSpan) { - return HitTestResult.createFromDOMInfo(ctx, tokenSpan, 0); - } - } - else if (parent2ClassName === viewLine_1.ViewLine.CLASS_NAME) { - // it returned the `` with the inline decoration - return HitTestResult.createFromDOMInfo(ctx, hitResult.offsetNode, 0); - } - } - return new UnknownHitTestResult(hitResult.offsetNode); - } - static _snapToSoftTabBoundary(position, viewModel) { - const lineContent = viewModel.getLineContent(position.lineNumber); - const { tabSize } = viewModel.getTextModelOptions(); - const newPosition = cursorAtomicMoveOperations_1.AtomicTabMoveOperations.atomicPosition(lineContent, position.column - 1, tabSize, 2 /* Nearest */); - if (newPosition !== -1) { - return new position_1.Position(position.lineNumber, newPosition + 1); - } - return position; - } - static _doHitTest(ctx, request) { - let result = new UnknownHitTestResult(); - if (typeof document.caretRangeFromPoint === 'function') { - result = this._doHitTestWithCaretRangeFromPoint(ctx, request); - } - else if (document.caretPositionFromPoint) { - result = this._doHitTestWithCaretPositionFromPoint(ctx, request.pos.toClientCoordinates()); - } - if (result.type === 1 /* Content */) { - const injectedText = ctx.model.getInjectedTextAt(result.position); - const normalizedPosition = ctx.model.normalizePosition(result.position, 2 /* None */); - if (injectedText || !normalizedPosition.equals(result.position)) { - result = new ContentHitTestResult(normalizedPosition, result.spanNode, injectedText); - } - } - // Snap to the nearest soft tab boundary if atomic soft tabs are enabled. - if (result.type === 1 /* Content */ && ctx.stickyTabStops) { - result = new ContentHitTestResult(this._snapToSoftTabBoundary(result.position, ctx.model), result.spanNode, result.injectedText); - } - return result; - } - } - exports.MouseTargetFactory = MouseTargetFactory; - function shadowCaretRangeFromPoint(shadowRoot, x, y) { - const range = document.createRange(); - // Get the element under the point - let el = shadowRoot.elementFromPoint(x, y); - if (el !== null) { - // Get the last child of the element until its firstChild is a text node - // This assumes that the pointer is on the right of the line, out of the tokens - // and that we want to get the offset of the last token of the line - while (el && el.firstChild && el.firstChild.nodeType !== el.firstChild.TEXT_NODE && el.lastChild && el.lastChild.firstChild) { - el = el.lastChild; - } - // Grab its rect - const rect = el.getBoundingClientRect(); - // And its font - const font = window.getComputedStyle(el, null).getPropertyValue('font'); - // And also its txt content - const text = el.innerText; - // Position the pixel cursor at the left of the element - let pixelCursor = rect.left; - let offset = 0; - let step; - // If the point is on the right of the box put the cursor after the last character - if (x > rect.left + rect.width) { - offset = text.length; - } - else { - const charWidthReader = CharWidthReader.getInstance(); - // Goes through all the characters of the innerText, and checks if the x of the point - // belongs to the character. - for (let i = 0; i < text.length + 1; i++) { - // The step is half the width of the character - step = charWidthReader.getCharWidth(text.charAt(i), font) / 2; - // Move to the center of the character - pixelCursor += step; - // If the x of the point is smaller that the position of the cursor, the point is over that character - if (x < pixelCursor) { - offset = i; - break; - } - // Move between the current character and the next - pixelCursor += step; - } - } - // Creates a range with the text node of the element and set the offset found - range.setStart(el.firstChild, offset); - range.setEnd(el.firstChild, offset); - } - return range; - } - exports.shadowCaretRangeFromPoint = shadowCaretRangeFromPoint; - class CharWidthReader { - constructor() { - this._cache = {}; - this._canvas = document.createElement('canvas'); - } - static getInstance() { - if (!CharWidthReader._INSTANCE) { - CharWidthReader._INSTANCE = new CharWidthReader(); - } - return CharWidthReader._INSTANCE; - } - getCharWidth(char, font) { - const cacheKey = char + font; - if (this._cache[cacheKey]) { - return this._cache[cacheKey]; - } - const context = this._canvas.getContext('2d'); - context.font = font; - const metrics = context.measureText(char); - const width = metrics.width; - this._cache[cacheKey] = width; - return width; - } - } - CharWidthReader._INSTANCE = 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[594/*vs/editor/browser/controller/mouseHandler*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,55/*vs/base/browser/mouseEvent*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,17/*vs/base/common/platform*/,191/*vs/editor/browser/controller/mouseTarget*/,167/*vs/editor/browser/editorDom*/,133/*vs/editor/common/config/editorZoom*/,13/*vs/editor/common/core/position*/,21/*vs/editor/common/core/selection*/,115/*vs/editor/common/viewModel/viewEventHandler*/]), function (require, exports, dom, mouseEvent_1, async_1, lifecycle_1, platform, mouseTarget_1, editorDom_1, editorZoom_1, position_1, selection_1, viewEventHandler_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MouseHandler = exports.createMouseMoveEventMerger = void 0; - /** - * Merges mouse events when mouse move events are throttled - */ - function createMouseMoveEventMerger(mouseTargetFactory) { - return function (lastEvent, currentEvent) { - let targetIsWidget = false; - if (mouseTargetFactory) { - targetIsWidget = mouseTargetFactory.mouseTargetIsWidget(currentEvent); - } - if (!targetIsWidget) { - currentEvent.preventDefault(); - } - return currentEvent; - }; - } - exports.createMouseMoveEventMerger = createMouseMoveEventMerger; - class MouseHandler extends viewEventHandler_1.ViewEventHandler { - constructor(context, viewController, viewHelper) { - super(); - this._context = context; - this.viewController = viewController; - this.viewHelper = viewHelper; - this.mouseTargetFactory = new mouseTarget_1.MouseTargetFactory(this._context, viewHelper); - this._mouseDownOperation = this._register(new MouseDownOperation(this._context, this.viewController, this.viewHelper, (e, testEventTarget) => this._createMouseTarget(e, testEventTarget), (e) => this._getMouseColumn(e))); - this.lastMouseLeaveTime = -1; - this._height = this._context.configuration.options.get(129 /* layoutInfo */).height; - const mouseEvents = new editorDom_1.EditorMouseEventFactory(this.viewHelper.viewDomNode); - this._register(mouseEvents.onContextMenu(this.viewHelper.viewDomNode, (e) => this._onContextMenu(e, true))); - this._register(mouseEvents.onMouseMoveThrottled(this.viewHelper.viewDomNode, (e) => this._onMouseMove(e), createMouseMoveEventMerger(this.mouseTargetFactory), MouseHandler.MOUSE_MOVE_MINIMUM_TIME)); - this._register(mouseEvents.onMouseUp(this.viewHelper.viewDomNode, (e) => this._onMouseUp(e))); - this._register(mouseEvents.onMouseLeave(this.viewHelper.viewDomNode, (e) => this._onMouseLeave(e))); - this._register(mouseEvents.onMouseDown(this.viewHelper.viewDomNode, (e) => this._onMouseDown(e))); - const onMouseWheel = (browserEvent) => { - this.viewController.emitMouseWheel(browserEvent); - if (!this._context.configuration.options.get(66 /* mouseWheelZoom */)) { - return; - } - const e = new mouseEvent_1.StandardWheelEvent(browserEvent); - const doMouseWheelZoom = (platform.isMacintosh - // on macOS we support cmd + two fingers scroll (`metaKey` set) - // and also the two fingers pinch gesture (`ctrKey` set) - ? ((browserEvent.metaKey || browserEvent.ctrlKey) && !browserEvent.shiftKey && !browserEvent.altKey) - : (browserEvent.ctrlKey && !browserEvent.metaKey && !browserEvent.shiftKey && !browserEvent.altKey)); - if (doMouseWheelZoom) { - const zoomLevel = editorZoom_1.EditorZoom.getZoomLevel(); - const delta = e.deltaY > 0 ? 1 : -1; - editorZoom_1.EditorZoom.setZoomLevel(zoomLevel + delta); - e.preventDefault(); - e.stopPropagation(); - } - }; - this._register(dom.addDisposableListener(this.viewHelper.viewDomNode, dom.EventType.MOUSE_WHEEL, onMouseWheel, { capture: true, passive: false })); - this._context.addEventHandler(this); - } - dispose() { - this._context.removeEventHandler(this); - super.dispose(); - } - // --- begin event handlers - onConfigurationChanged(e) { - if (e.hasChanged(129 /* layoutInfo */)) { - // layout change - const height = this._context.configuration.options.get(129 /* layoutInfo */).height; - if (this._height !== height) { - this._height = height; - this._mouseDownOperation.onHeightChanged(); - } - } - return false; - } - onCursorStateChanged(e) { - this._mouseDownOperation.onCursorStateChanged(e); - return false; - } - onFocusChanged(e) { - return false; - } - onScrollChanged(e) { - this._mouseDownOperation.onScrollChanged(); - return false; - } - // --- end event handlers - getTargetAtClientPoint(clientX, clientY) { - const clientPos = new editorDom_1.ClientCoordinates(clientX, clientY); - const pos = clientPos.toPageCoordinates(); - const editorPos = (0, editorDom_1.createEditorPagePosition)(this.viewHelper.viewDomNode); - if (pos.y < editorPos.y || pos.y > editorPos.y + editorPos.height || pos.x < editorPos.x || pos.x > editorPos.x + editorPos.width) { - return null; - } - return this.mouseTargetFactory.createMouseTarget(this.viewHelper.getLastRenderData(), editorPos, pos, null); - } - _createMouseTarget(e, testEventTarget) { - return this.mouseTargetFactory.createMouseTarget(this.viewHelper.getLastRenderData(), e.editorPos, e.pos, testEventTarget ? e.target : null); - } - _getMouseColumn(e) { - return this.mouseTargetFactory.getMouseColumn(e.editorPos, e.pos); - } - _onContextMenu(e, testEventTarget) { - this.viewController.emitContextMenu({ - event: e, - target: this._createMouseTarget(e, testEventTarget) - }); - } - _onMouseMove(e) { - if (this._mouseDownOperation.isActive()) { - // In selection/drag operation - return; - } - const actualMouseMoveTime = e.timestamp; - if (actualMouseMoveTime < this.lastMouseLeaveTime) { - // Due to throttling, this event occurred before the mouse left the editor, therefore ignore it. - return; - } - this.viewController.emitMouseMove({ - event: e, - target: this._createMouseTarget(e, true) - }); - } - _onMouseLeave(e) { - this.lastMouseLeaveTime = (new Date()).getTime(); - this.viewController.emitMouseLeave({ - event: e, - target: null - }); - } - _onMouseUp(e) { - this.viewController.emitMouseUp({ - event: e, - target: this._createMouseTarget(e, true) - }); - } - _onMouseDown(e) { - const t = this._createMouseTarget(e, true); - const targetIsContent = (t.type === 6 /* CONTENT_TEXT */ || t.type === 7 /* CONTENT_EMPTY */); - const targetIsGutter = (t.type === 2 /* GUTTER_GLYPH_MARGIN */ || t.type === 3 /* GUTTER_LINE_NUMBERS */ || t.type === 4 /* GUTTER_LINE_DECORATIONS */); - const targetIsLineNumbers = (t.type === 3 /* GUTTER_LINE_NUMBERS */); - const selectOnLineNumbers = this._context.configuration.options.get(97 /* selectOnLineNumbers */); - const targetIsViewZone = (t.type === 8 /* CONTENT_VIEW_ZONE */ || t.type === 5 /* GUTTER_VIEW_ZONE */); - const targetIsWidget = (t.type === 9 /* CONTENT_WIDGET */); - let shouldHandle = e.leftButton || e.middleButton; - if (platform.isMacintosh && e.leftButton && e.ctrlKey) { - shouldHandle = false; - } - const focus = () => { - e.preventDefault(); - this.viewHelper.focusTextArea(); - }; - if (shouldHandle && (targetIsContent || (targetIsLineNumbers && selectOnLineNumbers))) { - focus(); - this._mouseDownOperation.start(t.type, e); - } - else if (targetIsGutter) { - // Do not steal focus - e.preventDefault(); - } - else if (targetIsViewZone) { - const viewZoneData = t.detail; - if (this.viewHelper.shouldSuppressMouseDownOnViewZone(viewZoneData.viewZoneId)) { - focus(); - this._mouseDownOperation.start(t.type, e); - e.preventDefault(); - } - } - else if (targetIsWidget && this.viewHelper.shouldSuppressMouseDownOnWidget(t.detail)) { - focus(); - e.preventDefault(); - } - this.viewController.emitMouseDown({ - event: e, - target: t - }); - } - } - exports.MouseHandler = MouseHandler; - MouseHandler.MOUSE_MOVE_MINIMUM_TIME = 100; // ms - class MouseDownOperation extends lifecycle_1.Disposable { - constructor(context, viewController, viewHelper, createMouseTarget, getMouseColumn) { - super(); - this._context = context; - this._viewController = viewController; - this._viewHelper = viewHelper; - this._createMouseTarget = createMouseTarget; - this._getMouseColumn = getMouseColumn; - this._mouseMoveMonitor = this._register(new editorDom_1.GlobalEditorMouseMoveMonitor(this._viewHelper.viewDomNode)); - this._onScrollTimeout = this._register(new async_1.TimeoutTimer()); - this._mouseState = new MouseDownState(); - this._currentSelection = new selection_1.Selection(1, 1, 1, 1); - this._isActive = false; - this._lastMouseEvent = null; - } - dispose() { - super.dispose(); - } - isActive() { - return this._isActive; - } - _onMouseDownThenMove(e) { - this._lastMouseEvent = e; - this._mouseState.setModifiers(e); - const position = this._findMousePosition(e, true); - if (!position) { - // Ignoring because position is unknown - return; - } - if (this._mouseState.isDragAndDrop) { - this._viewController.emitMouseDrag({ - event: e, - target: position - }); - } - else { - this._dispatchMouse(position, true); - } - } - start(targetType, e) { - this._lastMouseEvent = e; - this._mouseState.setStartedOnLineNumbers(targetType === 3 /* GUTTER_LINE_NUMBERS */); - this._mouseState.setStartButtons(e); - this._mouseState.setModifiers(e); - const position = this._findMousePosition(e, true); - if (!position || !position.position) { - // Ignoring because position is unknown - return; - } - this._mouseState.trySetCount(e.detail, position.position); - // Overwrite the detail of the MouseEvent, as it will be sent out in an event and contributions might rely on it. - e.detail = this._mouseState.count; - const options = this._context.configuration.options; - if (!options.get(79 /* readOnly */) - && options.get(29 /* dragAndDrop */) - && !options.get(16 /* columnSelection */) - && !this._mouseState.altKey // we don't support multiple mouse - && e.detail < 2 // only single click on a selection can work - && !this._isActive // the mouse is not down yet - && !this._currentSelection.isEmpty() // we don't drag single cursor - && (position.type === 6 /* CONTENT_TEXT */) // single click on text - && position.position && this._currentSelection.containsPosition(position.position) // single click on a selection - ) { - this._mouseState.isDragAndDrop = true; - this._isActive = true; - this._mouseMoveMonitor.startMonitoring(e.target, e.buttons, createMouseMoveEventMerger(null), (e) => this._onMouseDownThenMove(e), (browserEvent) => { - const position = this._findMousePosition(this._lastMouseEvent, true); - if (browserEvent && browserEvent instanceof KeyboardEvent) { - // cancel - this._viewController.emitMouseDropCanceled(); - } - else { - this._viewController.emitMouseDrop({ - event: this._lastMouseEvent, - target: (position ? this._createMouseTarget(this._lastMouseEvent, true) : null) // Ignoring because position is unknown, e.g., Content View Zone - }); - } - this._stop(); - }); - return; - } - this._mouseState.isDragAndDrop = false; - this._dispatchMouse(position, e.shiftKey); - if (!this._isActive) { - this._isActive = true; - this._mouseMoveMonitor.startMonitoring(e.target, e.buttons, createMouseMoveEventMerger(null), (e) => this._onMouseDownThenMove(e), () => this._stop()); - } - } - _stop() { - this._isActive = false; - this._onScrollTimeout.cancel(); - } - onHeightChanged() { - this._mouseMoveMonitor.stopMonitoring(); - } - onScrollChanged() { - if (!this._isActive) { - return; - } - this._onScrollTimeout.setIfNotSet(() => { - if (!this._lastMouseEvent) { - return; - } - const position = this._findMousePosition(this._lastMouseEvent, false); - if (!position) { - // Ignoring because position is unknown - return; - } - if (this._mouseState.isDragAndDrop) { - // Ignoring because users are dragging the text - return; - } - this._dispatchMouse(position, true); - }, 10); - } - onCursorStateChanged(e) { - this._currentSelection = e.selections[0]; - } - _getPositionOutsideEditor(e) { - const editorContent = e.editorPos; - const model = this._context.model; - const viewLayout = this._context.viewLayout; - const mouseColumn = this._getMouseColumn(e); - if (e.posy < editorContent.y) { - const verticalOffset = Math.max(viewLayout.getCurrentScrollTop() - (editorContent.y - e.posy), 0); - const viewZoneData = mouseTarget_1.HitTestContext.getZoneAtCoord(this._context, verticalOffset); - if (viewZoneData) { - const newPosition = this._helpPositionJumpOverViewZone(viewZoneData); - if (newPosition) { - return new mouseTarget_1.MouseTarget(null, 13 /* OUTSIDE_EDITOR */, mouseColumn, newPosition); - } - } - const aboveLineNumber = viewLayout.getLineNumberAtVerticalOffset(verticalOffset); - return new mouseTarget_1.MouseTarget(null, 13 /* OUTSIDE_EDITOR */, mouseColumn, new position_1.Position(aboveLineNumber, 1)); - } - if (e.posy > editorContent.y + editorContent.height) { - const verticalOffset = viewLayout.getCurrentScrollTop() + (e.posy - editorContent.y); - const viewZoneData = mouseTarget_1.HitTestContext.getZoneAtCoord(this._context, verticalOffset); - if (viewZoneData) { - const newPosition = this._helpPositionJumpOverViewZone(viewZoneData); - if (newPosition) { - return new mouseTarget_1.MouseTarget(null, 13 /* OUTSIDE_EDITOR */, mouseColumn, newPosition); - } - } - const belowLineNumber = viewLayout.getLineNumberAtVerticalOffset(verticalOffset); - return new mouseTarget_1.MouseTarget(null, 13 /* OUTSIDE_EDITOR */, mouseColumn, new position_1.Position(belowLineNumber, model.getLineMaxColumn(belowLineNumber))); - } - const possibleLineNumber = viewLayout.getLineNumberAtVerticalOffset(viewLayout.getCurrentScrollTop() + (e.posy - editorContent.y)); - if (e.posx < editorContent.x) { - return new mouseTarget_1.MouseTarget(null, 13 /* OUTSIDE_EDITOR */, mouseColumn, new position_1.Position(possibleLineNumber, 1)); - } - if (e.posx > editorContent.x + editorContent.width) { - return new mouseTarget_1.MouseTarget(null, 13 /* OUTSIDE_EDITOR */, mouseColumn, new position_1.Position(possibleLineNumber, model.getLineMaxColumn(possibleLineNumber))); - } - return null; - } - _findMousePosition(e, testEventTarget) { - const positionOutsideEditor = this._getPositionOutsideEditor(e); - if (positionOutsideEditor) { - return positionOutsideEditor; - } - const t = this._createMouseTarget(e, testEventTarget); - const hintedPosition = t.position; - if (!hintedPosition) { - return null; - } - if (t.type === 8 /* CONTENT_VIEW_ZONE */ || t.type === 5 /* GUTTER_VIEW_ZONE */) { - const newPosition = this._helpPositionJumpOverViewZone(t.detail); - if (newPosition) { - return new mouseTarget_1.MouseTarget(t.element, t.type, t.mouseColumn, newPosition, null, t.detail); - } - } - return t; - } - _helpPositionJumpOverViewZone(viewZoneData) { - // Force position on view zones to go above or below depending on where selection started from - const selectionStart = new position_1.Position(this._currentSelection.selectionStartLineNumber, this._currentSelection.selectionStartColumn); - const positionBefore = viewZoneData.positionBefore; - const positionAfter = viewZoneData.positionAfter; - if (positionBefore && positionAfter) { - if (positionBefore.isBefore(selectionStart)) { - return positionBefore; - } - else { - return positionAfter; - } - } - return null; - } - _dispatchMouse(position, inSelectionMode) { - if (!position.position) { - return; - } - this._viewController.dispatchMouse({ - position: position.position, - mouseColumn: position.mouseColumn, - startedOnLineNumbers: this._mouseState.startedOnLineNumbers, - inSelectionMode: inSelectionMode, - mouseDownCount: this._mouseState.count, - altKey: this._mouseState.altKey, - ctrlKey: this._mouseState.ctrlKey, - metaKey: this._mouseState.metaKey, - shiftKey: this._mouseState.shiftKey, - leftButton: this._mouseState.leftButton, - middleButton: this._mouseState.middleButton, - }); - } - } - class MouseDownState { - constructor() { - this._altKey = false; - this._ctrlKey = false; - this._metaKey = false; - this._shiftKey = false; - this._leftButton = false; - this._middleButton = false; - this._startedOnLineNumbers = false; - this._lastMouseDownPosition = null; - this._lastMouseDownPositionEqualCount = 0; - this._lastMouseDownCount = 0; - this._lastSetMouseDownCountTime = 0; - this.isDragAndDrop = false; - } - get altKey() { return this._altKey; } - get ctrlKey() { return this._ctrlKey; } - get metaKey() { return this._metaKey; } - get shiftKey() { return this._shiftKey; } - get leftButton() { return this._leftButton; } - get middleButton() { return this._middleButton; } - get startedOnLineNumbers() { return this._startedOnLineNumbers; } - get count() { - return this._lastMouseDownCount; - } - setModifiers(source) { - this._altKey = source.altKey; - this._ctrlKey = source.ctrlKey; - this._metaKey = source.metaKey; - this._shiftKey = source.shiftKey; - } - setStartButtons(source) { - this._leftButton = source.leftButton; - this._middleButton = source.middleButton; - } - setStartedOnLineNumbers(startedOnLineNumbers) { - this._startedOnLineNumbers = startedOnLineNumbers; - } - trySetCount(setMouseDownCount, newMouseDownPosition) { - // a. Invalidate multiple clicking if too much time has passed (will be hit by IE because the detail field of mouse events contains garbage in IE10) - const currentTime = (new Date()).getTime(); - if (currentTime - this._lastSetMouseDownCountTime > MouseDownState.CLEAR_MOUSE_DOWN_COUNT_TIME) { - setMouseDownCount = 1; - } - this._lastSetMouseDownCountTime = currentTime; - // b. Ensure that we don't jump from single click to triple click in one go (will be hit by IE because the detail field of mouse events contains garbage in IE10) - if (setMouseDownCount > this._lastMouseDownCount + 1) { - setMouseDownCount = this._lastMouseDownCount + 1; - } - // c. Invalidate multiple clicking if the logical position is different - if (this._lastMouseDownPosition && this._lastMouseDownPosition.equals(newMouseDownPosition)) { - this._lastMouseDownPositionEqualCount++; - } - else { - this._lastMouseDownPositionEqualCount = 1; - } - this._lastMouseDownPosition = newMouseDownPosition; - // Finally set the lastMouseDownCount - this._lastMouseDownCount = Math.min(setMouseDownCount, this._lastMouseDownPositionEqualCount); - } - } - MouseDownState.CLEAR_MOUSE_DOWN_COUNT_TIME = 400; // ms -}); - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -define(__m[595/*vs/editor/browser/controller/pointerHandler*/], __M([0/*require*/,1/*exports*/,7/*vs/base/browser/dom*/,17/*vs/base/common/platform*/,60/*vs/base/browser/touch*/,2/*vs/base/common/lifecycle*/,594/*vs/editor/browser/controller/mouseHandler*/,167/*vs/editor/browser/editorDom*/,156/*vs/base/browser/canIUse*/,169/*vs/editor/browser/controller/textAreaInput*/]), function (require, exports, dom, platform, touch_1, lifecycle_1, mouseHandler_1, editorDom_1, canIUse_1, textAreaInput_1) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.PointerHandler = exports.PointerEventHandler = void 0; - /** - * Currently only tested on iOS 13/ iPadOS. - */ - class PointerEventHandler extends mouseHandler_1.MouseHandler { - constructor(context, viewController, viewHelper) { - super(context, viewController, viewHelper); - this._register(touch_1.Gesture.addTarget(this.viewHelper.linesContentDomNode)); - this._register(dom.addDisposableListener(this.viewHelper.linesContentDomNode, touch_1.EventType.Tap, (e) => this.onTap(e))); - this._register(dom.addDisposableListener(this.viewHelper.linesContentDomNode, touch_1.EventType.Change, (e) => this.onChange(e))); - this._register(dom.addDisposableListener(this.viewHelper.linesContentDomNode, touch_1.EventType.Contextmenu, (e) => this._onContextMenu(new editorDom_1.EditorMouseEvent(e, this.viewHelper.viewDomNode), false))); - this._lastPointerType = 'mouse'; - this._register(dom.addDisposableListener(this.viewHelper.linesContentDomNode, 'pointerdown', (e) => { - const pointerType = e.pointerType; - if (pointerType === 'mouse') { - this._lastPointerType = 'mouse'; - return; - } - else if (pointerType === 'touch') { - this._lastPointerType = 'touch'; - } - else { - this._lastPointerType = 'pen'; - } - })); - // PonterEvents - const pointerEvents = new editorDom_1.EditorPointerEventFactory(this.viewHelper.viewDomNode); - this._register(pointerEvents.onPointerMoveThrottled(this.viewHelper.viewDomNode, (e) => this._onMouseMove(e), (0, mouseHandler_1.createMouseMoveEventMerger)(this.mouseTargetFactory), mouseHandler_1.MouseHandler.MOUSE_MOVE_MINIMUM_TIME)); - this._register(pointerEvents.onPointerUp(this.viewHelper.viewDomNode, (e) => this._onMouseUp(e))); - this._register(pointerEvents.onPointerLeave(this.viewHelper.viewDomNode, (e) => this._onMouseLeave(e))); - this._register(pointerEvents.onPointerDown(this.viewHelper.viewDomNode, (e) => this._onMouseDown(e))); - } - onTap(event) { - if (!event.initialTarget || !this.viewHelper.linesContentDomNode.contains(event.initialTarget)) { - return; - } - event.preventDefault(); - this.viewHelper.focusTextArea(); - const target = this._createMouseTarget(new editorDom_1.EditorMouseEvent(event, this.viewHelper.viewDomNode), false); - if (target.position) { - // this.viewController.moveTo(target.position); - this.viewController.dispatchMouse({ - position: target.position, - mouseColumn: target.position.column, - startedOnLineNumbers: false, - mouseDownCount: event.tapCount, - inSelectionMode: false, - altKey: false, - ctrlKey: false, - metaKey: false, - shiftKey: false, - leftButton: false, - middleButton: false, - }); - } - } - onChange(e) { - if (this._lastPointerType === 'touch') { - this._context.model.deltaScrollNow(-e.translationX, -e.translationY); - } - } - _onMouseDown(e) { - if (e.browserEvent.pointerType === 'touch') { - return; - } - super._onMouseDown(e); - } - } - exports.PointerEventHandler = PointerEventHandler; - class TouchHandler extends mouseHandler_1.MouseHandler { - constructor(context, viewController, viewHelper) { - super(context, viewController, viewHelper); - this._register(touch_1.Gesture.addTarget(this.viewHelper.linesContentDomNode)); - this._register(dom.addDisposableListener(this.viewHelper.linesContentDomNode, touch_1.EventType.Tap, (e) => this.onTap(e))); - this._register(dom.addDisposableListener(this.viewHelper.linesContentDomNode, touch_1.EventType.Change, (e) => this.onChange(e))); - this._register(dom.addDisposableListener(this.viewHelper.linesContentDomNode, touch_1.EventType.Contextmenu, (e) => this._onContextMenu(new editorDom_1.EditorMouseEvent(e, this.viewHelper.viewDomNode), false))); - } - onTap(event) { - event.preventDefault(); - this.viewHelper.focusTextArea(); - const target = this._createMouseTarget(new editorDom_1.EditorMouseEvent(event, this.viewHelper.viewDomNode), false); - if (target.position) { - // Send the tap event also to the