"use strict";
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

require("core-js/modules/es.array.slice.js");

require("core-js/modules/es.function.name.js");

require("core-js/modules/es.array.from.js");

require("core-js/modules/es.string.iterator.js");

require("core-js/modules/es.symbol.js");

require("core-js/modules/es.symbol.description.js");

require("core-js/modules/es.symbol.iterator.js");

require("core-js/modules/es.array.iterator.js");

require("core-js/modules/web.dom-collections.iterator.js");

require("regenerator-runtime/runtime.js");

require("core-js/modules/es.object.to-string.js");

require("core-js/modules/es.promise.js");

require("core-js/modules/es.string.ends-with.js");

require("core-js/modules/es.regexp.exec.js");

require("core-js/modules/es.string.replace.js");

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

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 asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.format = format;

var languageModes_1 = require("./languageModes");

var arrays_1 = require("../utils/arrays");

var strings_1 = require("../utils/strings");

function format(_x, _x2, _x3, _x4, _x5, _x6) {
  return _format.apply(this, arguments);
}

function _format() {
  _format = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(languageModes, document, formatRange, formattingOptions, settings, enabledModes) {
    var result, endPos, endOffset, content, prevLineStart, allRanges, i, startPos, isHTML, range, edits, htmlMode, htmlEdits, htmlFormattedContent, newDocument, afterFormatRangeLength, newFormatRange, embeddedRanges, embeddedEdits, _iterator, _step, r, mode, _edits, _iterator2, _step2, edit, resultContent, resultReplaceText;

    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            result = [];
            endPos = formatRange.end;
            endOffset = document.offsetAt(endPos);
            content = document.getText();

            if (endPos.character === 0 && endPos.line > 0 && endOffset !== content.length) {
              // if selection ends after a new line, exclude that new line
              prevLineStart = document.offsetAt(languageModes_1.Position.create(endPos.line - 1, 0));

              while ((0, strings_1.isEOL)(content, endOffset - 1) && endOffset > prevLineStart) {
                endOffset--;
              }

              formatRange = languageModes_1.Range.create(formatRange.start, document.positionAt(endOffset));
            } // run the html formatter on the full range and pass the result content to the embedded formatters.
            // from the final content create a single edit
            // advantages of this approach are
            //  - correct indents in the html document
            //  - correct initial indent for embedded formatters
            //  - no worrying of overlapping edits
            // make sure we start in html


            allRanges = languageModes.getModesInRange(document, formatRange);
            i = 0;
            startPos = formatRange.start;

            isHTML = function isHTML(range) {
              return range.mode && range.mode.getId() === 'html';
            };

          case 9:
            if (!(i < allRanges.length && !isHTML(allRanges[i]))) {
              _context.next = 20;
              break;
            }

            range = allRanges[i];

            if (!(!range.attributeValue && range.mode && range.mode.format)) {
              _context.next = 16;
              break;
            }

            _context.next = 14;
            return range.mode.format(document, languageModes_1.Range.create(startPos, range.end), formattingOptions, settings);

          case 14:
            edits = _context.sent;
            (0, arrays_1.pushAll)(result, edits);

          case 16:
            startPos = range.end;
            i++;
            _context.next = 9;
            break;

          case 20:
            if (!(i === allRanges.length)) {
              _context.next = 22;
              break;
            }

            return _context.abrupt("return", result);

          case 22:
            // modify the range
            formatRange = languageModes_1.Range.create(startPos, formatRange.end); // perform a html format and apply changes to a new document

            htmlMode = languageModes.getMode('html');
            _context.next = 26;
            return htmlMode.format(document, formatRange, formattingOptions, settings);

          case 26:
            htmlEdits = _context.sent;
            htmlFormattedContent = languageModes_1.TextDocument.applyEdits(document, htmlEdits);

            if (formattingOptions.insertFinalNewline && endOffset === content.length && !htmlFormattedContent.endsWith('\n')) {
              htmlFormattedContent = htmlFormattedContent + '\n';
              htmlEdits.push(languageModes_1.TextEdit.insert(endPos, '\n'));
            }

            newDocument = languageModes_1.TextDocument.create(document.uri + '.tmp', document.languageId, document.version, htmlFormattedContent);
            _context.prev = 30;
            // run embedded formatters on html formatted content: - formatters see correct initial indent
            afterFormatRangeLength = document.getText().length - document.offsetAt(formatRange.end); // length of unchanged content after replace range

            newFormatRange = languageModes_1.Range.create(formatRange.start, newDocument.positionAt(htmlFormattedContent.length - afterFormatRangeLength));
            embeddedRanges = languageModes.getModesInRange(newDocument, newFormatRange);
            embeddedEdits = [];
            _iterator = _createForOfIteratorHelper(embeddedRanges);
            _context.prev = 36;

            _iterator.s();

          case 38:
            if ((_step = _iterator.n()).done) {
              _context.next = 49;
              break;
            }

            r = _step.value;
            mode = r.mode;

            if (!(mode && mode.format && enabledModes[mode.getId()] && !r.attributeValue)) {
              _context.next = 47;
              break;
            }

            _context.next = 44;
            return mode.format(newDocument, r, formattingOptions, settings);

          case 44:
            _edits = _context.sent;
            _iterator2 = _createForOfIteratorHelper(_edits);

            try {
              for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
                edit = _step2.value;
                embeddedEdits.push(edit);
              }
            } catch (err) {
              _iterator2.e(err);
            } finally {
              _iterator2.f();
            }

          case 47:
            _context.next = 38;
            break;

          case 49:
            _context.next = 54;
            break;

          case 51:
            _context.prev = 51;
            _context.t0 = _context["catch"](36);

            _iterator.e(_context.t0);

          case 54:
            _context.prev = 54;

            _iterator.f();

            return _context.finish(54);

          case 57:
            if (!(embeddedEdits.length === 0)) {
              _context.next = 60;
              break;
            }

            (0, arrays_1.pushAll)(result, htmlEdits);
            return _context.abrupt("return", result);

          case 60:
            // apply all embedded format edits and create a single edit for all changes
            resultContent = languageModes_1.TextDocument.applyEdits(newDocument, embeddedEdits);
            resultReplaceText = resultContent.substring(document.offsetAt(formatRange.start), resultContent.length - afterFormatRangeLength);
            result.push(languageModes_1.TextEdit.replace(formatRange, resultReplaceText));
            return _context.abrupt("return", result);

          case 64:
            _context.prev = 64;
            languageModes.onDocumentRemoved(newDocument);
            return _context.finish(64);

          case 67:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[30,, 64, 67], [36, 51, 54, 57]]);
  }));
  return _format.apply(this, arguments);
}