import { getActiveElement } from '../../../../base/browser/dom.js';
import { List } from '../../../../base/browser/ui/list/listWidget.js';
import { distinct, coalesce } from '../../../../base/common/arrays.js';
import { KeyMod as KeyMod$1, KeyCode, KeyChord } from '../../../../base/common/keyCodes.js';
import { matchesScheme, Schemas } from '../../../../base/common/network.js';
import { extname, isEqual } from '../../../../base/common/resources.js';
import { isObject, isString, isUndefined, isNumber } from '../../../../base/common/types.js';
import { URI } from '../../../../base/common/uri.js';
import { isDiffEditor } from '../../../../editor/browser/editorBrowser.js';
import { EditorContextKeys } from '../../../../editor/common/editorContextKeys.js';
import { localizeWithPath, localize2WithPath } from '../../../../nls.js';
import { Categories } from '../../../../platform/action/common/actionCommonCategories.js';
import { registerAction2, Action2 } from '../../../../platform/actions/common/actions.js';
import { CommandsRegistry } from '../../../../platform/commands/common/commands.js';
import { ICommandService } from '../../../../platform/commands/common/commands.service.js';
import { IConfigurationService } from '../../../../platform/configuration/common/configuration.service.js';
import { ContextKeyExpr } from '../../../../platform/contextkey/common/contextkey.js';
import { EditorResolution } from '../../../../platform/editor/common/editor.js';
import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js';
import { KeybindingsRegistry, KeybindingWeight } from '../../../../platform/keybinding/common/keybindingsRegistry.js';
import { IListService } from '../../../../platform/list/browser/listService.service.js';
import { IOpenerService } from '../../../../platform/opener/common/opener.service.js';
import { IQuickInputService } from '../../../../platform/quickinput/common/quickInput.service.js';
import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.service.js';
import { ActiveGroupEditorsByMostRecentlyUsedQuickAccess } from './editorQuickAccess.js';
import { SideBySideEditor } from './sideBySideEditor.js';
import { TextDiffEditor } from './textDiffEditor.js';
import { ActiveEditorGroupEmptyContext, MultipleEditorGroupsContext, ActiveEditorCanSplitInGroupContext, SideBySideEditorActiveContext, TextCompareEditorActiveContext, ActiveEditorGroupLockedContext, ActiveEditorStickyContext } from '../../../common/contextkeys.js';
import { EditorInputCapabilities, EditorsOrder, CloseDirection, isEditorInputWithOptionsAndGroup, isEditorCommandsContext, isEditorIdentifier } from '../../../common/editor.js';
import { DiffEditorInput } from '../../../common/editor/diffEditorInput.js';
import { SideBySideEditorInput } from '../../../common/editor/sideBySideEditorInput.js';
import { columnToEditorGroup } from '../../../services/editor/common/editorGroupColumn.js';
import { GroupsOrder, GroupLocation, preferredSideBySideGroupDirection, GroupDirection, isEditorGroup } from '../../../services/editor/common/editorGroupsService.js';
import { IEditorGroupsService } from '../../../services/editor/common/editorGroupsService.service.js';
import { IEditorResolverService } from '../../../services/editor/common/editorResolverService.service.js';
import { SIDE_GROUP } from '../../../services/editor/common/editorService.js';
import { IEditorService } from '../../../services/editor/common/editorService.service.js';
import { IPathService } from '../../../services/path/common/pathService.service.js';
import { IUntitledTextEditorService } from '../../../services/untitled/common/untitledTextEditorService.service.js';
import { registerDiffEditorCommands, DIFF_FOCUS_SECONDARY_SIDE, DIFF_FOCUS_PRIMARY_SIDE, DIFF_FOCUS_OTHER_SIDE, DIFF_OPEN_SIDE } from './diffEditorCommands.js';
const _moduleId = "vs/workbench/browser/parts/editor/editorCommands";
const CLOSE_SAVED_EDITORS_COMMAND_ID = 'workbench.action.closeUnmodifiedEditors';
const CLOSE_EDITORS_IN_GROUP_COMMAND_ID = 'workbench.action.closeEditorsInGroup';
const CLOSE_EDITORS_AND_GROUP_COMMAND_ID = 'workbench.action.closeEditorsAndGroup';
const CLOSE_EDITORS_TO_THE_RIGHT_COMMAND_ID = 'workbench.action.closeEditorsToTheRight';
const CLOSE_EDITOR_COMMAND_ID = 'workbench.action.closeActiveEditor';
const CLOSE_PINNED_EDITOR_COMMAND_ID = 'workbench.action.closeActivePinnedEditor';
const CLOSE_EDITOR_GROUP_COMMAND_ID = 'workbench.action.closeGroup';
const CLOSE_OTHER_EDITORS_IN_GROUP_COMMAND_ID = 'workbench.action.closeOtherEditors';
const MOVE_ACTIVE_EDITOR_COMMAND_ID = 'moveActiveEditor';
const COPY_ACTIVE_EDITOR_COMMAND_ID = 'copyActiveEditor';
const LAYOUT_EDITOR_GROUPS_COMMAND_ID = 'layoutEditorGroups';
const KEEP_EDITOR_COMMAND_ID = 'workbench.action.keepEditor';
const TOGGLE_KEEP_EDITORS_COMMAND_ID = 'workbench.action.toggleKeepEditors';
const TOGGLE_LOCK_GROUP_COMMAND_ID = 'workbench.action.toggleEditorGroupLock';
const LOCK_GROUP_COMMAND_ID = 'workbench.action.lockEditorGroup';
const UNLOCK_GROUP_COMMAND_ID = 'workbench.action.unlockEditorGroup';
const SHOW_EDITORS_IN_GROUP = 'workbench.action.showEditorsInGroup';
const REOPEN_WITH_COMMAND_ID = 'workbench.action.reopenWithEditor';
const PIN_EDITOR_COMMAND_ID = 'workbench.action.pinEditor';
const UNPIN_EDITOR_COMMAND_ID = 'workbench.action.unpinEditor';
const SPLIT_EDITOR = 'workbench.action.splitEditor';
const SPLIT_EDITOR_UP = 'workbench.action.splitEditorUp';
const SPLIT_EDITOR_DOWN = 'workbench.action.splitEditorDown';
const SPLIT_EDITOR_LEFT = 'workbench.action.splitEditorLeft';
const SPLIT_EDITOR_RIGHT = 'workbench.action.splitEditorRight';
const TOGGLE_MAXIMIZE_EDITOR_GROUP = 'workbench.action.toggleMaximizeEditorGroup';
const SPLIT_EDITOR_IN_GROUP = 'workbench.action.splitEditorInGroup';
const TOGGLE_SPLIT_EDITOR_IN_GROUP = 'workbench.action.toggleSplitEditorInGroup';
const JOIN_EDITOR_IN_GROUP = 'workbench.action.joinEditorInGroup';
const TOGGLE_SPLIT_EDITOR_IN_GROUP_LAYOUT = 'workbench.action.toggleSplitEditorInGroupLayout';
const FOCUS_FIRST_SIDE_EDITOR = 'workbench.action.focusFirstSideEditor';
const FOCUS_SECOND_SIDE_EDITOR = 'workbench.action.focusSecondSideEditor';
const FOCUS_OTHER_SIDE_EDITOR = 'workbench.action.focusOtherSideEditor';
const FOCUS_LEFT_GROUP_WITHOUT_WRAP_COMMAND_ID = 'workbench.action.focusLeftGroupWithoutWrap';
const FOCUS_RIGHT_GROUP_WITHOUT_WRAP_COMMAND_ID = 'workbench.action.focusRightGroupWithoutWrap';
const FOCUS_ABOVE_GROUP_WITHOUT_WRAP_COMMAND_ID = 'workbench.action.focusAboveGroupWithoutWrap';
const FOCUS_BELOW_GROUP_WITHOUT_WRAP_COMMAND_ID = 'workbench.action.focusBelowGroupWithoutWrap';
const OPEN_EDITOR_AT_INDEX_COMMAND_ID = 'workbench.action.openEditorAtIndex';
const MOVE_EDITOR_INTO_NEW_WINDOW_COMMAND_ID = 'workbench.action.moveEditorToNewWindow';
const COPY_EDITOR_INTO_NEW_WINDOW_COMMAND_ID = 'workbench.action.copyEditorToNewWindow';
const MOVE_EDITOR_GROUP_INTO_NEW_WINDOW_COMMAND_ID = 'workbench.action.moveEditorGroupToNewWindow';
const COPY_EDITOR_GROUP_INTO_NEW_WINDOW_COMMAND_ID = 'workbench.action.copyEditorGroupToNewWindow';
const NEW_EMPTY_EDITOR_WINDOW_COMMAND_ID = 'workbench.action.newEmptyEditorWindow';
const API_OPEN_EDITOR_COMMAND_ID = '_workbench.open';
const API_OPEN_DIFF_EDITOR_COMMAND_ID = '_workbench.diff';
const API_OPEN_WITH_EDITOR_COMMAND_ID = '_workbench.openWith';
const EDITOR_CORE_NAVIGATION_COMMANDS = [
    SPLIT_EDITOR,
    CLOSE_EDITOR_COMMAND_ID,
    UNPIN_EDITOR_COMMAND_ID,
    UNLOCK_GROUP_COMMAND_ID,
    TOGGLE_MAXIMIZE_EDITOR_GROUP
];
const isActiveEditorMoveCopyArg = function (arg) {
    if (!isObject(arg)) {
        return false;
    }
    if (!isString(arg.to)) {
        return false;
    }
    if (!isUndefined(arg.by) && !isString(arg.by)) {
        return false;
    }
    if (!isUndefined(arg.value) && !isNumber(arg.value)) {
        return false;
    }
    return true;
};
function registerActiveEditorMoveCopyCommand() {
    const moveCopyJSONSchema = {
        'type': 'object',
        'required': ['to'],
        'properties': {
            'to': {
                'type': 'string',
                'enum': ['left', 'right']
            },
            'by': {
                'type': 'string',
                'enum': ['tab', 'group']
            },
            'value': {
                'type': 'number'
            }
        }
    };
    KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: MOVE_ACTIVE_EDITOR_COMMAND_ID,
        weight: KeybindingWeight.WorkbenchContrib,
        when: EditorContextKeys.editorTextFocus,
        primary: 0,
        handler: (accessor, args) => moveCopyActiveEditor(true, args, accessor),
        metadata: {
            description: ( localizeWithPath(_moduleId, 0, "Move the active editor by tabs or groups")),
            args: [
                {
                    name: ( localizeWithPath(_moduleId, 1, "Active editor move argument")),
                    description: ( localizeWithPath(
                        _moduleId,
                        2,
                        "Argument Properties:\n\t* 'to': String value providing where to move.\n\t* 'by': String value providing the unit for move (by tab or by group).\n\t* 'value': Number value providing how many positions or an absolute position to move."
                    )),
                    constraint: isActiveEditorMoveCopyArg,
                    schema: moveCopyJSONSchema
                }
            ]
        }
    });
    KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: COPY_ACTIVE_EDITOR_COMMAND_ID,
        weight: KeybindingWeight.WorkbenchContrib,
        when: EditorContextKeys.editorTextFocus,
        primary: 0,
        handler: (accessor, args) => moveCopyActiveEditor(false, args, accessor),
        metadata: {
            description: ( localizeWithPath(_moduleId, 3, "Copy the active editor by groups")),
            args: [
                {
                    name: ( localizeWithPath(_moduleId, 4, "Active editor copy argument")),
                    description: ( localizeWithPath(
                        _moduleId,
                        5,
                        "Argument Properties:\n\t* 'to': String value providing where to copy.\n\t* 'value': Number value providing how many positions or an absolute position to copy."
                    )),
                    constraint: isActiveEditorMoveCopyArg,
                    schema: moveCopyJSONSchema
                }
            ]
        }
    });
    function moveCopyActiveEditor(isMove, args = Object.create(null), accessor) {
        args.to = args.to || 'right';
        args.by = args.by || 'tab';
        args.value = typeof args.value === 'number' ? args.value : 1;
        const activeEditorPane = accessor.get(IEditorService).activeEditorPane;
        if (activeEditorPane) {
            switch (args.by) {
                case 'tab':
                    if (isMove) {
                        return moveActiveTab(args, activeEditorPane);
                    }
                    break;
                case 'group':
                    return moveCopyActiveEditorToGroup(isMove, args, activeEditorPane, accessor);
            }
        }
    }
    function moveActiveTab(args, control) {
        const group = control.group;
        let index = group.getIndexOfEditor(control.input);
        switch (args.to) {
            case 'first':
                index = 0;
                break;
            case 'last':
                index = group.count - 1;
                break;
            case 'left':
                index = index - (args.value ?? 1);
                break;
            case 'right':
                index = index + (args.value ?? 1);
                break;
            case 'center':
                index = Math.round(group.count / 2) - 1;
                break;
            case 'position':
                index = (args.value ?? 1) - 1;
                break;
        }
        index = index < 0 ? 0 : index >= group.count ? group.count - 1 : index;
        group.moveEditor(control.input, group, { index });
    }
    function moveCopyActiveEditorToGroup(isMove, args, control, accessor) {
        const editorGroupService = accessor.get(IEditorGroupsService);
        const configurationService = accessor.get(IConfigurationService);
        const sourceGroup = control.group;
        let targetGroup;
        switch (args.to) {
            case 'left':
                targetGroup = editorGroupService.findGroup({ direction: GroupDirection.LEFT }, sourceGroup);
                if (!targetGroup) {
                    targetGroup = editorGroupService.addGroup(sourceGroup, GroupDirection.LEFT);
                }
                break;
            case 'right':
                targetGroup = editorGroupService.findGroup({ direction: GroupDirection.RIGHT }, sourceGroup);
                if (!targetGroup) {
                    targetGroup = editorGroupService.addGroup(sourceGroup, GroupDirection.RIGHT);
                }
                break;
            case 'up':
                targetGroup = editorGroupService.findGroup({ direction: GroupDirection.UP }, sourceGroup);
                if (!targetGroup) {
                    targetGroup = editorGroupService.addGroup(sourceGroup, GroupDirection.UP);
                }
                break;
            case 'down':
                targetGroup = editorGroupService.findGroup({ direction: GroupDirection.DOWN }, sourceGroup);
                if (!targetGroup) {
                    targetGroup = editorGroupService.addGroup(sourceGroup, GroupDirection.DOWN);
                }
                break;
            case 'first':
                targetGroup = editorGroupService.findGroup({ location: GroupLocation.FIRST }, sourceGroup);
                break;
            case 'last':
                targetGroup = editorGroupService.findGroup({ location: GroupLocation.LAST }, sourceGroup);
                break;
            case 'previous':
                targetGroup = editorGroupService.findGroup({ location: GroupLocation.PREVIOUS }, sourceGroup);
                break;
            case 'next':
                targetGroup = editorGroupService.findGroup({ location: GroupLocation.NEXT }, sourceGroup);
                if (!targetGroup) {
                    targetGroup = editorGroupService.addGroup(sourceGroup, preferredSideBySideGroupDirection(configurationService));
                }
                break;
            case 'center':
                targetGroup = editorGroupService.getGroups(GroupsOrder.GRID_APPEARANCE)[(editorGroupService.count / 2) - 1];
                break;
            case 'position':
                targetGroup = editorGroupService.getGroups(GroupsOrder.GRID_APPEARANCE)[(args.value ?? 1) - 1];
                break;
        }
        if (targetGroup) {
            if (isMove) {
                sourceGroup.moveEditor(control.input, targetGroup);
            }
            else if (sourceGroup.id !== targetGroup.id) {
                sourceGroup.copyEditor(control.input, targetGroup);
            }
            targetGroup.focus();
        }
    }
}
function registerEditorGroupsLayoutCommands() {
    function applyEditorLayout(accessor, layout) {
        if (!layout || typeof layout !== 'object') {
            return;
        }
        const editorGroupService = accessor.get(IEditorGroupsService);
        editorGroupService.applyLayout(layout);
    }
    CommandsRegistry.registerCommand(LAYOUT_EDITOR_GROUPS_COMMAND_ID, (accessor, args) => {
        applyEditorLayout(accessor, args);
    });
    CommandsRegistry.registerCommand({
        id: 'vscode.setEditorLayout',
        handler: (accessor, args) => applyEditorLayout(accessor, args),
        metadata: {
            description: 'Set Editor Layout',
            args: [{
                    name: 'args',
                    schema: {
                        'type': 'object',
                        'required': ['groups'],
                        'properties': {
                            'orientation': {
                                'type': 'number',
                                'default': 0,
                                'enum': [0, 1]
                            },
                            'groups': {
                                '$ref': '#/definitions/editorGroupsSchema',
                                'default': [{}, {}]
                            }
                        }
                    }
                }]
        }
    });
    CommandsRegistry.registerCommand({
        id: 'vscode.getEditorLayout',
        handler: (accessor) => {
            const editorGroupService = accessor.get(IEditorGroupsService);
            return editorGroupService.getLayout();
        },
        metadata: {
            description: 'Get Editor Layout',
            args: [],
            returns: 'An editor layout object, in the same format as vscode.setEditorLayout'
        }
    });
}
function registerOpenEditorAPICommands() {
    function mixinContext(context, options, column) {
        if (!context) {
            return [options, column];
        }
        return [
            { ...context.editorOptions, ...(options ?? Object.create(null)) },
            context.sideBySide ? SIDE_GROUP : column
        ];
    }
    CommandsRegistry.registerCommand({
        id: 'vscode.open',
        handler: (accessor, arg) => {
            accessor.get(ICommandService).executeCommand(API_OPEN_EDITOR_COMMAND_ID, arg);
        },
        metadata: {
            description: 'Opens the provided resource in the editor.',
            args: [{ name: 'Uri' }]
        }
    });
    CommandsRegistry.registerCommand(API_OPEN_EDITOR_COMMAND_ID, async function (accessor, resourceArg, columnAndOptions, label, context) {
        const editorService = accessor.get(IEditorService);
        const editorGroupService = accessor.get(IEditorGroupsService);
        const openerService = accessor.get(IOpenerService);
        const pathService = accessor.get(IPathService);
        const configurationService = accessor.get(IConfigurationService);
        const untitledTextEditorService = accessor.get(IUntitledTextEditorService);
        const resourceOrString = typeof resourceArg === 'string' ? resourceArg : ( (URI.from(resourceArg, true)));
        const [columnArg, optionsArg] = columnAndOptions ?? [];
        if (optionsArg || typeof columnArg === 'number' || matchesScheme(resourceOrString, Schemas.untitled)) {
            const [options, column] = mixinContext(context, optionsArg, columnArg);
            const resource = URI.isUri(resourceOrString) ? resourceOrString : ( (URI.parse(resourceOrString)));
            let input;
            if (untitledTextEditorService.isUntitledWithAssociatedResource(resource)) {
                input = { resource: resource.with({ scheme: pathService.defaultUriScheme }), forceUntitled: true, options, label };
            }
            else {
                input = { resource, options, label };
            }
            await editorService.openEditor(input, columnToEditorGroup(editorGroupService, configurationService, column));
        }
        else if (matchesScheme(resourceOrString, Schemas.command)) {
            return;
        }
        else {
            await openerService.open(resourceOrString, { openToSide: context?.sideBySide, editorOptions: context?.editorOptions });
        }
    });
    CommandsRegistry.registerCommand({
        id: 'vscode.diff',
        handler: (accessor, left, right, label) => {
            accessor.get(ICommandService).executeCommand(API_OPEN_DIFF_EDITOR_COMMAND_ID, left, right, label);
        },
        metadata: {
            description: 'Opens the provided resources in the diff editor to compare their contents.',
            args: [
                { name: 'left', description: 'Left-hand side resource of the diff editor' },
                { name: 'right', description: 'Right-hand side resource of the diff editor' },
                { name: 'title', description: 'Human readable title for the diff editor' },
            ]
        }
    });
    CommandsRegistry.registerCommand(API_OPEN_DIFF_EDITOR_COMMAND_ID, async function (accessor, originalResource, modifiedResource, labelAndOrDescription, columnAndOptions, context) {
        const editorService = accessor.get(IEditorService);
        const editorGroupService = accessor.get(IEditorGroupsService);
        const configurationService = accessor.get(IConfigurationService);
        const [columnArg, optionsArg] = columnAndOptions ?? [];
        const [options, column] = mixinContext(context, optionsArg, columnArg);
        let label = undefined;
        let description = undefined;
        if (typeof labelAndOrDescription === 'string') {
            label = labelAndOrDescription;
        }
        else if (labelAndOrDescription) {
            label = labelAndOrDescription.label;
            description = labelAndOrDescription.description;
        }
        await editorService.openEditor({
            original: { resource: ( (URI.from(originalResource, true))) },
            modified: { resource: ( (URI.from(modifiedResource, true))) },
            label,
            description,
            options
        }, columnToEditorGroup(editorGroupService, configurationService, column));
    });
    CommandsRegistry.registerCommand(API_OPEN_WITH_EDITOR_COMMAND_ID, async (accessor, resource, id, columnAndOptions) => {
        const editorService = accessor.get(IEditorService);
        const editorGroupsService = accessor.get(IEditorGroupsService);
        const configurationService = accessor.get(IConfigurationService);
        const [columnArg, optionsArg] = columnAndOptions ?? [];
        await editorService.openEditor({ resource: ( (URI.from(resource, true))), options: { ...optionsArg, pinned: true, override: id } }, columnToEditorGroup(editorGroupsService, configurationService, columnArg));
    });
    CommandsRegistry.registerCommand({
        id: 'vscode.changes',
        handler: (accessor, title, resources) => {
            accessor.get(ICommandService).executeCommand('_workbench.changes', title, resources);
        },
        metadata: {
            description: 'Opens a list of resources in the changes editor to compare their contents.',
            args: [
                { name: 'title', description: 'Human readable title for the diff editor' },
                { name: 'resources', description: 'List of resources to open in the changes editor' }
            ]
        }
    });
    CommandsRegistry.registerCommand('_workbench.changes', async (accessor, title, resources) => {
        const editorService = accessor.get(IEditorService);
        const editor = [];
        for (const [label, original, modified] of resources) {
            editor.push({
                resource: URI.revive(label),
                original: { resource: URI.revive(original) },
                modified: { resource: URI.revive(modified) },
            });
        }
        await editorService.openEditor({ resources: editor, label: title });
    });
    CommandsRegistry.registerCommand('_workbench.openMultiDiffEditor', async (accessor, options) => {
        const editorService = accessor.get(IEditorService);
        await editorService.openEditor({
            multiDiffSource: options.multiDiffSourceUri ? URI.revive(options.multiDiffSourceUri) : undefined,
            resources: options.resources?.map(r => ({ original: { resource: URI.revive(r.originalUri) }, modified: { resource: URI.revive(r.modifiedUri) } })),
            label: options.title,
        });
    });
}
function registerOpenEditorAtIndexCommands() {
    const openEditorAtIndex = (accessor, editorIndex) => {
        const editorService = accessor.get(IEditorService);
        const activeEditorPane = editorService.activeEditorPane;
        if (activeEditorPane) {
            const editor = activeEditorPane.group.getEditorByIndex(editorIndex);
            if (editor) {
                editorService.openEditor(editor);
            }
        }
    };
    CommandsRegistry.registerCommand({
        id: OPEN_EDITOR_AT_INDEX_COMMAND_ID,
        handler: openEditorAtIndex
    });
    for (let i = 0; i < 9; i++) {
        const editorIndex = i;
        const visibleIndex = i + 1;
        KeybindingsRegistry.registerCommandAndKeybindingRule({
            id: OPEN_EDITOR_AT_INDEX_COMMAND_ID + visibleIndex,
            weight: KeybindingWeight.WorkbenchContrib,
            when: undefined,
            primary: KeyMod$1.Alt | toKeyCode(visibleIndex),
            mac: { primary: KeyMod$1.WinCtrl | toKeyCode(visibleIndex) },
            handler: accessor => openEditorAtIndex(accessor, editorIndex)
        });
    }
    function toKeyCode(index) {
        switch (index) {
            case 0: return KeyCode.Digit0;
            case 1: return KeyCode.Digit1;
            case 2: return KeyCode.Digit2;
            case 3: return KeyCode.Digit3;
            case 4: return KeyCode.Digit4;
            case 5: return KeyCode.Digit5;
            case 6: return KeyCode.Digit6;
            case 7: return KeyCode.Digit7;
            case 8: return KeyCode.Digit8;
            case 9: return KeyCode.Digit9;
        }
        throw ( (new Error('invalid index')));
    }
}
function registerFocusEditorGroupAtIndexCommands() {
    for (let groupIndex = 1; groupIndex < 8; groupIndex++) {
        KeybindingsRegistry.registerCommandAndKeybindingRule({
            id: toCommandId(groupIndex),
            weight: KeybindingWeight.WorkbenchContrib,
            when: undefined,
            primary: KeyMod$1.CtrlCmd | toKeyCode(groupIndex),
            handler: accessor => {
                const editorGroupService = accessor.get(IEditorGroupsService);
                const configurationService = accessor.get(IConfigurationService);
                if (groupIndex > editorGroupService.count) {
                    return;
                }
                const groups = editorGroupService.getGroups(GroupsOrder.GRID_APPEARANCE);
                if (groups[groupIndex]) {
                    return groups[groupIndex].focus();
                }
                const direction = preferredSideBySideGroupDirection(configurationService);
                const lastGroup = editorGroupService.findGroup({ location: GroupLocation.LAST });
                if (!lastGroup) {
                    return;
                }
                const newGroup = editorGroupService.addGroup(lastGroup, direction);
                newGroup.focus();
            }
        });
    }
    function toCommandId(index) {
        switch (index) {
            case 1: return 'workbench.action.focusSecondEditorGroup';
            case 2: return 'workbench.action.focusThirdEditorGroup';
            case 3: return 'workbench.action.focusFourthEditorGroup';
            case 4: return 'workbench.action.focusFifthEditorGroup';
            case 5: return 'workbench.action.focusSixthEditorGroup';
            case 6: return 'workbench.action.focusSeventhEditorGroup';
            case 7: return 'workbench.action.focusEighthEditorGroup';
        }
        throw ( (new Error('Invalid index')));
    }
    function toKeyCode(index) {
        switch (index) {
            case 1: return KeyCode.Digit2;
            case 2: return KeyCode.Digit3;
            case 3: return KeyCode.Digit4;
            case 4: return KeyCode.Digit5;
            case 5: return KeyCode.Digit6;
            case 6: return KeyCode.Digit7;
            case 7: return KeyCode.Digit8;
        }
        throw ( (new Error('Invalid index')));
    }
}
function splitEditor(editorGroupService, direction, contexts) {
    let newGroup;
    let sourceGroup;
    for (const context of contexts ?? [undefined]) {
        let currentGroup;
        if (context) {
            currentGroup = editorGroupService.getGroup(context.groupId);
        }
        else {
            currentGroup = editorGroupService.activeGroup;
        }
        if (!currentGroup) {
            continue;
        }
        if (!sourceGroup) {
            sourceGroup = currentGroup;
        }
        else if (sourceGroup.id !== currentGroup.id) {
            continue;
        }
        if (!newGroup) {
            newGroup = editorGroupService.addGroup(currentGroup, direction);
        }
        let editorToCopy;
        if (context && typeof context.editorIndex === 'number') {
            editorToCopy = currentGroup.getEditorByIndex(context.editorIndex);
        }
        else {
            editorToCopy = currentGroup.activeEditor ?? undefined;
        }
        if (editorToCopy && !editorToCopy.hasCapability(EditorInputCapabilities.Singleton)) {
            currentGroup.copyEditor(editorToCopy, newGroup, { preserveFocus: context?.preserveFocus });
        }
    }
    newGroup?.focus();
}
function registerSplitEditorCommands() {
    [
        { id: SPLIT_EDITOR_UP, direction: GroupDirection.UP },
        { id: SPLIT_EDITOR_DOWN, direction: GroupDirection.DOWN },
        { id: SPLIT_EDITOR_LEFT, direction: GroupDirection.LEFT },
        { id: SPLIT_EDITOR_RIGHT, direction: GroupDirection.RIGHT }
    ].forEach(({ id, direction }) => {
        CommandsRegistry.registerCommand(id, function (accessor, resourceOrContext, context) {
            const { editors } = getEditorsContext(accessor, resourceOrContext, context);
            splitEditor(accessor.get(IEditorGroupsService), direction, editors);
        });
    });
}
function registerCloseEditorCommands() {
    function closeEditorHandler(accessor, forceCloseStickyEditors, resourceOrContext, context) {
        const editorGroupsService = accessor.get(IEditorGroupsService);
        const editorService = accessor.get(IEditorService);
        let keepStickyEditors = undefined;
        if (forceCloseStickyEditors) {
            keepStickyEditors = false;
        }
        else if (resourceOrContext || context) {
            keepStickyEditors = false;
        }
        else {
            keepStickyEditors = editorGroupsService.partOptions.preventPinnedEditorClose === 'keyboard' || editorGroupsService.partOptions.preventPinnedEditorClose === 'keyboardAndMouse';
        }
        if (keepStickyEditors) {
            const activeGroup = editorGroupsService.activeGroup;
            const activeEditor = activeGroup.activeEditor;
            if (activeEditor && activeGroup.isSticky(activeEditor)) {
                const nextNonStickyEditorInGroup = activeGroup.getEditors(EditorsOrder.MOST_RECENTLY_ACTIVE, { excludeSticky: true })[0];
                if (nextNonStickyEditorInGroup) {
                    return activeGroup.openEditor(nextNonStickyEditorInGroup);
                }
                const nextNonStickyEditorInAllGroups = editorService.getEditors(EditorsOrder.MOST_RECENTLY_ACTIVE, { excludeSticky: true })[0];
                if (nextNonStickyEditorInAllGroups) {
                    return Promise.resolve(editorGroupsService.getGroup(nextNonStickyEditorInAllGroups.groupId)?.openEditor(nextNonStickyEditorInAllGroups.editor));
                }
            }
        }
        const { editors, groups } = getEditorsContext(accessor, resourceOrContext, context);
        return Promise.all(( (groups.map(async (group) => {
            if (group) {
                const editorsToClose = coalesce(( (editors
                    .filter(editor => editor.groupId === group.id)
                    .map(
                    editor => typeof editor.editorIndex === 'number' ? group.getEditorByIndex(editor.editorIndex) : group.activeEditor
                ))))
                    .filter(editor => !keepStickyEditors || !group.isSticky(editor));
                await group.closeEditors(editorsToClose, { preserveFocus: context?.preserveFocus });
            }
        }))));
    }
    KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: CLOSE_EDITOR_COMMAND_ID,
        weight: KeybindingWeight.WorkbenchContrib,
        when: undefined,
        primary: KeyMod$1.CtrlCmd | KeyCode.KeyW,
        win: { primary: KeyMod$1.CtrlCmd | KeyCode.F4, secondary: [KeyMod$1.CtrlCmd | KeyCode.KeyW] },
        handler: (accessor, resourceOrContext, context) => {
            return closeEditorHandler(accessor, false, resourceOrContext, context);
        }
    });
    CommandsRegistry.registerCommand(CLOSE_PINNED_EDITOR_COMMAND_ID, (accessor, resourceOrContext, context) => {
        return closeEditorHandler(accessor, true , resourceOrContext, context);
    });
    KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: CLOSE_EDITORS_IN_GROUP_COMMAND_ID,
        weight: KeybindingWeight.WorkbenchContrib,
        when: undefined,
        primary: KeyChord(KeyMod$1.CtrlCmd | KeyCode.KeyK, KeyCode.KeyW),
        handler: (accessor, resourceOrContext, context) => {
            return Promise.all(( (getEditorsContext(accessor, resourceOrContext, context).groups.map(async (group) => {
                if (group) {
                    await group.closeAllEditors({ excludeSticky: true });
                    return;
                }
            }))));
        }
    });
    KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: CLOSE_EDITOR_GROUP_COMMAND_ID,
        weight: KeybindingWeight.WorkbenchContrib,
        when: ( (ContextKeyExpr.and(ActiveEditorGroupEmptyContext, MultipleEditorGroupsContext))),
        primary: KeyMod$1.CtrlCmd | KeyCode.KeyW,
        win: { primary: KeyMod$1.CtrlCmd | KeyCode.F4, secondary: [KeyMod$1.CtrlCmd | KeyCode.KeyW] },
        handler: (accessor, resourceOrContext, context) => {
            const editorGroupService = accessor.get(IEditorGroupsService);
            const commandsContext = getCommandsContext(accessor, resourceOrContext, context);
            let group;
            if (commandsContext && typeof commandsContext.groupId === 'number') {
                group = editorGroupService.getGroup(commandsContext.groupId);
            }
            else {
                group = editorGroupService.activeGroup;
            }
            if (group) {
                editorGroupService.removeGroup(group);
            }
        }
    });
    KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: CLOSE_SAVED_EDITORS_COMMAND_ID,
        weight: KeybindingWeight.WorkbenchContrib,
        when: undefined,
        primary: KeyChord(KeyMod$1.CtrlCmd | KeyCode.KeyK, KeyCode.KeyU),
        handler: (accessor, resourceOrContext, context) => {
            return Promise.all(( (getEditorsContext(accessor, resourceOrContext, context).groups.map(async (group) => {
                if (group) {
                    await group.closeEditors({ savedOnly: true, excludeSticky: true }, { preserveFocus: context?.preserveFocus });
                }
            }))));
        }
    });
    KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: CLOSE_OTHER_EDITORS_IN_GROUP_COMMAND_ID,
        weight: KeybindingWeight.WorkbenchContrib,
        when: undefined,
        primary: undefined,
        mac: { primary: KeyMod$1.CtrlCmd | KeyMod$1.Alt | KeyCode.KeyT },
        handler: (accessor, resourceOrContext, context) => {
            const { editors, groups } = getEditorsContext(accessor, resourceOrContext, context);
            return Promise.all(( (groups.map(async (group) => {
                if (group) {
                    const editorsToKeep = ( (editors
                        .filter(editor => editor.groupId === group.id)
                        .map(
                        editor => typeof editor.editorIndex === 'number' ? group.getEditorByIndex(editor.editorIndex) : group.activeEditor
                    )));
                    const editorsToClose = group.getEditors(EditorsOrder.SEQUENTIAL, { excludeSticky: true }).filter(editor => !editorsToKeep.includes(editor));
                    for (const editorToKeep of editorsToKeep) {
                        if (editorToKeep) {
                            group.pinEditor(editorToKeep);
                        }
                    }
                    await group.closeEditors(editorsToClose, { preserveFocus: context?.preserveFocus });
                }
            }))));
        }
    });
    KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: CLOSE_EDITORS_TO_THE_RIGHT_COMMAND_ID,
        weight: KeybindingWeight.WorkbenchContrib,
        when: undefined,
        primary: undefined,
        handler: async (accessor, resourceOrContext, context) => {
            const editorGroupService = accessor.get(IEditorGroupsService);
            const { group, editor } = resolveCommandsContext(editorGroupService, getCommandsContext(accessor, resourceOrContext, context));
            if (group && editor) {
                if (group.activeEditor) {
                    group.pinEditor(group.activeEditor);
                }
                await group.closeEditors({ direction: CloseDirection.RIGHT, except: editor, excludeSticky: true }, { preserveFocus: context?.preserveFocus });
            }
        }
    });
    KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: REOPEN_WITH_COMMAND_ID,
        weight: KeybindingWeight.WorkbenchContrib,
        when: undefined,
        primary: undefined,
        handler: async (accessor, resourceOrContext, context) => {
            const editorService = accessor.get(IEditorService);
            const editorResolverService = accessor.get(IEditorResolverService);
            const telemetryService = accessor.get(ITelemetryService);
            const editorsAndGroup = resolveEditorsContext(getEditorsContext(accessor, resourceOrContext, context));
            const editorReplacements = ( (new Map()));
            for (const { editor, group } of editorsAndGroup) {
                const untypedEditor = editor.toUntyped();
                if (!untypedEditor) {
                    return;
                }
                untypedEditor.options = { ...editorService.activeEditorPane?.options, override: EditorResolution.PICK };
                const resolvedEditor = await editorResolverService.resolveEditor(untypedEditor, group);
                if (!isEditorInputWithOptionsAndGroup(resolvedEditor)) {
                    return;
                }
                let editorReplacementsInGroup = editorReplacements.get(group);
                if (!editorReplacementsInGroup) {
                    editorReplacementsInGroup = [];
                    editorReplacements.set(group, editorReplacementsInGroup);
                }
                editorReplacementsInGroup.push({
                    editor: editor,
                    replacement: resolvedEditor.editor,
                    forceReplaceDirty: editor.resource?.scheme === Schemas.untitled,
                    options: resolvedEditor.options
                });
                telemetryService.publicLog2('workbenchEditorReopen', {
                    scheme: editor.resource?.scheme ?? '',
                    ext: editor.resource ? extname(editor.resource) : '',
                    from: editor.editorId ?? '',
                    to: resolvedEditor.editor.editorId ?? ''
                });
            }
            for (const [group, replacements] of editorReplacements) {
                await group.replaceEditors(replacements);
                await group.openEditor(replacements[0].replacement);
            }
        }
    });
    CommandsRegistry.registerCommand(CLOSE_EDITORS_AND_GROUP_COMMAND_ID, async (accessor, resourceOrContext, context) => {
        const editorGroupService = accessor.get(IEditorGroupsService);
        const { group } = resolveCommandsContext(editorGroupService, getCommandsContext(accessor, resourceOrContext, context));
        if (group) {
            await group.closeAllEditors();
            if (group.count === 0 && editorGroupService.getGroup(group.id) ) {
                editorGroupService.removeGroup(group);
            }
        }
    });
}
function registerFocusEditorGroupWihoutWrapCommands() {
    const commands = [
        {
            id: FOCUS_LEFT_GROUP_WITHOUT_WRAP_COMMAND_ID,
            direction: GroupDirection.LEFT
        },
        {
            id: FOCUS_RIGHT_GROUP_WITHOUT_WRAP_COMMAND_ID,
            direction: GroupDirection.RIGHT
        },
        {
            id: FOCUS_ABOVE_GROUP_WITHOUT_WRAP_COMMAND_ID,
            direction: GroupDirection.UP,
        },
        {
            id: FOCUS_BELOW_GROUP_WITHOUT_WRAP_COMMAND_ID,
            direction: GroupDirection.DOWN
        }
    ];
    for (const command of commands) {
        CommandsRegistry.registerCommand(command.id, async (accessor) => {
            const editorGroupService = accessor.get(IEditorGroupsService);
            const group = editorGroupService.findGroup({ direction: command.direction }, editorGroupService.activeGroup, false);
            group?.focus();
        });
    }
}
function registerSplitEditorInGroupCommands() {
    async function splitEditorInGroup(accessor, resourceOrContext, context) {
        const editorGroupService = accessor.get(IEditorGroupsService);
        const instantiationService = accessor.get(IInstantiationService);
        const { group, editor } = resolveCommandsContext(editorGroupService, getCommandsContext(accessor, resourceOrContext, context));
        if (!editor) {
            return;
        }
        await group.replaceEditors([{
                editor,
                replacement: instantiationService.createInstance(SideBySideEditorInput, undefined, undefined, editor, editor),
                forceReplaceDirty: true
            }]);
    }
    registerAction2(class extends Action2 {
        constructor() {
            super({
                id: SPLIT_EDITOR_IN_GROUP,
                title: ( localize2WithPath(_moduleId, 6, 'Split Editor in Group')),
                category: Categories.View,
                precondition: ActiveEditorCanSplitInGroupContext,
                f1: true,
                keybinding: {
                    weight: KeybindingWeight.WorkbenchContrib,
                    when: ActiveEditorCanSplitInGroupContext,
                    primary: KeyChord(KeyMod$1.CtrlCmd | KeyCode.KeyK, KeyMod$1.CtrlCmd | KeyMod$1.Shift | KeyCode.Backslash)
                }
            });
        }
        run(accessor, resourceOrContext, context) {
            return splitEditorInGroup(accessor, resourceOrContext, context);
        }
    });
    async function joinEditorInGroup(accessor, resourceOrContext, context) {
        const editorGroupService = accessor.get(IEditorGroupsService);
        const { group, editor } = resolveCommandsContext(editorGroupService, getCommandsContext(accessor, resourceOrContext, context));
        if (!(editor instanceof SideBySideEditorInput)) {
            return;
        }
        let options = undefined;
        const activeEditorPane = group.activeEditorPane;
        if (activeEditorPane instanceof SideBySideEditor && group.activeEditor === editor) {
            for (const pane of [activeEditorPane.getPrimaryEditorPane(), activeEditorPane.getSecondaryEditorPane()]) {
                if (pane?.hasFocus()) {
                    options = { viewState: pane.getViewState() };
                    break;
                }
            }
        }
        await group.replaceEditors([{
                editor,
                replacement: editor.primary,
                options
            }]);
    }
    registerAction2(class extends Action2 {
        constructor() {
            super({
                id: JOIN_EDITOR_IN_GROUP,
                title: ( localize2WithPath(_moduleId, 7, 'Join Editor in Group')),
                category: Categories.View,
                precondition: SideBySideEditorActiveContext,
                f1: true,
                keybinding: {
                    weight: KeybindingWeight.WorkbenchContrib,
                    when: SideBySideEditorActiveContext,
                    primary: KeyChord(KeyMod$1.CtrlCmd | KeyCode.KeyK, KeyMod$1.CtrlCmd | KeyMod$1.Shift | KeyCode.Backslash)
                }
            });
        }
        run(accessor, resourceOrContext, context) {
            return joinEditorInGroup(accessor, resourceOrContext, context);
        }
    });
    registerAction2(class extends Action2 {
        constructor() {
            super({
                id: TOGGLE_SPLIT_EDITOR_IN_GROUP,
                title: ( localize2WithPath(_moduleId, 8, 'Toggle Split Editor in Group')),
                category: Categories.View,
                precondition: ( (ContextKeyExpr.or(ActiveEditorCanSplitInGroupContext, SideBySideEditorActiveContext))),
                f1: true
            });
        }
        async run(accessor, resourceOrContext, context) {
            const editorGroupService = accessor.get(IEditorGroupsService);
            const { editor } = resolveCommandsContext(editorGroupService, getCommandsContext(accessor, resourceOrContext, context));
            if (editor instanceof SideBySideEditorInput) {
                await joinEditorInGroup(accessor, resourceOrContext, context);
            }
            else if (editor) {
                await splitEditorInGroup(accessor, resourceOrContext, context);
            }
        }
    });
    registerAction2(class extends Action2 {
        constructor() {
            super({
                id: TOGGLE_SPLIT_EDITOR_IN_GROUP_LAYOUT,
                title: ( localize2WithPath(_moduleId, 9, 'Toggle Layout of Split Editor in Group')),
                category: Categories.View,
                precondition: SideBySideEditorActiveContext,
                f1: true
            });
        }
        async run(accessor) {
            const configurationService = accessor.get(IConfigurationService);
            const currentSetting = configurationService.getValue(SideBySideEditor.SIDE_BY_SIDE_LAYOUT_SETTING);
            let newSetting;
            if (currentSetting !== 'horizontal') {
                newSetting = 'horizontal';
            }
            else {
                newSetting = 'vertical';
            }
            return configurationService.updateValue(SideBySideEditor.SIDE_BY_SIDE_LAYOUT_SETTING, newSetting);
        }
    });
}
function registerFocusSideEditorsCommands() {
    registerAction2(class extends Action2 {
        constructor() {
            super({
                id: FOCUS_FIRST_SIDE_EDITOR,
                title: ( localize2WithPath(_moduleId, 10, 'Focus First Side in Active Editor')),
                category: Categories.View,
                precondition: ( (ContextKeyExpr.or(SideBySideEditorActiveContext, TextCompareEditorActiveContext))),
                f1: true
            });
        }
        async run(accessor) {
            const editorService = accessor.get(IEditorService);
            const commandService = accessor.get(ICommandService);
            const activeEditorPane = editorService.activeEditorPane;
            if (activeEditorPane instanceof SideBySideEditor) {
                activeEditorPane.getSecondaryEditorPane()?.focus();
            }
            else if (activeEditorPane instanceof TextDiffEditor) {
                await commandService.executeCommand(DIFF_FOCUS_SECONDARY_SIDE);
            }
        }
    });
    registerAction2(class extends Action2 {
        constructor() {
            super({
                id: FOCUS_SECOND_SIDE_EDITOR,
                title: ( localize2WithPath(_moduleId, 11, 'Focus Second Side in Active Editor')),
                category: Categories.View,
                precondition: ( (ContextKeyExpr.or(SideBySideEditorActiveContext, TextCompareEditorActiveContext))),
                f1: true
            });
        }
        async run(accessor) {
            const editorService = accessor.get(IEditorService);
            const commandService = accessor.get(ICommandService);
            const activeEditorPane = editorService.activeEditorPane;
            if (activeEditorPane instanceof SideBySideEditor) {
                activeEditorPane.getPrimaryEditorPane()?.focus();
            }
            else if (activeEditorPane instanceof TextDiffEditor) {
                await commandService.executeCommand(DIFF_FOCUS_PRIMARY_SIDE);
            }
        }
    });
    registerAction2(class extends Action2 {
        constructor() {
            super({
                id: FOCUS_OTHER_SIDE_EDITOR,
                title: ( localize2WithPath(_moduleId, 12, 'Focus Other Side in Active Editor')),
                category: Categories.View,
                precondition: ( (ContextKeyExpr.or(SideBySideEditorActiveContext, TextCompareEditorActiveContext))),
                f1: true
            });
        }
        async run(accessor) {
            const editorService = accessor.get(IEditorService);
            const commandService = accessor.get(ICommandService);
            const activeEditorPane = editorService.activeEditorPane;
            if (activeEditorPane instanceof SideBySideEditor) {
                if (activeEditorPane.getPrimaryEditorPane()?.hasFocus()) {
                    activeEditorPane.getSecondaryEditorPane()?.focus();
                }
                else {
                    activeEditorPane.getPrimaryEditorPane()?.focus();
                }
            }
            else if (activeEditorPane instanceof TextDiffEditor) {
                await commandService.executeCommand(DIFF_FOCUS_OTHER_SIDE);
            }
        }
    });
}
function registerOtherEditorCommands() {
    KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: KEEP_EDITOR_COMMAND_ID,
        weight: KeybindingWeight.WorkbenchContrib,
        when: undefined,
        primary: KeyChord(KeyMod$1.CtrlCmd | KeyCode.KeyK, KeyCode.Enter),
        handler: async (accessor, resourceOrContext, context) => {
            const editorGroupService = accessor.get(IEditorGroupsService);
            const { group, editor } = resolveCommandsContext(editorGroupService, getCommandsContext(accessor, resourceOrContext, context));
            if (group && editor) {
                return group.pinEditor(editor);
            }
        }
    });
    CommandsRegistry.registerCommand({
        id: TOGGLE_KEEP_EDITORS_COMMAND_ID,
        handler: accessor => {
            const configurationService = accessor.get(IConfigurationService);
            const currentSetting = configurationService.getValue('workbench.editor.enablePreview');
            const newSetting = currentSetting === true ? false : true;
            configurationService.updateValue('workbench.editor.enablePreview', newSetting);
        }
    });
    function setEditorGroupLock(accessor, resourceOrContext, context, locked) {
        const editorGroupService = accessor.get(IEditorGroupsService);
        const { group } = resolveCommandsContext(editorGroupService, getCommandsContext(accessor, resourceOrContext, context));
        group?.lock(locked ?? !group.isLocked);
    }
    registerAction2(class extends Action2 {
        constructor() {
            super({
                id: TOGGLE_LOCK_GROUP_COMMAND_ID,
                title: ( localize2WithPath(_moduleId, 13, 'Toggle Editor Group Lock')),
                category: Categories.View,
                f1: true
            });
        }
        async run(accessor, resourceOrContext, context) {
            setEditorGroupLock(accessor, resourceOrContext, context);
        }
    });
    registerAction2(class extends Action2 {
        constructor() {
            super({
                id: LOCK_GROUP_COMMAND_ID,
                title: ( localize2WithPath(_moduleId, 14, 'Lock Editor Group')),
                category: Categories.View,
                precondition: ( (ActiveEditorGroupLockedContext.toNegated())),
                f1: true
            });
        }
        async run(accessor, resourceOrContext, context) {
            setEditorGroupLock(accessor, resourceOrContext, context, true);
        }
    });
    registerAction2(class extends Action2 {
        constructor() {
            super({
                id: UNLOCK_GROUP_COMMAND_ID,
                title: ( localize2WithPath(_moduleId, 15, 'Unlock Editor Group')),
                precondition: ActiveEditorGroupLockedContext,
                category: Categories.View,
                f1: true
            });
        }
        async run(accessor, resourceOrContext, context) {
            setEditorGroupLock(accessor, resourceOrContext, context, false);
        }
    });
    KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: PIN_EDITOR_COMMAND_ID,
        weight: KeybindingWeight.WorkbenchContrib,
        when: ( (ActiveEditorStickyContext.toNegated())),
        primary: KeyChord(KeyMod$1.CtrlCmd | KeyCode.KeyK, KeyMod$1.Shift | KeyCode.Enter),
        handler: async (accessor, resourceOrContext, context) => {
            for (const { editor, group } of resolveEditorsContext(getEditorsContext(accessor, resourceOrContext, context))) {
                group.stickEditor(editor);
            }
        }
    });
    KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: DIFF_OPEN_SIDE,
        weight: KeybindingWeight.WorkbenchContrib,
        when: EditorContextKeys.inDiffEditor,
        primary: KeyChord(KeyMod$1.CtrlCmd | KeyCode.KeyK, KeyMod$1.Shift | KeyCode.KeyO),
        handler: async (accessor) => {
            const editorService = accessor.get(IEditorService);
            const editorGroupService = accessor.get(IEditorGroupsService);
            const activeEditor = editorService.activeEditor;
            const activeTextEditorControl = editorService.activeTextEditorControl;
            if (!isDiffEditor(activeTextEditorControl) || !(activeEditor instanceof DiffEditorInput)) {
                return;
            }
            let editor;
            const originalEditor = activeTextEditorControl.getOriginalEditor();
            if (originalEditor.hasTextFocus()) {
                editor = activeEditor.original;
            }
            else {
                editor = activeEditor.modified;
            }
            return editorGroupService.activeGroup.openEditor(editor);
        }
    });
    KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: UNPIN_EDITOR_COMMAND_ID,
        weight: KeybindingWeight.WorkbenchContrib,
        when: ActiveEditorStickyContext,
        primary: KeyChord(KeyMod$1.CtrlCmd | KeyCode.KeyK, KeyMod$1.Shift | KeyCode.Enter),
        handler: async (accessor, resourceOrContext, context) => {
            for (const { editor, group } of resolveEditorsContext(getEditorsContext(accessor, resourceOrContext, context))) {
                group.unstickEditor(editor);
            }
        }
    });
    KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: SHOW_EDITORS_IN_GROUP,
        weight: KeybindingWeight.WorkbenchContrib,
        when: undefined,
        primary: undefined,
        handler: (accessor, resourceOrContext, context) => {
            const editorGroupService = accessor.get(IEditorGroupsService);
            const quickInputService = accessor.get(IQuickInputService);
            const commandsContext = getCommandsContext(accessor, resourceOrContext, context);
            if (commandsContext && typeof commandsContext.groupId === 'number') {
                const group = editorGroupService.getGroup(commandsContext.groupId);
                if (group) {
                    editorGroupService.activateGroup(group);
                }
            }
            return quickInputService.quickAccess.show(ActiveGroupEditorsByMostRecentlyUsedQuickAccess.PREFIX);
        }
    });
}
function getEditorsContext(accessor, resourceOrContext, context) {
    const editorGroupService = accessor.get(IEditorGroupsService);
    const listService = accessor.get(IListService);
    const editorContext = getMultiSelectedEditorContexts(getCommandsContext(accessor, resourceOrContext, context), listService, editorGroupService);
    const activeGroup = editorGroupService.activeGroup;
    if (editorContext.length === 0 && activeGroup.activeEditor) {
        editorContext.push({
            groupId: activeGroup.id,
            editorIndex: activeGroup.getIndexOfEditor(activeGroup.activeEditor)
        });
    }
    return {
        editors: editorContext,
        groups: ( (distinct(( (editorContext.map(context => context.groupId)))).map(groupId => editorGroupService.getGroup(groupId))))
    };
}
function resolveEditorsContext(context) {
    const { editors, groups } = context;
    const editorsAndGroup = ( (editors.map(e => {
        if (e.editorIndex === undefined) {
            return undefined;
        }
        const group = groups.find(group => group && group.id === e.groupId);
        const editor = group?.getEditorByIndex(e.editorIndex);
        if (!editor || !group) {
            return undefined;
        }
        return { editor, group };
    })));
    return coalesce(editorsAndGroup);
}
function getCommandsContext(accessor, resourceOrContext, context) {
    const isUri = URI.isUri(resourceOrContext);
    const editorCommandsContext = isUri ? context : resourceOrContext ? resourceOrContext : context;
    if (editorCommandsContext && isEditorCommandsContext(editorCommandsContext)) {
        return editorCommandsContext;
    }
    if (isUri) {
        const editorGroupService = accessor.get(IEditorGroupsService);
        const editorGroup = editorGroupService.getGroups(GroupsOrder.MOST_RECENTLY_ACTIVE).find(group => isEqual(group.activeEditor?.resource, resourceOrContext));
        if (editorGroup) {
            return { groupId: editorGroup.index, editorIndex: editorGroup.getIndexOfEditor(editorGroup.activeEditor) };
        }
    }
    return undefined;
}
function resolveCommandsContext(editorGroupService, context) {
    let group = context && typeof context.groupId === 'number' ? editorGroupService.getGroup(context.groupId) : undefined;
    let editor = group && context && typeof context.editorIndex === 'number' ? group.getEditorByIndex(context.editorIndex) ?? undefined : undefined;
    if (!group) {
        group = editorGroupService.activeGroup;
    }
    if (!editor) {
        editor = group.activeEditor ?? undefined;
    }
    return { group, editor };
}
function getMultiSelectedEditorContexts(editorContext, listService, editorGroupService) {
    const list = listService.lastFocusedList;
    if (list instanceof List && list.getHTMLElement() === getActiveElement()) {
        const elementToContext = (element) => {
            if (isEditorGroup(element)) {
                return { groupId: element.id, editorIndex: undefined };
            }
            const group = editorGroupService.getGroup(element.groupId);
            return { groupId: element.groupId, editorIndex: group ? group.getIndexOfEditor(element.editor) : -1 };
        };
        const onlyEditorGroupAndEditor = (e) => isEditorGroup(e) || isEditorIdentifier(e);
        const focusedElements = list.getFocusedElements().filter(onlyEditorGroupAndEditor);
        const focus = editorContext ? editorContext : focusedElements.length ? ( (focusedElements.map(elementToContext)))[0] : undefined;
        if (focus) {
            const selection = list.getSelectedElements().filter(onlyEditorGroupAndEditor);
            if (selection.length > 1) {
                return (
                     (selection.map(elementToContext))
                );
            }
            return [focus];
        }
    }
    else {
        const group = editorContext ? editorGroupService.getGroup(editorContext.groupId) : editorGroupService.activeGroup;
        const editor = editorContext && editorContext.editorIndex !== undefined ? group?.getEditorByIndex(editorContext.editorIndex) : group?.activeEditor;
        if (group && editor) {
            if (group.isSelected(editor)) {
                return (
                     (group.selectedEditors.map(se => ({ groupId: group.id, editorIndex: group.getIndexOfEditor(se) })))
                );
            }
        }
    }
    return !!editorContext ? [editorContext] : [];
}
function setup() {
    registerActiveEditorMoveCopyCommand();
    registerEditorGroupsLayoutCommands();
    registerDiffEditorCommands();
    registerOpenEditorAPICommands();
    registerOpenEditorAtIndexCommands();
    registerCloseEditorCommands();
    registerOtherEditorCommands();
    registerSplitEditorInGroupCommands();
    registerFocusSideEditorsCommands();
    registerFocusEditorGroupAtIndexCommands();
    registerSplitEditorCommands();
    registerFocusEditorGroupWihoutWrapCommands();
}
export { API_OPEN_DIFF_EDITOR_COMMAND_ID, API_OPEN_EDITOR_COMMAND_ID, API_OPEN_WITH_EDITOR_COMMAND_ID, CLOSE_EDITORS_AND_GROUP_COMMAND_ID, CLOSE_EDITORS_IN_GROUP_COMMAND_ID, CLOSE_EDITORS_TO_THE_RIGHT_COMMAND_ID, CLOSE_EDITOR_COMMAND_ID, CLOSE_EDITOR_GROUP_COMMAND_ID, CLOSE_OTHER_EDITORS_IN_GROUP_COMMAND_ID, CLOSE_PINNED_EDITOR_COMMAND_ID, CLOSE_SAVED_EDITORS_COMMAND_ID, COPY_ACTIVE_EDITOR_COMMAND_ID, COPY_EDITOR_GROUP_INTO_NEW_WINDOW_COMMAND_ID, COPY_EDITOR_INTO_NEW_WINDOW_COMMAND_ID, EDITOR_CORE_NAVIGATION_COMMANDS, FOCUS_ABOVE_GROUP_WITHOUT_WRAP_COMMAND_ID, FOCUS_BELOW_GROUP_WITHOUT_WRAP_COMMAND_ID, FOCUS_FIRST_SIDE_EDITOR, FOCUS_LEFT_GROUP_WITHOUT_WRAP_COMMAND_ID, FOCUS_OTHER_SIDE_EDITOR, FOCUS_RIGHT_GROUP_WITHOUT_WRAP_COMMAND_ID, FOCUS_SECOND_SIDE_EDITOR, JOIN_EDITOR_IN_GROUP, KEEP_EDITOR_COMMAND_ID, LAYOUT_EDITOR_GROUPS_COMMAND_ID, LOCK_GROUP_COMMAND_ID, MOVE_ACTIVE_EDITOR_COMMAND_ID, MOVE_EDITOR_GROUP_INTO_NEW_WINDOW_COMMAND_ID, MOVE_EDITOR_INTO_NEW_WINDOW_COMMAND_ID, NEW_EMPTY_EDITOR_WINDOW_COMMAND_ID, OPEN_EDITOR_AT_INDEX_COMMAND_ID, PIN_EDITOR_COMMAND_ID, REOPEN_WITH_COMMAND_ID, SHOW_EDITORS_IN_GROUP, SPLIT_EDITOR, SPLIT_EDITOR_DOWN, SPLIT_EDITOR_IN_GROUP, SPLIT_EDITOR_LEFT, SPLIT_EDITOR_RIGHT, SPLIT_EDITOR_UP, TOGGLE_KEEP_EDITORS_COMMAND_ID, TOGGLE_LOCK_GROUP_COMMAND_ID, TOGGLE_MAXIMIZE_EDITOR_GROUP, TOGGLE_SPLIT_EDITOR_IN_GROUP, TOGGLE_SPLIT_EDITOR_IN_GROUP_LAYOUT, UNLOCK_GROUP_COMMAND_ID, UNPIN_EDITOR_COMMAND_ID, getCommandsContext, getEditorsContext, getMultiSelectedEditorContexts, resolveCommandsContext, resolveEditorsContext, setup, splitEditor };
