hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 0, "code_window": [ "\t\tthis._tracer.traceResponse(response, callback.startTime);\n", "\t\tif (response.success) {\n", "\t\t\tcallback.onSuccess(response);\n", "\t\t} else if (response.message === 'No content available.') {\n", "\t\t\t// Special case where response itself is successful but there is not any data to return.\n", "\t\t\tcallback.onSuccess(new NoContentResponse());\n", "\t\t} else {\n", "\t\t\tcallback.onError(new TypeScriptServerError(this._version, response));\n", "\t\t}\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tcallback.onSuccess(NoContentResponse);\n" ], "file_path": "extensions/typescript-language-features/src/tsServer/server.ts", "type": "replace", "edit_start_line_idx": 303 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import * as types from 'vs/base/common/types'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { TextCompareEditorVisibleContext, EditorInput, IEditorIdentifier, IEditorCommandsContext, ActiveEditorGroupEmptyContext, MultipleEditorGroupsContext, CloseDirection, IEditor, IEditorInput } from 'vs/workbench/common/editor'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { TextDiffEditor } from 'vs/workbench/browser/parts/editor/textDiffEditor'; import { KeyMod, KeyCode, KeyChord } from 'vs/base/common/keyCodes'; import { URI } from 'vs/base/common/uri'; import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen'; import { IListService } from 'vs/platform/list/browser/listService'; import { List } from 'vs/base/browser/ui/list/listWidget'; import { distinct } from 'vs/base/common/arrays'; import { IEditorGroupsService, IEditorGroup, GroupDirection, GroupLocation, GroupsOrder, preferredSideBySideGroupDirection, EditorGroupLayout } from 'vs/workbench/services/group/common/editorGroupsService'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; import { CommandsRegistry, ICommandHandler } from 'vs/platform/commands/common/commands'; import { MenuRegistry, MenuId } from 'vs/platform/actions/common/actions'; export const CLOSE_SAVED_EDITORS_COMMAND_ID = 'workbench.action.closeUnmodifiedEditors'; export const CLOSE_EDITORS_IN_GROUP_COMMAND_ID = 'workbench.action.closeEditorsInGroup'; export const CLOSE_EDITORS_AND_GROUP_COMMAND_ID = 'workbench.action.closeEditorsAndGroup'; export const CLOSE_EDITORS_TO_THE_RIGHT_COMMAND_ID = 'workbench.action.closeEditorsToTheRight'; export const CLOSE_EDITOR_COMMAND_ID = 'workbench.action.closeActiveEditor'; export const CLOSE_EDITOR_GROUP_COMMAND_ID = 'workbench.action.closeGroup'; export const CLOSE_OTHER_EDITORS_IN_GROUP_COMMAND_ID = 'workbench.action.closeOtherEditors'; export const MOVE_ACTIVE_EDITOR_COMMAND_ID = 'moveActiveEditor'; export const LAYOUT_EDITOR_GROUPS_COMMAND_ID = 'layoutEditorGroups'; export const KEEP_EDITOR_COMMAND_ID = 'workbench.action.keepEditor'; export const SHOW_EDITORS_IN_GROUP = 'workbench.action.showEditorsInGroup'; export const TOGGLE_DIFF_SIDE_BY_SIDE = 'toggle.diff.renderSideBySide'; export const GOTO_NEXT_CHANGE = 'workbench.action.compareEditor.nextChange'; export const GOTO_PREVIOUS_CHANGE = 'workbench.action.compareEditor.previousChange'; export const TOGGLE_DIFF_IGNORE_TRIM_WHITESPACE = 'toggle.diff.ignoreTrimWhitespace'; export const SPLIT_EDITOR_UP = 'workbench.action.splitEditorUp'; export const SPLIT_EDITOR_DOWN = 'workbench.action.splitEditorDown'; export const SPLIT_EDITOR_LEFT = 'workbench.action.splitEditorLeft'; export const SPLIT_EDITOR_RIGHT = 'workbench.action.splitEditorRight'; export const NAVIGATE_ALL_EDITORS_GROUP_PREFIX = 'edt '; export const NAVIGATE_IN_ACTIVE_GROUP_PREFIX = 'edt active '; export const OPEN_EDITOR_AT_INDEX_COMMAND_ID = 'workbench.action.openEditorAtIndex'; export interface ActiveEditorMoveArguments { to?: 'first' | 'last' | 'left' | 'right' | 'up' | 'down' | 'center' | 'position' | 'previous' | 'next'; by?: 'tab' | 'group'; value?: number; } const isActiveEditorMoveArg = function (arg: ActiveEditorMoveArguments): boolean { if (!types.isObject(arg)) { return false; } if (!types.isString(arg.to)) { return false; } if (!types.isUndefined(arg.by) && !types.isString(arg.by)) { return false; } if (!types.isUndefined(arg.value) && !types.isNumber(arg.value)) { return false; } return true; }; function registerActiveEditorMoveCommand(): void { KeybindingsRegistry.registerCommandAndKeybindingRule({ id: MOVE_ACTIVE_EDITOR_COMMAND_ID, weight: KeybindingWeight.WorkbenchContrib, when: EditorContextKeys.editorTextFocus, primary: 0, handler: (accessor, args: any) => moveActiveEditor(args, accessor), description: { description: nls.localize('editorCommand.activeEditorMove.description', "Move the active editor by tabs or groups"), args: [ { name: nls.localize('editorCommand.activeEditorMove.arg.name', "Active editor move argument"), description: nls.localize('editorCommand.activeEditorMove.arg.description', "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: isActiveEditorMoveArg } ] } }); } function moveActiveEditor(args: ActiveEditorMoveArguments = Object.create(null), accessor: ServicesAccessor): void { args.to = args.to || 'right'; args.by = args.by || 'tab'; args.value = typeof args.value === 'number' ? args.value : 1; const activeControl = accessor.get(IEditorService).activeControl; if (activeControl) { switch (args.by) { case 'tab': return moveActiveTab(args, activeControl, accessor); case 'group': return moveActiveEditorToGroup(args, activeControl, accessor); } } } function moveActiveTab(args: ActiveEditorMoveArguments, control: IEditor, accessor: ServicesAccessor): void { 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; break; case 'right': index = index + args.value; break; case 'center': index = Math.round(group.count / 2) - 1; break; case 'position': index = args.value - 1; break; } index = index < 0 ? 0 : index >= group.count ? group.count - 1 : index; group.moveEditor(control.input, group, { index }); } function moveActiveEditorToGroup(args: ActiveEditorMoveArguments, control: IEditor, accessor: ServicesAccessor): void { const editorGroupService = accessor.get(IEditorGroupsService); const configurationService = accessor.get(IConfigurationService); const sourceGroup = control.group; let targetGroup: IEditorGroup; 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]; break; } if (targetGroup) { sourceGroup.moveEditor(control.input, targetGroup); targetGroup.focus(); } } function registerEditorGroupsLayoutCommand(): void { CommandsRegistry.registerCommand(LAYOUT_EDITOR_GROUPS_COMMAND_ID, (accessor: ServicesAccessor, args: EditorGroupLayout) => { if (!args || typeof args !== 'object') { return; } const editorGroupService = accessor.get(IEditorGroupsService); editorGroupService.applyLayout(args); }); } export function mergeAllGroups(editorGroupService: IEditorGroupsService): void { const target = editorGroupService.activeGroup; editorGroupService.getGroups(GroupsOrder.MOST_RECENTLY_ACTIVE).forEach(group => { if (group === target) { return; // keep target } editorGroupService.mergeGroup(group, target); }); } function registerDiffEditorCommands(): void { KeybindingsRegistry.registerCommandAndKeybindingRule({ id: GOTO_NEXT_CHANGE, weight: KeybindingWeight.WorkbenchContrib, when: TextCompareEditorVisibleContext, primary: KeyMod.Alt | KeyCode.F5, handler: accessor => navigateInDiffEditor(accessor, true) }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: GOTO_PREVIOUS_CHANGE, weight: KeybindingWeight.WorkbenchContrib, when: TextCompareEditorVisibleContext, primary: KeyMod.Alt | KeyMod.Shift | KeyCode.F5, handler: accessor => navigateInDiffEditor(accessor, false) }); function navigateInDiffEditor(accessor: ServicesAccessor, next: boolean): void { const editorService = accessor.get(IEditorService); const candidates = [editorService.activeControl, ...editorService.visibleControls].filter(e => e instanceof TextDiffEditor); if (candidates.length > 0) { next ? (<TextDiffEditor>candidates[0]).getDiffNavigator().next() : (<TextDiffEditor>candidates[0]).getDiffNavigator().previous(); } } function toggleDiffSideBySide(accessor: ServicesAccessor): void { const configurationService = accessor.get(IConfigurationService); const newValue = !configurationService.getValue<boolean>('diffEditor.renderSideBySide'); configurationService.updateValue('diffEditor.renderSideBySide', newValue, ConfigurationTarget.USER); } function toggleDiffIgnoreTrimWhitespace(accessor: ServicesAccessor): void { const configurationService = accessor.get(IConfigurationService); const newValue = !configurationService.getValue<boolean>('diffEditor.ignoreTrimWhitespace'); configurationService.updateValue('diffEditor.ignoreTrimWhitespace', newValue, ConfigurationTarget.USER); } KeybindingsRegistry.registerCommandAndKeybindingRule({ id: TOGGLE_DIFF_SIDE_BY_SIDE, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: undefined, handler: accessor => toggleDiffSideBySide(accessor) }); MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: TOGGLE_DIFF_SIDE_BY_SIDE, title: { value: nls.localize('toggleInlineView', "Toggle Inline View"), original: 'Compare: Toggle Inline View' }, category: nls.localize('compare', "Compare") }, when: ContextKeyExpr.has('textCompareEditorActive') }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: TOGGLE_DIFF_IGNORE_TRIM_WHITESPACE, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: undefined, handler: accessor => toggleDiffIgnoreTrimWhitespace(accessor) }); } function registerOpenEditorAtIndexCommands(): void { const openEditorAtIndex: ICommandHandler = (accessor: ServicesAccessor, editorIndex: number): void => { const editorService = accessor.get(IEditorService); const activeControl = editorService.activeControl; if (activeControl) { const editor = activeControl.group.getEditor(editorIndex); if (editor) { editorService.openEditor(editor); } } }; // This command takes in the editor index number to open as an argument CommandsRegistry.registerCommand({ id: OPEN_EDITOR_AT_INDEX_COMMAND_ID, handler: openEditorAtIndex }); // Keybindings to focus a specific index in the tab folder if tabs are enabled 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.Alt | toKeyCode(visibleIndex), mac: { primary: KeyMod.WinCtrl | toKeyCode(visibleIndex) }, handler: accessor => openEditorAtIndex(accessor, editorIndex) }); } function toKeyCode(index: number): KeyCode { switch (index) { case 0: return KeyCode.KEY_0; case 1: return KeyCode.KEY_1; case 2: return KeyCode.KEY_2; case 3: return KeyCode.KEY_3; case 4: return KeyCode.KEY_4; case 5: return KeyCode.KEY_5; case 6: return KeyCode.KEY_6; case 7: return KeyCode.KEY_7; case 8: return KeyCode.KEY_8; case 9: return KeyCode.KEY_9; } return undefined; } } function registerFocusEditorGroupAtIndexCommands(): void { // Keybindings to focus a specific group (2-8) in the editor area for (let groupIndex = 1; groupIndex < 8; groupIndex++) { KeybindingsRegistry.registerCommandAndKeybindingRule({ id: toCommandId(groupIndex), weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: KeyMod.CtrlCmd | toKeyCode(groupIndex), handler: accessor => { const editorGroupService = accessor.get(IEditorGroupsService); const configurationService = accessor.get(IConfigurationService); // To keep backwards compatibility (pre-grid), allow to focus a group // that does not exist as long as it is the next group after the last // opened group. Otherwise we return. if (groupIndex > editorGroupService.count) { return; } // Group exists: just focus const groups = editorGroupService.getGroups(GroupsOrder.GRID_APPEARANCE); if (groups[groupIndex]) { return groups[groupIndex].focus(); } // Group does not exist: create new by splitting the active one of the last group const direction = preferredSideBySideGroupDirection(configurationService); const lastGroup = editorGroupService.findGroup({ location: GroupLocation.LAST }); const newGroup = editorGroupService.addGroup(lastGroup, direction); // Focus newGroup.focus(); } }); } function toCommandId(index: number): string { 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'; } return undefined; } function toKeyCode(index: number): KeyCode { switch (index) { case 1: return KeyCode.KEY_2; case 2: return KeyCode.KEY_3; case 3: return KeyCode.KEY_4; case 4: return KeyCode.KEY_5; case 5: return KeyCode.KEY_6; case 6: return KeyCode.KEY_7; case 7: return KeyCode.KEY_8; } return undefined; } } export function splitEditor(editorGroupService: IEditorGroupsService, direction: GroupDirection, context?: IEditorCommandsContext): void { let sourceGroup: IEditorGroup; if (context && typeof context.groupId === 'number') { sourceGroup = editorGroupService.getGroup(context.groupId); } else { sourceGroup = editorGroupService.activeGroup; } // Add group const newGroup = editorGroupService.addGroup(sourceGroup, direction); // Split editor (if it can be split) let editorToCopy: IEditorInput; if (context && typeof context.editorIndex === 'number') { editorToCopy = sourceGroup.getEditor(context.editorIndex); } else { editorToCopy = sourceGroup.activeEditor; } if (editorToCopy && (editorToCopy as EditorInput).supportsSplitEditor()) { sourceGroup.copyEditor(editorToCopy, newGroup); } // Focus 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: URI | IEditorCommandsContext, context?: IEditorCommandsContext) { splitEditor(accessor.get(IEditorGroupsService), direction, getCommandsContext(resourceOrContext, context)); }); }); } function registerCloseEditorCommands() { KeybindingsRegistry.registerCommandAndKeybindingRule({ id: CLOSE_SAVED_EDITORS_COMMAND_ID, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyCode.KEY_U), handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => { const editorGroupService = accessor.get(IEditorGroupsService); const contexts = getMultiSelectedEditorContexts(getCommandsContext(resourceOrContext, context), accessor.get(IListService), editorGroupService); const activeGroup = editorGroupService.activeGroup; if (contexts.length === 0) { contexts.push({ groupId: activeGroup.id }); // active group as fallback } return Promise.all(distinct(contexts.map(c => c.groupId)).map(groupId => editorGroupService.getGroup(groupId).closeEditors({ savedOnly: true }) )); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: CLOSE_EDITORS_IN_GROUP_COMMAND_ID, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyCode.KEY_W), handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => { const editorGroupService = accessor.get(IEditorGroupsService); const contexts = getMultiSelectedEditorContexts(getCommandsContext(resourceOrContext, context), accessor.get(IListService), editorGroupService); const distinctGroupIds = distinct(contexts.map(c => c.groupId)); if (distinctGroupIds.length === 0) { distinctGroupIds.push(editorGroupService.activeGroup.id); } return Promise.all(distinctGroupIds.map(groupId => editorGroupService.getGroup(groupId).closeAllEditors() )); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: CLOSE_EDITOR_COMMAND_ID, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: KeyMod.CtrlCmd | KeyCode.KEY_W, win: { primary: KeyMod.CtrlCmd | KeyCode.F4, secondary: [KeyMod.CtrlCmd | KeyCode.KEY_W] }, handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => { const editorGroupService = accessor.get(IEditorGroupsService); const contexts = getMultiSelectedEditorContexts(getCommandsContext(resourceOrContext, context), accessor.get(IListService), editorGroupService); const activeGroup = editorGroupService.activeGroup; if (contexts.length === 0 && activeGroup.activeEditor) { contexts.push({ groupId: activeGroup.id, editorIndex: activeGroup.getIndexOfEditor(activeGroup.activeEditor) }); // active editor as fallback } const groupIds = distinct(contexts.map(context => context.groupId)); return Promise.all(groupIds.map(groupId => { const group = editorGroupService.getGroup(groupId); const editors = contexts .filter(context => context.groupId === groupId) .map(context => typeof context.editorIndex === 'number' ? group.getEditor(context.editorIndex) : group.activeEditor); return group.closeEditors(editors); })); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: CLOSE_EDITOR_GROUP_COMMAND_ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(ActiveEditorGroupEmptyContext, MultipleEditorGroupsContext), primary: KeyMod.CtrlCmd | KeyCode.KEY_W, win: { primary: KeyMod.CtrlCmd | KeyCode.F4, secondary: [KeyMod.CtrlCmd | KeyCode.KEY_W] }, handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => { const editorGroupService = accessor.get(IEditorGroupsService); const commandsContext = getCommandsContext(resourceOrContext, context); let group: IEditorGroup; if (commandsContext && typeof commandsContext.groupId === 'number') { group = editorGroupService.getGroup(commandsContext.groupId); } else { group = editorGroupService.activeGroup; } editorGroupService.removeGroup(group); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: CLOSE_OTHER_EDITORS_IN_GROUP_COMMAND_ID, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: undefined, mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_T }, handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => { const editorGroupService = accessor.get(IEditorGroupsService); const contexts = getMultiSelectedEditorContexts(getCommandsContext(resourceOrContext, context), accessor.get(IListService), editorGroupService); const activeGroup = editorGroupService.activeGroup; if (contexts.length === 0 && activeGroup.activeEditor) { contexts.push({ groupId: activeGroup.id, editorIndex: activeGroup.getIndexOfEditor(activeGroup.activeEditor) }); // active editor as fallback } const groupIds = distinct(contexts.map(context => context.groupId)); return Promise.all(groupIds.map(groupId => { const group = editorGroupService.getGroup(groupId); const editors = contexts .filter(context => context.groupId === groupId) .map(context => typeof context.editorIndex === 'number' ? group.getEditor(context.editorIndex) : group.activeEditor); const editorsToClose = group.editors.filter(e => editors.indexOf(e) === -1); return group.closeEditors(editorsToClose); })); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: CLOSE_EDITORS_TO_THE_RIGHT_COMMAND_ID, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: undefined, handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => { const editorGroupService = accessor.get(IEditorGroupsService); const { group, editor } = resolveCommandsContext(editorGroupService, getCommandsContext(resourceOrContext, context)); if (group && editor) { return group.closeEditors({ direction: CloseDirection.RIGHT, except: editor }); } return Promise.resolve(false); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: KEEP_EDITOR_COMMAND_ID, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyCode.Enter), handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => { const editorGroupService = accessor.get(IEditorGroupsService); const { group, editor } = resolveCommandsContext(editorGroupService, getCommandsContext(resourceOrContext, context)); if (group && editor) { return group.pinEditor(editor); } return Promise.resolve(false); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: SHOW_EDITORS_IN_GROUP, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: undefined, handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => { const editorGroupService = accessor.get(IEditorGroupsService); const quickOpenService = accessor.get(IQuickOpenService); if (editorGroupService.count <= 1) { return quickOpenService.show(NAVIGATE_ALL_EDITORS_GROUP_PREFIX); } const commandsContext = getCommandsContext(resourceOrContext, context); if (commandsContext && typeof commandsContext.groupId === 'number') { editorGroupService.activateGroup(editorGroupService.getGroup(commandsContext.groupId)); // we need the group to be active } return quickOpenService.show(NAVIGATE_IN_ACTIVE_GROUP_PREFIX); } }); CommandsRegistry.registerCommand(CLOSE_EDITORS_AND_GROUP_COMMAND_ID, (accessor: ServicesAccessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => { const editorGroupService = accessor.get(IEditorGroupsService); const { group } = resolveCommandsContext(editorGroupService, getCommandsContext(resourceOrContext, context)); if (group) { return group.closeAllEditors().then(() => { if (group.count === 0 && editorGroupService.getGroup(group.id) /* could be gone by now */) { editorGroupService.removeGroup(group); // only remove group if it is now empty } }); } return undefined; }); } function getCommandsContext(resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext): IEditorCommandsContext { if (URI.isUri(resourceOrContext)) { return context; } if (resourceOrContext && typeof resourceOrContext.groupId === 'number') { return resourceOrContext; } if (context && typeof context.groupId === 'number') { return context; } return undefined; } function resolveCommandsContext(editorGroupService: IEditorGroupsService, context?: IEditorCommandsContext): { group: IEditorGroup, editor: IEditorInput, control: IEditor } { // Resolve from context let group = context && typeof context.groupId === 'number' ? editorGroupService.getGroup(context.groupId) : undefined; let editor = group && typeof context.editorIndex === 'number' ? group.getEditor(context.editorIndex) : undefined; let control = group ? group.activeControl : undefined; // Fallback to active group as needed if (!group) { group = editorGroupService.activeGroup; editor = <EditorInput>group.activeEditor; control = group.activeControl; } return { group, editor, control }; } export function getMultiSelectedEditorContexts(editorContext: IEditorCommandsContext, listService: IListService, editorGroupService: IEditorGroupsService): IEditorCommandsContext[] { // First check for a focused list to return the selected items from const list = listService.lastFocusedList; if (list instanceof List && list.getHTMLElement() === document.activeElement) { const elementToContext = (element: IEditorIdentifier | IEditorGroup) => { if (isEditorGroup(element)) { return { groupId: element.id, editorIndex: undefined }; } return { groupId: element.groupId, editorIndex: editorGroupService.getGroup(element.groupId).getIndexOfEditor(element.editor) }; }; const onlyEditorGroupAndEditor = (e: IEditorIdentifier | IEditorGroup) => isEditorGroup(e) || isEditorIdentifier(e); const focusedElements: Array<IEditorIdentifier | IEditorGroup> = list.getFocusedElements().filter(onlyEditorGroupAndEditor); const focus = editorContext ? editorContext : focusedElements.length ? focusedElements.map(elementToContext)[0] : undefined; // need to take into account when editor context is { group: group } if (focus) { const selection: Array<IEditorIdentifier | IEditorGroup> = list.getSelectedElements().filter(onlyEditorGroupAndEditor); // Only respect selection if it contains focused element if (selection && selection.some(s => isEditorGroup(s) ? s.id === focus.groupId : s.groupId === focus.groupId && editorGroupService.getGroup(s.groupId).getIndexOfEditor(s.editor) === focus.editorIndex)) { return selection.map(elementToContext); } return [focus]; } } // Otherwise go with passed in context return !!editorContext ? [editorContext] : []; } function isEditorGroup(thing: any): thing is IEditorGroup { const group = thing as IEditorGroup; return group && typeof group.id === 'number' && Array.isArray(group.editors); } function isEditorIdentifier(thing: any): thing is IEditorIdentifier { const identifier = thing as IEditorIdentifier; return identifier && typeof identifier.groupId === 'number'; } export function setup(): void { registerActiveEditorMoveCommand(); registerEditorGroupsLayoutCommand(); registerDiffEditorCommands(); registerOpenEditorAtIndexCommands(); registerCloseEditorCommands(); registerFocusEditorGroupAtIndexCommands(); registerSplitEditorCommands(); }
src/vs/workbench/browser/parts/editor/editorCommands.ts
0
https://github.com/microsoft/vscode/commit/2f5d88899d9575d165aad0a3b6aa6514cdccd696
[ 0.0002490477345418185, 0.0001732117816573009, 0.0001656270178500563, 0.00017280603060498834, 0.000009292422873841133 ]
{ "id": 0, "code_window": [ "\t\tthis._tracer.traceResponse(response, callback.startTime);\n", "\t\tif (response.success) {\n", "\t\t\tcallback.onSuccess(response);\n", "\t\t} else if (response.message === 'No content available.') {\n", "\t\t\t// Special case where response itself is successful but there is not any data to return.\n", "\t\t\tcallback.onSuccess(new NoContentResponse());\n", "\t\t} else {\n", "\t\t\tcallback.onError(new TypeScriptServerError(this._version, response));\n", "\t\t}\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tcallback.onSuccess(NoContentResponse);\n" ], "file_path": "extensions/typescript-language-features/src/tsServer/server.ts", "type": "replace", "edit_start_line_idx": 303 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'path'; import * as vscode from 'vscode'; import * as Proto from '../protocol'; import { TypeScriptServiceConfiguration } from './configuration'; export function isImplicitProjectConfigFile(configFileName: string) { return configFileName.indexOf('/dev/null/') === 0; } export function inferredProjectConfig( config: TypeScriptServiceConfiguration ): Proto.ExternalProjectCompilerOptions { const base: Proto.ExternalProjectCompilerOptions = { module: 'commonjs' as Proto.ModuleKind, target: 'es2016' as Proto.ScriptTarget, jsx: 'preserve' as Proto.JsxEmit }; if (config.checkJs) { base.checkJs = true; } if (config.experimentalDecorators) { base.experimentalDecorators = true; } return base; } function inferredProjectConfigSnippet( config: TypeScriptServiceConfiguration ) { const baseConfig = inferredProjectConfig(config); const compilerOptions = Object.keys(baseConfig).map(key => `"${key}": ${JSON.stringify(baseConfig[key])}`); return new vscode.SnippetString(`{ "compilerOptions": { ${compilerOptions.join(',\n\t\t')}$0 }, "exclude": [ "node_modules", "**/node_modules/*" ] }`); } export async function openOrCreateConfigFile( isTypeScriptProject: boolean, rootPath: string, config: TypeScriptServiceConfiguration ): Promise<vscode.TextEditor | null> { const configFile = vscode.Uri.file(path.join(rootPath, isTypeScriptProject ? 'tsconfig.json' : 'jsconfig.json')); const col = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.viewColumn : undefined; try { const doc = await vscode.workspace.openTextDocument(configFile); return vscode.window.showTextDocument(doc, col); } catch { const doc = await vscode.workspace.openTextDocument(configFile.with({ scheme: 'untitled' })); const editor = await vscode.window.showTextDocument(doc, col); if (editor.document.getText().length === 0) { await editor.insertSnippet(inferredProjectConfigSnippet(config)); } return editor; } }
extensions/typescript-language-features/src/utils/tsconfig.ts
0
https://github.com/microsoft/vscode/commit/2f5d88899d9575d165aad0a3b6aa6514cdccd696
[ 0.00017691237735562027, 0.0001720764848869294, 0.0001660998968873173, 0.00017363666847813874, 0.000003920708877558354 ]
{ "id": 1, "code_window": [ "\t\tpublic readonly reason: string\n", "\t) { }\n", "}\n", "\n", "export class NoContentResponse {\n", "\tpublic readonly type: 'noContent' = 'noContent';\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "export const NoContentResponse = new class { readonly type = 'noContent'; };\n" ], "file_path": "extensions/typescript-language-features/src/typescriptService.ts", "type": "replace", "edit_start_line_idx": 21 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import BufferSyncSupport from './features/bufferSyncSupport'; import * as Proto from './protocol'; import API from './utils/api'; import { TypeScriptServiceConfiguration } from './utils/configuration'; import Logger from './utils/logger'; import { PluginManager } from './utils/plugins'; export class CancelledResponse { public readonly type: 'cancelled' = 'cancelled'; constructor( public readonly reason: string ) { } } export class NoContentResponse { public readonly type: 'noContent' = 'noContent'; } export type ServerResponse<T extends Proto.Response> = T | CancelledResponse | NoContentResponse; interface TypeScriptRequestTypes { 'applyCodeActionCommand': [Proto.ApplyCodeActionCommandRequestArgs, Proto.ApplyCodeActionCommandResponse]; 'completionEntryDetails': [Proto.CompletionDetailsRequestArgs, Proto.CompletionDetailsResponse]; 'completionInfo': [Proto.CompletionsRequestArgs, Proto.CompletionInfoResponse]; 'completions': [Proto.CompletionsRequestArgs, Proto.CompletionsResponse]; 'configure': [Proto.ConfigureRequestArguments, Proto.ConfigureResponse]; 'definition': [Proto.FileLocationRequestArgs, Proto.DefinitionResponse]; 'definitionAndBoundSpan': [Proto.FileLocationRequestArgs, Proto.DefinitionInfoAndBoundSpanReponse]; 'docCommentTemplate': [Proto.FileLocationRequestArgs, Proto.DocCommandTemplateResponse]; 'documentHighlights': [Proto.DocumentHighlightsRequestArgs, Proto.DocumentHighlightsResponse]; 'format': [Proto.FormatRequestArgs, Proto.FormatResponse]; 'formatonkey': [Proto.FormatOnKeyRequestArgs, Proto.FormatResponse]; 'getApplicableRefactors': [Proto.GetApplicableRefactorsRequestArgs, Proto.GetApplicableRefactorsResponse]; 'getCodeFixes': [Proto.CodeFixRequestArgs, Proto.GetCodeFixesResponse]; 'getCombinedCodeFix': [Proto.GetCombinedCodeFixRequestArgs, Proto.GetCombinedCodeFixResponse]; 'getEditsForFileRename': [Proto.GetEditsForFileRenameRequestArgs, Proto.GetEditsForFileRenameResponse]; 'getEditsForRefactor': [Proto.GetEditsForRefactorRequestArgs, Proto.GetEditsForRefactorResponse]; 'getOutliningSpans': [Proto.FileRequestArgs, Proto.OutliningSpansResponse]; 'getSupportedCodeFixes': [null, Proto.GetSupportedCodeFixesResponse]; 'implementation': [Proto.FileLocationRequestArgs, Proto.ImplementationResponse]; 'jsxClosingTag': [Proto.JsxClosingTagRequestArgs, Proto.JsxClosingTagResponse]; 'navto': [Proto.NavtoRequestArgs, Proto.NavtoResponse]; 'navtree': [Proto.FileRequestArgs, Proto.NavTreeResponse]; 'occurrences': [Proto.FileLocationRequestArgs, Proto.OccurrencesResponse]; 'organizeImports': [Proto.OrganizeImportsRequestArgs, Proto.OrganizeImportsResponse]; 'projectInfo': [Proto.ProjectInfoRequestArgs, Proto.ProjectInfoResponse]; 'quickinfo': [Proto.FileLocationRequestArgs, Proto.QuickInfoResponse]; 'references': [Proto.FileLocationRequestArgs, Proto.ReferencesResponse]; 'rename': [Proto.RenameRequestArgs, Proto.RenameResponse]; 'signatureHelp': [Proto.SignatureHelpRequestArgs, Proto.SignatureHelpResponse]; 'typeDefinition': [Proto.FileLocationRequestArgs, Proto.TypeDefinitionResponse]; } export interface ITypeScriptServiceClient { /** * Convert a resource (VS Code) to a normalized path (TypeScript). * * Does not try handling case insensitivity. */ normalizedPath(resource: vscode.Uri): string | undefined; /** * Map a resource to a normalized path * * This will attempt to handle case insensitivity. */ toPath(resource: vscode.Uri): string | undefined; /** * Convert a path to a resource. */ toResource(filepath: string): vscode.Uri; /** * Tries to ensure that a vscode document is open on the TS server. * * Returns the normalized path. */ toOpenedFilePath(document: vscode.TextDocument): string | undefined; getWorkspaceRootForResource(resource: vscode.Uri): string | undefined; readonly onTsServerStarted: vscode.Event<API>; readonly onProjectLanguageServiceStateChanged: vscode.Event<Proto.ProjectLanguageServiceStateEventBody>; readonly onDidBeginInstallTypings: vscode.Event<Proto.BeginInstallTypesEventBody>; readonly onDidEndInstallTypings: vscode.Event<Proto.EndInstallTypesEventBody>; readonly onTypesInstallerInitializationFailed: vscode.Event<Proto.TypesInstallerInitializationFailedEventBody>; readonly apiVersion: API; readonly pluginManager: PluginManager; readonly configuration: TypeScriptServiceConfiguration; readonly logger: Logger; readonly bufferSyncSupport: BufferSyncSupport; execute<K extends keyof TypeScriptRequestTypes>( command: K, args: TypeScriptRequestTypes[K][0], token: vscode.CancellationToken, lowPriority?: boolean ): Promise<ServerResponse<TypeScriptRequestTypes[K][1]>>; executeWithoutWaitingForResponse(command: 'open', args: Proto.OpenRequestArgs): void; executeWithoutWaitingForResponse(command: 'close', args: Proto.FileRequestArgs): void; executeWithoutWaitingForResponse(command: 'change', args: Proto.ChangeRequestArgs): void; executeWithoutWaitingForResponse(command: 'compilerOptionsForInferredProjects', args: Proto.SetCompilerOptionsForInferredProjectsArgs): void; executeWithoutWaitingForResponse(command: 'reloadProjects', args: null): void; executeAsync(command: 'geterr', args: Proto.GeterrRequestArgs, token: vscode.CancellationToken): Promise<any>; /** * Cancel on going geterr requests and re-queue them after `f` has been evaluated. */ interuptGetErr<R>(f: () => R): R; }
extensions/typescript-language-features/src/typescriptService.ts
1
https://github.com/microsoft/vscode/commit/2f5d88899d9575d165aad0a3b6aa6514cdccd696
[ 0.998429000377655, 0.07699746638536453, 0.00016773605602793396, 0.00017040630336850882, 0.2659943997859955 ]
{ "id": 1, "code_window": [ "\t\tpublic readonly reason: string\n", "\t) { }\n", "}\n", "\n", "export class NoContentResponse {\n", "\tpublic readonly type: 'noContent' = 'noContent';\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "export const NoContentResponse = new class { readonly type = 'noContent'; };\n" ], "file_path": "extensions/typescript-language-features/src/typescriptService.ts", "type": "replace", "edit_start_line_idx": 21 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" enable-background="new 0 0 16 16" height="16" width="16"><path fill="#F6F6F6" d="M16 2.6L13.4 0H6v6H0v10h10v-6h6z"/><g fill="#424242"><path d="M5 7h1v2H5zM11 1h1v2h-1zM13 1v3H9V1H7v5h.4L10 8.6V9h5V3zM7 10H3V7H1v8h8V9L7 7z"/></g></svg>
src/vs/workbench/parts/extensions/electron-browser/media/save.svg
0
https://github.com/microsoft/vscode/commit/2f5d88899d9575d165aad0a3b6aa6514cdccd696
[ 0.00016981911903712898, 0.00016981911903712898, 0.00016981911903712898, 0.00016981911903712898, 0 ]
{ "id": 1, "code_window": [ "\t\tpublic readonly reason: string\n", "\t) { }\n", "}\n", "\n", "export class NoContentResponse {\n", "\tpublic readonly type: 'noContent' = 'noContent';\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "export const NoContentResponse = new class { readonly type = 'noContent'; };\n" ], "file_path": "extensions/typescript-language-features/src/typescriptService.ts", "type": "replace", "edit_start_line_idx": 21 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'path'; import * as fs from 'fs'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { writeFileAndFlushSync } from 'vs/base/node/extfs'; import { isUndefined, isUndefinedOrNull } from 'vs/base/common/types'; import { IStateService } from 'vs/platform/state/common/state'; import { ILogService } from 'vs/platform/log/common/log'; import { readFile } from 'vs/base/node/pfs'; export class FileStorage { private _database: object | null = null; private lastFlushedSerializedDatabase: string | null = null; constructor(private dbPath: string, private onError: (error: Error) => void) { } private get database(): object { if (!this._database) { this._database = this.loadSync(); } return this._database; } init(): Promise<void> { return readFile(this.dbPath).then(contents => { try { this.lastFlushedSerializedDatabase = contents.toString(); this._database = JSON.parse(this.lastFlushedSerializedDatabase); } catch (error) { this._database = {}; } }, error => { if (error.code !== 'ENOENT') { this.onError(error); } this._database = {}; }); } private loadSync(): object { try { this.lastFlushedSerializedDatabase = fs.readFileSync(this.dbPath).toString(); return JSON.parse(this.lastFlushedSerializedDatabase); } catch (error) { if (error.code !== 'ENOENT') { this.onError(error); } return {}; } } getItem<T>(key: string, defaultValue: T): T; getItem<T>(key: string, defaultValue?: T): T | undefined; getItem<T>(key: string, defaultValue?: T): T | undefined { const res = this.database[key]; if (isUndefinedOrNull(res)) { return defaultValue; } return res; } setItem(key: string, data: any): void { // Remove an item when it is undefined or null if (isUndefinedOrNull(data)) { return this.removeItem(key); } // Shortcut for primitives that did not change if (typeof data === 'string' || typeof data === 'number' || typeof data === 'boolean') { if (this.database[key] === data) { return; } } this.database[key] = data; this.saveSync(); } removeItem(key: string): void { // Only update if the key is actually present (not undefined) if (!isUndefined(this.database[key])) { this.database[key] = undefined; this.saveSync(); } } private saveSync(): void { const serializedDatabase = JSON.stringify(this.database, null, 4); if (serializedDatabase === this.lastFlushedSerializedDatabase) { return; // return early if the database has not changed } try { writeFileAndFlushSync(this.dbPath, serializedDatabase); // permission issue can happen here this.lastFlushedSerializedDatabase = serializedDatabase; } catch (error) { this.onError(error); } } } export class StateService implements IStateService { _serviceBrand: any; private static STATE_FILE = 'storage.json'; private fileStorage: FileStorage; constructor( @IEnvironmentService environmentService: IEnvironmentService, @ILogService logService: ILogService ) { this.fileStorage = new FileStorage(path.join(environmentService.userDataPath, StateService.STATE_FILE), error => logService.error(error)); } init(): Promise<void> { return this.fileStorage.init(); } getItem<T>(key: string, defaultValue: T): T; getItem<T>(key: string, defaultValue: T | undefined): T | undefined; getItem<T>(key: string, defaultValue?: T): T | undefined { return this.fileStorage.getItem(key, defaultValue); } setItem(key: string, data: any): void { this.fileStorage.setItem(key, data); } removeItem(key: string): void { this.fileStorage.removeItem(key); } }
src/vs/platform/state/node/stateService.ts
0
https://github.com/microsoft/vscode/commit/2f5d88899d9575d165aad0a3b6aa6514cdccd696
[ 0.00024174693680834025, 0.0001753767137415707, 0.00016675562073942274, 0.00017066727741621435, 0.000017878426660900004 ]
{ "id": 1, "code_window": [ "\t\tpublic readonly reason: string\n", "\t) { }\n", "}\n", "\n", "export class NoContentResponse {\n", "\tpublic readonly type: 'noContent' = 'noContent';\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "export const NoContentResponse = new class { readonly type = 'noContent'; };\n" ], "file_path": "extensions/typescript-language-features/src/typescriptService.ts", "type": "replace", "edit_start_line_idx": 21 }
{ "Constructor": { "prefix": "ctor", "body": [ "/**", " *", " */", "constructor() {", "\tsuper();", "\t$0", "}" ], "description": "Constructor" }, "Class Definition": { "prefix": "class", "body": [ "class ${1:name} {", "\tconstructor(${2:parameters}) {", "\t\t$0", "\t}", "}" ], "description": "Class Definition" }, "Public Method Definition": { "prefix": "public method", "body": [ "/**", " * ${1:name}", " */", "public ${1:name}() {", "\t$0", "}" ], "description": "Public Method Definition" }, "Private Method Definition": { "prefix": "private method", "body": [ "private ${1:name}() {", "\t$0", "}" ], "description": "Private Method Definition" }, "Import external module.": { "prefix": "import statement", "body": [ "import { $0 } from \"${1:module}\";" ], "description": "Import external module." }, "Property getter": { "prefix": "get", "body": [ "", "public get ${1:value}() : ${2:string} {", "\t${3:return $0}", "}", "" ], "description": "Property getter" }, "Log to the console": { "prefix": "log", "body": [ "console.log($1);", "$0" ], "description": "Log to the console" }, "Log warning to console": { "prefix": "warn", "body": [ "console.warn($1);", "$0" ], "description": "Log warning to the console" }, "Log error to console": { "prefix": "error", "body": [ "console.error($1);", "$0" ], "description": "Log error to the console" }, "Define a full property": { "prefix": "prop", "body": [ "", "private _${1:value} : ${2:string};", "public get ${1:value}() : ${2:string} {", "\treturn this._${1:value};", "}", "public set ${1:value}(v : ${2:string}) {", "\tthis._${1:value} = v;", "}", "" ], "description": "Define a full property" }, "Triple-slash reference": { "prefix": "ref", "body": [ "/// <reference path=\"$1\" />", "$0" ], "description": "Triple-slash reference" }, "Property setter": { "prefix": "set", "body": [ "", "public set ${1:value}(v : ${2:string}) {", "\tthis.$3 = v;", "}", "" ], "description": "Property setter" }, "Throw Exception": { "prefix": "throw", "body": [ "throw \"$1\";", "$0" ], "description": "Throw Exception" }, "For Loop": { "prefix": "for", "body": [ "for (let ${1:index} = 0; ${1:index} < ${2:array}.length; ${1:index}++) {", "\tconst ${3:element} = ${2:array}[${1:index}];", "\t$0", "}" ], "description": "For Loop" }, "For-Each Loop using =>": { "prefix": "foreach =>", "body": [ "${1:array}.forEach(${2:element} => {", "\t$0", "});" ], "description": "For-Each Loop using =>" }, "For-In Loop": { "prefix": "forin", "body": [ "for (const ${1:key} in ${2:object}) {", "\tif (${2:object}.hasOwnProperty(${1:key})) {", "\t\tconst ${3:element} = ${2:object}[${1:key}];", "\t\t$0", "\t}", "}" ], "description": "For-In Loop" }, "For-Of Loop": { "prefix": "forof", "body": [ "for (const ${1:iterator} of ${2:object}) {", "\t$0", "}" ], "description": "For-Of Loop" }, "Function Statement": { "prefix": "function", "body": [ "function ${1:name}(${2:params}:${3:type}) {", "\t$0", "}" ], "description": "Function Statement" }, "If Statement": { "prefix": "if", "body": [ "if (${1:condition}) {", "\t$0", "}" ], "description": "If Statement" }, "If-Else Statement": { "prefix": "ifelse", "body": [ "if (${1:condition}) {", "\t$0", "} else {", "\t", "}" ], "description": "If-Else Statement" }, "New Statement": { "prefix": "new", "body": [ "const ${1:name} = new ${2:type}(${3:arguments});$0" ], "description": "New Statement" }, "Switch Statement": { "prefix": "switch", "body": [ "switch (${1:key}) {", "\tcase ${2:value}:", "\t\t$0", "\t\tbreak;", "", "\tdefault:", "\t\tbreak;", "}" ], "description": "Switch Statement" }, "While Statement": { "prefix": "while", "body": [ "while (${1:condition}) {", "\t$0", "}" ], "description": "While Statement" }, "Do-While Statement": { "prefix": "dowhile", "body": [ "do {", "\t$0", "} while (${1:condition});" ], "description": "Do-While Statement" }, "Try-Catch Statement": { "prefix": "trycatch", "body": [ "try {", "\t$0", "} catch (${1:error}) {", "\t", "}" ], "description": "Try-Catch Statement" }, "Set Timeout Function": { "prefix": "settimeout", "body": [ "setTimeout(() => {", "\t$0", "}, ${1:timeout});" ], "description": "Set Timeout Function" }, "Region Start": { "prefix": "#region", "body": [ "//#region $0" ], "description": "Folding Region Start" }, "Region End": { "prefix": "#endregion", "body": [ "//#endregion" ], "description": "Folding Region End" } }
extensions/typescript-basics/snippets/typescript.json
0
https://github.com/microsoft/vscode/commit/2f5d88899d9575d165aad0a3b6aa6514cdccd696
[ 0.00017334980657324195, 0.00017078632663469762, 0.00016766904445830733, 0.00017103416030295193, 0.0000013946856824986753 ]
{ "id": 2, "code_window": [ "\n", "export type ServerResponse<T extends Proto.Response> = T | CancelledResponse | NoContentResponse;\n", "\n", "interface TypeScriptRequestTypes {\n", "\t'applyCodeActionCommand': [Proto.ApplyCodeActionCommandRequestArgs, Proto.ApplyCodeActionCommandResponse];\n", "\t'completionEntryDetails': [Proto.CompletionDetailsRequestArgs, Proto.CompletionDetailsResponse];\n", "\t'completionInfo': [Proto.CompletionsRequestArgs, Proto.CompletionInfoResponse];\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export type ServerResponse<T extends Proto.Response> = T | CancelledResponse | typeof NoContentResponse;\n" ], "file_path": "extensions/typescript-language-features/src/typescriptService.ts", "type": "replace", "edit_start_line_idx": 25 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import BufferSyncSupport from './features/bufferSyncSupport'; import * as Proto from './protocol'; import API from './utils/api'; import { TypeScriptServiceConfiguration } from './utils/configuration'; import Logger from './utils/logger'; import { PluginManager } from './utils/plugins'; export class CancelledResponse { public readonly type: 'cancelled' = 'cancelled'; constructor( public readonly reason: string ) { } } export class NoContentResponse { public readonly type: 'noContent' = 'noContent'; } export type ServerResponse<T extends Proto.Response> = T | CancelledResponse | NoContentResponse; interface TypeScriptRequestTypes { 'applyCodeActionCommand': [Proto.ApplyCodeActionCommandRequestArgs, Proto.ApplyCodeActionCommandResponse]; 'completionEntryDetails': [Proto.CompletionDetailsRequestArgs, Proto.CompletionDetailsResponse]; 'completionInfo': [Proto.CompletionsRequestArgs, Proto.CompletionInfoResponse]; 'completions': [Proto.CompletionsRequestArgs, Proto.CompletionsResponse]; 'configure': [Proto.ConfigureRequestArguments, Proto.ConfigureResponse]; 'definition': [Proto.FileLocationRequestArgs, Proto.DefinitionResponse]; 'definitionAndBoundSpan': [Proto.FileLocationRequestArgs, Proto.DefinitionInfoAndBoundSpanReponse]; 'docCommentTemplate': [Proto.FileLocationRequestArgs, Proto.DocCommandTemplateResponse]; 'documentHighlights': [Proto.DocumentHighlightsRequestArgs, Proto.DocumentHighlightsResponse]; 'format': [Proto.FormatRequestArgs, Proto.FormatResponse]; 'formatonkey': [Proto.FormatOnKeyRequestArgs, Proto.FormatResponse]; 'getApplicableRefactors': [Proto.GetApplicableRefactorsRequestArgs, Proto.GetApplicableRefactorsResponse]; 'getCodeFixes': [Proto.CodeFixRequestArgs, Proto.GetCodeFixesResponse]; 'getCombinedCodeFix': [Proto.GetCombinedCodeFixRequestArgs, Proto.GetCombinedCodeFixResponse]; 'getEditsForFileRename': [Proto.GetEditsForFileRenameRequestArgs, Proto.GetEditsForFileRenameResponse]; 'getEditsForRefactor': [Proto.GetEditsForRefactorRequestArgs, Proto.GetEditsForRefactorResponse]; 'getOutliningSpans': [Proto.FileRequestArgs, Proto.OutliningSpansResponse]; 'getSupportedCodeFixes': [null, Proto.GetSupportedCodeFixesResponse]; 'implementation': [Proto.FileLocationRequestArgs, Proto.ImplementationResponse]; 'jsxClosingTag': [Proto.JsxClosingTagRequestArgs, Proto.JsxClosingTagResponse]; 'navto': [Proto.NavtoRequestArgs, Proto.NavtoResponse]; 'navtree': [Proto.FileRequestArgs, Proto.NavTreeResponse]; 'occurrences': [Proto.FileLocationRequestArgs, Proto.OccurrencesResponse]; 'organizeImports': [Proto.OrganizeImportsRequestArgs, Proto.OrganizeImportsResponse]; 'projectInfo': [Proto.ProjectInfoRequestArgs, Proto.ProjectInfoResponse]; 'quickinfo': [Proto.FileLocationRequestArgs, Proto.QuickInfoResponse]; 'references': [Proto.FileLocationRequestArgs, Proto.ReferencesResponse]; 'rename': [Proto.RenameRequestArgs, Proto.RenameResponse]; 'signatureHelp': [Proto.SignatureHelpRequestArgs, Proto.SignatureHelpResponse]; 'typeDefinition': [Proto.FileLocationRequestArgs, Proto.TypeDefinitionResponse]; } export interface ITypeScriptServiceClient { /** * Convert a resource (VS Code) to a normalized path (TypeScript). * * Does not try handling case insensitivity. */ normalizedPath(resource: vscode.Uri): string | undefined; /** * Map a resource to a normalized path * * This will attempt to handle case insensitivity. */ toPath(resource: vscode.Uri): string | undefined; /** * Convert a path to a resource. */ toResource(filepath: string): vscode.Uri; /** * Tries to ensure that a vscode document is open on the TS server. * * Returns the normalized path. */ toOpenedFilePath(document: vscode.TextDocument): string | undefined; getWorkspaceRootForResource(resource: vscode.Uri): string | undefined; readonly onTsServerStarted: vscode.Event<API>; readonly onProjectLanguageServiceStateChanged: vscode.Event<Proto.ProjectLanguageServiceStateEventBody>; readonly onDidBeginInstallTypings: vscode.Event<Proto.BeginInstallTypesEventBody>; readonly onDidEndInstallTypings: vscode.Event<Proto.EndInstallTypesEventBody>; readonly onTypesInstallerInitializationFailed: vscode.Event<Proto.TypesInstallerInitializationFailedEventBody>; readonly apiVersion: API; readonly pluginManager: PluginManager; readonly configuration: TypeScriptServiceConfiguration; readonly logger: Logger; readonly bufferSyncSupport: BufferSyncSupport; execute<K extends keyof TypeScriptRequestTypes>( command: K, args: TypeScriptRequestTypes[K][0], token: vscode.CancellationToken, lowPriority?: boolean ): Promise<ServerResponse<TypeScriptRequestTypes[K][1]>>; executeWithoutWaitingForResponse(command: 'open', args: Proto.OpenRequestArgs): void; executeWithoutWaitingForResponse(command: 'close', args: Proto.FileRequestArgs): void; executeWithoutWaitingForResponse(command: 'change', args: Proto.ChangeRequestArgs): void; executeWithoutWaitingForResponse(command: 'compilerOptionsForInferredProjects', args: Proto.SetCompilerOptionsForInferredProjectsArgs): void; executeWithoutWaitingForResponse(command: 'reloadProjects', args: null): void; executeAsync(command: 'geterr', args: Proto.GeterrRequestArgs, token: vscode.CancellationToken): Promise<any>; /** * Cancel on going geterr requests and re-queue them after `f` has been evaluated. */ interuptGetErr<R>(f: () => R): R; }
extensions/typescript-language-features/src/typescriptService.ts
1
https://github.com/microsoft/vscode/commit/2f5d88899d9575d165aad0a3b6aa6514cdccd696
[ 0.999104917049408, 0.1577226221561432, 0.00016766729822847992, 0.0024918708950281143, 0.3585067391395569 ]
{ "id": 2, "code_window": [ "\n", "export type ServerResponse<T extends Proto.Response> = T | CancelledResponse | NoContentResponse;\n", "\n", "interface TypeScriptRequestTypes {\n", "\t'applyCodeActionCommand': [Proto.ApplyCodeActionCommandRequestArgs, Proto.ApplyCodeActionCommandResponse];\n", "\t'completionEntryDetails': [Proto.CompletionDetailsRequestArgs, Proto.CompletionDetailsResponse];\n", "\t'completionInfo': [Proto.CompletionsRequestArgs, Proto.CompletionInfoResponse];\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export type ServerResponse<T extends Proto.Response> = T | CancelledResponse | typeof NoContentResponse;\n" ], "file_path": "extensions/typescript-language-features/src/typescriptService.ts", "type": "replace", "edit_start_line_idx": 25 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { editorActiveIndentGuides, editorIndentGuides } from 'vs/editor/common/view/editorColorRegistry'; import { IStandaloneThemeData } from 'vs/editor/standalone/common/standaloneThemeService'; import { editorBackground, editorForeground, editorInactiveSelection, editorSelectionHighlight } from 'vs/platform/theme/common/colorRegistry'; /* -------------------------------- Begin vs theme -------------------------------- */ export const vs: IStandaloneThemeData = { base: 'vs', inherit: false, rules: [ { token: '', foreground: '000000', background: 'fffffe' }, { token: 'invalid', foreground: 'cd3131' }, { token: 'emphasis', fontStyle: 'italic' }, { token: 'strong', fontStyle: 'bold' }, { token: 'variable', foreground: '001188' }, { token: 'variable.predefined', foreground: '4864AA' }, { token: 'constant', foreground: 'dd0000' }, { token: 'comment', foreground: '008000' }, { token: 'number', foreground: '09885A' }, { token: 'number.hex', foreground: '3030c0' }, { token: 'regexp', foreground: '800000' }, { token: 'annotation', foreground: '808080' }, { token: 'type', foreground: '008080' }, { token: 'delimiter', foreground: '000000' }, { token: 'delimiter.html', foreground: '383838' }, { token: 'delimiter.xml', foreground: '0000FF' }, { token: 'tag', foreground: '800000' }, { token: 'tag.id.pug', foreground: '4F76AC' }, { token: 'tag.class.pug', foreground: '4F76AC' }, { token: 'meta.scss', foreground: '800000' }, { token: 'metatag', foreground: 'e00000' }, { token: 'metatag.content.html', foreground: 'FF0000' }, { token: 'metatag.html', foreground: '808080' }, { token: 'metatag.xml', foreground: '808080' }, { token: 'metatag.php', fontStyle: 'bold' }, { token: 'key', foreground: '863B00' }, { token: 'string.key.json', foreground: 'A31515' }, { token: 'string.value.json', foreground: '0451A5' }, { token: 'attribute.name', foreground: 'FF0000' }, { token: 'attribute.value', foreground: '0451A5' }, { token: 'attribute.value.number', foreground: '09885A' }, { token: 'attribute.value.unit', foreground: '09885A' }, { token: 'attribute.value.html', foreground: '0000FF' }, { token: 'attribute.value.xml', foreground: '0000FF' }, { token: 'string', foreground: 'A31515' }, { token: 'string.html', foreground: '0000FF' }, { token: 'string.sql', foreground: 'FF0000' }, { token: 'string.yaml', foreground: '0451A5' }, { token: 'keyword', foreground: '0000FF' }, { token: 'keyword.json', foreground: '0451A5' }, { token: 'keyword.flow', foreground: 'AF00DB' }, { token: 'keyword.flow.scss', foreground: '0000FF' }, { token: 'operator.scss', foreground: '666666' }, { token: 'operator.sql', foreground: '778899' }, { token: 'operator.swift', foreground: '666666' }, { token: 'predefined.sql', foreground: 'FF00FF' }, ], colors: { [editorBackground]: '#FFFFFE', [editorForeground]: '#000000', [editorInactiveSelection]: '#E5EBF1', [editorIndentGuides]: '#D3D3D3', [editorActiveIndentGuides]: '#939393', [editorSelectionHighlight]: '#ADD6FF4D' } }; /* -------------------------------- End vs theme -------------------------------- */ /* -------------------------------- Begin vs-dark theme -------------------------------- */ export const vs_dark: IStandaloneThemeData = { base: 'vs-dark', inherit: false, rules: [ { token: '', foreground: 'D4D4D4', background: '1E1E1E' }, { token: 'invalid', foreground: 'f44747' }, { token: 'emphasis', fontStyle: 'italic' }, { token: 'strong', fontStyle: 'bold' }, { token: 'variable', foreground: '74B0DF' }, { token: 'variable.predefined', foreground: '4864AA' }, { token: 'variable.parameter', foreground: '9CDCFE' }, { token: 'constant', foreground: '569CD6' }, { token: 'comment', foreground: '608B4E' }, { token: 'number', foreground: 'B5CEA8' }, { token: 'number.hex', foreground: '5BB498' }, { token: 'regexp', foreground: 'B46695' }, { token: 'annotation', foreground: 'cc6666' }, { token: 'type', foreground: '3DC9B0' }, { token: 'delimiter', foreground: 'DCDCDC' }, { token: 'delimiter.html', foreground: '808080' }, { token: 'delimiter.xml', foreground: '808080' }, { token: 'tag', foreground: '569CD6' }, { token: 'tag.id.pug', foreground: '4F76AC' }, { token: 'tag.class.pug', foreground: '4F76AC' }, { token: 'meta.scss', foreground: 'A79873' }, { token: 'meta.tag', foreground: 'CE9178' }, { token: 'metatag', foreground: 'DD6A6F' }, { token: 'metatag.content.html', foreground: '9CDCFE' }, { token: 'metatag.html', foreground: '569CD6' }, { token: 'metatag.xml', foreground: '569CD6' }, { token: 'metatag.php', fontStyle: 'bold' }, { token: 'key', foreground: '9CDCFE' }, { token: 'string.key.json', foreground: '9CDCFE' }, { token: 'string.value.json', foreground: 'CE9178' }, { token: 'attribute.name', foreground: '9CDCFE' }, { token: 'attribute.value', foreground: 'CE9178' }, { token: 'attribute.value.number.css', foreground: 'B5CEA8' }, { token: 'attribute.value.unit.css', foreground: 'B5CEA8' }, { token: 'attribute.value.hex.css', foreground: 'D4D4D4' }, { token: 'string', foreground: 'CE9178' }, { token: 'string.sql', foreground: 'FF0000' }, { token: 'keyword', foreground: '569CD6' }, { token: 'keyword.flow', foreground: 'C586C0' }, { token: 'keyword.json', foreground: 'CE9178' }, { token: 'keyword.flow.scss', foreground: '569CD6' }, { token: 'operator.scss', foreground: '909090' }, { token: 'operator.sql', foreground: '778899' }, { token: 'operator.swift', foreground: '909090' }, { token: 'predefined.sql', foreground: 'FF00FF' }, ], colors: { [editorBackground]: '#1E1E1E', [editorForeground]: '#D4D4D4', [editorInactiveSelection]: '#3A3D41', [editorIndentGuides]: '#404040', [editorActiveIndentGuides]: '#707070', [editorSelectionHighlight]: '#ADD6FF26' } }; /* -------------------------------- End vs-dark theme -------------------------------- */ /* -------------------------------- Begin hc-black theme -------------------------------- */ export const hc_black: IStandaloneThemeData = { base: 'hc-black', inherit: false, rules: [ { token: '', foreground: 'FFFFFF', background: '000000' }, { token: 'invalid', foreground: 'f44747' }, { token: 'emphasis', fontStyle: 'italic' }, { token: 'strong', fontStyle: 'bold' }, { token: 'variable', foreground: '1AEBFF' }, { token: 'variable.parameter', foreground: '9CDCFE' }, { token: 'constant', foreground: '569CD6' }, { token: 'comment', foreground: '608B4E' }, { token: 'number', foreground: 'FFFFFF' }, { token: 'regexp', foreground: 'C0C0C0' }, { token: 'annotation', foreground: '569CD6' }, { token: 'type', foreground: '3DC9B0' }, { token: 'delimiter', foreground: 'FFFF00' }, { token: 'delimiter.html', foreground: 'FFFF00' }, { token: 'tag', foreground: '569CD6' }, { token: 'tag.id.pug', foreground: '4F76AC' }, { token: 'tag.class.pug', foreground: '4F76AC' }, { token: 'meta', foreground: 'D4D4D4' }, { token: 'meta.tag', foreground: 'CE9178' }, { token: 'metatag', foreground: '569CD6' }, { token: 'metatag.content.html', foreground: '1AEBFF' }, { token: 'metatag.html', foreground: '569CD6' }, { token: 'metatag.xml', foreground: '569CD6' }, { token: 'metatag.php', fontStyle: 'bold' }, { token: 'key', foreground: '9CDCFE' }, { token: 'string.key', foreground: '9CDCFE' }, { token: 'string.value', foreground: 'CE9178' }, { token: 'attribute.name', foreground: '569CD6' }, { token: 'attribute.value', foreground: '3FF23F' }, { token: 'string', foreground: 'CE9178' }, { token: 'string.sql', foreground: 'FF0000' }, { token: 'keyword', foreground: '569CD6' }, { token: 'keyword.flow', foreground: 'C586C0' }, { token: 'operator.sql', foreground: '778899' }, { token: 'operator.swift', foreground: '909090' }, { token: 'predefined.sql', foreground: 'FF00FF' }, ], colors: { [editorBackground]: '#000000', [editorForeground]: '#FFFFFF', [editorIndentGuides]: '#FFFFFF', [editorActiveIndentGuides]: '#FFFFFF', } }; /* -------------------------------- End hc-black theme -------------------------------- */
src/vs/editor/standalone/common/themes.ts
0
https://github.com/microsoft/vscode/commit/2f5d88899d9575d165aad0a3b6aa6514cdccd696
[ 0.00017372063302900642, 0.00017036472854670137, 0.00016856883303262293, 0.00017017751815728843, 0.0000012806135600840207 ]
{ "id": 2, "code_window": [ "\n", "export type ServerResponse<T extends Proto.Response> = T | CancelledResponse | NoContentResponse;\n", "\n", "interface TypeScriptRequestTypes {\n", "\t'applyCodeActionCommand': [Proto.ApplyCodeActionCommandRequestArgs, Proto.ApplyCodeActionCommandResponse];\n", "\t'completionEntryDetails': [Proto.CompletionDetailsRequestArgs, Proto.CompletionDetailsResponse];\n", "\t'completionInfo': [Proto.CompletionsRequestArgs, Proto.CompletionInfoResponse];\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export type ServerResponse<T extends Proto.Response> = T | CancelledResponse | typeof NoContentResponse;\n" ], "file_path": "extensions/typescript-language-features/src/typescriptService.ts", "type": "replace", "edit_start_line_idx": 25 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./octicons/octicons'; import 'vs/css!./octicons/octicons-animations'; import { escape } from 'vs/base/common/strings'; function expand(text: string): string { return text.replace(/\$\(((.+?)(~(.*?))?)\)/g, (_match, _g1, name, _g3, animation) => { return `<span class="octicon octicon-${name} ${animation ? `octicon-animation-${animation}` : ''}"></span>`; }); } export function renderOcticons(label: string): string { return expand(escape(label)); } export class OcticonLabel { constructor( private readonly _container: HTMLElement ) { } set text(text: string) { this._container.innerHTML = renderOcticons(text || ''); } set title(title: string) { this._container.title = title; } }
src/vs/base/browser/ui/octiconLabel/octiconLabel.ts
0
https://github.com/microsoft/vscode/commit/2f5d88899d9575d165aad0a3b6aa6514cdccd696
[ 0.00017362491053063422, 0.0001691131037659943, 0.0001668908225838095, 0.00016796833369880915, 0.0000026766431346914032 ]
{ "id": 2, "code_window": [ "\n", "export type ServerResponse<T extends Proto.Response> = T | CancelledResponse | NoContentResponse;\n", "\n", "interface TypeScriptRequestTypes {\n", "\t'applyCodeActionCommand': [Proto.ApplyCodeActionCommandRequestArgs, Proto.ApplyCodeActionCommandResponse];\n", "\t'completionEntryDetails': [Proto.CompletionDetailsRequestArgs, Proto.CompletionDetailsResponse];\n", "\t'completionInfo': [Proto.CompletionsRequestArgs, Proto.CompletionInfoResponse];\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export type ServerResponse<T extends Proto.Response> = T | CancelledResponse | typeof NoContentResponse;\n" ], "file_path": "extensions/typescript-language-features/src/typescriptService.ts", "type": "replace", "edit_start_line_idx": 25 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree'; import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { ObjectTree } from 'vs/base/browser/ui/tree/objectTree'; import { Iterator } from 'vs/base/common/iterator'; suite('ObjectTree', function () { suite('TreeNavigator', function () { let tree: ObjectTree<number>; let filter = (_: number) => true; setup(() => { const container = document.createElement('div'); container.style.width = '200px'; container.style.height = '200px'; const delegate = new class implements IListVirtualDelegate<number> { getHeight() { return 20; } getTemplateId(): string { return 'default'; } }; const renderer = new class implements ITreeRenderer<number, void, HTMLElement> { readonly templateId = 'default'; renderTemplate(container: HTMLElement): HTMLElement { return container; } renderElement(element: ITreeNode<number, void>, index: number, templateData: HTMLElement): void { templateData.textContent = `${element.element}`; } disposeTemplate(): void { } }; tree = new ObjectTree<number>(container, delegate, [renderer], { filter: { filter: (el) => filter(el) } }); tree.layout(200); }); teardown(() => { tree.dispose(); filter = (_: number) => true; }); test('should be able to navigate', () => { tree.setChildren(null, Iterator.fromArray([ { element: 0, children: Iterator.fromArray([ { element: 10 }, { element: 11 }, { element: 12 }, ]) }, { element: 1 }, { element: 2 } ])); const navigator = tree.navigate(); assert.equal(navigator.current(), null); assert.equal(navigator.next(), 0); assert.equal(navigator.current(), 0); assert.equal(navigator.next(), 10); assert.equal(navigator.current(), 10); assert.equal(navigator.next(), 11); assert.equal(navigator.current(), 11); assert.equal(navigator.next(), 12); assert.equal(navigator.current(), 12); assert.equal(navigator.next(), 1); assert.equal(navigator.current(), 1); assert.equal(navigator.next(), 2); assert.equal(navigator.current(), 2); assert.equal(navigator.previous(), 1); assert.equal(navigator.current(), 1); assert.equal(navigator.previous(), 12); assert.equal(navigator.previous(), 11); assert.equal(navigator.previous(), 10); assert.equal(navigator.previous(), 0); assert.equal(navigator.previous(), null); assert.equal(navigator.next(), 0); assert.equal(navigator.next(), 10); assert.equal(navigator.parent(), 0); assert.equal(navigator.parent(), null); assert.equal(navigator.first(), 0); assert.equal(navigator.last(), 2); }); test('should skip collapsed nodes', () => { tree.setChildren(null, Iterator.fromArray([ { element: 0, collapsed: true, children: Iterator.fromArray([ { element: 10 }, { element: 11 }, { element: 12 }, ]) }, { element: 1 }, { element: 2 } ])); const navigator = tree.navigate(); assert.equal(navigator.current(), null); assert.equal(navigator.next(), 0); assert.equal(navigator.next(), 1); assert.equal(navigator.next(), 2); assert.equal(navigator.next(), null); assert.equal(navigator.previous(), 2); assert.equal(navigator.previous(), 1); assert.equal(navigator.previous(), 0); assert.equal(navigator.previous(), null); assert.equal(navigator.next(), 0); assert.equal(navigator.parent(), null); assert.equal(navigator.first(), 0); assert.equal(navigator.last(), 2); }); test('should skip filtered elements', () => { filter = el => el % 2 === 0; tree.setChildren(null, Iterator.fromArray([ { element: 0, children: Iterator.fromArray([ { element: 10 }, { element: 11 }, { element: 12 }, ]) }, { element: 1 }, { element: 2 } ])); const navigator = tree.navigate(); assert.equal(navigator.current(), null); assert.equal(navigator.next(), 0); assert.equal(navigator.next(), 10); assert.equal(navigator.next(), 12); assert.equal(navigator.next(), 2); assert.equal(navigator.next(), null); assert.equal(navigator.previous(), 2); assert.equal(navigator.previous(), 12); assert.equal(navigator.previous(), 10); assert.equal(navigator.previous(), 0); assert.equal(navigator.previous(), null); assert.equal(navigator.next(), 0); assert.equal(navigator.next(), 10); assert.equal(navigator.parent(), 0); assert.equal(navigator.parent(), null); assert.equal(navigator.first(), 0); assert.equal(navigator.last(), 2); }); test('should be able to start from node', () => { tree.setChildren(null, Iterator.fromArray([ { element: 0, children: Iterator.fromArray([ { element: 10 }, { element: 11 }, { element: 12 }, ]) }, { element: 1 }, { element: 2 } ])); const navigator = tree.navigate(1); assert.equal(navigator.current(), 1); assert.equal(navigator.next(), 2); assert.equal(navigator.current(), 2); assert.equal(navigator.previous(), 1); assert.equal(navigator.current(), 1); assert.equal(navigator.previous(), 12); assert.equal(navigator.previous(), 11); assert.equal(navigator.previous(), 10); assert.equal(navigator.previous(), 0); assert.equal(navigator.previous(), null); assert.equal(navigator.next(), 0); assert.equal(navigator.next(), 10); assert.equal(navigator.parent(), 0); assert.equal(navigator.parent(), null); assert.equal(navigator.first(), 0); assert.equal(navigator.last(), 2); }); }); });
src/vs/base/test/browser/ui/tree/objectTree.test.ts
0
https://github.com/microsoft/vscode/commit/2f5d88899d9575d165aad0a3b6aa6514cdccd696
[ 0.0001780377351678908, 0.00016953771410044283, 0.00016662290727254003, 0.00016897967725526541, 0.000002405410214123549 ]
{ "id": 0, "code_window": [ "\t\tthis._processReady = new TPromise<void>(c => {\n", "\t\t\tthis.onProcessIdReady(() => c(void 0));\n", "\t\t});\n", "\n", "\t\tthis._initDimensions();\n", "\t\tthis._createProcess(this._shellLaunchConfig);\n", "\t\tthis._createXterm();\n", "\n", "\t\tif (platform.isWindows) {\n", "\t\t\tthis._processReady.then(() => {\n", "\t\t\t\tif (!this._isDisposed) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._createProcess();\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 159 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as cp from 'child_process'; import * as os from 'os'; import * as path from 'path'; import * as lifecycle from 'vs/base/common/lifecycle'; import * as nls from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import * as dom from 'vs/base/browser/dom'; import Event, { Emitter } from 'vs/base/common/event'; import Uri from 'vs/base/common/uri'; import { WindowsShellHelper } from 'vs/workbench/parts/terminal/electron-browser/windowsShellHelper'; import { Terminal as XTermTerminal } from 'xterm'; import { Dimension } from 'vs/base/browser/builder'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IMessageService, Severity } from 'vs/platform/message/common/message'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IStringDictionary } from 'vs/base/common/collections'; import { ITerminalInstance, KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED, TERMINAL_PANEL_ID, IShellLaunchConfig } from 'vs/workbench/parts/terminal/common/terminal'; import { ITerminalProcessFactory } from 'vs/workbench/parts/terminal/electron-browser/terminal'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { TabFocus } from 'vs/editor/common/config/commonEditorConfig'; import { TerminalConfigHelper } from 'vs/workbench/parts/terminal/electron-browser/terminalConfigHelper'; import { TerminalLinkHandler } from 'vs/workbench/parts/terminal/electron-browser/terminalLinkHandler'; import { TerminalWidgetManager } from 'vs/workbench/parts/terminal/browser/terminalWidgetManager'; import { registerThemingParticipant, ITheme, ICssStyleCollector } from 'vs/platform/theme/common/themeService'; import { scrollbarSliderBackground, scrollbarSliderHoverBackground, scrollbarSliderActiveBackground } from 'vs/platform/theme/common/colorRegistry'; import { TPromise } from 'vs/base/common/winjs.base'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { IHistoryService } from 'vs/workbench/services/history/common/history'; import pkg from 'vs/platform/node/package'; /** The amount of time to consider terminal errors to be related to the launch */ const LAUNCHING_DURATION = 500; // Enable search functionality in xterm.js instance XTermTerminal.loadAddon('search'); class StandardTerminalProcessFactory implements ITerminalProcessFactory { public create(env: { [key: string]: string }): cp.ChildProcess { return cp.fork('./terminalProcess', [], { env, cwd: Uri.parse(path.dirname(require.toUrl('./terminalProcess'))).fsPath }); } } enum ProcessState { // The process has not been initialized yet. UNINITIALIZED, // The process is currently launching, the process is marked as launching // for a short duration after being created and is helpful to indicate // whether the process died as a result of bad shell and args. LAUNCHING, // The process is running normally. RUNNING, // The process was killed during launch, likely as a result of bad shell and // args. KILLED_DURING_LAUNCH, // The process was killed by the user (the event originated from VS Code). KILLED_BY_USER, // The process was killed by itself, for example the shell crashed or `exit` // was run. KILLED_BY_PROCESS } export class TerminalInstance implements ITerminalInstance { private static readonly EOL_REGEX = /\r?\n/g; private static _terminalProcessFactory: ITerminalProcessFactory = new StandardTerminalProcessFactory(); private static _lastKnownDimensions: Dimension = null; private static _idCounter = 1; private _id: number; private _isExiting: boolean; private _hadFocusOnExit: boolean; private _isVisible: boolean; private _processState: ProcessState; private _processReady: TPromise<void>; private _isDisposed: boolean; private _onDisposed: Emitter<ITerminalInstance>; private _onDataForApi: Emitter<{ instance: ITerminalInstance, data: string }>; private _onProcessIdReady: Emitter<TerminalInstance>; private _onTitleChanged: Emitter<string>; private _process: cp.ChildProcess; private _processId: number; private _skipTerminalCommands: string[]; private _title: string; private _instanceDisposables: lifecycle.IDisposable[]; private _processDisposables: lifecycle.IDisposable[]; private _wrapperElement: HTMLDivElement; private _xterm: XTermTerminal; private _xtermElement: HTMLDivElement; private _terminalHasTextContextKey: IContextKey<boolean>; private _cols: number; private _rows: number; private _messageTitleListener: (message: { type: string, content: string }) => void; private _preLaunchInputQueue: string; private _initialCwd: string; private _windowsShellHelper: WindowsShellHelper; private _widgetManager: TerminalWidgetManager; private _linkHandler: TerminalLinkHandler; public get id(): number { return this._id; } public get processId(): number { return this._processId; } public get onDisposed(): Event<ITerminalInstance> { return this._onDisposed.event; } public get onDataForApi(): Event<{ instance: ITerminalInstance, data: string }> { return this._onDataForApi.event; } public get onProcessIdReady(): Event<TerminalInstance> { return this._onProcessIdReady.event; } public get onTitleChanged(): Event<string> { return this._onTitleChanged.event; } public get title(): string { return this._title; } public get hadFocusOnExit(): boolean { return this._hadFocusOnExit; } public get isTitleSetByProcess(): boolean { return !!this._messageTitleListener; } public constructor( private _terminalFocusContextKey: IContextKey<boolean>, private _configHelper: TerminalConfigHelper, private _container: HTMLElement, private _shellLaunchConfig: IShellLaunchConfig, @IContextKeyService private _contextKeyService: IContextKeyService, @IKeybindingService private _keybindingService: IKeybindingService, @IMessageService private _messageService: IMessageService, @IPanelService private _panelService: IPanelService, @IWorkspaceContextService private _contextService: IWorkspaceContextService, @IWorkbenchEditorService private _editorService: IWorkbenchEditorService, @IInstantiationService private _instantiationService: IInstantiationService, @IClipboardService private _clipboardService: IClipboardService, @IHistoryService private _historyService: IHistoryService ) { this._instanceDisposables = []; this._processDisposables = []; this._skipTerminalCommands = []; this._isExiting = false; this._hadFocusOnExit = false; this._processState = ProcessState.UNINITIALIZED; this._isVisible = false; this._isDisposed = false; this._id = TerminalInstance._idCounter++; this._terminalHasTextContextKey = KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED.bindTo(this._contextKeyService); this._preLaunchInputQueue = ''; this._onDisposed = new Emitter<TerminalInstance>(); this._onDataForApi = new Emitter<{ instance: ITerminalInstance, data: string }>(); this._onProcessIdReady = new Emitter<TerminalInstance>(); this._onTitleChanged = new Emitter<string>(); // Create a promise that resolves when the pty is ready this._processReady = new TPromise<void>(c => { this.onProcessIdReady(() => c(void 0)); }); this._initDimensions(); this._createProcess(this._shellLaunchConfig); this._createXterm(); if (platform.isWindows) { this._processReady.then(() => { if (!this._isDisposed) { import('vs/workbench/parts/terminal/electron-browser/windowsShellHelper').then((module) => { this._windowsShellHelper = new module.WindowsShellHelper(this._processId, this._shellLaunchConfig.executable, this, this._xterm); }); } }); } // Only attach xterm.js to the DOM if the terminal panel has been opened before. if (_container) { this.attachToElement(_container); } } public addDisposable(disposable: lifecycle.IDisposable): void { this._instanceDisposables.push(disposable); } private _initDimensions(): void { // The terminal panel needs to have been created if (!this._container) { return; } const computedStyle = window.getComputedStyle(this._container); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this._evaluateColsAndRows(width, height); } /** * Evaluates and sets the cols and rows of the terminal if possible. * @param width The width of the container. * @param height The height of the container. * @return The terminal's width if it requires a layout. */ private _evaluateColsAndRows(width: number, height: number): number { const dimension = this._getDimension(width, height); if (!dimension) { return null; } const font = this._configHelper.getFont(); this._cols = Math.max(Math.floor(dimension.width / font.charWidth), 1); this._rows = Math.max(Math.floor(dimension.height / font.charHeight), 1); return dimension.width; } private _getDimension(width: number, height: number): Dimension { // The font needs to have been initialized const font = this._configHelper.getFont(); if (!font || !font.charWidth || !font.charHeight) { return null; } // The panel is minimized if (!height) { return TerminalInstance._lastKnownDimensions; } else { // Trigger scroll event manually so that the viewport's scroll area is synced. This // needs to happen otherwise its scrollTop value is invalid when the panel is toggled as // it gets removed and then added back to the DOM (resetting scrollTop to 0). // Upstream issue: https://github.com/sourcelair/xterm.js/issues/291 if (this._xterm) { this._xterm.emit('scroll', this._xterm.ydisp); } } const outerContainer = document.querySelector('.terminal-outer-container'); const outerContainerStyle = getComputedStyle(outerContainer); const padding = parseInt(outerContainerStyle.paddingLeft.split('px')[0], 10); const paddingBottom = parseInt(outerContainerStyle.paddingBottom.split('px')[0], 10); // Use left padding as right padding, right padding is not defined in CSS just in case // xterm.js causes an unexpected overflow. const innerWidth = width - padding * 2; const innerHeight = height - paddingBottom; TerminalInstance._lastKnownDimensions = new Dimension(innerWidth, innerHeight); return TerminalInstance._lastKnownDimensions; } /** * Create xterm.js instance and attach data listeners. */ protected _createXterm(): void { this._xterm = new XTermTerminal({ scrollback: this._configHelper.config.scrollback }); if (this._shellLaunchConfig.initialText) { this._xterm.writeln(this._shellLaunchConfig.initialText); } this._process.on('message', (message) => this._sendPtyDataToXterm(message)); this._xterm.on('data', (data) => { if (this._processId) { // Send data if the pty is ready this._process.send({ event: 'input', data }); } else { // If the pty is not ready, queue the data received from // xterm.js until the pty is ready this._preLaunchInputQueue += data; } return false; }); this._linkHandler = this._instantiationService.createInstance(TerminalLinkHandler, this._xterm, platform.platform, this._initialCwd); this._linkHandler.registerLocalLinkHandler(); } public attachToElement(container: HTMLElement): void { if (this._wrapperElement) { throw new Error('The terminal instance has already been attached to a container'); } this._container = container; this._wrapperElement = document.createElement('div'); dom.addClass(this._wrapperElement, 'terminal-wrapper'); this._xtermElement = document.createElement('div'); this._xterm.open(this._xtermElement); this._xterm.attachCustomKeyEventHandler((event: KeyboardEvent) => { // Disable all input if the terminal is exiting if (this._isExiting) { return false; } // Skip processing by xterm.js of keyboard events that resolve to commands described // within commandsToSkipShell const standardKeyboardEvent = new StandardKeyboardEvent(event); const resolveResult = this._keybindingService.softDispatch(standardKeyboardEvent, standardKeyboardEvent.target); if (resolveResult && this._skipTerminalCommands.some(k => k === resolveResult.commandId)) { event.preventDefault(); return false; } // If tab focus mode is on, tab is not passed to the terminal if (TabFocus.getTabFocusMode() && event.keyCode === 9) { return false; } return undefined; }); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'mouseup', (event: KeyboardEvent) => { // Wait until mouseup has propagated through the DOM before // evaluating the new selection state. setTimeout(() => this._refreshSelectionContextKey(), 0); })); // xterm.js currently drops selection on keyup as we need to handle this case. this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'keyup', (event: KeyboardEvent) => { // Wait until keyup has propagated through the DOM before evaluating // the new selection state. setTimeout(() => this._refreshSelectionContextKey(), 0); })); const xtermHelper: HTMLElement = <HTMLElement>this._xterm.element.querySelector('.xterm-helpers'); const focusTrap: HTMLElement = document.createElement('div'); focusTrap.setAttribute('tabindex', '0'); dom.addClass(focusTrap, 'focus-trap'); this._instanceDisposables.push(dom.addDisposableListener(focusTrap, 'focus', (event: FocusEvent) => { let currentElement = focusTrap; while (!dom.hasClass(currentElement, 'part')) { currentElement = currentElement.parentElement; } const hidePanelElement = <HTMLElement>currentElement.querySelector('.hide-panel-action'); hidePanelElement.focus(); })); xtermHelper.insertBefore(focusTrap, this._xterm.textarea); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'focus', (event: KeyboardEvent) => { this._terminalFocusContextKey.set(true); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'blur', (event: KeyboardEvent) => { this._terminalFocusContextKey.reset(); this._refreshSelectionContextKey(); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'focus', (event: KeyboardEvent) => { this._terminalFocusContextKey.set(true); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'blur', (event: KeyboardEvent) => { this._terminalFocusContextKey.reset(); this._refreshSelectionContextKey(); })); this._wrapperElement.appendChild(this._xtermElement); this._widgetManager = new TerminalWidgetManager(this._configHelper, this._wrapperElement); this._linkHandler.setWidgetManager(this._widgetManager); this._container.appendChild(this._wrapperElement); const computedStyle = window.getComputedStyle(this._container); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this.layout(new Dimension(width, height)); this.setVisible(this._isVisible); this.updateConfig(); // If IShellLaunchConfig.waitOnExit was true and the process finished before the terminal // panel was initialized. if (this._xterm.getOption('disableStdin')) { this._attachPressAnyKeyToCloseListener(); } } public registerLinkMatcher(regex: RegExp, handler: (url: string) => void, matchIndex?: number, validationCallback?: (uri: string, element: HTMLElement, callback: (isValid: boolean) => void) => void): number { return this._linkHandler.registerCustomLinkHandler(regex, handler, matchIndex, validationCallback); } public deregisterLinkMatcher(linkMatcherId: number): void { this._xterm.deregisterLinkMatcher(linkMatcherId); } public hasSelection(): boolean { return this._xterm.hasSelection(); } public copySelection(): void { if (this.hasSelection()) { this._clipboardService.writeText(this._xterm.getSelection()); } else { this._messageService.show(Severity.Warning, nls.localize('terminal.integrated.copySelection.noSelection', 'The terminal has no selection to copy')); } } get selection(): string | undefined { return this.hasSelection() ? this._xterm.getSelection() : undefined; } public clearSelection(): void { this._xterm.clearSelection(); } public selectAll(): void { // Focus here to ensure the terminal context key is set this._xterm.focus(); this._xterm.selectAll(); } public findNext(term: string): boolean { return this._xterm.findNext(term); } public findPrevious(term: string): boolean { return this._xterm.findPrevious(term); } public notifyFindWidgetFocusChanged(isFocused: boolean): void { // In order to support escape to close the find widget when the terminal // is focused terminalFocus needs to be true when either the terminal or // the find widget are focused. this._terminalFocusContextKey.set(isFocused || document.activeElement === this._xterm.textarea); } public dispose(): void { if (this._windowsShellHelper) { this._windowsShellHelper.dispose(); } if (this._linkHandler) { this._linkHandler.dispose(); } if (this._xterm && this._xterm.element) { this._hadFocusOnExit = dom.hasClass(this._xterm.element, 'focus'); } if (this._wrapperElement) { this._container.removeChild(this._wrapperElement); this._wrapperElement = null; } if (this._xterm) { this._xterm.destroy(); this._xterm = null; } if (this._process) { if (this._process.connected) { // If the process was still connected this dispose came from // within VS Code, not the process, so mark the process as // killed by the user. this._processState = ProcessState.KILLED_BY_USER; this._process.send({ event: 'shutdown' }); } this._process = null; } if (!this._isDisposed) { this._isDisposed = true; this._onDisposed.fire(this); } this._processDisposables = lifecycle.dispose(this._processDisposables); this._instanceDisposables = lifecycle.dispose(this._instanceDisposables); } public focus(force?: boolean): void { if (!this._xterm) { return; } const text = window.getSelection().toString(); if (!text || force) { this._xterm.focus(); } } public paste(): void { this.focus(); document.execCommand('paste'); } public sendText(text: string, addNewLine: boolean): void { this._processReady.then(() => { // Normalize line endings to 'enter' press. text = text.replace(TerminalInstance.EOL_REGEX, '\r'); if (addNewLine && text.substr(text.length - 1) !== '\r') { text += '\r'; } this._process.send({ event: 'input', data: text }); }); } public setVisible(visible: boolean): void { this._isVisible = visible; if (this._wrapperElement) { dom.toggleClass(this._wrapperElement, 'active', visible); } if (visible && this._xterm) { // Trigger a manual scroll event which will sync the viewport and scroll bar. This is // necessary if the number of rows in the terminal has decreased while it was in the // background since scrollTop changes take no effect but the terminal's position does // change since the number of visible rows decreases. this._xterm.emit('scroll', this._xterm.ydisp); } } public scrollDownLine(): void { this._xterm.scrollDisp(1); } public scrollDownPage(): void { this._xterm.scrollPages(1); } public scrollToBottom(): void { this._xterm.scrollToBottom(); } public scrollUpLine(): void { this._xterm.scrollDisp(-1); } public scrollUpPage(): void { this._xterm.scrollPages(-1); } public scrollToTop(): void { this._xterm.scrollToTop(); } public clear(): void { this._xterm.clear(); } private _refreshSelectionContextKey() { const activePanel = this._panelService.getActivePanel(); const isActive = activePanel && activePanel.getId() === TERMINAL_PANEL_ID; this._terminalHasTextContextKey.set(isActive && this.hasSelection()); } protected _getCwd(shell: IShellLaunchConfig, root: Uri): string { if (shell.cwd) { return shell.cwd; } let cwd: string; // TODO: Handle non-existent customCwd if (!shell.ignoreConfigurationCwd) { // Evaluate custom cwd first const customCwd = this._configHelper.config.cwd; if (customCwd) { if (path.isAbsolute(customCwd)) { cwd = customCwd; } else if (root) { cwd = path.normalize(path.join(root.fsPath, customCwd)); } } } // If there was no custom cwd or it was relative with no workspace if (!cwd) { cwd = root ? root.fsPath : os.homedir(); } return TerminalInstance._sanitizeCwd(cwd); } protected _createProcess(shell: IShellLaunchConfig): void { const locale = this._configHelper.config.setLocaleVariables ? platform.locale : undefined; if (!shell.executable) { this._configHelper.mergeDefaultShellPathAndArgs(shell); } this._initialCwd = this._getCwd(this._shellLaunchConfig, this._historyService.getLastActiveWorkspaceRoot()); let envFromConfig: IStringDictionary<string>; if (platform.isWindows) { envFromConfig = { ...process.env }; for (let configKey in this._configHelper.config.env['windows']) { let actualKey = configKey; for (let envKey in envFromConfig) { if (configKey.toLowerCase() === envKey.toLowerCase()) { actualKey = envKey; break; } } envFromConfig[actualKey] = this._configHelper.config.env['windows'][configKey]; } } else { const platformKey = platform.isMacintosh ? 'osx' : 'linux'; envFromConfig = { ...process.env, ...this._configHelper.config.env[platformKey] }; } const env = TerminalInstance.createTerminalEnv(envFromConfig, shell, this._initialCwd, locale, this._cols, this._rows); this._process = cp.fork(Uri.parse(require.toUrl('bootstrap')).fsPath, ['--type=terminal'], { env, cwd: Uri.parse(path.dirname(require.toUrl('../node/terminalProcess'))).fsPath }); this._processState = ProcessState.LAUNCHING; if (shell.name) { this.setTitle(shell.name, false); } else { // Only listen for process title changes when a name is not provided this.setTitle(shell.executable, true); this._messageTitleListener = (message) => { if (message.type === 'title') { this.setTitle(message.content ? message.content : '', true); } }; this._process.on('message', this._messageTitleListener); } this._process.on('message', (message) => { if (message.type === 'pid') { this._processId = message.content; // Send any queued data that's waiting if (this._preLaunchInputQueue.length > 0) { this._process.send({ event: 'input', data: this._preLaunchInputQueue }); this._preLaunchInputQueue = null; } this._onProcessIdReady.fire(this); } }); this._process.on('exit', exitCode => this._onPtyProcessExit(exitCode)); setTimeout(() => { if (this._processState === ProcessState.LAUNCHING) { this._processState = ProcessState.RUNNING; } }, LAUNCHING_DURATION); } private _sendPtyDataToXterm(message: { type: string, content: string }): void { if (message.type === 'data') { if (this._widgetManager) { this._widgetManager.closeMessage(); } if (this._xterm) { this._xterm.write(message.content); } } } private _onPtyProcessExit(exitCode: number): void { // Prevent dispose functions being triggered multiple times if (this._isExiting) { return; } this._isExiting = true; this._process = null; let exitCodeMessage: string; if (exitCode) { exitCodeMessage = nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode); } // If the process is marked as launching then mark the process as killed // during launch. This typically means that there is a problem with the // shell and args. if (this._processState === ProcessState.LAUNCHING) { this._processState = ProcessState.KILLED_DURING_LAUNCH; } // If TerminalInstance did not know about the process exit then it was // triggered by the process, not on VS Code's side. if (this._processState === ProcessState.RUNNING) { this._processState = ProcessState.KILLED_BY_PROCESS; } // Only trigger wait on exit when the exit was triggered by the process, // not through the `workbench.action.terminal.kill` command if (this._processState === ProcessState.KILLED_BY_PROCESS && this._shellLaunchConfig.waitOnExit) { if (exitCode) { this._xterm.writeln(exitCodeMessage); } let message = typeof this._shellLaunchConfig.waitOnExit === 'string' ? this._shellLaunchConfig.waitOnExit : nls.localize('terminal.integrated.waitOnExit', 'Press any key to close the terminal'); // Bold the message and add an extra new line to make it stand out from the rest of the output message = `\n\x1b[1m${message}\x1b[0m`; this._xterm.writeln(message); // Disable all input if the terminal is exiting and listen for next keypress this._xterm.setOption('disableStdin', true); if (this._xterm.textarea) { this._attachPressAnyKeyToCloseListener(); } } else { this.dispose(); if (exitCode) { if (this._processState === ProcessState.KILLED_DURING_LAUNCH) { let args = ''; if (typeof this._shellLaunchConfig.args === 'string') { args = this._shellLaunchConfig.args; } else if (this._shellLaunchConfig.args && this._shellLaunchConfig.args.length) { args = ' ' + this._shellLaunchConfig.args.map(a => { if (typeof a === 'string' && a.indexOf(' ') !== -1) { return `'${a}'`; } return a; }).join(' '); } this._messageService.show(Severity.Error, nls.localize('terminal.integrated.launchFailed', 'The terminal process command `{0}{1}` failed to launch (exit code: {2})', this._shellLaunchConfig.executable, args, exitCode)); } else { this._messageService.show(Severity.Error, exitCodeMessage); } } } } private _attachPressAnyKeyToCloseListener() { this._processDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'keypress', (event: KeyboardEvent) => { this.dispose(); event.preventDefault(); })); } public reuseTerminal(shell?: IShellLaunchConfig): void { // Kill and clean up old process if (this._process) { this._process.removeAllListeners('exit'); if (this._process.connected) { this._process.kill(); } this._process = null; } lifecycle.dispose(this._processDisposables); this._processDisposables = []; // Ensure new processes' output starts at start of new line this._xterm.write('\n\x1b[G'); // Print initialText if specified if (shell.initialText) { this._xterm.writeln(shell.initialText); } // Initialize new process const oldTitle = this._title; this._createProcess(shell); if (oldTitle !== this._title) { this.setTitle(this._title, true); } this._process.on('message', (message) => this._sendPtyDataToXterm(message)); // Clean up waitOnExit state if (this._isExiting && this._shellLaunchConfig.waitOnExit) { this._xterm.setOption('disableStdin', false); this._isExiting = false; } // Set the new shell launch config this._shellLaunchConfig = shell; } // TODO: This should be private/protected // TODO: locale should not be optional public static createTerminalEnv(parentEnv: IStringDictionary<string>, shell: IShellLaunchConfig, cwd: string, locale?: string, cols?: number, rows?: number): IStringDictionary<string> { const env = shell.env ? shell.env : TerminalInstance._cloneEnv(parentEnv); env['PTYPID'] = process.pid.toString(); env['PTYSHELL'] = shell.executable; env['TERM_PROGRAM'] = 'vscode'; env['TERM_PROGRAM_VERSION'] = pkg.version; if (shell.args) { if (typeof shell.args === 'string') { env[`PTYSHELLCMDLINE`] = shell.args; } else { shell.args.forEach((arg, i) => env[`PTYSHELLARG${i}`] = arg); } } env['PTYCWD'] = cwd; env['LANG'] = TerminalInstance._getLangEnvVariable(locale); if (cols && rows) { env['PTYCOLS'] = cols.toString(); env['PTYROWS'] = rows.toString(); } env['AMD_ENTRYPOINT'] = 'vs/workbench/parts/terminal/node/terminalProcess'; return env; } public onData(listener: (data: string) => void): lifecycle.IDisposable { let callback = (message) => { if (message.type === 'data') { listener(message.content); } }; this._process.on('message', callback); return { dispose: () => { if (this._process) { this._process.removeListener('message', callback); } } }; } public onExit(listener: (exitCode: number) => void): lifecycle.IDisposable { if (this._process) { this._process.on('exit', listener); } return { dispose: () => { if (this._process) { this._process.removeListener('exit', listener); } } }; } private static _sanitizeCwd(cwd: string) { // Make the drive letter uppercase on Windows (see #9448) if (platform.platform === platform.Platform.Windows && cwd && cwd[1] === ':') { return cwd[0].toUpperCase() + cwd.substr(1); } return cwd; } private static _cloneEnv(env: IStringDictionary<string>): IStringDictionary<string> { const newEnv: IStringDictionary<string> = Object.create(null); Object.keys(env).forEach((key) => { newEnv[key] = env[key]; }); return newEnv; } private static _getLangEnvVariable(locale?: string) { const parts = locale ? locale.split('-') : []; const n = parts.length; if (n === 0) { // Fallback to en_US to prevent possible encoding issues. return 'en_US.UTF-8'; } if (n === 1) { // app.getLocale can return just a language without a variant, fill in the variant for // supported languages as many shells expect a 2-part locale. const languageVariants = { de: 'DE', en: 'US', es: 'ES', fr: 'FR', it: 'IT', ja: 'JP', ko: 'KR', ru: 'RU', zh: 'CN' }; if (parts[0] in languageVariants) { parts.push(languageVariants[parts[0]]); } } else { // Ensure the variant is uppercase parts[1] = parts[1].toUpperCase(); } return parts.join('_') + '.UTF-8'; } public updateConfig(): void { this._setCursorBlink(this._configHelper.config.cursorBlinking); this._setCursorStyle(this._configHelper.config.cursorStyle); this._setCommandsToSkipShell(this._configHelper.config.commandsToSkipShell); this._setScrollback(this._configHelper.config.scrollback); } private _setCursorBlink(blink: boolean): void { if (this._xterm && this._xterm.getOption('cursorBlink') !== blink) { this._xterm.setOption('cursorBlink', blink); this._xterm.refresh(0, this._xterm.rows - 1); } } private _setCursorStyle(style: string): void { if (this._xterm && this._xterm.getOption('cursorStyle') !== style) { // 'line' is used instead of bar in VS Code to be consistent with editor.cursorStyle const xtermOption = style === 'line' ? 'bar' : style; this._xterm.setOption('cursorStyle', xtermOption); } } private _setCommandsToSkipShell(commands: string[]): void { this._skipTerminalCommands = commands; } private _setScrollback(lineCount: number): void { if (this._xterm && this._xterm.getOption('scrollback') !== lineCount) { this._xterm.setOption('scrollback', lineCount); } } public layout(dimension: Dimension): void { const terminalWidth = this._evaluateColsAndRows(dimension.width, dimension.height); if (!terminalWidth) { return; } if (this._xterm) { this._xterm.resize(this._cols, this._rows); this._xterm.element.style.width = terminalWidth + 'px'; } this._processReady.then(() => { if (this._process && this._process.connected) { // The child process could aready be terminated try { this._process.send({ event: 'resize', cols: this._cols, rows: this._rows }); } catch (error) { // We tried to write to a closed pipe / channel. if (error.code !== 'EPIPE' && error.code !== 'ERR_IPC_CHANNEL_CLOSED') { throw (error); } } } }); } public static setTerminalProcessFactory(factory: ITerminalProcessFactory): void { this._terminalProcessFactory = factory; } public setTitle(title: string, eventFromProcess: boolean): void { if (!title) { return; } if (eventFromProcess) { title = path.basename(title); if (platform.isWindows) { // Remove the .exe extension title = title.split('.exe')[0]; } } else { // If the title has not been set by the API or the rename command, unregister the handler that // automatically updates the terminal name if (this._process && this._messageTitleListener) { this._process.removeListener('message', this._messageTitleListener); this._messageTitleListener = null; } } const didTitleChange = title !== this._title; this._title = title; if (didTitleChange) { this._onTitleChanged.fire(title); } } } registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { // Scrollbar const scrollbarSliderBackgroundColor = theme.getColor(scrollbarSliderBackground); if (scrollbarSliderBackgroundColor) { collector.addRule(` .monaco-workbench .panel.integrated-terminal .xterm.focus .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm:focus .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm:hover .xterm-viewport { background-color: ${scrollbarSliderBackgroundColor}; }` ); } const scrollbarSliderHoverBackgroundColor = theme.getColor(scrollbarSliderHoverBackground); if (scrollbarSliderHoverBackgroundColor) { collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:hover { background-color: ${scrollbarSliderHoverBackgroundColor}; }`); } const scrollbarSliderActiveBackgroundColor = theme.getColor(scrollbarSliderActiveBackground); if (scrollbarSliderActiveBackgroundColor) { collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:active { background-color: ${scrollbarSliderActiveBackgroundColor}; }`); } });
src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts
1
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.9887131452560425, 0.011673140339553356, 0.00016369273362215608, 0.00019487747340463102, 0.10033845901489258 ]
{ "id": 0, "code_window": [ "\t\tthis._processReady = new TPromise<void>(c => {\n", "\t\t\tthis.onProcessIdReady(() => c(void 0));\n", "\t\t});\n", "\n", "\t\tthis._initDimensions();\n", "\t\tthis._createProcess(this._shellLaunchConfig);\n", "\t\tthis._createXterm();\n", "\n", "\t\tif (platform.isWindows) {\n", "\t\t\tthis._processReady.then(() => {\n", "\t\t\t\tif (!this._isDisposed) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._createProcess();\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 159 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><style>.icon-canvas-transparent{opacity:0;fill:#f6f6f6}.icon-vs-out{fill:#f6f6f6}.icon-vs-bg{fill:#424242}.icon-vs-fg{fill:#f0eff1}</style><path class="icon-canvas-transparent" d="M16 0v16H0V0h16z" id="canvas"/><path class="icon-vs-out" d="M1 16V6h7V4c0-2.393 1.607-4 4-4s4 1.607 4 4v4h-3v8H1z" id="outline" style="display: none;"/><path class="icon-vs-fg" d="M3 8v6h8V8H3zm4.501 2.846L7.502 13h-1l-.001-2.153A.986.986 0 0 1 6 10a1 1 0 0 1 2 0 .984.984 0 0 1-.499.846z" id="iconFg" style="display: none;"/><path class="icon-vs-bg" d="M12 1c-1.822 0-3 1.178-3 3v3H2v8h10V7h-2V4c0-1.271.729-2 2-2s2 .729 2 2v3h1V4c0-1.822-1.178-3-3-3zm-1 7v6H3V8h8zm-3.499 2.846L7.502 13h-1l-.001-2.153A.986.986 0 0 1 6 10a1 1 0 0 1 2 0 .984.984 0 0 1-.499.846z" id="iconBg"/></svg>
src/vs/workbench/parts/output/browser/media/output_unlock.svg
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.0007151587633416057, 0.0007151587633416057, 0.0007151587633416057, 0.0007151587633416057, 0 ]
{ "id": 0, "code_window": [ "\t\tthis._processReady = new TPromise<void>(c => {\n", "\t\t\tthis.onProcessIdReady(() => c(void 0));\n", "\t\t});\n", "\n", "\t\tthis._initDimensions();\n", "\t\tthis._createProcess(this._shellLaunchConfig);\n", "\t\tthis._createXterm();\n", "\n", "\t\tif (platform.isWindows) {\n", "\t\t\tthis._processReady.then(() => {\n", "\t\t\t\tif (!this._isDisposed) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._createProcess();\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 159 }
function foo(): void { var a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; }
extensions/vscode-api-tests/testWorkspace/10linefile.ts
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.00017346240929327905, 0.00017292710253968835, 0.00017239179578609765, 0.00017292710253968835, 5.35306753590703e-7 ]
{ "id": 0, "code_window": [ "\t\tthis._processReady = new TPromise<void>(c => {\n", "\t\t\tthis.onProcessIdReady(() => c(void 0));\n", "\t\t});\n", "\n", "\t\tthis._initDimensions();\n", "\t\tthis._createProcess(this._shellLaunchConfig);\n", "\t\tthis._createXterm();\n", "\n", "\t\tif (platform.isWindows) {\n", "\t\t\tthis._processReady.then(() => {\n", "\t\t\t\tif (!this._isDisposed) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._createProcess();\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 159 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "textFileEditor": "Textdatei-Editor", "createFile": "Datei erstellen", "fileEditorWithInputAriaLabel": "{0}. Textdatei-Editor.", "fileEditorAriaLabel": "Textdatei-Editor" }
i18n/deu/src/vs/workbench/parts/files/browser/editors/textFileEditor.i18n.json
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.00017559666594024748, 0.00017558160470798612, 0.00017556654347572476, 0.00017558160470798612, 1.506123226135969e-8 ]
{ "id": 1, "code_window": [ "\n", "\t\treturn TerminalInstance._sanitizeCwd(cwd);\n", "\t}\n", "\n", "\tprotected _createProcess(shell: IShellLaunchConfig): void {\n", "\t\tconst locale = this._configHelper.config.setLocaleVariables ? platform.locale : undefined;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\tprotected _createProcess(): void {\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 558 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as cp from 'child_process'; import * as os from 'os'; import * as path from 'path'; import * as lifecycle from 'vs/base/common/lifecycle'; import * as nls from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import * as dom from 'vs/base/browser/dom'; import Event, { Emitter } from 'vs/base/common/event'; import Uri from 'vs/base/common/uri'; import { WindowsShellHelper } from 'vs/workbench/parts/terminal/electron-browser/windowsShellHelper'; import { Terminal as XTermTerminal } from 'xterm'; import { Dimension } from 'vs/base/browser/builder'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IMessageService, Severity } from 'vs/platform/message/common/message'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IStringDictionary } from 'vs/base/common/collections'; import { ITerminalInstance, KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED, TERMINAL_PANEL_ID, IShellLaunchConfig } from 'vs/workbench/parts/terminal/common/terminal'; import { ITerminalProcessFactory } from 'vs/workbench/parts/terminal/electron-browser/terminal'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { TabFocus } from 'vs/editor/common/config/commonEditorConfig'; import { TerminalConfigHelper } from 'vs/workbench/parts/terminal/electron-browser/terminalConfigHelper'; import { TerminalLinkHandler } from 'vs/workbench/parts/terminal/electron-browser/terminalLinkHandler'; import { TerminalWidgetManager } from 'vs/workbench/parts/terminal/browser/terminalWidgetManager'; import { registerThemingParticipant, ITheme, ICssStyleCollector } from 'vs/platform/theme/common/themeService'; import { scrollbarSliderBackground, scrollbarSliderHoverBackground, scrollbarSliderActiveBackground } from 'vs/platform/theme/common/colorRegistry'; import { TPromise } from 'vs/base/common/winjs.base'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { IHistoryService } from 'vs/workbench/services/history/common/history'; import pkg from 'vs/platform/node/package'; /** The amount of time to consider terminal errors to be related to the launch */ const LAUNCHING_DURATION = 500; // Enable search functionality in xterm.js instance XTermTerminal.loadAddon('search'); class StandardTerminalProcessFactory implements ITerminalProcessFactory { public create(env: { [key: string]: string }): cp.ChildProcess { return cp.fork('./terminalProcess', [], { env, cwd: Uri.parse(path.dirname(require.toUrl('./terminalProcess'))).fsPath }); } } enum ProcessState { // The process has not been initialized yet. UNINITIALIZED, // The process is currently launching, the process is marked as launching // for a short duration after being created and is helpful to indicate // whether the process died as a result of bad shell and args. LAUNCHING, // The process is running normally. RUNNING, // The process was killed during launch, likely as a result of bad shell and // args. KILLED_DURING_LAUNCH, // The process was killed by the user (the event originated from VS Code). KILLED_BY_USER, // The process was killed by itself, for example the shell crashed or `exit` // was run. KILLED_BY_PROCESS } export class TerminalInstance implements ITerminalInstance { private static readonly EOL_REGEX = /\r?\n/g; private static _terminalProcessFactory: ITerminalProcessFactory = new StandardTerminalProcessFactory(); private static _lastKnownDimensions: Dimension = null; private static _idCounter = 1; private _id: number; private _isExiting: boolean; private _hadFocusOnExit: boolean; private _isVisible: boolean; private _processState: ProcessState; private _processReady: TPromise<void>; private _isDisposed: boolean; private _onDisposed: Emitter<ITerminalInstance>; private _onDataForApi: Emitter<{ instance: ITerminalInstance, data: string }>; private _onProcessIdReady: Emitter<TerminalInstance>; private _onTitleChanged: Emitter<string>; private _process: cp.ChildProcess; private _processId: number; private _skipTerminalCommands: string[]; private _title: string; private _instanceDisposables: lifecycle.IDisposable[]; private _processDisposables: lifecycle.IDisposable[]; private _wrapperElement: HTMLDivElement; private _xterm: XTermTerminal; private _xtermElement: HTMLDivElement; private _terminalHasTextContextKey: IContextKey<boolean>; private _cols: number; private _rows: number; private _messageTitleListener: (message: { type: string, content: string }) => void; private _preLaunchInputQueue: string; private _initialCwd: string; private _windowsShellHelper: WindowsShellHelper; private _widgetManager: TerminalWidgetManager; private _linkHandler: TerminalLinkHandler; public get id(): number { return this._id; } public get processId(): number { return this._processId; } public get onDisposed(): Event<ITerminalInstance> { return this._onDisposed.event; } public get onDataForApi(): Event<{ instance: ITerminalInstance, data: string }> { return this._onDataForApi.event; } public get onProcessIdReady(): Event<TerminalInstance> { return this._onProcessIdReady.event; } public get onTitleChanged(): Event<string> { return this._onTitleChanged.event; } public get title(): string { return this._title; } public get hadFocusOnExit(): boolean { return this._hadFocusOnExit; } public get isTitleSetByProcess(): boolean { return !!this._messageTitleListener; } public constructor( private _terminalFocusContextKey: IContextKey<boolean>, private _configHelper: TerminalConfigHelper, private _container: HTMLElement, private _shellLaunchConfig: IShellLaunchConfig, @IContextKeyService private _contextKeyService: IContextKeyService, @IKeybindingService private _keybindingService: IKeybindingService, @IMessageService private _messageService: IMessageService, @IPanelService private _panelService: IPanelService, @IWorkspaceContextService private _contextService: IWorkspaceContextService, @IWorkbenchEditorService private _editorService: IWorkbenchEditorService, @IInstantiationService private _instantiationService: IInstantiationService, @IClipboardService private _clipboardService: IClipboardService, @IHistoryService private _historyService: IHistoryService ) { this._instanceDisposables = []; this._processDisposables = []; this._skipTerminalCommands = []; this._isExiting = false; this._hadFocusOnExit = false; this._processState = ProcessState.UNINITIALIZED; this._isVisible = false; this._isDisposed = false; this._id = TerminalInstance._idCounter++; this._terminalHasTextContextKey = KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED.bindTo(this._contextKeyService); this._preLaunchInputQueue = ''; this._onDisposed = new Emitter<TerminalInstance>(); this._onDataForApi = new Emitter<{ instance: ITerminalInstance, data: string }>(); this._onProcessIdReady = new Emitter<TerminalInstance>(); this._onTitleChanged = new Emitter<string>(); // Create a promise that resolves when the pty is ready this._processReady = new TPromise<void>(c => { this.onProcessIdReady(() => c(void 0)); }); this._initDimensions(); this._createProcess(this._shellLaunchConfig); this._createXterm(); if (platform.isWindows) { this._processReady.then(() => { if (!this._isDisposed) { import('vs/workbench/parts/terminal/electron-browser/windowsShellHelper').then((module) => { this._windowsShellHelper = new module.WindowsShellHelper(this._processId, this._shellLaunchConfig.executable, this, this._xterm); }); } }); } // Only attach xterm.js to the DOM if the terminal panel has been opened before. if (_container) { this.attachToElement(_container); } } public addDisposable(disposable: lifecycle.IDisposable): void { this._instanceDisposables.push(disposable); } private _initDimensions(): void { // The terminal panel needs to have been created if (!this._container) { return; } const computedStyle = window.getComputedStyle(this._container); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this._evaluateColsAndRows(width, height); } /** * Evaluates and sets the cols and rows of the terminal if possible. * @param width The width of the container. * @param height The height of the container. * @return The terminal's width if it requires a layout. */ private _evaluateColsAndRows(width: number, height: number): number { const dimension = this._getDimension(width, height); if (!dimension) { return null; } const font = this._configHelper.getFont(); this._cols = Math.max(Math.floor(dimension.width / font.charWidth), 1); this._rows = Math.max(Math.floor(dimension.height / font.charHeight), 1); return dimension.width; } private _getDimension(width: number, height: number): Dimension { // The font needs to have been initialized const font = this._configHelper.getFont(); if (!font || !font.charWidth || !font.charHeight) { return null; } // The panel is minimized if (!height) { return TerminalInstance._lastKnownDimensions; } else { // Trigger scroll event manually so that the viewport's scroll area is synced. This // needs to happen otherwise its scrollTop value is invalid when the panel is toggled as // it gets removed and then added back to the DOM (resetting scrollTop to 0). // Upstream issue: https://github.com/sourcelair/xterm.js/issues/291 if (this._xterm) { this._xterm.emit('scroll', this._xterm.ydisp); } } const outerContainer = document.querySelector('.terminal-outer-container'); const outerContainerStyle = getComputedStyle(outerContainer); const padding = parseInt(outerContainerStyle.paddingLeft.split('px')[0], 10); const paddingBottom = parseInt(outerContainerStyle.paddingBottom.split('px')[0], 10); // Use left padding as right padding, right padding is not defined in CSS just in case // xterm.js causes an unexpected overflow. const innerWidth = width - padding * 2; const innerHeight = height - paddingBottom; TerminalInstance._lastKnownDimensions = new Dimension(innerWidth, innerHeight); return TerminalInstance._lastKnownDimensions; } /** * Create xterm.js instance and attach data listeners. */ protected _createXterm(): void { this._xterm = new XTermTerminal({ scrollback: this._configHelper.config.scrollback }); if (this._shellLaunchConfig.initialText) { this._xterm.writeln(this._shellLaunchConfig.initialText); } this._process.on('message', (message) => this._sendPtyDataToXterm(message)); this._xterm.on('data', (data) => { if (this._processId) { // Send data if the pty is ready this._process.send({ event: 'input', data }); } else { // If the pty is not ready, queue the data received from // xterm.js until the pty is ready this._preLaunchInputQueue += data; } return false; }); this._linkHandler = this._instantiationService.createInstance(TerminalLinkHandler, this._xterm, platform.platform, this._initialCwd); this._linkHandler.registerLocalLinkHandler(); } public attachToElement(container: HTMLElement): void { if (this._wrapperElement) { throw new Error('The terminal instance has already been attached to a container'); } this._container = container; this._wrapperElement = document.createElement('div'); dom.addClass(this._wrapperElement, 'terminal-wrapper'); this._xtermElement = document.createElement('div'); this._xterm.open(this._xtermElement); this._xterm.attachCustomKeyEventHandler((event: KeyboardEvent) => { // Disable all input if the terminal is exiting if (this._isExiting) { return false; } // Skip processing by xterm.js of keyboard events that resolve to commands described // within commandsToSkipShell const standardKeyboardEvent = new StandardKeyboardEvent(event); const resolveResult = this._keybindingService.softDispatch(standardKeyboardEvent, standardKeyboardEvent.target); if (resolveResult && this._skipTerminalCommands.some(k => k === resolveResult.commandId)) { event.preventDefault(); return false; } // If tab focus mode is on, tab is not passed to the terminal if (TabFocus.getTabFocusMode() && event.keyCode === 9) { return false; } return undefined; }); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'mouseup', (event: KeyboardEvent) => { // Wait until mouseup has propagated through the DOM before // evaluating the new selection state. setTimeout(() => this._refreshSelectionContextKey(), 0); })); // xterm.js currently drops selection on keyup as we need to handle this case. this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'keyup', (event: KeyboardEvent) => { // Wait until keyup has propagated through the DOM before evaluating // the new selection state. setTimeout(() => this._refreshSelectionContextKey(), 0); })); const xtermHelper: HTMLElement = <HTMLElement>this._xterm.element.querySelector('.xterm-helpers'); const focusTrap: HTMLElement = document.createElement('div'); focusTrap.setAttribute('tabindex', '0'); dom.addClass(focusTrap, 'focus-trap'); this._instanceDisposables.push(dom.addDisposableListener(focusTrap, 'focus', (event: FocusEvent) => { let currentElement = focusTrap; while (!dom.hasClass(currentElement, 'part')) { currentElement = currentElement.parentElement; } const hidePanelElement = <HTMLElement>currentElement.querySelector('.hide-panel-action'); hidePanelElement.focus(); })); xtermHelper.insertBefore(focusTrap, this._xterm.textarea); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'focus', (event: KeyboardEvent) => { this._terminalFocusContextKey.set(true); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'blur', (event: KeyboardEvent) => { this._terminalFocusContextKey.reset(); this._refreshSelectionContextKey(); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'focus', (event: KeyboardEvent) => { this._terminalFocusContextKey.set(true); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'blur', (event: KeyboardEvent) => { this._terminalFocusContextKey.reset(); this._refreshSelectionContextKey(); })); this._wrapperElement.appendChild(this._xtermElement); this._widgetManager = new TerminalWidgetManager(this._configHelper, this._wrapperElement); this._linkHandler.setWidgetManager(this._widgetManager); this._container.appendChild(this._wrapperElement); const computedStyle = window.getComputedStyle(this._container); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this.layout(new Dimension(width, height)); this.setVisible(this._isVisible); this.updateConfig(); // If IShellLaunchConfig.waitOnExit was true and the process finished before the terminal // panel was initialized. if (this._xterm.getOption('disableStdin')) { this._attachPressAnyKeyToCloseListener(); } } public registerLinkMatcher(regex: RegExp, handler: (url: string) => void, matchIndex?: number, validationCallback?: (uri: string, element: HTMLElement, callback: (isValid: boolean) => void) => void): number { return this._linkHandler.registerCustomLinkHandler(regex, handler, matchIndex, validationCallback); } public deregisterLinkMatcher(linkMatcherId: number): void { this._xterm.deregisterLinkMatcher(linkMatcherId); } public hasSelection(): boolean { return this._xterm.hasSelection(); } public copySelection(): void { if (this.hasSelection()) { this._clipboardService.writeText(this._xterm.getSelection()); } else { this._messageService.show(Severity.Warning, nls.localize('terminal.integrated.copySelection.noSelection', 'The terminal has no selection to copy')); } } get selection(): string | undefined { return this.hasSelection() ? this._xterm.getSelection() : undefined; } public clearSelection(): void { this._xterm.clearSelection(); } public selectAll(): void { // Focus here to ensure the terminal context key is set this._xterm.focus(); this._xterm.selectAll(); } public findNext(term: string): boolean { return this._xterm.findNext(term); } public findPrevious(term: string): boolean { return this._xterm.findPrevious(term); } public notifyFindWidgetFocusChanged(isFocused: boolean): void { // In order to support escape to close the find widget when the terminal // is focused terminalFocus needs to be true when either the terminal or // the find widget are focused. this._terminalFocusContextKey.set(isFocused || document.activeElement === this._xterm.textarea); } public dispose(): void { if (this._windowsShellHelper) { this._windowsShellHelper.dispose(); } if (this._linkHandler) { this._linkHandler.dispose(); } if (this._xterm && this._xterm.element) { this._hadFocusOnExit = dom.hasClass(this._xterm.element, 'focus'); } if (this._wrapperElement) { this._container.removeChild(this._wrapperElement); this._wrapperElement = null; } if (this._xterm) { this._xterm.destroy(); this._xterm = null; } if (this._process) { if (this._process.connected) { // If the process was still connected this dispose came from // within VS Code, not the process, so mark the process as // killed by the user. this._processState = ProcessState.KILLED_BY_USER; this._process.send({ event: 'shutdown' }); } this._process = null; } if (!this._isDisposed) { this._isDisposed = true; this._onDisposed.fire(this); } this._processDisposables = lifecycle.dispose(this._processDisposables); this._instanceDisposables = lifecycle.dispose(this._instanceDisposables); } public focus(force?: boolean): void { if (!this._xterm) { return; } const text = window.getSelection().toString(); if (!text || force) { this._xterm.focus(); } } public paste(): void { this.focus(); document.execCommand('paste'); } public sendText(text: string, addNewLine: boolean): void { this._processReady.then(() => { // Normalize line endings to 'enter' press. text = text.replace(TerminalInstance.EOL_REGEX, '\r'); if (addNewLine && text.substr(text.length - 1) !== '\r') { text += '\r'; } this._process.send({ event: 'input', data: text }); }); } public setVisible(visible: boolean): void { this._isVisible = visible; if (this._wrapperElement) { dom.toggleClass(this._wrapperElement, 'active', visible); } if (visible && this._xterm) { // Trigger a manual scroll event which will sync the viewport and scroll bar. This is // necessary if the number of rows in the terminal has decreased while it was in the // background since scrollTop changes take no effect but the terminal's position does // change since the number of visible rows decreases. this._xterm.emit('scroll', this._xterm.ydisp); } } public scrollDownLine(): void { this._xterm.scrollDisp(1); } public scrollDownPage(): void { this._xterm.scrollPages(1); } public scrollToBottom(): void { this._xterm.scrollToBottom(); } public scrollUpLine(): void { this._xterm.scrollDisp(-1); } public scrollUpPage(): void { this._xterm.scrollPages(-1); } public scrollToTop(): void { this._xterm.scrollToTop(); } public clear(): void { this._xterm.clear(); } private _refreshSelectionContextKey() { const activePanel = this._panelService.getActivePanel(); const isActive = activePanel && activePanel.getId() === TERMINAL_PANEL_ID; this._terminalHasTextContextKey.set(isActive && this.hasSelection()); } protected _getCwd(shell: IShellLaunchConfig, root: Uri): string { if (shell.cwd) { return shell.cwd; } let cwd: string; // TODO: Handle non-existent customCwd if (!shell.ignoreConfigurationCwd) { // Evaluate custom cwd first const customCwd = this._configHelper.config.cwd; if (customCwd) { if (path.isAbsolute(customCwd)) { cwd = customCwd; } else if (root) { cwd = path.normalize(path.join(root.fsPath, customCwd)); } } } // If there was no custom cwd or it was relative with no workspace if (!cwd) { cwd = root ? root.fsPath : os.homedir(); } return TerminalInstance._sanitizeCwd(cwd); } protected _createProcess(shell: IShellLaunchConfig): void { const locale = this._configHelper.config.setLocaleVariables ? platform.locale : undefined; if (!shell.executable) { this._configHelper.mergeDefaultShellPathAndArgs(shell); } this._initialCwd = this._getCwd(this._shellLaunchConfig, this._historyService.getLastActiveWorkspaceRoot()); let envFromConfig: IStringDictionary<string>; if (platform.isWindows) { envFromConfig = { ...process.env }; for (let configKey in this._configHelper.config.env['windows']) { let actualKey = configKey; for (let envKey in envFromConfig) { if (configKey.toLowerCase() === envKey.toLowerCase()) { actualKey = envKey; break; } } envFromConfig[actualKey] = this._configHelper.config.env['windows'][configKey]; } } else { const platformKey = platform.isMacintosh ? 'osx' : 'linux'; envFromConfig = { ...process.env, ...this._configHelper.config.env[platformKey] }; } const env = TerminalInstance.createTerminalEnv(envFromConfig, shell, this._initialCwd, locale, this._cols, this._rows); this._process = cp.fork(Uri.parse(require.toUrl('bootstrap')).fsPath, ['--type=terminal'], { env, cwd: Uri.parse(path.dirname(require.toUrl('../node/terminalProcess'))).fsPath }); this._processState = ProcessState.LAUNCHING; if (shell.name) { this.setTitle(shell.name, false); } else { // Only listen for process title changes when a name is not provided this.setTitle(shell.executable, true); this._messageTitleListener = (message) => { if (message.type === 'title') { this.setTitle(message.content ? message.content : '', true); } }; this._process.on('message', this._messageTitleListener); } this._process.on('message', (message) => { if (message.type === 'pid') { this._processId = message.content; // Send any queued data that's waiting if (this._preLaunchInputQueue.length > 0) { this._process.send({ event: 'input', data: this._preLaunchInputQueue }); this._preLaunchInputQueue = null; } this._onProcessIdReady.fire(this); } }); this._process.on('exit', exitCode => this._onPtyProcessExit(exitCode)); setTimeout(() => { if (this._processState === ProcessState.LAUNCHING) { this._processState = ProcessState.RUNNING; } }, LAUNCHING_DURATION); } private _sendPtyDataToXterm(message: { type: string, content: string }): void { if (message.type === 'data') { if (this._widgetManager) { this._widgetManager.closeMessage(); } if (this._xterm) { this._xterm.write(message.content); } } } private _onPtyProcessExit(exitCode: number): void { // Prevent dispose functions being triggered multiple times if (this._isExiting) { return; } this._isExiting = true; this._process = null; let exitCodeMessage: string; if (exitCode) { exitCodeMessage = nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode); } // If the process is marked as launching then mark the process as killed // during launch. This typically means that there is a problem with the // shell and args. if (this._processState === ProcessState.LAUNCHING) { this._processState = ProcessState.KILLED_DURING_LAUNCH; } // If TerminalInstance did not know about the process exit then it was // triggered by the process, not on VS Code's side. if (this._processState === ProcessState.RUNNING) { this._processState = ProcessState.KILLED_BY_PROCESS; } // Only trigger wait on exit when the exit was triggered by the process, // not through the `workbench.action.terminal.kill` command if (this._processState === ProcessState.KILLED_BY_PROCESS && this._shellLaunchConfig.waitOnExit) { if (exitCode) { this._xterm.writeln(exitCodeMessage); } let message = typeof this._shellLaunchConfig.waitOnExit === 'string' ? this._shellLaunchConfig.waitOnExit : nls.localize('terminal.integrated.waitOnExit', 'Press any key to close the terminal'); // Bold the message and add an extra new line to make it stand out from the rest of the output message = `\n\x1b[1m${message}\x1b[0m`; this._xterm.writeln(message); // Disable all input if the terminal is exiting and listen for next keypress this._xterm.setOption('disableStdin', true); if (this._xterm.textarea) { this._attachPressAnyKeyToCloseListener(); } } else { this.dispose(); if (exitCode) { if (this._processState === ProcessState.KILLED_DURING_LAUNCH) { let args = ''; if (typeof this._shellLaunchConfig.args === 'string') { args = this._shellLaunchConfig.args; } else if (this._shellLaunchConfig.args && this._shellLaunchConfig.args.length) { args = ' ' + this._shellLaunchConfig.args.map(a => { if (typeof a === 'string' && a.indexOf(' ') !== -1) { return `'${a}'`; } return a; }).join(' '); } this._messageService.show(Severity.Error, nls.localize('terminal.integrated.launchFailed', 'The terminal process command `{0}{1}` failed to launch (exit code: {2})', this._shellLaunchConfig.executable, args, exitCode)); } else { this._messageService.show(Severity.Error, exitCodeMessage); } } } } private _attachPressAnyKeyToCloseListener() { this._processDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'keypress', (event: KeyboardEvent) => { this.dispose(); event.preventDefault(); })); } public reuseTerminal(shell?: IShellLaunchConfig): void { // Kill and clean up old process if (this._process) { this._process.removeAllListeners('exit'); if (this._process.connected) { this._process.kill(); } this._process = null; } lifecycle.dispose(this._processDisposables); this._processDisposables = []; // Ensure new processes' output starts at start of new line this._xterm.write('\n\x1b[G'); // Print initialText if specified if (shell.initialText) { this._xterm.writeln(shell.initialText); } // Initialize new process const oldTitle = this._title; this._createProcess(shell); if (oldTitle !== this._title) { this.setTitle(this._title, true); } this._process.on('message', (message) => this._sendPtyDataToXterm(message)); // Clean up waitOnExit state if (this._isExiting && this._shellLaunchConfig.waitOnExit) { this._xterm.setOption('disableStdin', false); this._isExiting = false; } // Set the new shell launch config this._shellLaunchConfig = shell; } // TODO: This should be private/protected // TODO: locale should not be optional public static createTerminalEnv(parentEnv: IStringDictionary<string>, shell: IShellLaunchConfig, cwd: string, locale?: string, cols?: number, rows?: number): IStringDictionary<string> { const env = shell.env ? shell.env : TerminalInstance._cloneEnv(parentEnv); env['PTYPID'] = process.pid.toString(); env['PTYSHELL'] = shell.executable; env['TERM_PROGRAM'] = 'vscode'; env['TERM_PROGRAM_VERSION'] = pkg.version; if (shell.args) { if (typeof shell.args === 'string') { env[`PTYSHELLCMDLINE`] = shell.args; } else { shell.args.forEach((arg, i) => env[`PTYSHELLARG${i}`] = arg); } } env['PTYCWD'] = cwd; env['LANG'] = TerminalInstance._getLangEnvVariable(locale); if (cols && rows) { env['PTYCOLS'] = cols.toString(); env['PTYROWS'] = rows.toString(); } env['AMD_ENTRYPOINT'] = 'vs/workbench/parts/terminal/node/terminalProcess'; return env; } public onData(listener: (data: string) => void): lifecycle.IDisposable { let callback = (message) => { if (message.type === 'data') { listener(message.content); } }; this._process.on('message', callback); return { dispose: () => { if (this._process) { this._process.removeListener('message', callback); } } }; } public onExit(listener: (exitCode: number) => void): lifecycle.IDisposable { if (this._process) { this._process.on('exit', listener); } return { dispose: () => { if (this._process) { this._process.removeListener('exit', listener); } } }; } private static _sanitizeCwd(cwd: string) { // Make the drive letter uppercase on Windows (see #9448) if (platform.platform === platform.Platform.Windows && cwd && cwd[1] === ':') { return cwd[0].toUpperCase() + cwd.substr(1); } return cwd; } private static _cloneEnv(env: IStringDictionary<string>): IStringDictionary<string> { const newEnv: IStringDictionary<string> = Object.create(null); Object.keys(env).forEach((key) => { newEnv[key] = env[key]; }); return newEnv; } private static _getLangEnvVariable(locale?: string) { const parts = locale ? locale.split('-') : []; const n = parts.length; if (n === 0) { // Fallback to en_US to prevent possible encoding issues. return 'en_US.UTF-8'; } if (n === 1) { // app.getLocale can return just a language without a variant, fill in the variant for // supported languages as many shells expect a 2-part locale. const languageVariants = { de: 'DE', en: 'US', es: 'ES', fr: 'FR', it: 'IT', ja: 'JP', ko: 'KR', ru: 'RU', zh: 'CN' }; if (parts[0] in languageVariants) { parts.push(languageVariants[parts[0]]); } } else { // Ensure the variant is uppercase parts[1] = parts[1].toUpperCase(); } return parts.join('_') + '.UTF-8'; } public updateConfig(): void { this._setCursorBlink(this._configHelper.config.cursorBlinking); this._setCursorStyle(this._configHelper.config.cursorStyle); this._setCommandsToSkipShell(this._configHelper.config.commandsToSkipShell); this._setScrollback(this._configHelper.config.scrollback); } private _setCursorBlink(blink: boolean): void { if (this._xterm && this._xterm.getOption('cursorBlink') !== blink) { this._xterm.setOption('cursorBlink', blink); this._xterm.refresh(0, this._xterm.rows - 1); } } private _setCursorStyle(style: string): void { if (this._xterm && this._xterm.getOption('cursorStyle') !== style) { // 'line' is used instead of bar in VS Code to be consistent with editor.cursorStyle const xtermOption = style === 'line' ? 'bar' : style; this._xterm.setOption('cursorStyle', xtermOption); } } private _setCommandsToSkipShell(commands: string[]): void { this._skipTerminalCommands = commands; } private _setScrollback(lineCount: number): void { if (this._xterm && this._xterm.getOption('scrollback') !== lineCount) { this._xterm.setOption('scrollback', lineCount); } } public layout(dimension: Dimension): void { const terminalWidth = this._evaluateColsAndRows(dimension.width, dimension.height); if (!terminalWidth) { return; } if (this._xterm) { this._xterm.resize(this._cols, this._rows); this._xterm.element.style.width = terminalWidth + 'px'; } this._processReady.then(() => { if (this._process && this._process.connected) { // The child process could aready be terminated try { this._process.send({ event: 'resize', cols: this._cols, rows: this._rows }); } catch (error) { // We tried to write to a closed pipe / channel. if (error.code !== 'EPIPE' && error.code !== 'ERR_IPC_CHANNEL_CLOSED') { throw (error); } } } }); } public static setTerminalProcessFactory(factory: ITerminalProcessFactory): void { this._terminalProcessFactory = factory; } public setTitle(title: string, eventFromProcess: boolean): void { if (!title) { return; } if (eventFromProcess) { title = path.basename(title); if (platform.isWindows) { // Remove the .exe extension title = title.split('.exe')[0]; } } else { // If the title has not been set by the API or the rename command, unregister the handler that // automatically updates the terminal name if (this._process && this._messageTitleListener) { this._process.removeListener('message', this._messageTitleListener); this._messageTitleListener = null; } } const didTitleChange = title !== this._title; this._title = title; if (didTitleChange) { this._onTitleChanged.fire(title); } } } registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { // Scrollbar const scrollbarSliderBackgroundColor = theme.getColor(scrollbarSliderBackground); if (scrollbarSliderBackgroundColor) { collector.addRule(` .monaco-workbench .panel.integrated-terminal .xterm.focus .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm:focus .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm:hover .xterm-viewport { background-color: ${scrollbarSliderBackgroundColor}; }` ); } const scrollbarSliderHoverBackgroundColor = theme.getColor(scrollbarSliderHoverBackground); if (scrollbarSliderHoverBackgroundColor) { collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:hover { background-color: ${scrollbarSliderHoverBackgroundColor}; }`); } const scrollbarSliderActiveBackgroundColor = theme.getColor(scrollbarSliderActiveBackground); if (scrollbarSliderActiveBackgroundColor) { collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:active { background-color: ${scrollbarSliderActiveBackgroundColor}; }`); } });
src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts
1
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.9989521503448486, 0.08719804137945175, 0.0001646086893742904, 0.0002737675094977021, 0.27448344230651855 ]
{ "id": 1, "code_window": [ "\n", "\t\treturn TerminalInstance._sanitizeCwd(cwd);\n", "\t}\n", "\n", "\tprotected _createProcess(shell: IShellLaunchConfig): void {\n", "\t\tconst locale = this._configHelper.config.setLocaleVariables ? platform.locale : undefined;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\tprotected _createProcess(): void {\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 558 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { localize } from 'vs/nls'; import { escapeRegExpCharacters } from 'vs/base/common/strings'; import { ITelemetryService, ITelemetryInfo, ITelemetryData } from 'vs/platform/telemetry/common/telemetry'; import { ITelemetryAppender } from 'vs/platform/telemetry/common/telemetryUtils'; import { optional } from 'vs/platform/instantiation/common/instantiation'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IConfigurationRegistry, Extensions } from 'vs/platform/configuration/common/configurationRegistry'; import { TPromise } from 'vs/base/common/winjs.base'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { cloneAndChange, mixin } from 'vs/base/common/objects'; import { Registry } from 'vs/platform/registry/common/platform'; export interface ITelemetryServiceConfig { appender: ITelemetryAppender; commonProperties?: TPromise<{ [name: string]: any }>; piiPaths?: string[]; userOptIn?: boolean; } export class TelemetryService implements ITelemetryService { static IDLE_START_EVENT_NAME = 'UserIdleStart'; static IDLE_STOP_EVENT_NAME = 'UserIdleStop'; _serviceBrand: any; private _appender: ITelemetryAppender; private _commonProperties: TPromise<{ [name: string]: any; }>; private _piiPaths: string[]; private _userOptIn: boolean; private _disposables: IDisposable[] = []; private _cleanupPatterns: [RegExp, string][] = []; constructor( config: ITelemetryServiceConfig, @optional(IConfigurationService) private _configurationService: IConfigurationService ) { this._appender = config.appender; this._commonProperties = config.commonProperties || TPromise.as({}); this._piiPaths = config.piiPaths || []; this._userOptIn = typeof config.userOptIn === 'undefined' ? true : config.userOptIn; // static cleanup patterns for: // #1 `file:///DANGEROUS/PATH/resources/app/Useful/Information` // #2 // Any other file path that doesn't match the approved form above should be cleaned. // #3 "Error: ENOENT; no such file or directory" is often followed with PII, clean it this._cleanupPatterns.push( [/file:\/\/\/.*?\/resources\/app\//gi, ''], [/file:\/\/\/.*/gi, ''], [/ENOENT: no such file or directory.*?\'([^\']+)\'/gi, 'ENOENT: no such file or directory'] ); for (let piiPath of this._piiPaths) { this._cleanupPatterns.push([new RegExp(escapeRegExpCharacters(piiPath), 'gi'), '']); } if (this._configurationService) { this._updateUserOptIn(); this._configurationService.onDidUpdateConfiguration(this._updateUserOptIn, this, this._disposables); this.publicLog('optInStatus', { optIn: this._userOptIn }); } } private _updateUserOptIn(): void { const config = this._configurationService.getConfiguration<any>(TELEMETRY_SECTION_ID); this._userOptIn = config ? config.enableTelemetry : this._userOptIn; } get isOptedIn(): boolean { return this._userOptIn; } getTelemetryInfo(): TPromise<ITelemetryInfo> { return this._commonProperties.then(values => { // well known properties let sessionId = values['sessionID']; let instanceId = values['common.instanceId']; let machineId = values['common.machineId']; return { sessionId, instanceId, machineId }; }); } dispose(): void { this._disposables = dispose(this._disposables); } publicLog(eventName: string, data?: ITelemetryData): TPromise<any> { // don't send events when the user is optout if (!this._userOptIn) { return TPromise.as(undefined); } return this._commonProperties.then(values => { // (first) add common properties data = mixin(data, values); // (last) remove all PII from data data = cloneAndChange(data, value => { if (typeof value === 'string') { return this._cleanupInfo(value); } return undefined; }); this._appender.log(eventName, data); }, err => { // unsure what to do now... console.error(err); }); } private _cleanupInfo(stack: string): string { // sanitize with configured cleanup patterns for (let tuple of this._cleanupPatterns) { let [regexp, replaceValue] = tuple; stack = stack.replace(regexp, replaceValue); } return stack; } } const TELEMETRY_SECTION_ID = 'telemetry'; Registry.as<IConfigurationRegistry>(Extensions.Configuration).registerConfiguration({ 'id': TELEMETRY_SECTION_ID, 'order': 110, 'type': 'object', 'title': localize('telemetryConfigurationTitle', "Telemetry"), 'properties': { 'telemetry.enableTelemetry': { 'type': 'boolean', 'description': localize('telemetry.enableTelemetry', "Enable usage data and errors to be sent to Microsoft."), 'default': true } } });
src/vs/platform/telemetry/common/telemetryService.ts
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.001451353426091373, 0.00024870538618415594, 0.00016381453315261751, 0.00016872797277756035, 0.0003105362120550126 ]
{ "id": 1, "code_window": [ "\n", "\t\treturn TerminalInstance._sanitizeCwd(cwd);\n", "\t}\n", "\n", "\tprotected _createProcess(shell: IShellLaunchConfig): void {\n", "\t\tconst locale = this._configHelper.config.setLocaleVariables ? platform.locale : undefined;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\tprotected _createProcess(): void {\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 558 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { IColorTheme, ITokenColorizationSetting } from 'vs/workbench/services/themes/common/workbenchThemeService'; export function findMatchingThemeRule(theme: IColorTheme, scopes: string[]): ThemeRule { for (let i = scopes.length - 1; i >= 0; i--) { let parentScopes = scopes.slice(0, i); let scope = scopes[i]; let r = findMatchingThemeRule2(theme, scope, parentScopes); if (r) { return r; } } return null; } function findMatchingThemeRule2(theme: IColorTheme, scope: string, parentScopes: string[]): ThemeRule { let result: ThemeRule = null; // Loop backwards, to ensure the last most specific rule wins for (let i = theme.tokenColors.length - 1; i >= 0; i--) { let rule = theme.tokenColors[i]; if (!rule.settings.foreground) { continue; } let selectors: string[]; if (typeof rule.scope === 'string') { selectors = rule.scope.split(/,/).map(scope => scope.trim()); } else if (Array.isArray(rule.scope)) { selectors = rule.scope; } else { continue; } for (let j = 0, lenJ = selectors.length; j < lenJ; j++) { let rawSelector = selectors[j]; let themeRule = new ThemeRule(rawSelector, rule.settings); if (themeRule.matches(scope, parentScopes)) { if (themeRule.isMoreSpecific(result)) { result = themeRule; } } } } return result; } export class ThemeRule { readonly rawSelector: string; readonly settings: ITokenColorizationSetting; readonly scope: string; readonly parentScopes: string[]; constructor(rawSelector: string, settings: ITokenColorizationSetting) { this.rawSelector = rawSelector; this.settings = settings; let rawSelectorPieces = this.rawSelector.split(/ /); this.scope = rawSelectorPieces[rawSelectorPieces.length - 1]; this.parentScopes = rawSelectorPieces.slice(0, rawSelectorPieces.length - 1); } public matches(scope: string, parentScopes: string[]): boolean { return ThemeRule._matches(this.scope, this.parentScopes, scope, parentScopes); } private static _cmp(a: ThemeRule, b: ThemeRule): number { if (a === null && b === null) { return 0; } if (a === null) { // b > a return -1; } if (b === null) { // a > b return 1; } if (a.scope.length !== b.scope.length) { // longer scope length > shorter scope length return a.scope.length - b.scope.length; } const aParentScopesLen = a.parentScopes.length; const bParentScopesLen = b.parentScopes.length; if (aParentScopesLen !== bParentScopesLen) { // more parents > less parents return aParentScopesLen - bParentScopesLen; } for (let i = 0; i < aParentScopesLen; i++) { var aLen = a.parentScopes[i].length; var bLen = b.parentScopes[i].length; if (aLen !== bLen) { return aLen - bLen; } } return 0; } public isMoreSpecific(other: ThemeRule): boolean { return (ThemeRule._cmp(this, other) > 0); } private static _matchesOne(selectorScope: string, scope: string): boolean { let selectorPrefix = selectorScope + '.'; if (selectorScope === scope || scope.substring(0, selectorPrefix.length) === selectorPrefix) { return true; } return false; } private static _matches(selectorScope: string, selectorParentScopes: string[], scope: string, parentScopes: string[]): boolean { if (!this._matchesOne(selectorScope, scope)) { return false; } let selectorParentIndex = selectorParentScopes.length - 1; let parentIndex = parentScopes.length - 1; while (selectorParentIndex >= 0 && parentIndex >= 0) { if (this._matchesOne(selectorParentScopes[selectorParentIndex], parentScopes[parentIndex])) { selectorParentIndex--; } parentIndex--; } if (selectorParentIndex === -1) { return true; } return false; } }
src/vs/workbench/services/textMate/electron-browser/TMHelper.ts
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.0001758186554070562, 0.00017220016161445528, 0.00016796027193777263, 0.0001718697603791952, 0.000002291094460815657 ]
{ "id": 1, "code_window": [ "\n", "\t\treturn TerminalInstance._sanitizeCwd(cwd);\n", "\t}\n", "\n", "\tprotected _createProcess(shell: IShellLaunchConfig): void {\n", "\t\tconst locale = this._configHelper.config.setLocaleVariables ? platform.locale : undefined;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\tprotected _createProcess(): void {\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 558 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import URI from 'vs/base/common/uri'; import { TestEditorService, workbenchInstantiationService } from 'vs/workbench/test/workbenchTestServices'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IModeService } from 'vs/editor/common/services/modeService'; import { ModeServiceImpl } from 'vs/editor/common/services/modeServiceImpl'; import WorkbenchEditorService = require('vs/workbench/services/editor/common/editorService'); import { RangeHighlightDecorations } from 'vs/workbench/common/editor/rangeDecorations'; import { Model } from 'vs/editor/common/model/model'; import { mockCodeEditor } from 'vs/editor/test/common/mocks/mockCodeEditor'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { IEditorInput } from 'vs/platform/editor/common/editor'; import { FileEditorInput } from 'vs/workbench/parts/files/common/editors/fileEditorInput'; import { TextModel } from 'vs/editor/common/model/textModel'; import { Range, IRange } from 'vs/editor/common/core/range'; import { Position } from 'vs/editor/common/core/position'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { ModelServiceImpl } from 'vs/editor/common/services/modelServiceImpl'; import { CoreNavigationCommands } from 'vs/editor/common/controller/coreCommands'; suite('Editor - Range decorations', () => { let instantiationService: TestInstantiationService; let editorService: WorkbenchEditorService.IWorkbenchEditorService; let modelService: IModelService; let modeService: IModeService; let codeEditor: editorCommon.ICommonCodeEditor; let model: Model; let text: string; let testObject: RangeHighlightDecorations; let modelsToDispose: Model[] = []; setup(() => { instantiationService = <TestInstantiationService>workbenchInstantiationService(); editorService = <WorkbenchEditorService.IWorkbenchEditorService>instantiationService.stub(WorkbenchEditorService.IWorkbenchEditorService, new TestEditorService()); modeService = instantiationService.stub(IModeService, ModeServiceImpl); modelService = <IModelService>instantiationService.stub(IModelService, stubModelService(instantiationService)); text = 'LINE1' + '\n' + 'LINE2' + '\n' + 'LINE3' + '\n' + 'LINE4' + '\r\n' + 'LINE5'; model = aModel(URI.file('some_file')); codeEditor = mockCodeEditor([], { model }); mockEditorService(codeEditor.getModel().uri); instantiationService.stub(WorkbenchEditorService.IWorkbenchEditorService, 'getActiveEditor', { getControl: () => { return codeEditor; } }); testObject = instantiationService.createInstance(RangeHighlightDecorations); }); teardown(() => { codeEditor.dispose(); modelsToDispose.forEach(model => model.dispose()); }); test('highlight range for the resource if it is an active editor', function () { let range: IRange = { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 }; testObject.highlightRange({ resource: model.uri, range }); let actuals = rangeHighlightDecorations(model); assert.deepEqual([range], actuals); }); test('remove highlight range', function () { testObject.highlightRange({ resource: model.uri, range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 } }); testObject.removeHighlightRange(); let actuals = rangeHighlightDecorations(model); assert.deepEqual([], actuals); }); test('highlight range for the resource removes previous highlight', function () { testObject.highlightRange({ resource: model.uri, range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 } }); let range: IRange = { startLineNumber: 2, startColumn: 2, endLineNumber: 4, endColumn: 3 }; testObject.highlightRange({ resource: model.uri, range }); let actuals = rangeHighlightDecorations(model); assert.deepEqual([range], actuals); }); test('highlight range for a new resource removes highlight of previous resource', function () { testObject.highlightRange({ resource: model.uri, range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 } }); let anotherModel = prepareActiveEditor('anotherModel'); let range: IRange = { startLineNumber: 2, startColumn: 2, endLineNumber: 4, endColumn: 3 }; testObject.highlightRange({ resource: anotherModel.uri, range }); let actuals = rangeHighlightDecorations(model); assert.deepEqual([], actuals); actuals = rangeHighlightDecorations(anotherModel); assert.deepEqual([range], actuals); }); test('highlight is removed on model change', function () { testObject.highlightRange({ resource: model.uri, range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 } }); prepareActiveEditor('anotherModel'); let actuals = rangeHighlightDecorations(model); assert.deepEqual([], actuals); }); test('highlight is removed on cursor position change', function () { testObject.highlightRange({ resource: model.uri, range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 } }); codeEditor.trigger('mouse', CoreNavigationCommands.MoveTo.id, { position: new Position(2, 1) }); let actuals = rangeHighlightDecorations(model); assert.deepEqual([], actuals); }); test('range is not highlight if not active editor', function () { let model = aModel(URI.file('some model')); testObject.highlightRange({ resource: model.uri, range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 } }); let actuals = rangeHighlightDecorations(model); assert.deepEqual([], actuals); }); test('previous highlight is not removed if not active editor', function () { let range: IRange = { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 }; testObject.highlightRange({ resource: model.uri, range }); let model1 = aModel(URI.file('some model')); testObject.highlightRange({ resource: model1.uri, range: { startLineNumber: 2, startColumn: 1, endLineNumber: 2, endColumn: 1 } }); let actuals = rangeHighlightDecorations(model); assert.deepEqual([range], actuals); }); function prepareActiveEditor(resource: string): Model { let model = aModel(URI.file(resource)); codeEditor.setModel(model); mockEditorService(model.uri); return model; } function aModel(resource: URI, content: string = text): Model { let model = Model.createFromString(content, TextModel.DEFAULT_CREATION_OPTIONS, null, resource); modelsToDispose.push(model); return model; } function mockEditorService(editorInput: IEditorInput); function mockEditorService(resource: URI); function mockEditorService(arg: any) { let editorInput: IEditorInput = arg instanceof URI ? instantiationService.createInstance(FileEditorInput, arg, void 0) : arg; instantiationService.stub(WorkbenchEditorService.IWorkbenchEditorService, 'getActiveEditorInput', editorInput); } function rangeHighlightDecorations(m: Model): IRange[] { let rangeHighlights: IRange[] = []; for (let dec of m.getAllDecorations()) { if (dec.options.className === 'rangeHighlight') { rangeHighlights.push(dec.range); } } rangeHighlights.sort(Range.compareRangesUsingStarts); return rangeHighlights; } function stubModelService(instantiationService: TestInstantiationService): IModelService { instantiationService.stub(IConfigurationService, new TestConfigurationService()); return instantiationService.createInstance(ModelServiceImpl); } });
src/vs/workbench/test/common/editor/rangeDecorations.test.ts
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.0001768102083588019, 0.00017393344023730606, 0.0001678976695984602, 0.00017500888498034328, 0.0000026946029265673133 ]
{ "id": 2, "code_window": [ "\t\tconst locale = this._configHelper.config.setLocaleVariables ? platform.locale : undefined;\n", "\t\tif (!shell.executable) {\n", "\t\t\tthis._configHelper.mergeDefaultShellPathAndArgs(shell);\n", "\t\t}\n", "\t\tthis._initialCwd = this._getCwd(this._shellLaunchConfig, this._historyService.getLastActiveWorkspaceRoot());\n", "\t\tlet envFromConfig: IStringDictionary<string>;\n", "\t\tif (platform.isWindows) {\n", "\t\t\tenvFromConfig = { ...process.env };\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (!this._shellLaunchConfig.executable) {\n", "\t\t\tthis._configHelper.mergeDefaultShellPathAndArgs(this._shellLaunchConfig);\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 560 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as cp from 'child_process'; import * as os from 'os'; import * as path from 'path'; import * as lifecycle from 'vs/base/common/lifecycle'; import * as nls from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import * as dom from 'vs/base/browser/dom'; import Event, { Emitter } from 'vs/base/common/event'; import Uri from 'vs/base/common/uri'; import { WindowsShellHelper } from 'vs/workbench/parts/terminal/electron-browser/windowsShellHelper'; import { Terminal as XTermTerminal } from 'xterm'; import { Dimension } from 'vs/base/browser/builder'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IMessageService, Severity } from 'vs/platform/message/common/message'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IStringDictionary } from 'vs/base/common/collections'; import { ITerminalInstance, KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED, TERMINAL_PANEL_ID, IShellLaunchConfig } from 'vs/workbench/parts/terminal/common/terminal'; import { ITerminalProcessFactory } from 'vs/workbench/parts/terminal/electron-browser/terminal'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { TabFocus } from 'vs/editor/common/config/commonEditorConfig'; import { TerminalConfigHelper } from 'vs/workbench/parts/terminal/electron-browser/terminalConfigHelper'; import { TerminalLinkHandler } from 'vs/workbench/parts/terminal/electron-browser/terminalLinkHandler'; import { TerminalWidgetManager } from 'vs/workbench/parts/terminal/browser/terminalWidgetManager'; import { registerThemingParticipant, ITheme, ICssStyleCollector } from 'vs/platform/theme/common/themeService'; import { scrollbarSliderBackground, scrollbarSliderHoverBackground, scrollbarSliderActiveBackground } from 'vs/platform/theme/common/colorRegistry'; import { TPromise } from 'vs/base/common/winjs.base'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { IHistoryService } from 'vs/workbench/services/history/common/history'; import pkg from 'vs/platform/node/package'; /** The amount of time to consider terminal errors to be related to the launch */ const LAUNCHING_DURATION = 500; // Enable search functionality in xterm.js instance XTermTerminal.loadAddon('search'); class StandardTerminalProcessFactory implements ITerminalProcessFactory { public create(env: { [key: string]: string }): cp.ChildProcess { return cp.fork('./terminalProcess', [], { env, cwd: Uri.parse(path.dirname(require.toUrl('./terminalProcess'))).fsPath }); } } enum ProcessState { // The process has not been initialized yet. UNINITIALIZED, // The process is currently launching, the process is marked as launching // for a short duration after being created and is helpful to indicate // whether the process died as a result of bad shell and args. LAUNCHING, // The process is running normally. RUNNING, // The process was killed during launch, likely as a result of bad shell and // args. KILLED_DURING_LAUNCH, // The process was killed by the user (the event originated from VS Code). KILLED_BY_USER, // The process was killed by itself, for example the shell crashed or `exit` // was run. KILLED_BY_PROCESS } export class TerminalInstance implements ITerminalInstance { private static readonly EOL_REGEX = /\r?\n/g; private static _terminalProcessFactory: ITerminalProcessFactory = new StandardTerminalProcessFactory(); private static _lastKnownDimensions: Dimension = null; private static _idCounter = 1; private _id: number; private _isExiting: boolean; private _hadFocusOnExit: boolean; private _isVisible: boolean; private _processState: ProcessState; private _processReady: TPromise<void>; private _isDisposed: boolean; private _onDisposed: Emitter<ITerminalInstance>; private _onDataForApi: Emitter<{ instance: ITerminalInstance, data: string }>; private _onProcessIdReady: Emitter<TerminalInstance>; private _onTitleChanged: Emitter<string>; private _process: cp.ChildProcess; private _processId: number; private _skipTerminalCommands: string[]; private _title: string; private _instanceDisposables: lifecycle.IDisposable[]; private _processDisposables: lifecycle.IDisposable[]; private _wrapperElement: HTMLDivElement; private _xterm: XTermTerminal; private _xtermElement: HTMLDivElement; private _terminalHasTextContextKey: IContextKey<boolean>; private _cols: number; private _rows: number; private _messageTitleListener: (message: { type: string, content: string }) => void; private _preLaunchInputQueue: string; private _initialCwd: string; private _windowsShellHelper: WindowsShellHelper; private _widgetManager: TerminalWidgetManager; private _linkHandler: TerminalLinkHandler; public get id(): number { return this._id; } public get processId(): number { return this._processId; } public get onDisposed(): Event<ITerminalInstance> { return this._onDisposed.event; } public get onDataForApi(): Event<{ instance: ITerminalInstance, data: string }> { return this._onDataForApi.event; } public get onProcessIdReady(): Event<TerminalInstance> { return this._onProcessIdReady.event; } public get onTitleChanged(): Event<string> { return this._onTitleChanged.event; } public get title(): string { return this._title; } public get hadFocusOnExit(): boolean { return this._hadFocusOnExit; } public get isTitleSetByProcess(): boolean { return !!this._messageTitleListener; } public constructor( private _terminalFocusContextKey: IContextKey<boolean>, private _configHelper: TerminalConfigHelper, private _container: HTMLElement, private _shellLaunchConfig: IShellLaunchConfig, @IContextKeyService private _contextKeyService: IContextKeyService, @IKeybindingService private _keybindingService: IKeybindingService, @IMessageService private _messageService: IMessageService, @IPanelService private _panelService: IPanelService, @IWorkspaceContextService private _contextService: IWorkspaceContextService, @IWorkbenchEditorService private _editorService: IWorkbenchEditorService, @IInstantiationService private _instantiationService: IInstantiationService, @IClipboardService private _clipboardService: IClipboardService, @IHistoryService private _historyService: IHistoryService ) { this._instanceDisposables = []; this._processDisposables = []; this._skipTerminalCommands = []; this._isExiting = false; this._hadFocusOnExit = false; this._processState = ProcessState.UNINITIALIZED; this._isVisible = false; this._isDisposed = false; this._id = TerminalInstance._idCounter++; this._terminalHasTextContextKey = KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED.bindTo(this._contextKeyService); this._preLaunchInputQueue = ''; this._onDisposed = new Emitter<TerminalInstance>(); this._onDataForApi = new Emitter<{ instance: ITerminalInstance, data: string }>(); this._onProcessIdReady = new Emitter<TerminalInstance>(); this._onTitleChanged = new Emitter<string>(); // Create a promise that resolves when the pty is ready this._processReady = new TPromise<void>(c => { this.onProcessIdReady(() => c(void 0)); }); this._initDimensions(); this._createProcess(this._shellLaunchConfig); this._createXterm(); if (platform.isWindows) { this._processReady.then(() => { if (!this._isDisposed) { import('vs/workbench/parts/terminal/electron-browser/windowsShellHelper').then((module) => { this._windowsShellHelper = new module.WindowsShellHelper(this._processId, this._shellLaunchConfig.executable, this, this._xterm); }); } }); } // Only attach xterm.js to the DOM if the terminal panel has been opened before. if (_container) { this.attachToElement(_container); } } public addDisposable(disposable: lifecycle.IDisposable): void { this._instanceDisposables.push(disposable); } private _initDimensions(): void { // The terminal panel needs to have been created if (!this._container) { return; } const computedStyle = window.getComputedStyle(this._container); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this._evaluateColsAndRows(width, height); } /** * Evaluates and sets the cols and rows of the terminal if possible. * @param width The width of the container. * @param height The height of the container. * @return The terminal's width if it requires a layout. */ private _evaluateColsAndRows(width: number, height: number): number { const dimension = this._getDimension(width, height); if (!dimension) { return null; } const font = this._configHelper.getFont(); this._cols = Math.max(Math.floor(dimension.width / font.charWidth), 1); this._rows = Math.max(Math.floor(dimension.height / font.charHeight), 1); return dimension.width; } private _getDimension(width: number, height: number): Dimension { // The font needs to have been initialized const font = this._configHelper.getFont(); if (!font || !font.charWidth || !font.charHeight) { return null; } // The panel is minimized if (!height) { return TerminalInstance._lastKnownDimensions; } else { // Trigger scroll event manually so that the viewport's scroll area is synced. This // needs to happen otherwise its scrollTop value is invalid when the panel is toggled as // it gets removed and then added back to the DOM (resetting scrollTop to 0). // Upstream issue: https://github.com/sourcelair/xterm.js/issues/291 if (this._xterm) { this._xterm.emit('scroll', this._xterm.ydisp); } } const outerContainer = document.querySelector('.terminal-outer-container'); const outerContainerStyle = getComputedStyle(outerContainer); const padding = parseInt(outerContainerStyle.paddingLeft.split('px')[0], 10); const paddingBottom = parseInt(outerContainerStyle.paddingBottom.split('px')[0], 10); // Use left padding as right padding, right padding is not defined in CSS just in case // xterm.js causes an unexpected overflow. const innerWidth = width - padding * 2; const innerHeight = height - paddingBottom; TerminalInstance._lastKnownDimensions = new Dimension(innerWidth, innerHeight); return TerminalInstance._lastKnownDimensions; } /** * Create xterm.js instance and attach data listeners. */ protected _createXterm(): void { this._xterm = new XTermTerminal({ scrollback: this._configHelper.config.scrollback }); if (this._shellLaunchConfig.initialText) { this._xterm.writeln(this._shellLaunchConfig.initialText); } this._process.on('message', (message) => this._sendPtyDataToXterm(message)); this._xterm.on('data', (data) => { if (this._processId) { // Send data if the pty is ready this._process.send({ event: 'input', data }); } else { // If the pty is not ready, queue the data received from // xterm.js until the pty is ready this._preLaunchInputQueue += data; } return false; }); this._linkHandler = this._instantiationService.createInstance(TerminalLinkHandler, this._xterm, platform.platform, this._initialCwd); this._linkHandler.registerLocalLinkHandler(); } public attachToElement(container: HTMLElement): void { if (this._wrapperElement) { throw new Error('The terminal instance has already been attached to a container'); } this._container = container; this._wrapperElement = document.createElement('div'); dom.addClass(this._wrapperElement, 'terminal-wrapper'); this._xtermElement = document.createElement('div'); this._xterm.open(this._xtermElement); this._xterm.attachCustomKeyEventHandler((event: KeyboardEvent) => { // Disable all input if the terminal is exiting if (this._isExiting) { return false; } // Skip processing by xterm.js of keyboard events that resolve to commands described // within commandsToSkipShell const standardKeyboardEvent = new StandardKeyboardEvent(event); const resolveResult = this._keybindingService.softDispatch(standardKeyboardEvent, standardKeyboardEvent.target); if (resolveResult && this._skipTerminalCommands.some(k => k === resolveResult.commandId)) { event.preventDefault(); return false; } // If tab focus mode is on, tab is not passed to the terminal if (TabFocus.getTabFocusMode() && event.keyCode === 9) { return false; } return undefined; }); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'mouseup', (event: KeyboardEvent) => { // Wait until mouseup has propagated through the DOM before // evaluating the new selection state. setTimeout(() => this._refreshSelectionContextKey(), 0); })); // xterm.js currently drops selection on keyup as we need to handle this case. this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'keyup', (event: KeyboardEvent) => { // Wait until keyup has propagated through the DOM before evaluating // the new selection state. setTimeout(() => this._refreshSelectionContextKey(), 0); })); const xtermHelper: HTMLElement = <HTMLElement>this._xterm.element.querySelector('.xterm-helpers'); const focusTrap: HTMLElement = document.createElement('div'); focusTrap.setAttribute('tabindex', '0'); dom.addClass(focusTrap, 'focus-trap'); this._instanceDisposables.push(dom.addDisposableListener(focusTrap, 'focus', (event: FocusEvent) => { let currentElement = focusTrap; while (!dom.hasClass(currentElement, 'part')) { currentElement = currentElement.parentElement; } const hidePanelElement = <HTMLElement>currentElement.querySelector('.hide-panel-action'); hidePanelElement.focus(); })); xtermHelper.insertBefore(focusTrap, this._xterm.textarea); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'focus', (event: KeyboardEvent) => { this._terminalFocusContextKey.set(true); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'blur', (event: KeyboardEvent) => { this._terminalFocusContextKey.reset(); this._refreshSelectionContextKey(); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'focus', (event: KeyboardEvent) => { this._terminalFocusContextKey.set(true); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'blur', (event: KeyboardEvent) => { this._terminalFocusContextKey.reset(); this._refreshSelectionContextKey(); })); this._wrapperElement.appendChild(this._xtermElement); this._widgetManager = new TerminalWidgetManager(this._configHelper, this._wrapperElement); this._linkHandler.setWidgetManager(this._widgetManager); this._container.appendChild(this._wrapperElement); const computedStyle = window.getComputedStyle(this._container); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this.layout(new Dimension(width, height)); this.setVisible(this._isVisible); this.updateConfig(); // If IShellLaunchConfig.waitOnExit was true and the process finished before the terminal // panel was initialized. if (this._xterm.getOption('disableStdin')) { this._attachPressAnyKeyToCloseListener(); } } public registerLinkMatcher(regex: RegExp, handler: (url: string) => void, matchIndex?: number, validationCallback?: (uri: string, element: HTMLElement, callback: (isValid: boolean) => void) => void): number { return this._linkHandler.registerCustomLinkHandler(regex, handler, matchIndex, validationCallback); } public deregisterLinkMatcher(linkMatcherId: number): void { this._xterm.deregisterLinkMatcher(linkMatcherId); } public hasSelection(): boolean { return this._xterm.hasSelection(); } public copySelection(): void { if (this.hasSelection()) { this._clipboardService.writeText(this._xterm.getSelection()); } else { this._messageService.show(Severity.Warning, nls.localize('terminal.integrated.copySelection.noSelection', 'The terminal has no selection to copy')); } } get selection(): string | undefined { return this.hasSelection() ? this._xterm.getSelection() : undefined; } public clearSelection(): void { this._xterm.clearSelection(); } public selectAll(): void { // Focus here to ensure the terminal context key is set this._xterm.focus(); this._xterm.selectAll(); } public findNext(term: string): boolean { return this._xterm.findNext(term); } public findPrevious(term: string): boolean { return this._xterm.findPrevious(term); } public notifyFindWidgetFocusChanged(isFocused: boolean): void { // In order to support escape to close the find widget when the terminal // is focused terminalFocus needs to be true when either the terminal or // the find widget are focused. this._terminalFocusContextKey.set(isFocused || document.activeElement === this._xterm.textarea); } public dispose(): void { if (this._windowsShellHelper) { this._windowsShellHelper.dispose(); } if (this._linkHandler) { this._linkHandler.dispose(); } if (this._xterm && this._xterm.element) { this._hadFocusOnExit = dom.hasClass(this._xterm.element, 'focus'); } if (this._wrapperElement) { this._container.removeChild(this._wrapperElement); this._wrapperElement = null; } if (this._xterm) { this._xterm.destroy(); this._xterm = null; } if (this._process) { if (this._process.connected) { // If the process was still connected this dispose came from // within VS Code, not the process, so mark the process as // killed by the user. this._processState = ProcessState.KILLED_BY_USER; this._process.send({ event: 'shutdown' }); } this._process = null; } if (!this._isDisposed) { this._isDisposed = true; this._onDisposed.fire(this); } this._processDisposables = lifecycle.dispose(this._processDisposables); this._instanceDisposables = lifecycle.dispose(this._instanceDisposables); } public focus(force?: boolean): void { if (!this._xterm) { return; } const text = window.getSelection().toString(); if (!text || force) { this._xterm.focus(); } } public paste(): void { this.focus(); document.execCommand('paste'); } public sendText(text: string, addNewLine: boolean): void { this._processReady.then(() => { // Normalize line endings to 'enter' press. text = text.replace(TerminalInstance.EOL_REGEX, '\r'); if (addNewLine && text.substr(text.length - 1) !== '\r') { text += '\r'; } this._process.send({ event: 'input', data: text }); }); } public setVisible(visible: boolean): void { this._isVisible = visible; if (this._wrapperElement) { dom.toggleClass(this._wrapperElement, 'active', visible); } if (visible && this._xterm) { // Trigger a manual scroll event which will sync the viewport and scroll bar. This is // necessary if the number of rows in the terminal has decreased while it was in the // background since scrollTop changes take no effect but the terminal's position does // change since the number of visible rows decreases. this._xterm.emit('scroll', this._xterm.ydisp); } } public scrollDownLine(): void { this._xterm.scrollDisp(1); } public scrollDownPage(): void { this._xterm.scrollPages(1); } public scrollToBottom(): void { this._xterm.scrollToBottom(); } public scrollUpLine(): void { this._xterm.scrollDisp(-1); } public scrollUpPage(): void { this._xterm.scrollPages(-1); } public scrollToTop(): void { this._xterm.scrollToTop(); } public clear(): void { this._xterm.clear(); } private _refreshSelectionContextKey() { const activePanel = this._panelService.getActivePanel(); const isActive = activePanel && activePanel.getId() === TERMINAL_PANEL_ID; this._terminalHasTextContextKey.set(isActive && this.hasSelection()); } protected _getCwd(shell: IShellLaunchConfig, root: Uri): string { if (shell.cwd) { return shell.cwd; } let cwd: string; // TODO: Handle non-existent customCwd if (!shell.ignoreConfigurationCwd) { // Evaluate custom cwd first const customCwd = this._configHelper.config.cwd; if (customCwd) { if (path.isAbsolute(customCwd)) { cwd = customCwd; } else if (root) { cwd = path.normalize(path.join(root.fsPath, customCwd)); } } } // If there was no custom cwd or it was relative with no workspace if (!cwd) { cwd = root ? root.fsPath : os.homedir(); } return TerminalInstance._sanitizeCwd(cwd); } protected _createProcess(shell: IShellLaunchConfig): void { const locale = this._configHelper.config.setLocaleVariables ? platform.locale : undefined; if (!shell.executable) { this._configHelper.mergeDefaultShellPathAndArgs(shell); } this._initialCwd = this._getCwd(this._shellLaunchConfig, this._historyService.getLastActiveWorkspaceRoot()); let envFromConfig: IStringDictionary<string>; if (platform.isWindows) { envFromConfig = { ...process.env }; for (let configKey in this._configHelper.config.env['windows']) { let actualKey = configKey; for (let envKey in envFromConfig) { if (configKey.toLowerCase() === envKey.toLowerCase()) { actualKey = envKey; break; } } envFromConfig[actualKey] = this._configHelper.config.env['windows'][configKey]; } } else { const platformKey = platform.isMacintosh ? 'osx' : 'linux'; envFromConfig = { ...process.env, ...this._configHelper.config.env[platformKey] }; } const env = TerminalInstance.createTerminalEnv(envFromConfig, shell, this._initialCwd, locale, this._cols, this._rows); this._process = cp.fork(Uri.parse(require.toUrl('bootstrap')).fsPath, ['--type=terminal'], { env, cwd: Uri.parse(path.dirname(require.toUrl('../node/terminalProcess'))).fsPath }); this._processState = ProcessState.LAUNCHING; if (shell.name) { this.setTitle(shell.name, false); } else { // Only listen for process title changes when a name is not provided this.setTitle(shell.executable, true); this._messageTitleListener = (message) => { if (message.type === 'title') { this.setTitle(message.content ? message.content : '', true); } }; this._process.on('message', this._messageTitleListener); } this._process.on('message', (message) => { if (message.type === 'pid') { this._processId = message.content; // Send any queued data that's waiting if (this._preLaunchInputQueue.length > 0) { this._process.send({ event: 'input', data: this._preLaunchInputQueue }); this._preLaunchInputQueue = null; } this._onProcessIdReady.fire(this); } }); this._process.on('exit', exitCode => this._onPtyProcessExit(exitCode)); setTimeout(() => { if (this._processState === ProcessState.LAUNCHING) { this._processState = ProcessState.RUNNING; } }, LAUNCHING_DURATION); } private _sendPtyDataToXterm(message: { type: string, content: string }): void { if (message.type === 'data') { if (this._widgetManager) { this._widgetManager.closeMessage(); } if (this._xterm) { this._xterm.write(message.content); } } } private _onPtyProcessExit(exitCode: number): void { // Prevent dispose functions being triggered multiple times if (this._isExiting) { return; } this._isExiting = true; this._process = null; let exitCodeMessage: string; if (exitCode) { exitCodeMessage = nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode); } // If the process is marked as launching then mark the process as killed // during launch. This typically means that there is a problem with the // shell and args. if (this._processState === ProcessState.LAUNCHING) { this._processState = ProcessState.KILLED_DURING_LAUNCH; } // If TerminalInstance did not know about the process exit then it was // triggered by the process, not on VS Code's side. if (this._processState === ProcessState.RUNNING) { this._processState = ProcessState.KILLED_BY_PROCESS; } // Only trigger wait on exit when the exit was triggered by the process, // not through the `workbench.action.terminal.kill` command if (this._processState === ProcessState.KILLED_BY_PROCESS && this._shellLaunchConfig.waitOnExit) { if (exitCode) { this._xterm.writeln(exitCodeMessage); } let message = typeof this._shellLaunchConfig.waitOnExit === 'string' ? this._shellLaunchConfig.waitOnExit : nls.localize('terminal.integrated.waitOnExit', 'Press any key to close the terminal'); // Bold the message and add an extra new line to make it stand out from the rest of the output message = `\n\x1b[1m${message}\x1b[0m`; this._xterm.writeln(message); // Disable all input if the terminal is exiting and listen for next keypress this._xterm.setOption('disableStdin', true); if (this._xterm.textarea) { this._attachPressAnyKeyToCloseListener(); } } else { this.dispose(); if (exitCode) { if (this._processState === ProcessState.KILLED_DURING_LAUNCH) { let args = ''; if (typeof this._shellLaunchConfig.args === 'string') { args = this._shellLaunchConfig.args; } else if (this._shellLaunchConfig.args && this._shellLaunchConfig.args.length) { args = ' ' + this._shellLaunchConfig.args.map(a => { if (typeof a === 'string' && a.indexOf(' ') !== -1) { return `'${a}'`; } return a; }).join(' '); } this._messageService.show(Severity.Error, nls.localize('terminal.integrated.launchFailed', 'The terminal process command `{0}{1}` failed to launch (exit code: {2})', this._shellLaunchConfig.executable, args, exitCode)); } else { this._messageService.show(Severity.Error, exitCodeMessage); } } } } private _attachPressAnyKeyToCloseListener() { this._processDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'keypress', (event: KeyboardEvent) => { this.dispose(); event.preventDefault(); })); } public reuseTerminal(shell?: IShellLaunchConfig): void { // Kill and clean up old process if (this._process) { this._process.removeAllListeners('exit'); if (this._process.connected) { this._process.kill(); } this._process = null; } lifecycle.dispose(this._processDisposables); this._processDisposables = []; // Ensure new processes' output starts at start of new line this._xterm.write('\n\x1b[G'); // Print initialText if specified if (shell.initialText) { this._xterm.writeln(shell.initialText); } // Initialize new process const oldTitle = this._title; this._createProcess(shell); if (oldTitle !== this._title) { this.setTitle(this._title, true); } this._process.on('message', (message) => this._sendPtyDataToXterm(message)); // Clean up waitOnExit state if (this._isExiting && this._shellLaunchConfig.waitOnExit) { this._xterm.setOption('disableStdin', false); this._isExiting = false; } // Set the new shell launch config this._shellLaunchConfig = shell; } // TODO: This should be private/protected // TODO: locale should not be optional public static createTerminalEnv(parentEnv: IStringDictionary<string>, shell: IShellLaunchConfig, cwd: string, locale?: string, cols?: number, rows?: number): IStringDictionary<string> { const env = shell.env ? shell.env : TerminalInstance._cloneEnv(parentEnv); env['PTYPID'] = process.pid.toString(); env['PTYSHELL'] = shell.executable; env['TERM_PROGRAM'] = 'vscode'; env['TERM_PROGRAM_VERSION'] = pkg.version; if (shell.args) { if (typeof shell.args === 'string') { env[`PTYSHELLCMDLINE`] = shell.args; } else { shell.args.forEach((arg, i) => env[`PTYSHELLARG${i}`] = arg); } } env['PTYCWD'] = cwd; env['LANG'] = TerminalInstance._getLangEnvVariable(locale); if (cols && rows) { env['PTYCOLS'] = cols.toString(); env['PTYROWS'] = rows.toString(); } env['AMD_ENTRYPOINT'] = 'vs/workbench/parts/terminal/node/terminalProcess'; return env; } public onData(listener: (data: string) => void): lifecycle.IDisposable { let callback = (message) => { if (message.type === 'data') { listener(message.content); } }; this._process.on('message', callback); return { dispose: () => { if (this._process) { this._process.removeListener('message', callback); } } }; } public onExit(listener: (exitCode: number) => void): lifecycle.IDisposable { if (this._process) { this._process.on('exit', listener); } return { dispose: () => { if (this._process) { this._process.removeListener('exit', listener); } } }; } private static _sanitizeCwd(cwd: string) { // Make the drive letter uppercase on Windows (see #9448) if (platform.platform === platform.Platform.Windows && cwd && cwd[1] === ':') { return cwd[0].toUpperCase() + cwd.substr(1); } return cwd; } private static _cloneEnv(env: IStringDictionary<string>): IStringDictionary<string> { const newEnv: IStringDictionary<string> = Object.create(null); Object.keys(env).forEach((key) => { newEnv[key] = env[key]; }); return newEnv; } private static _getLangEnvVariable(locale?: string) { const parts = locale ? locale.split('-') : []; const n = parts.length; if (n === 0) { // Fallback to en_US to prevent possible encoding issues. return 'en_US.UTF-8'; } if (n === 1) { // app.getLocale can return just a language without a variant, fill in the variant for // supported languages as many shells expect a 2-part locale. const languageVariants = { de: 'DE', en: 'US', es: 'ES', fr: 'FR', it: 'IT', ja: 'JP', ko: 'KR', ru: 'RU', zh: 'CN' }; if (parts[0] in languageVariants) { parts.push(languageVariants[parts[0]]); } } else { // Ensure the variant is uppercase parts[1] = parts[1].toUpperCase(); } return parts.join('_') + '.UTF-8'; } public updateConfig(): void { this._setCursorBlink(this._configHelper.config.cursorBlinking); this._setCursorStyle(this._configHelper.config.cursorStyle); this._setCommandsToSkipShell(this._configHelper.config.commandsToSkipShell); this._setScrollback(this._configHelper.config.scrollback); } private _setCursorBlink(blink: boolean): void { if (this._xterm && this._xterm.getOption('cursorBlink') !== blink) { this._xterm.setOption('cursorBlink', blink); this._xterm.refresh(0, this._xterm.rows - 1); } } private _setCursorStyle(style: string): void { if (this._xterm && this._xterm.getOption('cursorStyle') !== style) { // 'line' is used instead of bar in VS Code to be consistent with editor.cursorStyle const xtermOption = style === 'line' ? 'bar' : style; this._xterm.setOption('cursorStyle', xtermOption); } } private _setCommandsToSkipShell(commands: string[]): void { this._skipTerminalCommands = commands; } private _setScrollback(lineCount: number): void { if (this._xterm && this._xterm.getOption('scrollback') !== lineCount) { this._xterm.setOption('scrollback', lineCount); } } public layout(dimension: Dimension): void { const terminalWidth = this._evaluateColsAndRows(dimension.width, dimension.height); if (!terminalWidth) { return; } if (this._xterm) { this._xterm.resize(this._cols, this._rows); this._xterm.element.style.width = terminalWidth + 'px'; } this._processReady.then(() => { if (this._process && this._process.connected) { // The child process could aready be terminated try { this._process.send({ event: 'resize', cols: this._cols, rows: this._rows }); } catch (error) { // We tried to write to a closed pipe / channel. if (error.code !== 'EPIPE' && error.code !== 'ERR_IPC_CHANNEL_CLOSED') { throw (error); } } } }); } public static setTerminalProcessFactory(factory: ITerminalProcessFactory): void { this._terminalProcessFactory = factory; } public setTitle(title: string, eventFromProcess: boolean): void { if (!title) { return; } if (eventFromProcess) { title = path.basename(title); if (platform.isWindows) { // Remove the .exe extension title = title.split('.exe')[0]; } } else { // If the title has not been set by the API or the rename command, unregister the handler that // automatically updates the terminal name if (this._process && this._messageTitleListener) { this._process.removeListener('message', this._messageTitleListener); this._messageTitleListener = null; } } const didTitleChange = title !== this._title; this._title = title; if (didTitleChange) { this._onTitleChanged.fire(title); } } } registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { // Scrollbar const scrollbarSliderBackgroundColor = theme.getColor(scrollbarSliderBackground); if (scrollbarSliderBackgroundColor) { collector.addRule(` .monaco-workbench .panel.integrated-terminal .xterm.focus .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm:focus .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm:hover .xterm-viewport { background-color: ${scrollbarSliderBackgroundColor}; }` ); } const scrollbarSliderHoverBackgroundColor = theme.getColor(scrollbarSliderHoverBackground); if (scrollbarSliderHoverBackgroundColor) { collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:hover { background-color: ${scrollbarSliderHoverBackgroundColor}; }`); } const scrollbarSliderActiveBackgroundColor = theme.getColor(scrollbarSliderActiveBackground); if (scrollbarSliderActiveBackgroundColor) { collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:active { background-color: ${scrollbarSliderActiveBackgroundColor}; }`); } });
src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts
1
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.9992327690124512, 0.045835431665182114, 0.00016341653827112168, 0.0001803035120246932, 0.20013965666294098 ]
{ "id": 2, "code_window": [ "\t\tconst locale = this._configHelper.config.setLocaleVariables ? platform.locale : undefined;\n", "\t\tif (!shell.executable) {\n", "\t\t\tthis._configHelper.mergeDefaultShellPathAndArgs(shell);\n", "\t\t}\n", "\t\tthis._initialCwd = this._getCwd(this._shellLaunchConfig, this._historyService.getLastActiveWorkspaceRoot());\n", "\t\tlet envFromConfig: IStringDictionary<string>;\n", "\t\tif (platform.isWindows) {\n", "\t\t\tenvFromConfig = { ...process.env };\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (!this._shellLaunchConfig.executable) {\n", "\t\t\tthis._configHelper.mergeDefaultShellPathAndArgs(this._shellLaunchConfig);\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 560 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "debugAdapterBinNotFound": "Die ausführbare Datei \"{0}\" des Debugadapters ist nicht vorhanden.", "debugAdapterCannotDetermineExecutable": "Die ausführbare Datei \"{0}\" des Debugadapters kann nicht bestimmt werden.", "debugType": "Der Typ der Konfiguration.", "debugTypeNotRecognised": "Dieser Debugging-Typ wurde nicht erkannt. Bitte installieren und aktivieren Sie die dazugehörige Debugging-Erweiterung.", "node2NotSupported": "\"node2\" wird nicht mehr unterstützt, verwenden Sie stattdessen \"node\", und legen Sie das Attribut \"protocol\" auf \"inspector\" fest.", "debugName": "Der Name der Konfiguration. Er wird im Dropdownmenü der Startkonfiguration angezeigt.", "debugRequest": "Der Anforderungstyp der Konfiguration. Der Wert kann \"launch\" oder \"attach\" sein.", "debugServer": "Nur für die Entwicklung von Debugerweiterungen: Wenn ein Port angegeben ist, versucht der VS-Code, eine Verbindung mit einem Debugadapter herzustellen, der im Servermodus ausgeführt wird.", "debugPrelaunchTask": "Ein Task, der ausgeführt werden soll, bevor die Debugsitzung beginnt.", "debugWindowsConfiguration": "Windows-spezifische Startkonfigurationsattribute.", "debugOSXConfiguration": "OS X-spezifische Startkonfigurationsattribute.", "debugLinuxConfiguration": "Linux-spezifische Startkonfigurationsattribute.", "deprecatedVariables": "\"env.\", \"config.\" und \"command.\" sind veraltet, verwenden Sie stattdessen \"env:\", \"config:\" und \"command:\"." }
i18n/deu/src/vs/workbench/parts/debug/node/debugAdapter.i18n.json
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.00017405870312359184, 0.00017085940635297447, 0.00016569651779718697, 0.0001728229981381446, 0.000003685404180941987 ]
{ "id": 2, "code_window": [ "\t\tconst locale = this._configHelper.config.setLocaleVariables ? platform.locale : undefined;\n", "\t\tif (!shell.executable) {\n", "\t\t\tthis._configHelper.mergeDefaultShellPathAndArgs(shell);\n", "\t\t}\n", "\t\tthis._initialCwd = this._getCwd(this._shellLaunchConfig, this._historyService.getLastActiveWorkspaceRoot());\n", "\t\tlet envFromConfig: IStringDictionary<string>;\n", "\t\tif (platform.isWindows) {\n", "\t\t\tenvFromConfig = { ...process.env };\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (!this._shellLaunchConfig.executable) {\n", "\t\t\tthis._configHelper.mergeDefaultShellPathAndArgs(this._shellLaunchConfig);\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 560 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "config.gulp.autoDetect": "Gulp タスクの自動検出をオンにするかオフにするかを制御します。既定はオンです。" }
i18n/jpn/extensions/gulp/package.i18n.json
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.00017436301277484745, 0.00017436301277484745, 0.00017436301277484745, 0.00017436301277484745, 0 ]
{ "id": 2, "code_window": [ "\t\tconst locale = this._configHelper.config.setLocaleVariables ? platform.locale : undefined;\n", "\t\tif (!shell.executable) {\n", "\t\t\tthis._configHelper.mergeDefaultShellPathAndArgs(shell);\n", "\t\t}\n", "\t\tthis._initialCwd = this._getCwd(this._shellLaunchConfig, this._historyService.getLastActiveWorkspaceRoot());\n", "\t\tlet envFromConfig: IStringDictionary<string>;\n", "\t\tif (platform.isWindows) {\n", "\t\t\tenvFromConfig = { ...process.env };\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (!this._shellLaunchConfig.executable) {\n", "\t\t\tthis._configHelper.mergeDefaultShellPathAndArgs(this._shellLaunchConfig);\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 560 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { Disposable } from 'vs/base/common/lifecycle'; import { IDimension } from 'vs/editor/common/editorCommon'; export class ElementSizeObserver extends Disposable { private referenceDomElement: HTMLElement; private measureReferenceDomElementToken: number; private changeCallback: () => void; private width: number; private height: number; constructor(referenceDomElement: HTMLElement, changeCallback: () => void) { super(); this.referenceDomElement = referenceDomElement; this.changeCallback = changeCallback; this.measureReferenceDomElementToken = -1; this.width = -1; this.height = -1; this.measureReferenceDomElement(false); } public dispose(): void { this.stopObserving(); super.dispose(); } public getWidth(): number { return this.width; } public getHeight(): number { return this.height; } public startObserving(): void { if (this.measureReferenceDomElementToken === -1) { this.measureReferenceDomElementToken = setInterval(() => this.measureReferenceDomElement(true), 100); } } public stopObserving(): void { if (this.measureReferenceDomElementToken !== -1) { clearInterval(this.measureReferenceDomElementToken); this.measureReferenceDomElementToken = -1; } } public observe(dimension?: IDimension): void { this.measureReferenceDomElement(true, dimension); } private measureReferenceDomElement(callChangeCallback: boolean, dimension?: IDimension): void { 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(); } } } }
src/vs/editor/browser/config/elementSizeObserver.ts
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.00017669812950771302, 0.00017483907868154347, 0.00017269699310418218, 0.00017473178741056472, 0.0000012102699429306085 ]
{ "id": 3, "code_window": [ "\t\t\t}\n", "\t\t} else {\n", "\t\t\tconst platformKey = platform.isMacintosh ? 'osx' : 'linux';\n", "\t\t\tenvFromConfig = { ...process.env, ...this._configHelper.config.env[platformKey] };\n", "\t\t}\n", "\t\tconst env = TerminalInstance.createTerminalEnv(envFromConfig, shell, this._initialCwd, locale, this._cols, this._rows);\n", "\t\tthis._process = cp.fork(Uri.parse(require.toUrl('bootstrap')).fsPath, ['--type=terminal'], {\n", "\t\t\tenv,\n", "\t\t\tcwd: Uri.parse(path.dirname(require.toUrl('../node/terminalProcess'))).fsPath\n", "\t\t});\n", "\t\tthis._processState = ProcessState.LAUNCHING;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst env = TerminalInstance.createTerminalEnv(envFromConfig, this._shellLaunchConfig, this._initialCwd, locale, this._cols, this._rows);\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 581 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as cp from 'child_process'; import * as os from 'os'; import * as path from 'path'; import * as lifecycle from 'vs/base/common/lifecycle'; import * as nls from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import * as dom from 'vs/base/browser/dom'; import Event, { Emitter } from 'vs/base/common/event'; import Uri from 'vs/base/common/uri'; import { WindowsShellHelper } from 'vs/workbench/parts/terminal/electron-browser/windowsShellHelper'; import { Terminal as XTermTerminal } from 'xterm'; import { Dimension } from 'vs/base/browser/builder'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IMessageService, Severity } from 'vs/platform/message/common/message'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IStringDictionary } from 'vs/base/common/collections'; import { ITerminalInstance, KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED, TERMINAL_PANEL_ID, IShellLaunchConfig } from 'vs/workbench/parts/terminal/common/terminal'; import { ITerminalProcessFactory } from 'vs/workbench/parts/terminal/electron-browser/terminal'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { TabFocus } from 'vs/editor/common/config/commonEditorConfig'; import { TerminalConfigHelper } from 'vs/workbench/parts/terminal/electron-browser/terminalConfigHelper'; import { TerminalLinkHandler } from 'vs/workbench/parts/terminal/electron-browser/terminalLinkHandler'; import { TerminalWidgetManager } from 'vs/workbench/parts/terminal/browser/terminalWidgetManager'; import { registerThemingParticipant, ITheme, ICssStyleCollector } from 'vs/platform/theme/common/themeService'; import { scrollbarSliderBackground, scrollbarSliderHoverBackground, scrollbarSliderActiveBackground } from 'vs/platform/theme/common/colorRegistry'; import { TPromise } from 'vs/base/common/winjs.base'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { IHistoryService } from 'vs/workbench/services/history/common/history'; import pkg from 'vs/platform/node/package'; /** The amount of time to consider terminal errors to be related to the launch */ const LAUNCHING_DURATION = 500; // Enable search functionality in xterm.js instance XTermTerminal.loadAddon('search'); class StandardTerminalProcessFactory implements ITerminalProcessFactory { public create(env: { [key: string]: string }): cp.ChildProcess { return cp.fork('./terminalProcess', [], { env, cwd: Uri.parse(path.dirname(require.toUrl('./terminalProcess'))).fsPath }); } } enum ProcessState { // The process has not been initialized yet. UNINITIALIZED, // The process is currently launching, the process is marked as launching // for a short duration after being created and is helpful to indicate // whether the process died as a result of bad shell and args. LAUNCHING, // The process is running normally. RUNNING, // The process was killed during launch, likely as a result of bad shell and // args. KILLED_DURING_LAUNCH, // The process was killed by the user (the event originated from VS Code). KILLED_BY_USER, // The process was killed by itself, for example the shell crashed or `exit` // was run. KILLED_BY_PROCESS } export class TerminalInstance implements ITerminalInstance { private static readonly EOL_REGEX = /\r?\n/g; private static _terminalProcessFactory: ITerminalProcessFactory = new StandardTerminalProcessFactory(); private static _lastKnownDimensions: Dimension = null; private static _idCounter = 1; private _id: number; private _isExiting: boolean; private _hadFocusOnExit: boolean; private _isVisible: boolean; private _processState: ProcessState; private _processReady: TPromise<void>; private _isDisposed: boolean; private _onDisposed: Emitter<ITerminalInstance>; private _onDataForApi: Emitter<{ instance: ITerminalInstance, data: string }>; private _onProcessIdReady: Emitter<TerminalInstance>; private _onTitleChanged: Emitter<string>; private _process: cp.ChildProcess; private _processId: number; private _skipTerminalCommands: string[]; private _title: string; private _instanceDisposables: lifecycle.IDisposable[]; private _processDisposables: lifecycle.IDisposable[]; private _wrapperElement: HTMLDivElement; private _xterm: XTermTerminal; private _xtermElement: HTMLDivElement; private _terminalHasTextContextKey: IContextKey<boolean>; private _cols: number; private _rows: number; private _messageTitleListener: (message: { type: string, content: string }) => void; private _preLaunchInputQueue: string; private _initialCwd: string; private _windowsShellHelper: WindowsShellHelper; private _widgetManager: TerminalWidgetManager; private _linkHandler: TerminalLinkHandler; public get id(): number { return this._id; } public get processId(): number { return this._processId; } public get onDisposed(): Event<ITerminalInstance> { return this._onDisposed.event; } public get onDataForApi(): Event<{ instance: ITerminalInstance, data: string }> { return this._onDataForApi.event; } public get onProcessIdReady(): Event<TerminalInstance> { return this._onProcessIdReady.event; } public get onTitleChanged(): Event<string> { return this._onTitleChanged.event; } public get title(): string { return this._title; } public get hadFocusOnExit(): boolean { return this._hadFocusOnExit; } public get isTitleSetByProcess(): boolean { return !!this._messageTitleListener; } public constructor( private _terminalFocusContextKey: IContextKey<boolean>, private _configHelper: TerminalConfigHelper, private _container: HTMLElement, private _shellLaunchConfig: IShellLaunchConfig, @IContextKeyService private _contextKeyService: IContextKeyService, @IKeybindingService private _keybindingService: IKeybindingService, @IMessageService private _messageService: IMessageService, @IPanelService private _panelService: IPanelService, @IWorkspaceContextService private _contextService: IWorkspaceContextService, @IWorkbenchEditorService private _editorService: IWorkbenchEditorService, @IInstantiationService private _instantiationService: IInstantiationService, @IClipboardService private _clipboardService: IClipboardService, @IHistoryService private _historyService: IHistoryService ) { this._instanceDisposables = []; this._processDisposables = []; this._skipTerminalCommands = []; this._isExiting = false; this._hadFocusOnExit = false; this._processState = ProcessState.UNINITIALIZED; this._isVisible = false; this._isDisposed = false; this._id = TerminalInstance._idCounter++; this._terminalHasTextContextKey = KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED.bindTo(this._contextKeyService); this._preLaunchInputQueue = ''; this._onDisposed = new Emitter<TerminalInstance>(); this._onDataForApi = new Emitter<{ instance: ITerminalInstance, data: string }>(); this._onProcessIdReady = new Emitter<TerminalInstance>(); this._onTitleChanged = new Emitter<string>(); // Create a promise that resolves when the pty is ready this._processReady = new TPromise<void>(c => { this.onProcessIdReady(() => c(void 0)); }); this._initDimensions(); this._createProcess(this._shellLaunchConfig); this._createXterm(); if (platform.isWindows) { this._processReady.then(() => { if (!this._isDisposed) { import('vs/workbench/parts/terminal/electron-browser/windowsShellHelper').then((module) => { this._windowsShellHelper = new module.WindowsShellHelper(this._processId, this._shellLaunchConfig.executable, this, this._xterm); }); } }); } // Only attach xterm.js to the DOM if the terminal panel has been opened before. if (_container) { this.attachToElement(_container); } } public addDisposable(disposable: lifecycle.IDisposable): void { this._instanceDisposables.push(disposable); } private _initDimensions(): void { // The terminal panel needs to have been created if (!this._container) { return; } const computedStyle = window.getComputedStyle(this._container); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this._evaluateColsAndRows(width, height); } /** * Evaluates and sets the cols and rows of the terminal if possible. * @param width The width of the container. * @param height The height of the container. * @return The terminal's width if it requires a layout. */ private _evaluateColsAndRows(width: number, height: number): number { const dimension = this._getDimension(width, height); if (!dimension) { return null; } const font = this._configHelper.getFont(); this._cols = Math.max(Math.floor(dimension.width / font.charWidth), 1); this._rows = Math.max(Math.floor(dimension.height / font.charHeight), 1); return dimension.width; } private _getDimension(width: number, height: number): Dimension { // The font needs to have been initialized const font = this._configHelper.getFont(); if (!font || !font.charWidth || !font.charHeight) { return null; } // The panel is minimized if (!height) { return TerminalInstance._lastKnownDimensions; } else { // Trigger scroll event manually so that the viewport's scroll area is synced. This // needs to happen otherwise its scrollTop value is invalid when the panel is toggled as // it gets removed and then added back to the DOM (resetting scrollTop to 0). // Upstream issue: https://github.com/sourcelair/xterm.js/issues/291 if (this._xterm) { this._xterm.emit('scroll', this._xterm.ydisp); } } const outerContainer = document.querySelector('.terminal-outer-container'); const outerContainerStyle = getComputedStyle(outerContainer); const padding = parseInt(outerContainerStyle.paddingLeft.split('px')[0], 10); const paddingBottom = parseInt(outerContainerStyle.paddingBottom.split('px')[0], 10); // Use left padding as right padding, right padding is not defined in CSS just in case // xterm.js causes an unexpected overflow. const innerWidth = width - padding * 2; const innerHeight = height - paddingBottom; TerminalInstance._lastKnownDimensions = new Dimension(innerWidth, innerHeight); return TerminalInstance._lastKnownDimensions; } /** * Create xterm.js instance and attach data listeners. */ protected _createXterm(): void { this._xterm = new XTermTerminal({ scrollback: this._configHelper.config.scrollback }); if (this._shellLaunchConfig.initialText) { this._xterm.writeln(this._shellLaunchConfig.initialText); } this._process.on('message', (message) => this._sendPtyDataToXterm(message)); this._xterm.on('data', (data) => { if (this._processId) { // Send data if the pty is ready this._process.send({ event: 'input', data }); } else { // If the pty is not ready, queue the data received from // xterm.js until the pty is ready this._preLaunchInputQueue += data; } return false; }); this._linkHandler = this._instantiationService.createInstance(TerminalLinkHandler, this._xterm, platform.platform, this._initialCwd); this._linkHandler.registerLocalLinkHandler(); } public attachToElement(container: HTMLElement): void { if (this._wrapperElement) { throw new Error('The terminal instance has already been attached to a container'); } this._container = container; this._wrapperElement = document.createElement('div'); dom.addClass(this._wrapperElement, 'terminal-wrapper'); this._xtermElement = document.createElement('div'); this._xterm.open(this._xtermElement); this._xterm.attachCustomKeyEventHandler((event: KeyboardEvent) => { // Disable all input if the terminal is exiting if (this._isExiting) { return false; } // Skip processing by xterm.js of keyboard events that resolve to commands described // within commandsToSkipShell const standardKeyboardEvent = new StandardKeyboardEvent(event); const resolveResult = this._keybindingService.softDispatch(standardKeyboardEvent, standardKeyboardEvent.target); if (resolveResult && this._skipTerminalCommands.some(k => k === resolveResult.commandId)) { event.preventDefault(); return false; } // If tab focus mode is on, tab is not passed to the terminal if (TabFocus.getTabFocusMode() && event.keyCode === 9) { return false; } return undefined; }); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'mouseup', (event: KeyboardEvent) => { // Wait until mouseup has propagated through the DOM before // evaluating the new selection state. setTimeout(() => this._refreshSelectionContextKey(), 0); })); // xterm.js currently drops selection on keyup as we need to handle this case. this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'keyup', (event: KeyboardEvent) => { // Wait until keyup has propagated through the DOM before evaluating // the new selection state. setTimeout(() => this._refreshSelectionContextKey(), 0); })); const xtermHelper: HTMLElement = <HTMLElement>this._xterm.element.querySelector('.xterm-helpers'); const focusTrap: HTMLElement = document.createElement('div'); focusTrap.setAttribute('tabindex', '0'); dom.addClass(focusTrap, 'focus-trap'); this._instanceDisposables.push(dom.addDisposableListener(focusTrap, 'focus', (event: FocusEvent) => { let currentElement = focusTrap; while (!dom.hasClass(currentElement, 'part')) { currentElement = currentElement.parentElement; } const hidePanelElement = <HTMLElement>currentElement.querySelector('.hide-panel-action'); hidePanelElement.focus(); })); xtermHelper.insertBefore(focusTrap, this._xterm.textarea); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'focus', (event: KeyboardEvent) => { this._terminalFocusContextKey.set(true); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'blur', (event: KeyboardEvent) => { this._terminalFocusContextKey.reset(); this._refreshSelectionContextKey(); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'focus', (event: KeyboardEvent) => { this._terminalFocusContextKey.set(true); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'blur', (event: KeyboardEvent) => { this._terminalFocusContextKey.reset(); this._refreshSelectionContextKey(); })); this._wrapperElement.appendChild(this._xtermElement); this._widgetManager = new TerminalWidgetManager(this._configHelper, this._wrapperElement); this._linkHandler.setWidgetManager(this._widgetManager); this._container.appendChild(this._wrapperElement); const computedStyle = window.getComputedStyle(this._container); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this.layout(new Dimension(width, height)); this.setVisible(this._isVisible); this.updateConfig(); // If IShellLaunchConfig.waitOnExit was true and the process finished before the terminal // panel was initialized. if (this._xterm.getOption('disableStdin')) { this._attachPressAnyKeyToCloseListener(); } } public registerLinkMatcher(regex: RegExp, handler: (url: string) => void, matchIndex?: number, validationCallback?: (uri: string, element: HTMLElement, callback: (isValid: boolean) => void) => void): number { return this._linkHandler.registerCustomLinkHandler(regex, handler, matchIndex, validationCallback); } public deregisterLinkMatcher(linkMatcherId: number): void { this._xterm.deregisterLinkMatcher(linkMatcherId); } public hasSelection(): boolean { return this._xterm.hasSelection(); } public copySelection(): void { if (this.hasSelection()) { this._clipboardService.writeText(this._xterm.getSelection()); } else { this._messageService.show(Severity.Warning, nls.localize('terminal.integrated.copySelection.noSelection', 'The terminal has no selection to copy')); } } get selection(): string | undefined { return this.hasSelection() ? this._xterm.getSelection() : undefined; } public clearSelection(): void { this._xterm.clearSelection(); } public selectAll(): void { // Focus here to ensure the terminal context key is set this._xterm.focus(); this._xterm.selectAll(); } public findNext(term: string): boolean { return this._xterm.findNext(term); } public findPrevious(term: string): boolean { return this._xterm.findPrevious(term); } public notifyFindWidgetFocusChanged(isFocused: boolean): void { // In order to support escape to close the find widget when the terminal // is focused terminalFocus needs to be true when either the terminal or // the find widget are focused. this._terminalFocusContextKey.set(isFocused || document.activeElement === this._xterm.textarea); } public dispose(): void { if (this._windowsShellHelper) { this._windowsShellHelper.dispose(); } if (this._linkHandler) { this._linkHandler.dispose(); } if (this._xterm && this._xterm.element) { this._hadFocusOnExit = dom.hasClass(this._xterm.element, 'focus'); } if (this._wrapperElement) { this._container.removeChild(this._wrapperElement); this._wrapperElement = null; } if (this._xterm) { this._xterm.destroy(); this._xterm = null; } if (this._process) { if (this._process.connected) { // If the process was still connected this dispose came from // within VS Code, not the process, so mark the process as // killed by the user. this._processState = ProcessState.KILLED_BY_USER; this._process.send({ event: 'shutdown' }); } this._process = null; } if (!this._isDisposed) { this._isDisposed = true; this._onDisposed.fire(this); } this._processDisposables = lifecycle.dispose(this._processDisposables); this._instanceDisposables = lifecycle.dispose(this._instanceDisposables); } public focus(force?: boolean): void { if (!this._xterm) { return; } const text = window.getSelection().toString(); if (!text || force) { this._xterm.focus(); } } public paste(): void { this.focus(); document.execCommand('paste'); } public sendText(text: string, addNewLine: boolean): void { this._processReady.then(() => { // Normalize line endings to 'enter' press. text = text.replace(TerminalInstance.EOL_REGEX, '\r'); if (addNewLine && text.substr(text.length - 1) !== '\r') { text += '\r'; } this._process.send({ event: 'input', data: text }); }); } public setVisible(visible: boolean): void { this._isVisible = visible; if (this._wrapperElement) { dom.toggleClass(this._wrapperElement, 'active', visible); } if (visible && this._xterm) { // Trigger a manual scroll event which will sync the viewport and scroll bar. This is // necessary if the number of rows in the terminal has decreased while it was in the // background since scrollTop changes take no effect but the terminal's position does // change since the number of visible rows decreases. this._xterm.emit('scroll', this._xterm.ydisp); } } public scrollDownLine(): void { this._xterm.scrollDisp(1); } public scrollDownPage(): void { this._xterm.scrollPages(1); } public scrollToBottom(): void { this._xterm.scrollToBottom(); } public scrollUpLine(): void { this._xterm.scrollDisp(-1); } public scrollUpPage(): void { this._xterm.scrollPages(-1); } public scrollToTop(): void { this._xterm.scrollToTop(); } public clear(): void { this._xterm.clear(); } private _refreshSelectionContextKey() { const activePanel = this._panelService.getActivePanel(); const isActive = activePanel && activePanel.getId() === TERMINAL_PANEL_ID; this._terminalHasTextContextKey.set(isActive && this.hasSelection()); } protected _getCwd(shell: IShellLaunchConfig, root: Uri): string { if (shell.cwd) { return shell.cwd; } let cwd: string; // TODO: Handle non-existent customCwd if (!shell.ignoreConfigurationCwd) { // Evaluate custom cwd first const customCwd = this._configHelper.config.cwd; if (customCwd) { if (path.isAbsolute(customCwd)) { cwd = customCwd; } else if (root) { cwd = path.normalize(path.join(root.fsPath, customCwd)); } } } // If there was no custom cwd or it was relative with no workspace if (!cwd) { cwd = root ? root.fsPath : os.homedir(); } return TerminalInstance._sanitizeCwd(cwd); } protected _createProcess(shell: IShellLaunchConfig): void { const locale = this._configHelper.config.setLocaleVariables ? platform.locale : undefined; if (!shell.executable) { this._configHelper.mergeDefaultShellPathAndArgs(shell); } this._initialCwd = this._getCwd(this._shellLaunchConfig, this._historyService.getLastActiveWorkspaceRoot()); let envFromConfig: IStringDictionary<string>; if (platform.isWindows) { envFromConfig = { ...process.env }; for (let configKey in this._configHelper.config.env['windows']) { let actualKey = configKey; for (let envKey in envFromConfig) { if (configKey.toLowerCase() === envKey.toLowerCase()) { actualKey = envKey; break; } } envFromConfig[actualKey] = this._configHelper.config.env['windows'][configKey]; } } else { const platformKey = platform.isMacintosh ? 'osx' : 'linux'; envFromConfig = { ...process.env, ...this._configHelper.config.env[platformKey] }; } const env = TerminalInstance.createTerminalEnv(envFromConfig, shell, this._initialCwd, locale, this._cols, this._rows); this._process = cp.fork(Uri.parse(require.toUrl('bootstrap')).fsPath, ['--type=terminal'], { env, cwd: Uri.parse(path.dirname(require.toUrl('../node/terminalProcess'))).fsPath }); this._processState = ProcessState.LAUNCHING; if (shell.name) { this.setTitle(shell.name, false); } else { // Only listen for process title changes when a name is not provided this.setTitle(shell.executable, true); this._messageTitleListener = (message) => { if (message.type === 'title') { this.setTitle(message.content ? message.content : '', true); } }; this._process.on('message', this._messageTitleListener); } this._process.on('message', (message) => { if (message.type === 'pid') { this._processId = message.content; // Send any queued data that's waiting if (this._preLaunchInputQueue.length > 0) { this._process.send({ event: 'input', data: this._preLaunchInputQueue }); this._preLaunchInputQueue = null; } this._onProcessIdReady.fire(this); } }); this._process.on('exit', exitCode => this._onPtyProcessExit(exitCode)); setTimeout(() => { if (this._processState === ProcessState.LAUNCHING) { this._processState = ProcessState.RUNNING; } }, LAUNCHING_DURATION); } private _sendPtyDataToXterm(message: { type: string, content: string }): void { if (message.type === 'data') { if (this._widgetManager) { this._widgetManager.closeMessage(); } if (this._xterm) { this._xterm.write(message.content); } } } private _onPtyProcessExit(exitCode: number): void { // Prevent dispose functions being triggered multiple times if (this._isExiting) { return; } this._isExiting = true; this._process = null; let exitCodeMessage: string; if (exitCode) { exitCodeMessage = nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode); } // If the process is marked as launching then mark the process as killed // during launch. This typically means that there is a problem with the // shell and args. if (this._processState === ProcessState.LAUNCHING) { this._processState = ProcessState.KILLED_DURING_LAUNCH; } // If TerminalInstance did not know about the process exit then it was // triggered by the process, not on VS Code's side. if (this._processState === ProcessState.RUNNING) { this._processState = ProcessState.KILLED_BY_PROCESS; } // Only trigger wait on exit when the exit was triggered by the process, // not through the `workbench.action.terminal.kill` command if (this._processState === ProcessState.KILLED_BY_PROCESS && this._shellLaunchConfig.waitOnExit) { if (exitCode) { this._xterm.writeln(exitCodeMessage); } let message = typeof this._shellLaunchConfig.waitOnExit === 'string' ? this._shellLaunchConfig.waitOnExit : nls.localize('terminal.integrated.waitOnExit', 'Press any key to close the terminal'); // Bold the message and add an extra new line to make it stand out from the rest of the output message = `\n\x1b[1m${message}\x1b[0m`; this._xterm.writeln(message); // Disable all input if the terminal is exiting and listen for next keypress this._xterm.setOption('disableStdin', true); if (this._xterm.textarea) { this._attachPressAnyKeyToCloseListener(); } } else { this.dispose(); if (exitCode) { if (this._processState === ProcessState.KILLED_DURING_LAUNCH) { let args = ''; if (typeof this._shellLaunchConfig.args === 'string') { args = this._shellLaunchConfig.args; } else if (this._shellLaunchConfig.args && this._shellLaunchConfig.args.length) { args = ' ' + this._shellLaunchConfig.args.map(a => { if (typeof a === 'string' && a.indexOf(' ') !== -1) { return `'${a}'`; } return a; }).join(' '); } this._messageService.show(Severity.Error, nls.localize('terminal.integrated.launchFailed', 'The terminal process command `{0}{1}` failed to launch (exit code: {2})', this._shellLaunchConfig.executable, args, exitCode)); } else { this._messageService.show(Severity.Error, exitCodeMessage); } } } } private _attachPressAnyKeyToCloseListener() { this._processDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'keypress', (event: KeyboardEvent) => { this.dispose(); event.preventDefault(); })); } public reuseTerminal(shell?: IShellLaunchConfig): void { // Kill and clean up old process if (this._process) { this._process.removeAllListeners('exit'); if (this._process.connected) { this._process.kill(); } this._process = null; } lifecycle.dispose(this._processDisposables); this._processDisposables = []; // Ensure new processes' output starts at start of new line this._xterm.write('\n\x1b[G'); // Print initialText if specified if (shell.initialText) { this._xterm.writeln(shell.initialText); } // Initialize new process const oldTitle = this._title; this._createProcess(shell); if (oldTitle !== this._title) { this.setTitle(this._title, true); } this._process.on('message', (message) => this._sendPtyDataToXterm(message)); // Clean up waitOnExit state if (this._isExiting && this._shellLaunchConfig.waitOnExit) { this._xterm.setOption('disableStdin', false); this._isExiting = false; } // Set the new shell launch config this._shellLaunchConfig = shell; } // TODO: This should be private/protected // TODO: locale should not be optional public static createTerminalEnv(parentEnv: IStringDictionary<string>, shell: IShellLaunchConfig, cwd: string, locale?: string, cols?: number, rows?: number): IStringDictionary<string> { const env = shell.env ? shell.env : TerminalInstance._cloneEnv(parentEnv); env['PTYPID'] = process.pid.toString(); env['PTYSHELL'] = shell.executable; env['TERM_PROGRAM'] = 'vscode'; env['TERM_PROGRAM_VERSION'] = pkg.version; if (shell.args) { if (typeof shell.args === 'string') { env[`PTYSHELLCMDLINE`] = shell.args; } else { shell.args.forEach((arg, i) => env[`PTYSHELLARG${i}`] = arg); } } env['PTYCWD'] = cwd; env['LANG'] = TerminalInstance._getLangEnvVariable(locale); if (cols && rows) { env['PTYCOLS'] = cols.toString(); env['PTYROWS'] = rows.toString(); } env['AMD_ENTRYPOINT'] = 'vs/workbench/parts/terminal/node/terminalProcess'; return env; } public onData(listener: (data: string) => void): lifecycle.IDisposable { let callback = (message) => { if (message.type === 'data') { listener(message.content); } }; this._process.on('message', callback); return { dispose: () => { if (this._process) { this._process.removeListener('message', callback); } } }; } public onExit(listener: (exitCode: number) => void): lifecycle.IDisposable { if (this._process) { this._process.on('exit', listener); } return { dispose: () => { if (this._process) { this._process.removeListener('exit', listener); } } }; } private static _sanitizeCwd(cwd: string) { // Make the drive letter uppercase on Windows (see #9448) if (platform.platform === platform.Platform.Windows && cwd && cwd[1] === ':') { return cwd[0].toUpperCase() + cwd.substr(1); } return cwd; } private static _cloneEnv(env: IStringDictionary<string>): IStringDictionary<string> { const newEnv: IStringDictionary<string> = Object.create(null); Object.keys(env).forEach((key) => { newEnv[key] = env[key]; }); return newEnv; } private static _getLangEnvVariable(locale?: string) { const parts = locale ? locale.split('-') : []; const n = parts.length; if (n === 0) { // Fallback to en_US to prevent possible encoding issues. return 'en_US.UTF-8'; } if (n === 1) { // app.getLocale can return just a language without a variant, fill in the variant for // supported languages as many shells expect a 2-part locale. const languageVariants = { de: 'DE', en: 'US', es: 'ES', fr: 'FR', it: 'IT', ja: 'JP', ko: 'KR', ru: 'RU', zh: 'CN' }; if (parts[0] in languageVariants) { parts.push(languageVariants[parts[0]]); } } else { // Ensure the variant is uppercase parts[1] = parts[1].toUpperCase(); } return parts.join('_') + '.UTF-8'; } public updateConfig(): void { this._setCursorBlink(this._configHelper.config.cursorBlinking); this._setCursorStyle(this._configHelper.config.cursorStyle); this._setCommandsToSkipShell(this._configHelper.config.commandsToSkipShell); this._setScrollback(this._configHelper.config.scrollback); } private _setCursorBlink(blink: boolean): void { if (this._xterm && this._xterm.getOption('cursorBlink') !== blink) { this._xterm.setOption('cursorBlink', blink); this._xterm.refresh(0, this._xterm.rows - 1); } } private _setCursorStyle(style: string): void { if (this._xterm && this._xterm.getOption('cursorStyle') !== style) { // 'line' is used instead of bar in VS Code to be consistent with editor.cursorStyle const xtermOption = style === 'line' ? 'bar' : style; this._xterm.setOption('cursorStyle', xtermOption); } } private _setCommandsToSkipShell(commands: string[]): void { this._skipTerminalCommands = commands; } private _setScrollback(lineCount: number): void { if (this._xterm && this._xterm.getOption('scrollback') !== lineCount) { this._xterm.setOption('scrollback', lineCount); } } public layout(dimension: Dimension): void { const terminalWidth = this._evaluateColsAndRows(dimension.width, dimension.height); if (!terminalWidth) { return; } if (this._xterm) { this._xterm.resize(this._cols, this._rows); this._xterm.element.style.width = terminalWidth + 'px'; } this._processReady.then(() => { if (this._process && this._process.connected) { // The child process could aready be terminated try { this._process.send({ event: 'resize', cols: this._cols, rows: this._rows }); } catch (error) { // We tried to write to a closed pipe / channel. if (error.code !== 'EPIPE' && error.code !== 'ERR_IPC_CHANNEL_CLOSED') { throw (error); } } } }); } public static setTerminalProcessFactory(factory: ITerminalProcessFactory): void { this._terminalProcessFactory = factory; } public setTitle(title: string, eventFromProcess: boolean): void { if (!title) { return; } if (eventFromProcess) { title = path.basename(title); if (platform.isWindows) { // Remove the .exe extension title = title.split('.exe')[0]; } } else { // If the title has not been set by the API or the rename command, unregister the handler that // automatically updates the terminal name if (this._process && this._messageTitleListener) { this._process.removeListener('message', this._messageTitleListener); this._messageTitleListener = null; } } const didTitleChange = title !== this._title; this._title = title; if (didTitleChange) { this._onTitleChanged.fire(title); } } } registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { // Scrollbar const scrollbarSliderBackgroundColor = theme.getColor(scrollbarSliderBackground); if (scrollbarSliderBackgroundColor) { collector.addRule(` .monaco-workbench .panel.integrated-terminal .xterm.focus .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm:focus .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm:hover .xterm-viewport { background-color: ${scrollbarSliderBackgroundColor}; }` ); } const scrollbarSliderHoverBackgroundColor = theme.getColor(scrollbarSliderHoverBackground); if (scrollbarSliderHoverBackgroundColor) { collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:hover { background-color: ${scrollbarSliderHoverBackgroundColor}; }`); } const scrollbarSliderActiveBackgroundColor = theme.getColor(scrollbarSliderActiveBackground); if (scrollbarSliderActiveBackgroundColor) { collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:active { background-color: ${scrollbarSliderActiveBackgroundColor}; }`); } });
src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts
1
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.9982681274414062, 0.07265274226665497, 0.0001634363434277475, 0.00020558625692501664, 0.2559053897857666 ]
{ "id": 3, "code_window": [ "\t\t\t}\n", "\t\t} else {\n", "\t\t\tconst platformKey = platform.isMacintosh ? 'osx' : 'linux';\n", "\t\t\tenvFromConfig = { ...process.env, ...this._configHelper.config.env[platformKey] };\n", "\t\t}\n", "\t\tconst env = TerminalInstance.createTerminalEnv(envFromConfig, shell, this._initialCwd, locale, this._cols, this._rows);\n", "\t\tthis._process = cp.fork(Uri.parse(require.toUrl('bootstrap')).fsPath, ['--type=terminal'], {\n", "\t\t\tenv,\n", "\t\t\tcwd: Uri.parse(path.dirname(require.toUrl('../node/terminalProcess'))).fsPath\n", "\t\t});\n", "\t\tthis._processState = ProcessState.LAUNCHING;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst env = TerminalInstance.createTerminalEnv(envFromConfig, this._shellLaunchConfig, this._initialCwd, locale, this._cols, this._rows);\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 581 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "extensionsInputName": "拡張機能: {0}" }
i18n/jpn/src/vs/workbench/parts/extensions/common/extensionsInput.i18n.json
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.00017592162475921214, 0.00017592162475921214, 0.00017592162475921214, 0.00017592162475921214, 0 ]
{ "id": 3, "code_window": [ "\t\t\t}\n", "\t\t} else {\n", "\t\t\tconst platformKey = platform.isMacintosh ? 'osx' : 'linux';\n", "\t\t\tenvFromConfig = { ...process.env, ...this._configHelper.config.env[platformKey] };\n", "\t\t}\n", "\t\tconst env = TerminalInstance.createTerminalEnv(envFromConfig, shell, this._initialCwd, locale, this._cols, this._rows);\n", "\t\tthis._process = cp.fork(Uri.parse(require.toUrl('bootstrap')).fsPath, ['--type=terminal'], {\n", "\t\t\tenv,\n", "\t\t\tcwd: Uri.parse(path.dirname(require.toUrl('../node/terminalProcess'))).fsPath\n", "\t\t});\n", "\t\tthis._processState = ProcessState.LAUNCHING;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst env = TerminalInstance.createTerminalEnv(envFromConfig, this._shellLaunchConfig, this._initialCwd, locale, this._cols, this._rows);\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 581 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><g fill="#F6F6F6"><circle cx="3.5" cy="7.5" r="2.5"/><circle cx="8.5" cy="7.5" r="2.5"/><circle cx="13.5" cy="7.5" r="2.5"/></g><g fill="#424242"><circle cx="3.5" cy="7.5" r="1.5"/><circle cx="8.5" cy="7.5" r="1.5"/><circle cx="13.5" cy="7.5" r="1.5"/></g></svg>
src/vs/workbench/parts/search/browser/media/ellipsis.svg
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.00017233083781320602, 0.00017233083781320602, 0.00017233083781320602, 0.00017233083781320602, 0 ]
{ "id": 3, "code_window": [ "\t\t\t}\n", "\t\t} else {\n", "\t\t\tconst platformKey = platform.isMacintosh ? 'osx' : 'linux';\n", "\t\t\tenvFromConfig = { ...process.env, ...this._configHelper.config.env[platformKey] };\n", "\t\t}\n", "\t\tconst env = TerminalInstance.createTerminalEnv(envFromConfig, shell, this._initialCwd, locale, this._cols, this._rows);\n", "\t\tthis._process = cp.fork(Uri.parse(require.toUrl('bootstrap')).fsPath, ['--type=terminal'], {\n", "\t\t\tenv,\n", "\t\t\tcwd: Uri.parse(path.dirname(require.toUrl('../node/terminalProcess'))).fsPath\n", "\t\t});\n", "\t\tthis._processState = ProcessState.LAUNCHING;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst env = TerminalInstance.createTerminalEnv(envFromConfig, this._shellLaunchConfig, this._initialCwd, locale, this._cols, this._rows);\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 581 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "commandsHandlerDescriptionDefault": "Parancsok megjelenítése és futtatása", "gotoLineDescriptionMac": "Sor megkeresése", "gotoLineDescriptionWin": "Sor megkeresése", "gotoSymbolDescription": "Ugrás szimbólumhoz egy fájlban...", "gotoSymbolDescriptionScoped": "Szimbólum megkeresése kategória alapján", "helpDescription": "Súgó megjelenítése", "viewPickerDescription": "Nézet megnyitása" }
i18n/hun/src/vs/workbench/parts/quickopen/browser/quickopen.contribution.i18n.json
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.00017580590792931616, 0.0001747185451677069, 0.00017363118240609765, 0.0001747185451677069, 0.0000010873627616092563 ]
{ "id": 4, "code_window": [ "\t\t\tenv,\n", "\t\t\tcwd: Uri.parse(path.dirname(require.toUrl('../node/terminalProcess'))).fsPath\n", "\t\t});\n", "\t\tthis._processState = ProcessState.LAUNCHING;\n", "\n", "\t\tif (shell.name) {\n", "\t\t\tthis.setTitle(shell.name, false);\n", "\t\t} else {\n", "\t\t\t// Only listen for process title changes when a name is not provided\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\tif (this._shellLaunchConfig.name) {\n", "\t\t\tthis.setTitle(this._shellLaunchConfig.name, false);\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 588 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as cp from 'child_process'; import * as os from 'os'; import * as path from 'path'; import * as lifecycle from 'vs/base/common/lifecycle'; import * as nls from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import * as dom from 'vs/base/browser/dom'; import Event, { Emitter } from 'vs/base/common/event'; import Uri from 'vs/base/common/uri'; import { WindowsShellHelper } from 'vs/workbench/parts/terminal/electron-browser/windowsShellHelper'; import { Terminal as XTermTerminal } from 'xterm'; import { Dimension } from 'vs/base/browser/builder'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IMessageService, Severity } from 'vs/platform/message/common/message'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IStringDictionary } from 'vs/base/common/collections'; import { ITerminalInstance, KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED, TERMINAL_PANEL_ID, IShellLaunchConfig } from 'vs/workbench/parts/terminal/common/terminal'; import { ITerminalProcessFactory } from 'vs/workbench/parts/terminal/electron-browser/terminal'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { TabFocus } from 'vs/editor/common/config/commonEditorConfig'; import { TerminalConfigHelper } from 'vs/workbench/parts/terminal/electron-browser/terminalConfigHelper'; import { TerminalLinkHandler } from 'vs/workbench/parts/terminal/electron-browser/terminalLinkHandler'; import { TerminalWidgetManager } from 'vs/workbench/parts/terminal/browser/terminalWidgetManager'; import { registerThemingParticipant, ITheme, ICssStyleCollector } from 'vs/platform/theme/common/themeService'; import { scrollbarSliderBackground, scrollbarSliderHoverBackground, scrollbarSliderActiveBackground } from 'vs/platform/theme/common/colorRegistry'; import { TPromise } from 'vs/base/common/winjs.base'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { IHistoryService } from 'vs/workbench/services/history/common/history'; import pkg from 'vs/platform/node/package'; /** The amount of time to consider terminal errors to be related to the launch */ const LAUNCHING_DURATION = 500; // Enable search functionality in xterm.js instance XTermTerminal.loadAddon('search'); class StandardTerminalProcessFactory implements ITerminalProcessFactory { public create(env: { [key: string]: string }): cp.ChildProcess { return cp.fork('./terminalProcess', [], { env, cwd: Uri.parse(path.dirname(require.toUrl('./terminalProcess'))).fsPath }); } } enum ProcessState { // The process has not been initialized yet. UNINITIALIZED, // The process is currently launching, the process is marked as launching // for a short duration after being created and is helpful to indicate // whether the process died as a result of bad shell and args. LAUNCHING, // The process is running normally. RUNNING, // The process was killed during launch, likely as a result of bad shell and // args. KILLED_DURING_LAUNCH, // The process was killed by the user (the event originated from VS Code). KILLED_BY_USER, // The process was killed by itself, for example the shell crashed or `exit` // was run. KILLED_BY_PROCESS } export class TerminalInstance implements ITerminalInstance { private static readonly EOL_REGEX = /\r?\n/g; private static _terminalProcessFactory: ITerminalProcessFactory = new StandardTerminalProcessFactory(); private static _lastKnownDimensions: Dimension = null; private static _idCounter = 1; private _id: number; private _isExiting: boolean; private _hadFocusOnExit: boolean; private _isVisible: boolean; private _processState: ProcessState; private _processReady: TPromise<void>; private _isDisposed: boolean; private _onDisposed: Emitter<ITerminalInstance>; private _onDataForApi: Emitter<{ instance: ITerminalInstance, data: string }>; private _onProcessIdReady: Emitter<TerminalInstance>; private _onTitleChanged: Emitter<string>; private _process: cp.ChildProcess; private _processId: number; private _skipTerminalCommands: string[]; private _title: string; private _instanceDisposables: lifecycle.IDisposable[]; private _processDisposables: lifecycle.IDisposable[]; private _wrapperElement: HTMLDivElement; private _xterm: XTermTerminal; private _xtermElement: HTMLDivElement; private _terminalHasTextContextKey: IContextKey<boolean>; private _cols: number; private _rows: number; private _messageTitleListener: (message: { type: string, content: string }) => void; private _preLaunchInputQueue: string; private _initialCwd: string; private _windowsShellHelper: WindowsShellHelper; private _widgetManager: TerminalWidgetManager; private _linkHandler: TerminalLinkHandler; public get id(): number { return this._id; } public get processId(): number { return this._processId; } public get onDisposed(): Event<ITerminalInstance> { return this._onDisposed.event; } public get onDataForApi(): Event<{ instance: ITerminalInstance, data: string }> { return this._onDataForApi.event; } public get onProcessIdReady(): Event<TerminalInstance> { return this._onProcessIdReady.event; } public get onTitleChanged(): Event<string> { return this._onTitleChanged.event; } public get title(): string { return this._title; } public get hadFocusOnExit(): boolean { return this._hadFocusOnExit; } public get isTitleSetByProcess(): boolean { return !!this._messageTitleListener; } public constructor( private _terminalFocusContextKey: IContextKey<boolean>, private _configHelper: TerminalConfigHelper, private _container: HTMLElement, private _shellLaunchConfig: IShellLaunchConfig, @IContextKeyService private _contextKeyService: IContextKeyService, @IKeybindingService private _keybindingService: IKeybindingService, @IMessageService private _messageService: IMessageService, @IPanelService private _panelService: IPanelService, @IWorkspaceContextService private _contextService: IWorkspaceContextService, @IWorkbenchEditorService private _editorService: IWorkbenchEditorService, @IInstantiationService private _instantiationService: IInstantiationService, @IClipboardService private _clipboardService: IClipboardService, @IHistoryService private _historyService: IHistoryService ) { this._instanceDisposables = []; this._processDisposables = []; this._skipTerminalCommands = []; this._isExiting = false; this._hadFocusOnExit = false; this._processState = ProcessState.UNINITIALIZED; this._isVisible = false; this._isDisposed = false; this._id = TerminalInstance._idCounter++; this._terminalHasTextContextKey = KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED.bindTo(this._contextKeyService); this._preLaunchInputQueue = ''; this._onDisposed = new Emitter<TerminalInstance>(); this._onDataForApi = new Emitter<{ instance: ITerminalInstance, data: string }>(); this._onProcessIdReady = new Emitter<TerminalInstance>(); this._onTitleChanged = new Emitter<string>(); // Create a promise that resolves when the pty is ready this._processReady = new TPromise<void>(c => { this.onProcessIdReady(() => c(void 0)); }); this._initDimensions(); this._createProcess(this._shellLaunchConfig); this._createXterm(); if (platform.isWindows) { this._processReady.then(() => { if (!this._isDisposed) { import('vs/workbench/parts/terminal/electron-browser/windowsShellHelper').then((module) => { this._windowsShellHelper = new module.WindowsShellHelper(this._processId, this._shellLaunchConfig.executable, this, this._xterm); }); } }); } // Only attach xterm.js to the DOM if the terminal panel has been opened before. if (_container) { this.attachToElement(_container); } } public addDisposable(disposable: lifecycle.IDisposable): void { this._instanceDisposables.push(disposable); } private _initDimensions(): void { // The terminal panel needs to have been created if (!this._container) { return; } const computedStyle = window.getComputedStyle(this._container); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this._evaluateColsAndRows(width, height); } /** * Evaluates and sets the cols and rows of the terminal if possible. * @param width The width of the container. * @param height The height of the container. * @return The terminal's width if it requires a layout. */ private _evaluateColsAndRows(width: number, height: number): number { const dimension = this._getDimension(width, height); if (!dimension) { return null; } const font = this._configHelper.getFont(); this._cols = Math.max(Math.floor(dimension.width / font.charWidth), 1); this._rows = Math.max(Math.floor(dimension.height / font.charHeight), 1); return dimension.width; } private _getDimension(width: number, height: number): Dimension { // The font needs to have been initialized const font = this._configHelper.getFont(); if (!font || !font.charWidth || !font.charHeight) { return null; } // The panel is minimized if (!height) { return TerminalInstance._lastKnownDimensions; } else { // Trigger scroll event manually so that the viewport's scroll area is synced. This // needs to happen otherwise its scrollTop value is invalid when the panel is toggled as // it gets removed and then added back to the DOM (resetting scrollTop to 0). // Upstream issue: https://github.com/sourcelair/xterm.js/issues/291 if (this._xterm) { this._xterm.emit('scroll', this._xterm.ydisp); } } const outerContainer = document.querySelector('.terminal-outer-container'); const outerContainerStyle = getComputedStyle(outerContainer); const padding = parseInt(outerContainerStyle.paddingLeft.split('px')[0], 10); const paddingBottom = parseInt(outerContainerStyle.paddingBottom.split('px')[0], 10); // Use left padding as right padding, right padding is not defined in CSS just in case // xterm.js causes an unexpected overflow. const innerWidth = width - padding * 2; const innerHeight = height - paddingBottom; TerminalInstance._lastKnownDimensions = new Dimension(innerWidth, innerHeight); return TerminalInstance._lastKnownDimensions; } /** * Create xterm.js instance and attach data listeners. */ protected _createXterm(): void { this._xterm = new XTermTerminal({ scrollback: this._configHelper.config.scrollback }); if (this._shellLaunchConfig.initialText) { this._xterm.writeln(this._shellLaunchConfig.initialText); } this._process.on('message', (message) => this._sendPtyDataToXterm(message)); this._xterm.on('data', (data) => { if (this._processId) { // Send data if the pty is ready this._process.send({ event: 'input', data }); } else { // If the pty is not ready, queue the data received from // xterm.js until the pty is ready this._preLaunchInputQueue += data; } return false; }); this._linkHandler = this._instantiationService.createInstance(TerminalLinkHandler, this._xterm, platform.platform, this._initialCwd); this._linkHandler.registerLocalLinkHandler(); } public attachToElement(container: HTMLElement): void { if (this._wrapperElement) { throw new Error('The terminal instance has already been attached to a container'); } this._container = container; this._wrapperElement = document.createElement('div'); dom.addClass(this._wrapperElement, 'terminal-wrapper'); this._xtermElement = document.createElement('div'); this._xterm.open(this._xtermElement); this._xterm.attachCustomKeyEventHandler((event: KeyboardEvent) => { // Disable all input if the terminal is exiting if (this._isExiting) { return false; } // Skip processing by xterm.js of keyboard events that resolve to commands described // within commandsToSkipShell const standardKeyboardEvent = new StandardKeyboardEvent(event); const resolveResult = this._keybindingService.softDispatch(standardKeyboardEvent, standardKeyboardEvent.target); if (resolveResult && this._skipTerminalCommands.some(k => k === resolveResult.commandId)) { event.preventDefault(); return false; } // If tab focus mode is on, tab is not passed to the terminal if (TabFocus.getTabFocusMode() && event.keyCode === 9) { return false; } return undefined; }); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'mouseup', (event: KeyboardEvent) => { // Wait until mouseup has propagated through the DOM before // evaluating the new selection state. setTimeout(() => this._refreshSelectionContextKey(), 0); })); // xterm.js currently drops selection on keyup as we need to handle this case. this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'keyup', (event: KeyboardEvent) => { // Wait until keyup has propagated through the DOM before evaluating // the new selection state. setTimeout(() => this._refreshSelectionContextKey(), 0); })); const xtermHelper: HTMLElement = <HTMLElement>this._xterm.element.querySelector('.xterm-helpers'); const focusTrap: HTMLElement = document.createElement('div'); focusTrap.setAttribute('tabindex', '0'); dom.addClass(focusTrap, 'focus-trap'); this._instanceDisposables.push(dom.addDisposableListener(focusTrap, 'focus', (event: FocusEvent) => { let currentElement = focusTrap; while (!dom.hasClass(currentElement, 'part')) { currentElement = currentElement.parentElement; } const hidePanelElement = <HTMLElement>currentElement.querySelector('.hide-panel-action'); hidePanelElement.focus(); })); xtermHelper.insertBefore(focusTrap, this._xterm.textarea); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'focus', (event: KeyboardEvent) => { this._terminalFocusContextKey.set(true); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'blur', (event: KeyboardEvent) => { this._terminalFocusContextKey.reset(); this._refreshSelectionContextKey(); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'focus', (event: KeyboardEvent) => { this._terminalFocusContextKey.set(true); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'blur', (event: KeyboardEvent) => { this._terminalFocusContextKey.reset(); this._refreshSelectionContextKey(); })); this._wrapperElement.appendChild(this._xtermElement); this._widgetManager = new TerminalWidgetManager(this._configHelper, this._wrapperElement); this._linkHandler.setWidgetManager(this._widgetManager); this._container.appendChild(this._wrapperElement); const computedStyle = window.getComputedStyle(this._container); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this.layout(new Dimension(width, height)); this.setVisible(this._isVisible); this.updateConfig(); // If IShellLaunchConfig.waitOnExit was true and the process finished before the terminal // panel was initialized. if (this._xterm.getOption('disableStdin')) { this._attachPressAnyKeyToCloseListener(); } } public registerLinkMatcher(regex: RegExp, handler: (url: string) => void, matchIndex?: number, validationCallback?: (uri: string, element: HTMLElement, callback: (isValid: boolean) => void) => void): number { return this._linkHandler.registerCustomLinkHandler(regex, handler, matchIndex, validationCallback); } public deregisterLinkMatcher(linkMatcherId: number): void { this._xterm.deregisterLinkMatcher(linkMatcherId); } public hasSelection(): boolean { return this._xterm.hasSelection(); } public copySelection(): void { if (this.hasSelection()) { this._clipboardService.writeText(this._xterm.getSelection()); } else { this._messageService.show(Severity.Warning, nls.localize('terminal.integrated.copySelection.noSelection', 'The terminal has no selection to copy')); } } get selection(): string | undefined { return this.hasSelection() ? this._xterm.getSelection() : undefined; } public clearSelection(): void { this._xterm.clearSelection(); } public selectAll(): void { // Focus here to ensure the terminal context key is set this._xterm.focus(); this._xterm.selectAll(); } public findNext(term: string): boolean { return this._xterm.findNext(term); } public findPrevious(term: string): boolean { return this._xterm.findPrevious(term); } public notifyFindWidgetFocusChanged(isFocused: boolean): void { // In order to support escape to close the find widget when the terminal // is focused terminalFocus needs to be true when either the terminal or // the find widget are focused. this._terminalFocusContextKey.set(isFocused || document.activeElement === this._xterm.textarea); } public dispose(): void { if (this._windowsShellHelper) { this._windowsShellHelper.dispose(); } if (this._linkHandler) { this._linkHandler.dispose(); } if (this._xterm && this._xterm.element) { this._hadFocusOnExit = dom.hasClass(this._xterm.element, 'focus'); } if (this._wrapperElement) { this._container.removeChild(this._wrapperElement); this._wrapperElement = null; } if (this._xterm) { this._xterm.destroy(); this._xterm = null; } if (this._process) { if (this._process.connected) { // If the process was still connected this dispose came from // within VS Code, not the process, so mark the process as // killed by the user. this._processState = ProcessState.KILLED_BY_USER; this._process.send({ event: 'shutdown' }); } this._process = null; } if (!this._isDisposed) { this._isDisposed = true; this._onDisposed.fire(this); } this._processDisposables = lifecycle.dispose(this._processDisposables); this._instanceDisposables = lifecycle.dispose(this._instanceDisposables); } public focus(force?: boolean): void { if (!this._xterm) { return; } const text = window.getSelection().toString(); if (!text || force) { this._xterm.focus(); } } public paste(): void { this.focus(); document.execCommand('paste'); } public sendText(text: string, addNewLine: boolean): void { this._processReady.then(() => { // Normalize line endings to 'enter' press. text = text.replace(TerminalInstance.EOL_REGEX, '\r'); if (addNewLine && text.substr(text.length - 1) !== '\r') { text += '\r'; } this._process.send({ event: 'input', data: text }); }); } public setVisible(visible: boolean): void { this._isVisible = visible; if (this._wrapperElement) { dom.toggleClass(this._wrapperElement, 'active', visible); } if (visible && this._xterm) { // Trigger a manual scroll event which will sync the viewport and scroll bar. This is // necessary if the number of rows in the terminal has decreased while it was in the // background since scrollTop changes take no effect but the terminal's position does // change since the number of visible rows decreases. this._xterm.emit('scroll', this._xterm.ydisp); } } public scrollDownLine(): void { this._xterm.scrollDisp(1); } public scrollDownPage(): void { this._xterm.scrollPages(1); } public scrollToBottom(): void { this._xterm.scrollToBottom(); } public scrollUpLine(): void { this._xterm.scrollDisp(-1); } public scrollUpPage(): void { this._xterm.scrollPages(-1); } public scrollToTop(): void { this._xterm.scrollToTop(); } public clear(): void { this._xterm.clear(); } private _refreshSelectionContextKey() { const activePanel = this._panelService.getActivePanel(); const isActive = activePanel && activePanel.getId() === TERMINAL_PANEL_ID; this._terminalHasTextContextKey.set(isActive && this.hasSelection()); } protected _getCwd(shell: IShellLaunchConfig, root: Uri): string { if (shell.cwd) { return shell.cwd; } let cwd: string; // TODO: Handle non-existent customCwd if (!shell.ignoreConfigurationCwd) { // Evaluate custom cwd first const customCwd = this._configHelper.config.cwd; if (customCwd) { if (path.isAbsolute(customCwd)) { cwd = customCwd; } else if (root) { cwd = path.normalize(path.join(root.fsPath, customCwd)); } } } // If there was no custom cwd or it was relative with no workspace if (!cwd) { cwd = root ? root.fsPath : os.homedir(); } return TerminalInstance._sanitizeCwd(cwd); } protected _createProcess(shell: IShellLaunchConfig): void { const locale = this._configHelper.config.setLocaleVariables ? platform.locale : undefined; if (!shell.executable) { this._configHelper.mergeDefaultShellPathAndArgs(shell); } this._initialCwd = this._getCwd(this._shellLaunchConfig, this._historyService.getLastActiveWorkspaceRoot()); let envFromConfig: IStringDictionary<string>; if (platform.isWindows) { envFromConfig = { ...process.env }; for (let configKey in this._configHelper.config.env['windows']) { let actualKey = configKey; for (let envKey in envFromConfig) { if (configKey.toLowerCase() === envKey.toLowerCase()) { actualKey = envKey; break; } } envFromConfig[actualKey] = this._configHelper.config.env['windows'][configKey]; } } else { const platformKey = platform.isMacintosh ? 'osx' : 'linux'; envFromConfig = { ...process.env, ...this._configHelper.config.env[platformKey] }; } const env = TerminalInstance.createTerminalEnv(envFromConfig, shell, this._initialCwd, locale, this._cols, this._rows); this._process = cp.fork(Uri.parse(require.toUrl('bootstrap')).fsPath, ['--type=terminal'], { env, cwd: Uri.parse(path.dirname(require.toUrl('../node/terminalProcess'))).fsPath }); this._processState = ProcessState.LAUNCHING; if (shell.name) { this.setTitle(shell.name, false); } else { // Only listen for process title changes when a name is not provided this.setTitle(shell.executable, true); this._messageTitleListener = (message) => { if (message.type === 'title') { this.setTitle(message.content ? message.content : '', true); } }; this._process.on('message', this._messageTitleListener); } this._process.on('message', (message) => { if (message.type === 'pid') { this._processId = message.content; // Send any queued data that's waiting if (this._preLaunchInputQueue.length > 0) { this._process.send({ event: 'input', data: this._preLaunchInputQueue }); this._preLaunchInputQueue = null; } this._onProcessIdReady.fire(this); } }); this._process.on('exit', exitCode => this._onPtyProcessExit(exitCode)); setTimeout(() => { if (this._processState === ProcessState.LAUNCHING) { this._processState = ProcessState.RUNNING; } }, LAUNCHING_DURATION); } private _sendPtyDataToXterm(message: { type: string, content: string }): void { if (message.type === 'data') { if (this._widgetManager) { this._widgetManager.closeMessage(); } if (this._xterm) { this._xterm.write(message.content); } } } private _onPtyProcessExit(exitCode: number): void { // Prevent dispose functions being triggered multiple times if (this._isExiting) { return; } this._isExiting = true; this._process = null; let exitCodeMessage: string; if (exitCode) { exitCodeMessage = nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode); } // If the process is marked as launching then mark the process as killed // during launch. This typically means that there is a problem with the // shell and args. if (this._processState === ProcessState.LAUNCHING) { this._processState = ProcessState.KILLED_DURING_LAUNCH; } // If TerminalInstance did not know about the process exit then it was // triggered by the process, not on VS Code's side. if (this._processState === ProcessState.RUNNING) { this._processState = ProcessState.KILLED_BY_PROCESS; } // Only trigger wait on exit when the exit was triggered by the process, // not through the `workbench.action.terminal.kill` command if (this._processState === ProcessState.KILLED_BY_PROCESS && this._shellLaunchConfig.waitOnExit) { if (exitCode) { this._xterm.writeln(exitCodeMessage); } let message = typeof this._shellLaunchConfig.waitOnExit === 'string' ? this._shellLaunchConfig.waitOnExit : nls.localize('terminal.integrated.waitOnExit', 'Press any key to close the terminal'); // Bold the message and add an extra new line to make it stand out from the rest of the output message = `\n\x1b[1m${message}\x1b[0m`; this._xterm.writeln(message); // Disable all input if the terminal is exiting and listen for next keypress this._xterm.setOption('disableStdin', true); if (this._xterm.textarea) { this._attachPressAnyKeyToCloseListener(); } } else { this.dispose(); if (exitCode) { if (this._processState === ProcessState.KILLED_DURING_LAUNCH) { let args = ''; if (typeof this._shellLaunchConfig.args === 'string') { args = this._shellLaunchConfig.args; } else if (this._shellLaunchConfig.args && this._shellLaunchConfig.args.length) { args = ' ' + this._shellLaunchConfig.args.map(a => { if (typeof a === 'string' && a.indexOf(' ') !== -1) { return `'${a}'`; } return a; }).join(' '); } this._messageService.show(Severity.Error, nls.localize('terminal.integrated.launchFailed', 'The terminal process command `{0}{1}` failed to launch (exit code: {2})', this._shellLaunchConfig.executable, args, exitCode)); } else { this._messageService.show(Severity.Error, exitCodeMessage); } } } } private _attachPressAnyKeyToCloseListener() { this._processDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'keypress', (event: KeyboardEvent) => { this.dispose(); event.preventDefault(); })); } public reuseTerminal(shell?: IShellLaunchConfig): void { // Kill and clean up old process if (this._process) { this._process.removeAllListeners('exit'); if (this._process.connected) { this._process.kill(); } this._process = null; } lifecycle.dispose(this._processDisposables); this._processDisposables = []; // Ensure new processes' output starts at start of new line this._xterm.write('\n\x1b[G'); // Print initialText if specified if (shell.initialText) { this._xterm.writeln(shell.initialText); } // Initialize new process const oldTitle = this._title; this._createProcess(shell); if (oldTitle !== this._title) { this.setTitle(this._title, true); } this._process.on('message', (message) => this._sendPtyDataToXterm(message)); // Clean up waitOnExit state if (this._isExiting && this._shellLaunchConfig.waitOnExit) { this._xterm.setOption('disableStdin', false); this._isExiting = false; } // Set the new shell launch config this._shellLaunchConfig = shell; } // TODO: This should be private/protected // TODO: locale should not be optional public static createTerminalEnv(parentEnv: IStringDictionary<string>, shell: IShellLaunchConfig, cwd: string, locale?: string, cols?: number, rows?: number): IStringDictionary<string> { const env = shell.env ? shell.env : TerminalInstance._cloneEnv(parentEnv); env['PTYPID'] = process.pid.toString(); env['PTYSHELL'] = shell.executable; env['TERM_PROGRAM'] = 'vscode'; env['TERM_PROGRAM_VERSION'] = pkg.version; if (shell.args) { if (typeof shell.args === 'string') { env[`PTYSHELLCMDLINE`] = shell.args; } else { shell.args.forEach((arg, i) => env[`PTYSHELLARG${i}`] = arg); } } env['PTYCWD'] = cwd; env['LANG'] = TerminalInstance._getLangEnvVariable(locale); if (cols && rows) { env['PTYCOLS'] = cols.toString(); env['PTYROWS'] = rows.toString(); } env['AMD_ENTRYPOINT'] = 'vs/workbench/parts/terminal/node/terminalProcess'; return env; } public onData(listener: (data: string) => void): lifecycle.IDisposable { let callback = (message) => { if (message.type === 'data') { listener(message.content); } }; this._process.on('message', callback); return { dispose: () => { if (this._process) { this._process.removeListener('message', callback); } } }; } public onExit(listener: (exitCode: number) => void): lifecycle.IDisposable { if (this._process) { this._process.on('exit', listener); } return { dispose: () => { if (this._process) { this._process.removeListener('exit', listener); } } }; } private static _sanitizeCwd(cwd: string) { // Make the drive letter uppercase on Windows (see #9448) if (platform.platform === platform.Platform.Windows && cwd && cwd[1] === ':') { return cwd[0].toUpperCase() + cwd.substr(1); } return cwd; } private static _cloneEnv(env: IStringDictionary<string>): IStringDictionary<string> { const newEnv: IStringDictionary<string> = Object.create(null); Object.keys(env).forEach((key) => { newEnv[key] = env[key]; }); return newEnv; } private static _getLangEnvVariable(locale?: string) { const parts = locale ? locale.split('-') : []; const n = parts.length; if (n === 0) { // Fallback to en_US to prevent possible encoding issues. return 'en_US.UTF-8'; } if (n === 1) { // app.getLocale can return just a language without a variant, fill in the variant for // supported languages as many shells expect a 2-part locale. const languageVariants = { de: 'DE', en: 'US', es: 'ES', fr: 'FR', it: 'IT', ja: 'JP', ko: 'KR', ru: 'RU', zh: 'CN' }; if (parts[0] in languageVariants) { parts.push(languageVariants[parts[0]]); } } else { // Ensure the variant is uppercase parts[1] = parts[1].toUpperCase(); } return parts.join('_') + '.UTF-8'; } public updateConfig(): void { this._setCursorBlink(this._configHelper.config.cursorBlinking); this._setCursorStyle(this._configHelper.config.cursorStyle); this._setCommandsToSkipShell(this._configHelper.config.commandsToSkipShell); this._setScrollback(this._configHelper.config.scrollback); } private _setCursorBlink(blink: boolean): void { if (this._xterm && this._xterm.getOption('cursorBlink') !== blink) { this._xterm.setOption('cursorBlink', blink); this._xterm.refresh(0, this._xterm.rows - 1); } } private _setCursorStyle(style: string): void { if (this._xterm && this._xterm.getOption('cursorStyle') !== style) { // 'line' is used instead of bar in VS Code to be consistent with editor.cursorStyle const xtermOption = style === 'line' ? 'bar' : style; this._xterm.setOption('cursorStyle', xtermOption); } } private _setCommandsToSkipShell(commands: string[]): void { this._skipTerminalCommands = commands; } private _setScrollback(lineCount: number): void { if (this._xterm && this._xterm.getOption('scrollback') !== lineCount) { this._xterm.setOption('scrollback', lineCount); } } public layout(dimension: Dimension): void { const terminalWidth = this._evaluateColsAndRows(dimension.width, dimension.height); if (!terminalWidth) { return; } if (this._xterm) { this._xterm.resize(this._cols, this._rows); this._xterm.element.style.width = terminalWidth + 'px'; } this._processReady.then(() => { if (this._process && this._process.connected) { // The child process could aready be terminated try { this._process.send({ event: 'resize', cols: this._cols, rows: this._rows }); } catch (error) { // We tried to write to a closed pipe / channel. if (error.code !== 'EPIPE' && error.code !== 'ERR_IPC_CHANNEL_CLOSED') { throw (error); } } } }); } public static setTerminalProcessFactory(factory: ITerminalProcessFactory): void { this._terminalProcessFactory = factory; } public setTitle(title: string, eventFromProcess: boolean): void { if (!title) { return; } if (eventFromProcess) { title = path.basename(title); if (platform.isWindows) { // Remove the .exe extension title = title.split('.exe')[0]; } } else { // If the title has not been set by the API or the rename command, unregister the handler that // automatically updates the terminal name if (this._process && this._messageTitleListener) { this._process.removeListener('message', this._messageTitleListener); this._messageTitleListener = null; } } const didTitleChange = title !== this._title; this._title = title; if (didTitleChange) { this._onTitleChanged.fire(title); } } } registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { // Scrollbar const scrollbarSliderBackgroundColor = theme.getColor(scrollbarSliderBackground); if (scrollbarSliderBackgroundColor) { collector.addRule(` .monaco-workbench .panel.integrated-terminal .xterm.focus .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm:focus .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm:hover .xterm-viewport { background-color: ${scrollbarSliderBackgroundColor}; }` ); } const scrollbarSliderHoverBackgroundColor = theme.getColor(scrollbarSliderHoverBackground); if (scrollbarSliderHoverBackgroundColor) { collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:hover { background-color: ${scrollbarSliderHoverBackgroundColor}; }`); } const scrollbarSliderActiveBackgroundColor = theme.getColor(scrollbarSliderActiveBackground); if (scrollbarSliderActiveBackgroundColor) { collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:active { background-color: ${scrollbarSliderActiveBackgroundColor}; }`); } });
src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts
1
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.9956997632980347, 0.05947871506214142, 0.00016396422870457172, 0.00018772660405375063, 0.2177293598651886 ]
{ "id": 4, "code_window": [ "\t\t\tenv,\n", "\t\t\tcwd: Uri.parse(path.dirname(require.toUrl('../node/terminalProcess'))).fsPath\n", "\t\t});\n", "\t\tthis._processState = ProcessState.LAUNCHING;\n", "\n", "\t\tif (shell.name) {\n", "\t\t\tthis.setTitle(shell.name, false);\n", "\t\t} else {\n", "\t\t\t// Only listen for process title changes when a name is not provided\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\tif (this._shellLaunchConfig.name) {\n", "\t\t\tthis.setTitle(this._shellLaunchConfig.name, false);\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 588 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "contributes.jsonValidation": "提供 JSON 結構描述組態。", "contributes.jsonValidation.fileMatch": "要比對的檔案模式,例如 \"package.json\" 或 \"*.launch\"。", "contributes.jsonValidation.url": "結構描述 URL ('http:'、'https:') 或擴充功能資料夾的相對路徑 ('./')。", "invalid.jsonValidation": "'configuration.jsonValidation' 必須是陣列", "invalid.fileMatch": "必須定義 'configuration.jsonValidation.fileMatch'", "invalid.url": "'configuration.jsonValidation.url' 必須是 URL 或相對路徑", "invalid.url.fileschema": "'configuration.jsonValidation.url' 是無效的相對 URL: {0}", "invalid.url.schema": "'configuration.jsonValidation.url' 必須以 'http:'、'https:' 或 './' 開頭,以參考位於擴充功能中的結構描述" }
i18n/cht/src/vs/platform/jsonschemas/common/jsonValidationExtensionPoint.i18n.json
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.00017419550567865372, 0.00017280373140238225, 0.00017141194257419556, 0.00017280373140238225, 0.0000013917815522290766 ]
{ "id": 4, "code_window": [ "\t\t\tenv,\n", "\t\t\tcwd: Uri.parse(path.dirname(require.toUrl('../node/terminalProcess'))).fsPath\n", "\t\t});\n", "\t\tthis._processState = ProcessState.LAUNCHING;\n", "\n", "\t\tif (shell.name) {\n", "\t\t\tthis.setTitle(shell.name, false);\n", "\t\t} else {\n", "\t\t\t// Only listen for process title changes when a name is not provided\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\tif (this._shellLaunchConfig.name) {\n", "\t\t\tthis.setTitle(this._shellLaunchConfig.name, false);\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 588 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "patchedWindowTitle": "[Non supportata]", "devExtensionWindowTitlePrefix": "[Host di sviluppo estensione]" }
i18n/ita/src/vs/workbench/browser/parts/titlebar/titlebarPart.i18n.json
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.00017649555229581892, 0.00017649555229581892, 0.00017649555229581892, 0.00017649555229581892, 0 ]
{ "id": 4, "code_window": [ "\t\t\tenv,\n", "\t\t\tcwd: Uri.parse(path.dirname(require.toUrl('../node/terminalProcess'))).fsPath\n", "\t\t});\n", "\t\tthis._processState = ProcessState.LAUNCHING;\n", "\n", "\t\tif (shell.name) {\n", "\t\t\tthis.setTitle(shell.name, false);\n", "\t\t} else {\n", "\t\t\t// Only listen for process title changes when a name is not provided\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\tif (this._shellLaunchConfig.name) {\n", "\t\t\tthis.setTitle(this._shellLaunchConfig.name, false);\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 588 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "fileInvalidPath": "Recurso de archivo no válido ({0})", "fileIsDirectoryError": "El archivo es un directorio ({0})", "fileNotModifiedError": "Archivo no modificado desde", "fileTooLargeError": "Archivo demasiado grande para abrirlo", "fileBinaryError": "El archivo parece ser binario y no se puede abrir como texto", "fileNotFoundError": "Archivo no encontrado ({0})", "fileMoveConflict": "No se puede mover o copiar. El archivo ya existe en la ubicación de destino. ", "unableToMoveCopyError": "No se puede mover o copiar. El archivo reemplazaría a la carpeta que lo contiene.", "foldersCopyError": "No se pueden copiar carpetas en el área de trabajo. Seleccione archivos individuales para copiarlos.", "fileModifiedError": "Archivo Modificado Desde", "fileReadOnlyError": "El archivo es de solo lectura" }
i18n/esn/src/vs/workbench/services/files/node/fileService.i18n.json
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.0001752028038026765, 0.0001742708554957062, 0.0001733389071887359, 0.0001742708554957062, 9.319483069702983e-7 ]
{ "id": 5, "code_window": [ "\t\t} else {\n", "\t\t\t// Only listen for process title changes when a name is not provided\n", "\t\t\tthis.setTitle(shell.executable, true);\n", "\t\t\tthis._messageTitleListener = (message) => {\n", "\t\t\t\tif (message.type === 'title') {\n", "\t\t\t\t\tthis.setTitle(message.content ? message.content : '', true);\n", "\t\t\t\t}\n", "\t\t\t};\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.setTitle(this._shellLaunchConfig.executable, true);\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 592 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as cp from 'child_process'; import * as os from 'os'; import * as path from 'path'; import * as lifecycle from 'vs/base/common/lifecycle'; import * as nls from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import * as dom from 'vs/base/browser/dom'; import Event, { Emitter } from 'vs/base/common/event'; import Uri from 'vs/base/common/uri'; import { WindowsShellHelper } from 'vs/workbench/parts/terminal/electron-browser/windowsShellHelper'; import { Terminal as XTermTerminal } from 'xterm'; import { Dimension } from 'vs/base/browser/builder'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IMessageService, Severity } from 'vs/platform/message/common/message'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IStringDictionary } from 'vs/base/common/collections'; import { ITerminalInstance, KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED, TERMINAL_PANEL_ID, IShellLaunchConfig } from 'vs/workbench/parts/terminal/common/terminal'; import { ITerminalProcessFactory } from 'vs/workbench/parts/terminal/electron-browser/terminal'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { TabFocus } from 'vs/editor/common/config/commonEditorConfig'; import { TerminalConfigHelper } from 'vs/workbench/parts/terminal/electron-browser/terminalConfigHelper'; import { TerminalLinkHandler } from 'vs/workbench/parts/terminal/electron-browser/terminalLinkHandler'; import { TerminalWidgetManager } from 'vs/workbench/parts/terminal/browser/terminalWidgetManager'; import { registerThemingParticipant, ITheme, ICssStyleCollector } from 'vs/platform/theme/common/themeService'; import { scrollbarSliderBackground, scrollbarSliderHoverBackground, scrollbarSliderActiveBackground } from 'vs/platform/theme/common/colorRegistry'; import { TPromise } from 'vs/base/common/winjs.base'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { IHistoryService } from 'vs/workbench/services/history/common/history'; import pkg from 'vs/platform/node/package'; /** The amount of time to consider terminal errors to be related to the launch */ const LAUNCHING_DURATION = 500; // Enable search functionality in xterm.js instance XTermTerminal.loadAddon('search'); class StandardTerminalProcessFactory implements ITerminalProcessFactory { public create(env: { [key: string]: string }): cp.ChildProcess { return cp.fork('./terminalProcess', [], { env, cwd: Uri.parse(path.dirname(require.toUrl('./terminalProcess'))).fsPath }); } } enum ProcessState { // The process has not been initialized yet. UNINITIALIZED, // The process is currently launching, the process is marked as launching // for a short duration after being created and is helpful to indicate // whether the process died as a result of bad shell and args. LAUNCHING, // The process is running normally. RUNNING, // The process was killed during launch, likely as a result of bad shell and // args. KILLED_DURING_LAUNCH, // The process was killed by the user (the event originated from VS Code). KILLED_BY_USER, // The process was killed by itself, for example the shell crashed or `exit` // was run. KILLED_BY_PROCESS } export class TerminalInstance implements ITerminalInstance { private static readonly EOL_REGEX = /\r?\n/g; private static _terminalProcessFactory: ITerminalProcessFactory = new StandardTerminalProcessFactory(); private static _lastKnownDimensions: Dimension = null; private static _idCounter = 1; private _id: number; private _isExiting: boolean; private _hadFocusOnExit: boolean; private _isVisible: boolean; private _processState: ProcessState; private _processReady: TPromise<void>; private _isDisposed: boolean; private _onDisposed: Emitter<ITerminalInstance>; private _onDataForApi: Emitter<{ instance: ITerminalInstance, data: string }>; private _onProcessIdReady: Emitter<TerminalInstance>; private _onTitleChanged: Emitter<string>; private _process: cp.ChildProcess; private _processId: number; private _skipTerminalCommands: string[]; private _title: string; private _instanceDisposables: lifecycle.IDisposable[]; private _processDisposables: lifecycle.IDisposable[]; private _wrapperElement: HTMLDivElement; private _xterm: XTermTerminal; private _xtermElement: HTMLDivElement; private _terminalHasTextContextKey: IContextKey<boolean>; private _cols: number; private _rows: number; private _messageTitleListener: (message: { type: string, content: string }) => void; private _preLaunchInputQueue: string; private _initialCwd: string; private _windowsShellHelper: WindowsShellHelper; private _widgetManager: TerminalWidgetManager; private _linkHandler: TerminalLinkHandler; public get id(): number { return this._id; } public get processId(): number { return this._processId; } public get onDisposed(): Event<ITerminalInstance> { return this._onDisposed.event; } public get onDataForApi(): Event<{ instance: ITerminalInstance, data: string }> { return this._onDataForApi.event; } public get onProcessIdReady(): Event<TerminalInstance> { return this._onProcessIdReady.event; } public get onTitleChanged(): Event<string> { return this._onTitleChanged.event; } public get title(): string { return this._title; } public get hadFocusOnExit(): boolean { return this._hadFocusOnExit; } public get isTitleSetByProcess(): boolean { return !!this._messageTitleListener; } public constructor( private _terminalFocusContextKey: IContextKey<boolean>, private _configHelper: TerminalConfigHelper, private _container: HTMLElement, private _shellLaunchConfig: IShellLaunchConfig, @IContextKeyService private _contextKeyService: IContextKeyService, @IKeybindingService private _keybindingService: IKeybindingService, @IMessageService private _messageService: IMessageService, @IPanelService private _panelService: IPanelService, @IWorkspaceContextService private _contextService: IWorkspaceContextService, @IWorkbenchEditorService private _editorService: IWorkbenchEditorService, @IInstantiationService private _instantiationService: IInstantiationService, @IClipboardService private _clipboardService: IClipboardService, @IHistoryService private _historyService: IHistoryService ) { this._instanceDisposables = []; this._processDisposables = []; this._skipTerminalCommands = []; this._isExiting = false; this._hadFocusOnExit = false; this._processState = ProcessState.UNINITIALIZED; this._isVisible = false; this._isDisposed = false; this._id = TerminalInstance._idCounter++; this._terminalHasTextContextKey = KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED.bindTo(this._contextKeyService); this._preLaunchInputQueue = ''; this._onDisposed = new Emitter<TerminalInstance>(); this._onDataForApi = new Emitter<{ instance: ITerminalInstance, data: string }>(); this._onProcessIdReady = new Emitter<TerminalInstance>(); this._onTitleChanged = new Emitter<string>(); // Create a promise that resolves when the pty is ready this._processReady = new TPromise<void>(c => { this.onProcessIdReady(() => c(void 0)); }); this._initDimensions(); this._createProcess(this._shellLaunchConfig); this._createXterm(); if (platform.isWindows) { this._processReady.then(() => { if (!this._isDisposed) { import('vs/workbench/parts/terminal/electron-browser/windowsShellHelper').then((module) => { this._windowsShellHelper = new module.WindowsShellHelper(this._processId, this._shellLaunchConfig.executable, this, this._xterm); }); } }); } // Only attach xterm.js to the DOM if the terminal panel has been opened before. if (_container) { this.attachToElement(_container); } } public addDisposable(disposable: lifecycle.IDisposable): void { this._instanceDisposables.push(disposable); } private _initDimensions(): void { // The terminal panel needs to have been created if (!this._container) { return; } const computedStyle = window.getComputedStyle(this._container); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this._evaluateColsAndRows(width, height); } /** * Evaluates and sets the cols and rows of the terminal if possible. * @param width The width of the container. * @param height The height of the container. * @return The terminal's width if it requires a layout. */ private _evaluateColsAndRows(width: number, height: number): number { const dimension = this._getDimension(width, height); if (!dimension) { return null; } const font = this._configHelper.getFont(); this._cols = Math.max(Math.floor(dimension.width / font.charWidth), 1); this._rows = Math.max(Math.floor(dimension.height / font.charHeight), 1); return dimension.width; } private _getDimension(width: number, height: number): Dimension { // The font needs to have been initialized const font = this._configHelper.getFont(); if (!font || !font.charWidth || !font.charHeight) { return null; } // The panel is minimized if (!height) { return TerminalInstance._lastKnownDimensions; } else { // Trigger scroll event manually so that the viewport's scroll area is synced. This // needs to happen otherwise its scrollTop value is invalid when the panel is toggled as // it gets removed and then added back to the DOM (resetting scrollTop to 0). // Upstream issue: https://github.com/sourcelair/xterm.js/issues/291 if (this._xterm) { this._xterm.emit('scroll', this._xterm.ydisp); } } const outerContainer = document.querySelector('.terminal-outer-container'); const outerContainerStyle = getComputedStyle(outerContainer); const padding = parseInt(outerContainerStyle.paddingLeft.split('px')[0], 10); const paddingBottom = parseInt(outerContainerStyle.paddingBottom.split('px')[0], 10); // Use left padding as right padding, right padding is not defined in CSS just in case // xterm.js causes an unexpected overflow. const innerWidth = width - padding * 2; const innerHeight = height - paddingBottom; TerminalInstance._lastKnownDimensions = new Dimension(innerWidth, innerHeight); return TerminalInstance._lastKnownDimensions; } /** * Create xterm.js instance and attach data listeners. */ protected _createXterm(): void { this._xterm = new XTermTerminal({ scrollback: this._configHelper.config.scrollback }); if (this._shellLaunchConfig.initialText) { this._xterm.writeln(this._shellLaunchConfig.initialText); } this._process.on('message', (message) => this._sendPtyDataToXterm(message)); this._xterm.on('data', (data) => { if (this._processId) { // Send data if the pty is ready this._process.send({ event: 'input', data }); } else { // If the pty is not ready, queue the data received from // xterm.js until the pty is ready this._preLaunchInputQueue += data; } return false; }); this._linkHandler = this._instantiationService.createInstance(TerminalLinkHandler, this._xterm, platform.platform, this._initialCwd); this._linkHandler.registerLocalLinkHandler(); } public attachToElement(container: HTMLElement): void { if (this._wrapperElement) { throw new Error('The terminal instance has already been attached to a container'); } this._container = container; this._wrapperElement = document.createElement('div'); dom.addClass(this._wrapperElement, 'terminal-wrapper'); this._xtermElement = document.createElement('div'); this._xterm.open(this._xtermElement); this._xterm.attachCustomKeyEventHandler((event: KeyboardEvent) => { // Disable all input if the terminal is exiting if (this._isExiting) { return false; } // Skip processing by xterm.js of keyboard events that resolve to commands described // within commandsToSkipShell const standardKeyboardEvent = new StandardKeyboardEvent(event); const resolveResult = this._keybindingService.softDispatch(standardKeyboardEvent, standardKeyboardEvent.target); if (resolveResult && this._skipTerminalCommands.some(k => k === resolveResult.commandId)) { event.preventDefault(); return false; } // If tab focus mode is on, tab is not passed to the terminal if (TabFocus.getTabFocusMode() && event.keyCode === 9) { return false; } return undefined; }); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'mouseup', (event: KeyboardEvent) => { // Wait until mouseup has propagated through the DOM before // evaluating the new selection state. setTimeout(() => this._refreshSelectionContextKey(), 0); })); // xterm.js currently drops selection on keyup as we need to handle this case. this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'keyup', (event: KeyboardEvent) => { // Wait until keyup has propagated through the DOM before evaluating // the new selection state. setTimeout(() => this._refreshSelectionContextKey(), 0); })); const xtermHelper: HTMLElement = <HTMLElement>this._xterm.element.querySelector('.xterm-helpers'); const focusTrap: HTMLElement = document.createElement('div'); focusTrap.setAttribute('tabindex', '0'); dom.addClass(focusTrap, 'focus-trap'); this._instanceDisposables.push(dom.addDisposableListener(focusTrap, 'focus', (event: FocusEvent) => { let currentElement = focusTrap; while (!dom.hasClass(currentElement, 'part')) { currentElement = currentElement.parentElement; } const hidePanelElement = <HTMLElement>currentElement.querySelector('.hide-panel-action'); hidePanelElement.focus(); })); xtermHelper.insertBefore(focusTrap, this._xterm.textarea); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'focus', (event: KeyboardEvent) => { this._terminalFocusContextKey.set(true); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'blur', (event: KeyboardEvent) => { this._terminalFocusContextKey.reset(); this._refreshSelectionContextKey(); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'focus', (event: KeyboardEvent) => { this._terminalFocusContextKey.set(true); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'blur', (event: KeyboardEvent) => { this._terminalFocusContextKey.reset(); this._refreshSelectionContextKey(); })); this._wrapperElement.appendChild(this._xtermElement); this._widgetManager = new TerminalWidgetManager(this._configHelper, this._wrapperElement); this._linkHandler.setWidgetManager(this._widgetManager); this._container.appendChild(this._wrapperElement); const computedStyle = window.getComputedStyle(this._container); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this.layout(new Dimension(width, height)); this.setVisible(this._isVisible); this.updateConfig(); // If IShellLaunchConfig.waitOnExit was true and the process finished before the terminal // panel was initialized. if (this._xterm.getOption('disableStdin')) { this._attachPressAnyKeyToCloseListener(); } } public registerLinkMatcher(regex: RegExp, handler: (url: string) => void, matchIndex?: number, validationCallback?: (uri: string, element: HTMLElement, callback: (isValid: boolean) => void) => void): number { return this._linkHandler.registerCustomLinkHandler(regex, handler, matchIndex, validationCallback); } public deregisterLinkMatcher(linkMatcherId: number): void { this._xterm.deregisterLinkMatcher(linkMatcherId); } public hasSelection(): boolean { return this._xterm.hasSelection(); } public copySelection(): void { if (this.hasSelection()) { this._clipboardService.writeText(this._xterm.getSelection()); } else { this._messageService.show(Severity.Warning, nls.localize('terminal.integrated.copySelection.noSelection', 'The terminal has no selection to copy')); } } get selection(): string | undefined { return this.hasSelection() ? this._xterm.getSelection() : undefined; } public clearSelection(): void { this._xterm.clearSelection(); } public selectAll(): void { // Focus here to ensure the terminal context key is set this._xterm.focus(); this._xterm.selectAll(); } public findNext(term: string): boolean { return this._xterm.findNext(term); } public findPrevious(term: string): boolean { return this._xterm.findPrevious(term); } public notifyFindWidgetFocusChanged(isFocused: boolean): void { // In order to support escape to close the find widget when the terminal // is focused terminalFocus needs to be true when either the terminal or // the find widget are focused. this._terminalFocusContextKey.set(isFocused || document.activeElement === this._xterm.textarea); } public dispose(): void { if (this._windowsShellHelper) { this._windowsShellHelper.dispose(); } if (this._linkHandler) { this._linkHandler.dispose(); } if (this._xterm && this._xterm.element) { this._hadFocusOnExit = dom.hasClass(this._xterm.element, 'focus'); } if (this._wrapperElement) { this._container.removeChild(this._wrapperElement); this._wrapperElement = null; } if (this._xterm) { this._xterm.destroy(); this._xterm = null; } if (this._process) { if (this._process.connected) { // If the process was still connected this dispose came from // within VS Code, not the process, so mark the process as // killed by the user. this._processState = ProcessState.KILLED_BY_USER; this._process.send({ event: 'shutdown' }); } this._process = null; } if (!this._isDisposed) { this._isDisposed = true; this._onDisposed.fire(this); } this._processDisposables = lifecycle.dispose(this._processDisposables); this._instanceDisposables = lifecycle.dispose(this._instanceDisposables); } public focus(force?: boolean): void { if (!this._xterm) { return; } const text = window.getSelection().toString(); if (!text || force) { this._xterm.focus(); } } public paste(): void { this.focus(); document.execCommand('paste'); } public sendText(text: string, addNewLine: boolean): void { this._processReady.then(() => { // Normalize line endings to 'enter' press. text = text.replace(TerminalInstance.EOL_REGEX, '\r'); if (addNewLine && text.substr(text.length - 1) !== '\r') { text += '\r'; } this._process.send({ event: 'input', data: text }); }); } public setVisible(visible: boolean): void { this._isVisible = visible; if (this._wrapperElement) { dom.toggleClass(this._wrapperElement, 'active', visible); } if (visible && this._xterm) { // Trigger a manual scroll event which will sync the viewport and scroll bar. This is // necessary if the number of rows in the terminal has decreased while it was in the // background since scrollTop changes take no effect but the terminal's position does // change since the number of visible rows decreases. this._xterm.emit('scroll', this._xterm.ydisp); } } public scrollDownLine(): void { this._xterm.scrollDisp(1); } public scrollDownPage(): void { this._xterm.scrollPages(1); } public scrollToBottom(): void { this._xterm.scrollToBottom(); } public scrollUpLine(): void { this._xterm.scrollDisp(-1); } public scrollUpPage(): void { this._xterm.scrollPages(-1); } public scrollToTop(): void { this._xterm.scrollToTop(); } public clear(): void { this._xterm.clear(); } private _refreshSelectionContextKey() { const activePanel = this._panelService.getActivePanel(); const isActive = activePanel && activePanel.getId() === TERMINAL_PANEL_ID; this._terminalHasTextContextKey.set(isActive && this.hasSelection()); } protected _getCwd(shell: IShellLaunchConfig, root: Uri): string { if (shell.cwd) { return shell.cwd; } let cwd: string; // TODO: Handle non-existent customCwd if (!shell.ignoreConfigurationCwd) { // Evaluate custom cwd first const customCwd = this._configHelper.config.cwd; if (customCwd) { if (path.isAbsolute(customCwd)) { cwd = customCwd; } else if (root) { cwd = path.normalize(path.join(root.fsPath, customCwd)); } } } // If there was no custom cwd or it was relative with no workspace if (!cwd) { cwd = root ? root.fsPath : os.homedir(); } return TerminalInstance._sanitizeCwd(cwd); } protected _createProcess(shell: IShellLaunchConfig): void { const locale = this._configHelper.config.setLocaleVariables ? platform.locale : undefined; if (!shell.executable) { this._configHelper.mergeDefaultShellPathAndArgs(shell); } this._initialCwd = this._getCwd(this._shellLaunchConfig, this._historyService.getLastActiveWorkspaceRoot()); let envFromConfig: IStringDictionary<string>; if (platform.isWindows) { envFromConfig = { ...process.env }; for (let configKey in this._configHelper.config.env['windows']) { let actualKey = configKey; for (let envKey in envFromConfig) { if (configKey.toLowerCase() === envKey.toLowerCase()) { actualKey = envKey; break; } } envFromConfig[actualKey] = this._configHelper.config.env['windows'][configKey]; } } else { const platformKey = platform.isMacintosh ? 'osx' : 'linux'; envFromConfig = { ...process.env, ...this._configHelper.config.env[platformKey] }; } const env = TerminalInstance.createTerminalEnv(envFromConfig, shell, this._initialCwd, locale, this._cols, this._rows); this._process = cp.fork(Uri.parse(require.toUrl('bootstrap')).fsPath, ['--type=terminal'], { env, cwd: Uri.parse(path.dirname(require.toUrl('../node/terminalProcess'))).fsPath }); this._processState = ProcessState.LAUNCHING; if (shell.name) { this.setTitle(shell.name, false); } else { // Only listen for process title changes when a name is not provided this.setTitle(shell.executable, true); this._messageTitleListener = (message) => { if (message.type === 'title') { this.setTitle(message.content ? message.content : '', true); } }; this._process.on('message', this._messageTitleListener); } this._process.on('message', (message) => { if (message.type === 'pid') { this._processId = message.content; // Send any queued data that's waiting if (this._preLaunchInputQueue.length > 0) { this._process.send({ event: 'input', data: this._preLaunchInputQueue }); this._preLaunchInputQueue = null; } this._onProcessIdReady.fire(this); } }); this._process.on('exit', exitCode => this._onPtyProcessExit(exitCode)); setTimeout(() => { if (this._processState === ProcessState.LAUNCHING) { this._processState = ProcessState.RUNNING; } }, LAUNCHING_DURATION); } private _sendPtyDataToXterm(message: { type: string, content: string }): void { if (message.type === 'data') { if (this._widgetManager) { this._widgetManager.closeMessage(); } if (this._xterm) { this._xterm.write(message.content); } } } private _onPtyProcessExit(exitCode: number): void { // Prevent dispose functions being triggered multiple times if (this._isExiting) { return; } this._isExiting = true; this._process = null; let exitCodeMessage: string; if (exitCode) { exitCodeMessage = nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode); } // If the process is marked as launching then mark the process as killed // during launch. This typically means that there is a problem with the // shell and args. if (this._processState === ProcessState.LAUNCHING) { this._processState = ProcessState.KILLED_DURING_LAUNCH; } // If TerminalInstance did not know about the process exit then it was // triggered by the process, not on VS Code's side. if (this._processState === ProcessState.RUNNING) { this._processState = ProcessState.KILLED_BY_PROCESS; } // Only trigger wait on exit when the exit was triggered by the process, // not through the `workbench.action.terminal.kill` command if (this._processState === ProcessState.KILLED_BY_PROCESS && this._shellLaunchConfig.waitOnExit) { if (exitCode) { this._xterm.writeln(exitCodeMessage); } let message = typeof this._shellLaunchConfig.waitOnExit === 'string' ? this._shellLaunchConfig.waitOnExit : nls.localize('terminal.integrated.waitOnExit', 'Press any key to close the terminal'); // Bold the message and add an extra new line to make it stand out from the rest of the output message = `\n\x1b[1m${message}\x1b[0m`; this._xterm.writeln(message); // Disable all input if the terminal is exiting and listen for next keypress this._xterm.setOption('disableStdin', true); if (this._xterm.textarea) { this._attachPressAnyKeyToCloseListener(); } } else { this.dispose(); if (exitCode) { if (this._processState === ProcessState.KILLED_DURING_LAUNCH) { let args = ''; if (typeof this._shellLaunchConfig.args === 'string') { args = this._shellLaunchConfig.args; } else if (this._shellLaunchConfig.args && this._shellLaunchConfig.args.length) { args = ' ' + this._shellLaunchConfig.args.map(a => { if (typeof a === 'string' && a.indexOf(' ') !== -1) { return `'${a}'`; } return a; }).join(' '); } this._messageService.show(Severity.Error, nls.localize('terminal.integrated.launchFailed', 'The terminal process command `{0}{1}` failed to launch (exit code: {2})', this._shellLaunchConfig.executable, args, exitCode)); } else { this._messageService.show(Severity.Error, exitCodeMessage); } } } } private _attachPressAnyKeyToCloseListener() { this._processDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'keypress', (event: KeyboardEvent) => { this.dispose(); event.preventDefault(); })); } public reuseTerminal(shell?: IShellLaunchConfig): void { // Kill and clean up old process if (this._process) { this._process.removeAllListeners('exit'); if (this._process.connected) { this._process.kill(); } this._process = null; } lifecycle.dispose(this._processDisposables); this._processDisposables = []; // Ensure new processes' output starts at start of new line this._xterm.write('\n\x1b[G'); // Print initialText if specified if (shell.initialText) { this._xterm.writeln(shell.initialText); } // Initialize new process const oldTitle = this._title; this._createProcess(shell); if (oldTitle !== this._title) { this.setTitle(this._title, true); } this._process.on('message', (message) => this._sendPtyDataToXterm(message)); // Clean up waitOnExit state if (this._isExiting && this._shellLaunchConfig.waitOnExit) { this._xterm.setOption('disableStdin', false); this._isExiting = false; } // Set the new shell launch config this._shellLaunchConfig = shell; } // TODO: This should be private/protected // TODO: locale should not be optional public static createTerminalEnv(parentEnv: IStringDictionary<string>, shell: IShellLaunchConfig, cwd: string, locale?: string, cols?: number, rows?: number): IStringDictionary<string> { const env = shell.env ? shell.env : TerminalInstance._cloneEnv(parentEnv); env['PTYPID'] = process.pid.toString(); env['PTYSHELL'] = shell.executable; env['TERM_PROGRAM'] = 'vscode'; env['TERM_PROGRAM_VERSION'] = pkg.version; if (shell.args) { if (typeof shell.args === 'string') { env[`PTYSHELLCMDLINE`] = shell.args; } else { shell.args.forEach((arg, i) => env[`PTYSHELLARG${i}`] = arg); } } env['PTYCWD'] = cwd; env['LANG'] = TerminalInstance._getLangEnvVariable(locale); if (cols && rows) { env['PTYCOLS'] = cols.toString(); env['PTYROWS'] = rows.toString(); } env['AMD_ENTRYPOINT'] = 'vs/workbench/parts/terminal/node/terminalProcess'; return env; } public onData(listener: (data: string) => void): lifecycle.IDisposable { let callback = (message) => { if (message.type === 'data') { listener(message.content); } }; this._process.on('message', callback); return { dispose: () => { if (this._process) { this._process.removeListener('message', callback); } } }; } public onExit(listener: (exitCode: number) => void): lifecycle.IDisposable { if (this._process) { this._process.on('exit', listener); } return { dispose: () => { if (this._process) { this._process.removeListener('exit', listener); } } }; } private static _sanitizeCwd(cwd: string) { // Make the drive letter uppercase on Windows (see #9448) if (platform.platform === platform.Platform.Windows && cwd && cwd[1] === ':') { return cwd[0].toUpperCase() + cwd.substr(1); } return cwd; } private static _cloneEnv(env: IStringDictionary<string>): IStringDictionary<string> { const newEnv: IStringDictionary<string> = Object.create(null); Object.keys(env).forEach((key) => { newEnv[key] = env[key]; }); return newEnv; } private static _getLangEnvVariable(locale?: string) { const parts = locale ? locale.split('-') : []; const n = parts.length; if (n === 0) { // Fallback to en_US to prevent possible encoding issues. return 'en_US.UTF-8'; } if (n === 1) { // app.getLocale can return just a language without a variant, fill in the variant for // supported languages as many shells expect a 2-part locale. const languageVariants = { de: 'DE', en: 'US', es: 'ES', fr: 'FR', it: 'IT', ja: 'JP', ko: 'KR', ru: 'RU', zh: 'CN' }; if (parts[0] in languageVariants) { parts.push(languageVariants[parts[0]]); } } else { // Ensure the variant is uppercase parts[1] = parts[1].toUpperCase(); } return parts.join('_') + '.UTF-8'; } public updateConfig(): void { this._setCursorBlink(this._configHelper.config.cursorBlinking); this._setCursorStyle(this._configHelper.config.cursorStyle); this._setCommandsToSkipShell(this._configHelper.config.commandsToSkipShell); this._setScrollback(this._configHelper.config.scrollback); } private _setCursorBlink(blink: boolean): void { if (this._xterm && this._xterm.getOption('cursorBlink') !== blink) { this._xterm.setOption('cursorBlink', blink); this._xterm.refresh(0, this._xterm.rows - 1); } } private _setCursorStyle(style: string): void { if (this._xterm && this._xterm.getOption('cursorStyle') !== style) { // 'line' is used instead of bar in VS Code to be consistent with editor.cursorStyle const xtermOption = style === 'line' ? 'bar' : style; this._xterm.setOption('cursorStyle', xtermOption); } } private _setCommandsToSkipShell(commands: string[]): void { this._skipTerminalCommands = commands; } private _setScrollback(lineCount: number): void { if (this._xterm && this._xterm.getOption('scrollback') !== lineCount) { this._xterm.setOption('scrollback', lineCount); } } public layout(dimension: Dimension): void { const terminalWidth = this._evaluateColsAndRows(dimension.width, dimension.height); if (!terminalWidth) { return; } if (this._xterm) { this._xterm.resize(this._cols, this._rows); this._xterm.element.style.width = terminalWidth + 'px'; } this._processReady.then(() => { if (this._process && this._process.connected) { // The child process could aready be terminated try { this._process.send({ event: 'resize', cols: this._cols, rows: this._rows }); } catch (error) { // We tried to write to a closed pipe / channel. if (error.code !== 'EPIPE' && error.code !== 'ERR_IPC_CHANNEL_CLOSED') { throw (error); } } } }); } public static setTerminalProcessFactory(factory: ITerminalProcessFactory): void { this._terminalProcessFactory = factory; } public setTitle(title: string, eventFromProcess: boolean): void { if (!title) { return; } if (eventFromProcess) { title = path.basename(title); if (platform.isWindows) { // Remove the .exe extension title = title.split('.exe')[0]; } } else { // If the title has not been set by the API or the rename command, unregister the handler that // automatically updates the terminal name if (this._process && this._messageTitleListener) { this._process.removeListener('message', this._messageTitleListener); this._messageTitleListener = null; } } const didTitleChange = title !== this._title; this._title = title; if (didTitleChange) { this._onTitleChanged.fire(title); } } } registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { // Scrollbar const scrollbarSliderBackgroundColor = theme.getColor(scrollbarSliderBackground); if (scrollbarSliderBackgroundColor) { collector.addRule(` .monaco-workbench .panel.integrated-terminal .xterm.focus .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm:focus .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm:hover .xterm-viewport { background-color: ${scrollbarSliderBackgroundColor}; }` ); } const scrollbarSliderHoverBackgroundColor = theme.getColor(scrollbarSliderHoverBackground); if (scrollbarSliderHoverBackgroundColor) { collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:hover { background-color: ${scrollbarSliderHoverBackgroundColor}; }`); } const scrollbarSliderActiveBackgroundColor = theme.getColor(scrollbarSliderActiveBackground); if (scrollbarSliderActiveBackgroundColor) { collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:active { background-color: ${scrollbarSliderActiveBackgroundColor}; }`); } });
src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts
1
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.9981766939163208, 0.021291466429829597, 0.0001629455655347556, 0.0001724678004393354, 0.14138969779014587 ]
{ "id": 5, "code_window": [ "\t\t} else {\n", "\t\t\t// Only listen for process title changes when a name is not provided\n", "\t\t\tthis.setTitle(shell.executable, true);\n", "\t\t\tthis._messageTitleListener = (message) => {\n", "\t\t\t\tif (message.type === 'title') {\n", "\t\t\t\t\tthis.setTitle(message.content ? message.content : '', true);\n", "\t\t\t\t}\n", "\t\t\t};\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.setTitle(this._shellLaunchConfig.executable, true);\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 592 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "reflectCSSValue": "Emmet: 反射 CSS 值" }
i18n/chs/src/vs/workbench/parts/emmet/node/actions/reflectCssValue.i18n.json
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.0001745967601891607, 0.0001745967601891607, 0.0001745967601891607, 0.0001745967601891607, 0 ]
{ "id": 5, "code_window": [ "\t\t} else {\n", "\t\t\t// Only listen for process title changes when a name is not provided\n", "\t\t\tthis.setTitle(shell.executable, true);\n", "\t\t\tthis._messageTitleListener = (message) => {\n", "\t\t\t\tif (message.type === 'title') {\n", "\t\t\t\t\tthis.setTitle(message.content ? message.content : '', true);\n", "\t\t\t\t}\n", "\t\t\t};\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.setTitle(this._shellLaunchConfig.executable, true);\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 592 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "workbenchConfigurationTitle": "Workbench", "workbench.startupEditor.none": "Ohne Editor starten.", "workbench.startupEditor.welcomePage": "Willkommensseite öffnen (Standard).", "workbench.startupEditor.newUntitledFile": "Eine neue unbenannte Datei öffnen.", "help": "Hilfe" }
i18n/deu/src/vs/workbench/parts/welcome/page/electron-browser/welcomePage.contribution.i18n.json
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.00017273107368964702, 0.00017190691141877323, 0.00017108274914789945, 0.00017190691141877323, 8.24162270873785e-7 ]
{ "id": 5, "code_window": [ "\t\t} else {\n", "\t\t\t// Only listen for process title changes when a name is not provided\n", "\t\t\tthis.setTitle(shell.executable, true);\n", "\t\t\tthis._messageTitleListener = (message) => {\n", "\t\t\t\tif (message.type === 'title') {\n", "\t\t\t\t\tthis.setTitle(message.content ? message.content : '', true);\n", "\t\t\t\t}\n", "\t\t\t};\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.setTitle(this._shellLaunchConfig.executable, true);\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 592 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "markdown.preview.breaks.desc": "Imposta come le interruzioni di riga vengono visualizzate nell'anteprima di markdown. Impostarlo a 'true' crea un <br>per ogni carattere di nuova riga.", "markdown.preview.doubleClickToSwitchToEditor.desc": "Fare doppio clic nell'anteprima markdown per passare all'editor.", "markdown.preview.fontFamily.desc": "Consente di controllare la famiglia di caratteri usata nell'anteprima markdown.", "markdown.preview.fontSize.desc": "Consente di controllare le dimensioni del carattere in pixel usate nell'anteprima markdown.", "markdown.preview.lineHeight.desc": "Consente di controllare l'altezza della riga usata nell'anteprima markdown. Questo numero è relativo alle dimensioni del carattere.", "markdown.preview.markEditorSelection.desc": "Contrassegna la selezione dell'editor corrente nell'anteprima markdown.", "markdown.preview.scrollEditorWithPreview.desc": "Quando si scorre l'anteprima markdown, aggiorna la visualizzazione dell'editor.", "markdown.preview.scrollPreviewWithEditorSelection.desc": "Scorre l'anteprima markdown in modo da visualizzare la riga attualmente selezionata dall'editor.", "markdown.preview.title": "Apri anteprima", "markdown.previewFrontMatter.dec": "Consente di impostare il rendering del front matter YAML nell'anteprima markdown. Con 'hide' il front matter viene rimosso; altrimenti il front matter viene considerato come contenuto markdown.", "markdown.previewSide.title": "Apri anteprima lateralmente", "markdown.showSource.title": "Mostra origine", "markdown.styles.dec": "Elenco di URL o percorsi locali dei fogli di stile CSS da usare dall'anteprima markdown. I percorsi relativi vengono interpretati come relativi alla cartella aperta nella finestra di esplorazione. Se non è presente alcuna cartella aperta, vengono interpretati come relativi al percorso del file markdown. Tutti i caratteri '\\' devono essere scritti come '\\\\'.", "markdown.showPreviewSecuritySelector.title": "Modifica impostazioni di sicurezza anteprima markdown", "markdown.trace.desc": "Abilitare la registrazione debug per l'estensione markdown." }
i18n/ita/extensions/markdown/package.i18n.json
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.00017085697618313134, 0.00016833457630127668, 0.00016382562171202153, 0.00017032117466442287, 0.000003195817271262058 ]
{ "id": 6, "code_window": [ "\t\t\tthis._xterm.writeln(shell.initialText);\n", "\t\t}\n", "\n", "\t\t// Initialize new process\n", "\t\tconst oldTitle = this._title;\n", "\t\tthis._createProcess(shell);\n", "\t\tif (oldTitle !== this._title) {\n", "\t\t\tthis.setTitle(this._title, true);\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._shellLaunchConfig = shell;\n", "\t\tthis._createProcess();\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 729 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as cp from 'child_process'; import * as os from 'os'; import * as path from 'path'; import * as lifecycle from 'vs/base/common/lifecycle'; import * as nls from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import * as dom from 'vs/base/browser/dom'; import Event, { Emitter } from 'vs/base/common/event'; import Uri from 'vs/base/common/uri'; import { WindowsShellHelper } from 'vs/workbench/parts/terminal/electron-browser/windowsShellHelper'; import { Terminal as XTermTerminal } from 'xterm'; import { Dimension } from 'vs/base/browser/builder'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IMessageService, Severity } from 'vs/platform/message/common/message'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IStringDictionary } from 'vs/base/common/collections'; import { ITerminalInstance, KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED, TERMINAL_PANEL_ID, IShellLaunchConfig } from 'vs/workbench/parts/terminal/common/terminal'; import { ITerminalProcessFactory } from 'vs/workbench/parts/terminal/electron-browser/terminal'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { TabFocus } from 'vs/editor/common/config/commonEditorConfig'; import { TerminalConfigHelper } from 'vs/workbench/parts/terminal/electron-browser/terminalConfigHelper'; import { TerminalLinkHandler } from 'vs/workbench/parts/terminal/electron-browser/terminalLinkHandler'; import { TerminalWidgetManager } from 'vs/workbench/parts/terminal/browser/terminalWidgetManager'; import { registerThemingParticipant, ITheme, ICssStyleCollector } from 'vs/platform/theme/common/themeService'; import { scrollbarSliderBackground, scrollbarSliderHoverBackground, scrollbarSliderActiveBackground } from 'vs/platform/theme/common/colorRegistry'; import { TPromise } from 'vs/base/common/winjs.base'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { IHistoryService } from 'vs/workbench/services/history/common/history'; import pkg from 'vs/platform/node/package'; /** The amount of time to consider terminal errors to be related to the launch */ const LAUNCHING_DURATION = 500; // Enable search functionality in xterm.js instance XTermTerminal.loadAddon('search'); class StandardTerminalProcessFactory implements ITerminalProcessFactory { public create(env: { [key: string]: string }): cp.ChildProcess { return cp.fork('./terminalProcess', [], { env, cwd: Uri.parse(path.dirname(require.toUrl('./terminalProcess'))).fsPath }); } } enum ProcessState { // The process has not been initialized yet. UNINITIALIZED, // The process is currently launching, the process is marked as launching // for a short duration after being created and is helpful to indicate // whether the process died as a result of bad shell and args. LAUNCHING, // The process is running normally. RUNNING, // The process was killed during launch, likely as a result of bad shell and // args. KILLED_DURING_LAUNCH, // The process was killed by the user (the event originated from VS Code). KILLED_BY_USER, // The process was killed by itself, for example the shell crashed or `exit` // was run. KILLED_BY_PROCESS } export class TerminalInstance implements ITerminalInstance { private static readonly EOL_REGEX = /\r?\n/g; private static _terminalProcessFactory: ITerminalProcessFactory = new StandardTerminalProcessFactory(); private static _lastKnownDimensions: Dimension = null; private static _idCounter = 1; private _id: number; private _isExiting: boolean; private _hadFocusOnExit: boolean; private _isVisible: boolean; private _processState: ProcessState; private _processReady: TPromise<void>; private _isDisposed: boolean; private _onDisposed: Emitter<ITerminalInstance>; private _onDataForApi: Emitter<{ instance: ITerminalInstance, data: string }>; private _onProcessIdReady: Emitter<TerminalInstance>; private _onTitleChanged: Emitter<string>; private _process: cp.ChildProcess; private _processId: number; private _skipTerminalCommands: string[]; private _title: string; private _instanceDisposables: lifecycle.IDisposable[]; private _processDisposables: lifecycle.IDisposable[]; private _wrapperElement: HTMLDivElement; private _xterm: XTermTerminal; private _xtermElement: HTMLDivElement; private _terminalHasTextContextKey: IContextKey<boolean>; private _cols: number; private _rows: number; private _messageTitleListener: (message: { type: string, content: string }) => void; private _preLaunchInputQueue: string; private _initialCwd: string; private _windowsShellHelper: WindowsShellHelper; private _widgetManager: TerminalWidgetManager; private _linkHandler: TerminalLinkHandler; public get id(): number { return this._id; } public get processId(): number { return this._processId; } public get onDisposed(): Event<ITerminalInstance> { return this._onDisposed.event; } public get onDataForApi(): Event<{ instance: ITerminalInstance, data: string }> { return this._onDataForApi.event; } public get onProcessIdReady(): Event<TerminalInstance> { return this._onProcessIdReady.event; } public get onTitleChanged(): Event<string> { return this._onTitleChanged.event; } public get title(): string { return this._title; } public get hadFocusOnExit(): boolean { return this._hadFocusOnExit; } public get isTitleSetByProcess(): boolean { return !!this._messageTitleListener; } public constructor( private _terminalFocusContextKey: IContextKey<boolean>, private _configHelper: TerminalConfigHelper, private _container: HTMLElement, private _shellLaunchConfig: IShellLaunchConfig, @IContextKeyService private _contextKeyService: IContextKeyService, @IKeybindingService private _keybindingService: IKeybindingService, @IMessageService private _messageService: IMessageService, @IPanelService private _panelService: IPanelService, @IWorkspaceContextService private _contextService: IWorkspaceContextService, @IWorkbenchEditorService private _editorService: IWorkbenchEditorService, @IInstantiationService private _instantiationService: IInstantiationService, @IClipboardService private _clipboardService: IClipboardService, @IHistoryService private _historyService: IHistoryService ) { this._instanceDisposables = []; this._processDisposables = []; this._skipTerminalCommands = []; this._isExiting = false; this._hadFocusOnExit = false; this._processState = ProcessState.UNINITIALIZED; this._isVisible = false; this._isDisposed = false; this._id = TerminalInstance._idCounter++; this._terminalHasTextContextKey = KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED.bindTo(this._contextKeyService); this._preLaunchInputQueue = ''; this._onDisposed = new Emitter<TerminalInstance>(); this._onDataForApi = new Emitter<{ instance: ITerminalInstance, data: string }>(); this._onProcessIdReady = new Emitter<TerminalInstance>(); this._onTitleChanged = new Emitter<string>(); // Create a promise that resolves when the pty is ready this._processReady = new TPromise<void>(c => { this.onProcessIdReady(() => c(void 0)); }); this._initDimensions(); this._createProcess(this._shellLaunchConfig); this._createXterm(); if (platform.isWindows) { this._processReady.then(() => { if (!this._isDisposed) { import('vs/workbench/parts/terminal/electron-browser/windowsShellHelper').then((module) => { this._windowsShellHelper = new module.WindowsShellHelper(this._processId, this._shellLaunchConfig.executable, this, this._xterm); }); } }); } // Only attach xterm.js to the DOM if the terminal panel has been opened before. if (_container) { this.attachToElement(_container); } } public addDisposable(disposable: lifecycle.IDisposable): void { this._instanceDisposables.push(disposable); } private _initDimensions(): void { // The terminal panel needs to have been created if (!this._container) { return; } const computedStyle = window.getComputedStyle(this._container); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this._evaluateColsAndRows(width, height); } /** * Evaluates and sets the cols and rows of the terminal if possible. * @param width The width of the container. * @param height The height of the container. * @return The terminal's width if it requires a layout. */ private _evaluateColsAndRows(width: number, height: number): number { const dimension = this._getDimension(width, height); if (!dimension) { return null; } const font = this._configHelper.getFont(); this._cols = Math.max(Math.floor(dimension.width / font.charWidth), 1); this._rows = Math.max(Math.floor(dimension.height / font.charHeight), 1); return dimension.width; } private _getDimension(width: number, height: number): Dimension { // The font needs to have been initialized const font = this._configHelper.getFont(); if (!font || !font.charWidth || !font.charHeight) { return null; } // The panel is minimized if (!height) { return TerminalInstance._lastKnownDimensions; } else { // Trigger scroll event manually so that the viewport's scroll area is synced. This // needs to happen otherwise its scrollTop value is invalid when the panel is toggled as // it gets removed and then added back to the DOM (resetting scrollTop to 0). // Upstream issue: https://github.com/sourcelair/xterm.js/issues/291 if (this._xterm) { this._xterm.emit('scroll', this._xterm.ydisp); } } const outerContainer = document.querySelector('.terminal-outer-container'); const outerContainerStyle = getComputedStyle(outerContainer); const padding = parseInt(outerContainerStyle.paddingLeft.split('px')[0], 10); const paddingBottom = parseInt(outerContainerStyle.paddingBottom.split('px')[0], 10); // Use left padding as right padding, right padding is not defined in CSS just in case // xterm.js causes an unexpected overflow. const innerWidth = width - padding * 2; const innerHeight = height - paddingBottom; TerminalInstance._lastKnownDimensions = new Dimension(innerWidth, innerHeight); return TerminalInstance._lastKnownDimensions; } /** * Create xterm.js instance and attach data listeners. */ protected _createXterm(): void { this._xterm = new XTermTerminal({ scrollback: this._configHelper.config.scrollback }); if (this._shellLaunchConfig.initialText) { this._xterm.writeln(this._shellLaunchConfig.initialText); } this._process.on('message', (message) => this._sendPtyDataToXterm(message)); this._xterm.on('data', (data) => { if (this._processId) { // Send data if the pty is ready this._process.send({ event: 'input', data }); } else { // If the pty is not ready, queue the data received from // xterm.js until the pty is ready this._preLaunchInputQueue += data; } return false; }); this._linkHandler = this._instantiationService.createInstance(TerminalLinkHandler, this._xterm, platform.platform, this._initialCwd); this._linkHandler.registerLocalLinkHandler(); } public attachToElement(container: HTMLElement): void { if (this._wrapperElement) { throw new Error('The terminal instance has already been attached to a container'); } this._container = container; this._wrapperElement = document.createElement('div'); dom.addClass(this._wrapperElement, 'terminal-wrapper'); this._xtermElement = document.createElement('div'); this._xterm.open(this._xtermElement); this._xterm.attachCustomKeyEventHandler((event: KeyboardEvent) => { // Disable all input if the terminal is exiting if (this._isExiting) { return false; } // Skip processing by xterm.js of keyboard events that resolve to commands described // within commandsToSkipShell const standardKeyboardEvent = new StandardKeyboardEvent(event); const resolveResult = this._keybindingService.softDispatch(standardKeyboardEvent, standardKeyboardEvent.target); if (resolveResult && this._skipTerminalCommands.some(k => k === resolveResult.commandId)) { event.preventDefault(); return false; } // If tab focus mode is on, tab is not passed to the terminal if (TabFocus.getTabFocusMode() && event.keyCode === 9) { return false; } return undefined; }); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'mouseup', (event: KeyboardEvent) => { // Wait until mouseup has propagated through the DOM before // evaluating the new selection state. setTimeout(() => this._refreshSelectionContextKey(), 0); })); // xterm.js currently drops selection on keyup as we need to handle this case. this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'keyup', (event: KeyboardEvent) => { // Wait until keyup has propagated through the DOM before evaluating // the new selection state. setTimeout(() => this._refreshSelectionContextKey(), 0); })); const xtermHelper: HTMLElement = <HTMLElement>this._xterm.element.querySelector('.xterm-helpers'); const focusTrap: HTMLElement = document.createElement('div'); focusTrap.setAttribute('tabindex', '0'); dom.addClass(focusTrap, 'focus-trap'); this._instanceDisposables.push(dom.addDisposableListener(focusTrap, 'focus', (event: FocusEvent) => { let currentElement = focusTrap; while (!dom.hasClass(currentElement, 'part')) { currentElement = currentElement.parentElement; } const hidePanelElement = <HTMLElement>currentElement.querySelector('.hide-panel-action'); hidePanelElement.focus(); })); xtermHelper.insertBefore(focusTrap, this._xterm.textarea); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'focus', (event: KeyboardEvent) => { this._terminalFocusContextKey.set(true); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'blur', (event: KeyboardEvent) => { this._terminalFocusContextKey.reset(); this._refreshSelectionContextKey(); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'focus', (event: KeyboardEvent) => { this._terminalFocusContextKey.set(true); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'blur', (event: KeyboardEvent) => { this._terminalFocusContextKey.reset(); this._refreshSelectionContextKey(); })); this._wrapperElement.appendChild(this._xtermElement); this._widgetManager = new TerminalWidgetManager(this._configHelper, this._wrapperElement); this._linkHandler.setWidgetManager(this._widgetManager); this._container.appendChild(this._wrapperElement); const computedStyle = window.getComputedStyle(this._container); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this.layout(new Dimension(width, height)); this.setVisible(this._isVisible); this.updateConfig(); // If IShellLaunchConfig.waitOnExit was true and the process finished before the terminal // panel was initialized. if (this._xterm.getOption('disableStdin')) { this._attachPressAnyKeyToCloseListener(); } } public registerLinkMatcher(regex: RegExp, handler: (url: string) => void, matchIndex?: number, validationCallback?: (uri: string, element: HTMLElement, callback: (isValid: boolean) => void) => void): number { return this._linkHandler.registerCustomLinkHandler(regex, handler, matchIndex, validationCallback); } public deregisterLinkMatcher(linkMatcherId: number): void { this._xterm.deregisterLinkMatcher(linkMatcherId); } public hasSelection(): boolean { return this._xterm.hasSelection(); } public copySelection(): void { if (this.hasSelection()) { this._clipboardService.writeText(this._xterm.getSelection()); } else { this._messageService.show(Severity.Warning, nls.localize('terminal.integrated.copySelection.noSelection', 'The terminal has no selection to copy')); } } get selection(): string | undefined { return this.hasSelection() ? this._xterm.getSelection() : undefined; } public clearSelection(): void { this._xterm.clearSelection(); } public selectAll(): void { // Focus here to ensure the terminal context key is set this._xterm.focus(); this._xterm.selectAll(); } public findNext(term: string): boolean { return this._xterm.findNext(term); } public findPrevious(term: string): boolean { return this._xterm.findPrevious(term); } public notifyFindWidgetFocusChanged(isFocused: boolean): void { // In order to support escape to close the find widget when the terminal // is focused terminalFocus needs to be true when either the terminal or // the find widget are focused. this._terminalFocusContextKey.set(isFocused || document.activeElement === this._xterm.textarea); } public dispose(): void { if (this._windowsShellHelper) { this._windowsShellHelper.dispose(); } if (this._linkHandler) { this._linkHandler.dispose(); } if (this._xterm && this._xterm.element) { this._hadFocusOnExit = dom.hasClass(this._xterm.element, 'focus'); } if (this._wrapperElement) { this._container.removeChild(this._wrapperElement); this._wrapperElement = null; } if (this._xterm) { this._xterm.destroy(); this._xterm = null; } if (this._process) { if (this._process.connected) { // If the process was still connected this dispose came from // within VS Code, not the process, so mark the process as // killed by the user. this._processState = ProcessState.KILLED_BY_USER; this._process.send({ event: 'shutdown' }); } this._process = null; } if (!this._isDisposed) { this._isDisposed = true; this._onDisposed.fire(this); } this._processDisposables = lifecycle.dispose(this._processDisposables); this._instanceDisposables = lifecycle.dispose(this._instanceDisposables); } public focus(force?: boolean): void { if (!this._xterm) { return; } const text = window.getSelection().toString(); if (!text || force) { this._xterm.focus(); } } public paste(): void { this.focus(); document.execCommand('paste'); } public sendText(text: string, addNewLine: boolean): void { this._processReady.then(() => { // Normalize line endings to 'enter' press. text = text.replace(TerminalInstance.EOL_REGEX, '\r'); if (addNewLine && text.substr(text.length - 1) !== '\r') { text += '\r'; } this._process.send({ event: 'input', data: text }); }); } public setVisible(visible: boolean): void { this._isVisible = visible; if (this._wrapperElement) { dom.toggleClass(this._wrapperElement, 'active', visible); } if (visible && this._xterm) { // Trigger a manual scroll event which will sync the viewport and scroll bar. This is // necessary if the number of rows in the terminal has decreased while it was in the // background since scrollTop changes take no effect but the terminal's position does // change since the number of visible rows decreases. this._xterm.emit('scroll', this._xterm.ydisp); } } public scrollDownLine(): void { this._xterm.scrollDisp(1); } public scrollDownPage(): void { this._xterm.scrollPages(1); } public scrollToBottom(): void { this._xterm.scrollToBottom(); } public scrollUpLine(): void { this._xterm.scrollDisp(-1); } public scrollUpPage(): void { this._xterm.scrollPages(-1); } public scrollToTop(): void { this._xterm.scrollToTop(); } public clear(): void { this._xterm.clear(); } private _refreshSelectionContextKey() { const activePanel = this._panelService.getActivePanel(); const isActive = activePanel && activePanel.getId() === TERMINAL_PANEL_ID; this._terminalHasTextContextKey.set(isActive && this.hasSelection()); } protected _getCwd(shell: IShellLaunchConfig, root: Uri): string { if (shell.cwd) { return shell.cwd; } let cwd: string; // TODO: Handle non-existent customCwd if (!shell.ignoreConfigurationCwd) { // Evaluate custom cwd first const customCwd = this._configHelper.config.cwd; if (customCwd) { if (path.isAbsolute(customCwd)) { cwd = customCwd; } else if (root) { cwd = path.normalize(path.join(root.fsPath, customCwd)); } } } // If there was no custom cwd or it was relative with no workspace if (!cwd) { cwd = root ? root.fsPath : os.homedir(); } return TerminalInstance._sanitizeCwd(cwd); } protected _createProcess(shell: IShellLaunchConfig): void { const locale = this._configHelper.config.setLocaleVariables ? platform.locale : undefined; if (!shell.executable) { this._configHelper.mergeDefaultShellPathAndArgs(shell); } this._initialCwd = this._getCwd(this._shellLaunchConfig, this._historyService.getLastActiveWorkspaceRoot()); let envFromConfig: IStringDictionary<string>; if (platform.isWindows) { envFromConfig = { ...process.env }; for (let configKey in this._configHelper.config.env['windows']) { let actualKey = configKey; for (let envKey in envFromConfig) { if (configKey.toLowerCase() === envKey.toLowerCase()) { actualKey = envKey; break; } } envFromConfig[actualKey] = this._configHelper.config.env['windows'][configKey]; } } else { const platformKey = platform.isMacintosh ? 'osx' : 'linux'; envFromConfig = { ...process.env, ...this._configHelper.config.env[platformKey] }; } const env = TerminalInstance.createTerminalEnv(envFromConfig, shell, this._initialCwd, locale, this._cols, this._rows); this._process = cp.fork(Uri.parse(require.toUrl('bootstrap')).fsPath, ['--type=terminal'], { env, cwd: Uri.parse(path.dirname(require.toUrl('../node/terminalProcess'))).fsPath }); this._processState = ProcessState.LAUNCHING; if (shell.name) { this.setTitle(shell.name, false); } else { // Only listen for process title changes when a name is not provided this.setTitle(shell.executable, true); this._messageTitleListener = (message) => { if (message.type === 'title') { this.setTitle(message.content ? message.content : '', true); } }; this._process.on('message', this._messageTitleListener); } this._process.on('message', (message) => { if (message.type === 'pid') { this._processId = message.content; // Send any queued data that's waiting if (this._preLaunchInputQueue.length > 0) { this._process.send({ event: 'input', data: this._preLaunchInputQueue }); this._preLaunchInputQueue = null; } this._onProcessIdReady.fire(this); } }); this._process.on('exit', exitCode => this._onPtyProcessExit(exitCode)); setTimeout(() => { if (this._processState === ProcessState.LAUNCHING) { this._processState = ProcessState.RUNNING; } }, LAUNCHING_DURATION); } private _sendPtyDataToXterm(message: { type: string, content: string }): void { if (message.type === 'data') { if (this._widgetManager) { this._widgetManager.closeMessage(); } if (this._xterm) { this._xterm.write(message.content); } } } private _onPtyProcessExit(exitCode: number): void { // Prevent dispose functions being triggered multiple times if (this._isExiting) { return; } this._isExiting = true; this._process = null; let exitCodeMessage: string; if (exitCode) { exitCodeMessage = nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode); } // If the process is marked as launching then mark the process as killed // during launch. This typically means that there is a problem with the // shell and args. if (this._processState === ProcessState.LAUNCHING) { this._processState = ProcessState.KILLED_DURING_LAUNCH; } // If TerminalInstance did not know about the process exit then it was // triggered by the process, not on VS Code's side. if (this._processState === ProcessState.RUNNING) { this._processState = ProcessState.KILLED_BY_PROCESS; } // Only trigger wait on exit when the exit was triggered by the process, // not through the `workbench.action.terminal.kill` command if (this._processState === ProcessState.KILLED_BY_PROCESS && this._shellLaunchConfig.waitOnExit) { if (exitCode) { this._xterm.writeln(exitCodeMessage); } let message = typeof this._shellLaunchConfig.waitOnExit === 'string' ? this._shellLaunchConfig.waitOnExit : nls.localize('terminal.integrated.waitOnExit', 'Press any key to close the terminal'); // Bold the message and add an extra new line to make it stand out from the rest of the output message = `\n\x1b[1m${message}\x1b[0m`; this._xterm.writeln(message); // Disable all input if the terminal is exiting and listen for next keypress this._xterm.setOption('disableStdin', true); if (this._xterm.textarea) { this._attachPressAnyKeyToCloseListener(); } } else { this.dispose(); if (exitCode) { if (this._processState === ProcessState.KILLED_DURING_LAUNCH) { let args = ''; if (typeof this._shellLaunchConfig.args === 'string') { args = this._shellLaunchConfig.args; } else if (this._shellLaunchConfig.args && this._shellLaunchConfig.args.length) { args = ' ' + this._shellLaunchConfig.args.map(a => { if (typeof a === 'string' && a.indexOf(' ') !== -1) { return `'${a}'`; } return a; }).join(' '); } this._messageService.show(Severity.Error, nls.localize('terminal.integrated.launchFailed', 'The terminal process command `{0}{1}` failed to launch (exit code: {2})', this._shellLaunchConfig.executable, args, exitCode)); } else { this._messageService.show(Severity.Error, exitCodeMessage); } } } } private _attachPressAnyKeyToCloseListener() { this._processDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'keypress', (event: KeyboardEvent) => { this.dispose(); event.preventDefault(); })); } public reuseTerminal(shell?: IShellLaunchConfig): void { // Kill and clean up old process if (this._process) { this._process.removeAllListeners('exit'); if (this._process.connected) { this._process.kill(); } this._process = null; } lifecycle.dispose(this._processDisposables); this._processDisposables = []; // Ensure new processes' output starts at start of new line this._xterm.write('\n\x1b[G'); // Print initialText if specified if (shell.initialText) { this._xterm.writeln(shell.initialText); } // Initialize new process const oldTitle = this._title; this._createProcess(shell); if (oldTitle !== this._title) { this.setTitle(this._title, true); } this._process.on('message', (message) => this._sendPtyDataToXterm(message)); // Clean up waitOnExit state if (this._isExiting && this._shellLaunchConfig.waitOnExit) { this._xterm.setOption('disableStdin', false); this._isExiting = false; } // Set the new shell launch config this._shellLaunchConfig = shell; } // TODO: This should be private/protected // TODO: locale should not be optional public static createTerminalEnv(parentEnv: IStringDictionary<string>, shell: IShellLaunchConfig, cwd: string, locale?: string, cols?: number, rows?: number): IStringDictionary<string> { const env = shell.env ? shell.env : TerminalInstance._cloneEnv(parentEnv); env['PTYPID'] = process.pid.toString(); env['PTYSHELL'] = shell.executable; env['TERM_PROGRAM'] = 'vscode'; env['TERM_PROGRAM_VERSION'] = pkg.version; if (shell.args) { if (typeof shell.args === 'string') { env[`PTYSHELLCMDLINE`] = shell.args; } else { shell.args.forEach((arg, i) => env[`PTYSHELLARG${i}`] = arg); } } env['PTYCWD'] = cwd; env['LANG'] = TerminalInstance._getLangEnvVariable(locale); if (cols && rows) { env['PTYCOLS'] = cols.toString(); env['PTYROWS'] = rows.toString(); } env['AMD_ENTRYPOINT'] = 'vs/workbench/parts/terminal/node/terminalProcess'; return env; } public onData(listener: (data: string) => void): lifecycle.IDisposable { let callback = (message) => { if (message.type === 'data') { listener(message.content); } }; this._process.on('message', callback); return { dispose: () => { if (this._process) { this._process.removeListener('message', callback); } } }; } public onExit(listener: (exitCode: number) => void): lifecycle.IDisposable { if (this._process) { this._process.on('exit', listener); } return { dispose: () => { if (this._process) { this._process.removeListener('exit', listener); } } }; } private static _sanitizeCwd(cwd: string) { // Make the drive letter uppercase on Windows (see #9448) if (platform.platform === platform.Platform.Windows && cwd && cwd[1] === ':') { return cwd[0].toUpperCase() + cwd.substr(1); } return cwd; } private static _cloneEnv(env: IStringDictionary<string>): IStringDictionary<string> { const newEnv: IStringDictionary<string> = Object.create(null); Object.keys(env).forEach((key) => { newEnv[key] = env[key]; }); return newEnv; } private static _getLangEnvVariable(locale?: string) { const parts = locale ? locale.split('-') : []; const n = parts.length; if (n === 0) { // Fallback to en_US to prevent possible encoding issues. return 'en_US.UTF-8'; } if (n === 1) { // app.getLocale can return just a language without a variant, fill in the variant for // supported languages as many shells expect a 2-part locale. const languageVariants = { de: 'DE', en: 'US', es: 'ES', fr: 'FR', it: 'IT', ja: 'JP', ko: 'KR', ru: 'RU', zh: 'CN' }; if (parts[0] in languageVariants) { parts.push(languageVariants[parts[0]]); } } else { // Ensure the variant is uppercase parts[1] = parts[1].toUpperCase(); } return parts.join('_') + '.UTF-8'; } public updateConfig(): void { this._setCursorBlink(this._configHelper.config.cursorBlinking); this._setCursorStyle(this._configHelper.config.cursorStyle); this._setCommandsToSkipShell(this._configHelper.config.commandsToSkipShell); this._setScrollback(this._configHelper.config.scrollback); } private _setCursorBlink(blink: boolean): void { if (this._xterm && this._xterm.getOption('cursorBlink') !== blink) { this._xterm.setOption('cursorBlink', blink); this._xterm.refresh(0, this._xterm.rows - 1); } } private _setCursorStyle(style: string): void { if (this._xterm && this._xterm.getOption('cursorStyle') !== style) { // 'line' is used instead of bar in VS Code to be consistent with editor.cursorStyle const xtermOption = style === 'line' ? 'bar' : style; this._xterm.setOption('cursorStyle', xtermOption); } } private _setCommandsToSkipShell(commands: string[]): void { this._skipTerminalCommands = commands; } private _setScrollback(lineCount: number): void { if (this._xterm && this._xterm.getOption('scrollback') !== lineCount) { this._xterm.setOption('scrollback', lineCount); } } public layout(dimension: Dimension): void { const terminalWidth = this._evaluateColsAndRows(dimension.width, dimension.height); if (!terminalWidth) { return; } if (this._xterm) { this._xterm.resize(this._cols, this._rows); this._xterm.element.style.width = terminalWidth + 'px'; } this._processReady.then(() => { if (this._process && this._process.connected) { // The child process could aready be terminated try { this._process.send({ event: 'resize', cols: this._cols, rows: this._rows }); } catch (error) { // We tried to write to a closed pipe / channel. if (error.code !== 'EPIPE' && error.code !== 'ERR_IPC_CHANNEL_CLOSED') { throw (error); } } } }); } public static setTerminalProcessFactory(factory: ITerminalProcessFactory): void { this._terminalProcessFactory = factory; } public setTitle(title: string, eventFromProcess: boolean): void { if (!title) { return; } if (eventFromProcess) { title = path.basename(title); if (platform.isWindows) { // Remove the .exe extension title = title.split('.exe')[0]; } } else { // If the title has not been set by the API or the rename command, unregister the handler that // automatically updates the terminal name if (this._process && this._messageTitleListener) { this._process.removeListener('message', this._messageTitleListener); this._messageTitleListener = null; } } const didTitleChange = title !== this._title; this._title = title; if (didTitleChange) { this._onTitleChanged.fire(title); } } } registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { // Scrollbar const scrollbarSliderBackgroundColor = theme.getColor(scrollbarSliderBackground); if (scrollbarSliderBackgroundColor) { collector.addRule(` .monaco-workbench .panel.integrated-terminal .xterm.focus .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm:focus .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm:hover .xterm-viewport { background-color: ${scrollbarSliderBackgroundColor}; }` ); } const scrollbarSliderHoverBackgroundColor = theme.getColor(scrollbarSliderHoverBackground); if (scrollbarSliderHoverBackgroundColor) { collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:hover { background-color: ${scrollbarSliderHoverBackgroundColor}; }`); } const scrollbarSliderActiveBackgroundColor = theme.getColor(scrollbarSliderActiveBackground); if (scrollbarSliderActiveBackgroundColor) { collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:active { background-color: ${scrollbarSliderActiveBackgroundColor}; }`); } });
src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts
1
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.9985089898109436, 0.021574871614575386, 0.00016274805238936096, 0.0002516965614631772, 0.14249376952648163 ]
{ "id": 6, "code_window": [ "\t\t\tthis._xterm.writeln(shell.initialText);\n", "\t\t}\n", "\n", "\t\t// Initialize new process\n", "\t\tconst oldTitle = this._title;\n", "\t\tthis._createProcess(shell);\n", "\t\tif (oldTitle !== this._title) {\n", "\t\t\tthis.setTitle(this._title, true);\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._shellLaunchConfig = shell;\n", "\t\tthis._createProcess();\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 729 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "inspectTMScopes": "Entwickler: TM-Bereiche untersuchen", "inspectTMScopesWidget.loading": "Wird geladen..." }
i18n/deu/src/vs/workbench/parts/codeEditor/electron-browser/inspectTMScopes.i18n.json
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.00017674682021606714, 0.00017674682021606714, 0.00017674682021606714, 0.00017674682021606714, 0 ]
{ "id": 6, "code_window": [ "\t\t\tthis._xterm.writeln(shell.initialText);\n", "\t\t}\n", "\n", "\t\t// Initialize new process\n", "\t\tconst oldTitle = this._title;\n", "\t\tthis._createProcess(shell);\n", "\t\tif (oldTitle !== this._title) {\n", "\t\t\tthis.setTitle(this._title, true);\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._shellLaunchConfig = shell;\n", "\t\tthis._createProcess();\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 729 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "vscode.extension.contributes.snippets": "Ajoute des extraits de code.", "vscode.extension.contributes.snippets-language": "Identificateur de langage pour lequel cet extrait de code est ajouté.", "vscode.extension.contributes.snippets-path": "Chemin du fichier d'extraits de code. Le chemin est relatif au dossier d'extensions et commence généralement par './snippets/'.", "invalid.language": "Langage inconnu dans 'contributes.{0}.language'. Valeur fournie : {1}", "invalid.path.0": "Chaîne attendue dans 'contributes.{0}.path'. Valeur fournie : {1}", "invalid.path.1": "'contributes.{0}.path' ({1}) est censé être inclus dans le dossier ({2}) de l'extension. Cela risque de rendre l'extension non portable.", "badVariableUse": "L'extrait de code \"{0}\" confond très probablement les variables et les espaces réservés d'extrait de code. Consultez https://code.visualstudio.com/docs/editor/userdefinedsnippets#_snippet-syntax pour plus d'informations." }
i18n/fra/src/vs/workbench/parts/snippets/electron-browser/TMSnippets.i18n.json
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.00017363832739647478, 0.00017217916320078075, 0.00017072001355700195, 0.00017217916320078075, 0.0000014591569197364151 ]
{ "id": 6, "code_window": [ "\t\t\tthis._xterm.writeln(shell.initialText);\n", "\t\t}\n", "\n", "\t\t// Initialize new process\n", "\t\tconst oldTitle = this._title;\n", "\t\tthis._createProcess(shell);\n", "\t\tif (oldTitle !== this._title) {\n", "\t\t\tthis.setTitle(this._title, true);\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._shellLaunchConfig = shell;\n", "\t\tthis._createProcess();\n" ], "file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts", "type": "replace", "edit_start_line_idx": 729 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "vscode.extension.contributes.view": "提供自訂檢視", "vscode.extension.contributes.view.id": "用以識別透過 vscode.workspace.createTreeView 建立之檢視的唯一識別碼", "vscode.extension.contributes.view.label": "用以轉譯檢視的易讀字串", "vscode.extension.contributes.view.icon": "連到檢視圖示的路徑", "vscode.extension.contributes.views": "提供自訂檢視", "showViewlet": "顯示 {0}", "view": "檢視" }
i18n/cht/src/vs/workbench/parts/explorers/browser/treeExplorer.contribution.i18n.json
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.0001739423896651715, 0.00017366527754347771, 0.00017338816542178392, 0.00017366527754347771, 2.7711212169378996e-7 ]
{ "id": 7, "code_window": [ "\tpublic _getCwd(shell: IShellLaunchConfig, root: Uri): string {\n", "\t\treturn super._getCwd(shell, root);\n", "\t}\n", "\n", "\tprotected _createProcess(shell: IShellLaunchConfig): void { }\n", "\tprotected _createXterm(): void { }\n", "}\n", "\n", "suite('Workbench - TerminalInstance', () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprotected _createProcess(): void { }\n" ], "file_path": "src/vs/workbench/parts/terminal/test/electron-browser/terminalInstance.test.ts", "type": "replace", "edit_start_line_idx": 27 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as cp from 'child_process'; import * as os from 'os'; import * as path from 'path'; import * as lifecycle from 'vs/base/common/lifecycle'; import * as nls from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import * as dom from 'vs/base/browser/dom'; import Event, { Emitter } from 'vs/base/common/event'; import Uri from 'vs/base/common/uri'; import { WindowsShellHelper } from 'vs/workbench/parts/terminal/electron-browser/windowsShellHelper'; import { Terminal as XTermTerminal } from 'xterm'; import { Dimension } from 'vs/base/browser/builder'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IMessageService, Severity } from 'vs/platform/message/common/message'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IStringDictionary } from 'vs/base/common/collections'; import { ITerminalInstance, KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED, TERMINAL_PANEL_ID, IShellLaunchConfig } from 'vs/workbench/parts/terminal/common/terminal'; import { ITerminalProcessFactory } from 'vs/workbench/parts/terminal/electron-browser/terminal'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { TabFocus } from 'vs/editor/common/config/commonEditorConfig'; import { TerminalConfigHelper } from 'vs/workbench/parts/terminal/electron-browser/terminalConfigHelper'; import { TerminalLinkHandler } from 'vs/workbench/parts/terminal/electron-browser/terminalLinkHandler'; import { TerminalWidgetManager } from 'vs/workbench/parts/terminal/browser/terminalWidgetManager'; import { registerThemingParticipant, ITheme, ICssStyleCollector } from 'vs/platform/theme/common/themeService'; import { scrollbarSliderBackground, scrollbarSliderHoverBackground, scrollbarSliderActiveBackground } from 'vs/platform/theme/common/colorRegistry'; import { TPromise } from 'vs/base/common/winjs.base'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { IHistoryService } from 'vs/workbench/services/history/common/history'; import pkg from 'vs/platform/node/package'; /** The amount of time to consider terminal errors to be related to the launch */ const LAUNCHING_DURATION = 500; // Enable search functionality in xterm.js instance XTermTerminal.loadAddon('search'); class StandardTerminalProcessFactory implements ITerminalProcessFactory { public create(env: { [key: string]: string }): cp.ChildProcess { return cp.fork('./terminalProcess', [], { env, cwd: Uri.parse(path.dirname(require.toUrl('./terminalProcess'))).fsPath }); } } enum ProcessState { // The process has not been initialized yet. UNINITIALIZED, // The process is currently launching, the process is marked as launching // for a short duration after being created and is helpful to indicate // whether the process died as a result of bad shell and args. LAUNCHING, // The process is running normally. RUNNING, // The process was killed during launch, likely as a result of bad shell and // args. KILLED_DURING_LAUNCH, // The process was killed by the user (the event originated from VS Code). KILLED_BY_USER, // The process was killed by itself, for example the shell crashed or `exit` // was run. KILLED_BY_PROCESS } export class TerminalInstance implements ITerminalInstance { private static readonly EOL_REGEX = /\r?\n/g; private static _terminalProcessFactory: ITerminalProcessFactory = new StandardTerminalProcessFactory(); private static _lastKnownDimensions: Dimension = null; private static _idCounter = 1; private _id: number; private _isExiting: boolean; private _hadFocusOnExit: boolean; private _isVisible: boolean; private _processState: ProcessState; private _processReady: TPromise<void>; private _isDisposed: boolean; private _onDisposed: Emitter<ITerminalInstance>; private _onDataForApi: Emitter<{ instance: ITerminalInstance, data: string }>; private _onProcessIdReady: Emitter<TerminalInstance>; private _onTitleChanged: Emitter<string>; private _process: cp.ChildProcess; private _processId: number; private _skipTerminalCommands: string[]; private _title: string; private _instanceDisposables: lifecycle.IDisposable[]; private _processDisposables: lifecycle.IDisposable[]; private _wrapperElement: HTMLDivElement; private _xterm: XTermTerminal; private _xtermElement: HTMLDivElement; private _terminalHasTextContextKey: IContextKey<boolean>; private _cols: number; private _rows: number; private _messageTitleListener: (message: { type: string, content: string }) => void; private _preLaunchInputQueue: string; private _initialCwd: string; private _windowsShellHelper: WindowsShellHelper; private _widgetManager: TerminalWidgetManager; private _linkHandler: TerminalLinkHandler; public get id(): number { return this._id; } public get processId(): number { return this._processId; } public get onDisposed(): Event<ITerminalInstance> { return this._onDisposed.event; } public get onDataForApi(): Event<{ instance: ITerminalInstance, data: string }> { return this._onDataForApi.event; } public get onProcessIdReady(): Event<TerminalInstance> { return this._onProcessIdReady.event; } public get onTitleChanged(): Event<string> { return this._onTitleChanged.event; } public get title(): string { return this._title; } public get hadFocusOnExit(): boolean { return this._hadFocusOnExit; } public get isTitleSetByProcess(): boolean { return !!this._messageTitleListener; } public constructor( private _terminalFocusContextKey: IContextKey<boolean>, private _configHelper: TerminalConfigHelper, private _container: HTMLElement, private _shellLaunchConfig: IShellLaunchConfig, @IContextKeyService private _contextKeyService: IContextKeyService, @IKeybindingService private _keybindingService: IKeybindingService, @IMessageService private _messageService: IMessageService, @IPanelService private _panelService: IPanelService, @IWorkspaceContextService private _contextService: IWorkspaceContextService, @IWorkbenchEditorService private _editorService: IWorkbenchEditorService, @IInstantiationService private _instantiationService: IInstantiationService, @IClipboardService private _clipboardService: IClipboardService, @IHistoryService private _historyService: IHistoryService ) { this._instanceDisposables = []; this._processDisposables = []; this._skipTerminalCommands = []; this._isExiting = false; this._hadFocusOnExit = false; this._processState = ProcessState.UNINITIALIZED; this._isVisible = false; this._isDisposed = false; this._id = TerminalInstance._idCounter++; this._terminalHasTextContextKey = KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED.bindTo(this._contextKeyService); this._preLaunchInputQueue = ''; this._onDisposed = new Emitter<TerminalInstance>(); this._onDataForApi = new Emitter<{ instance: ITerminalInstance, data: string }>(); this._onProcessIdReady = new Emitter<TerminalInstance>(); this._onTitleChanged = new Emitter<string>(); // Create a promise that resolves when the pty is ready this._processReady = new TPromise<void>(c => { this.onProcessIdReady(() => c(void 0)); }); this._initDimensions(); this._createProcess(this._shellLaunchConfig); this._createXterm(); if (platform.isWindows) { this._processReady.then(() => { if (!this._isDisposed) { import('vs/workbench/parts/terminal/electron-browser/windowsShellHelper').then((module) => { this._windowsShellHelper = new module.WindowsShellHelper(this._processId, this._shellLaunchConfig.executable, this, this._xterm); }); } }); } // Only attach xterm.js to the DOM if the terminal panel has been opened before. if (_container) { this.attachToElement(_container); } } public addDisposable(disposable: lifecycle.IDisposable): void { this._instanceDisposables.push(disposable); } private _initDimensions(): void { // The terminal panel needs to have been created if (!this._container) { return; } const computedStyle = window.getComputedStyle(this._container); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this._evaluateColsAndRows(width, height); } /** * Evaluates and sets the cols and rows of the terminal if possible. * @param width The width of the container. * @param height The height of the container. * @return The terminal's width if it requires a layout. */ private _evaluateColsAndRows(width: number, height: number): number { const dimension = this._getDimension(width, height); if (!dimension) { return null; } const font = this._configHelper.getFont(); this._cols = Math.max(Math.floor(dimension.width / font.charWidth), 1); this._rows = Math.max(Math.floor(dimension.height / font.charHeight), 1); return dimension.width; } private _getDimension(width: number, height: number): Dimension { // The font needs to have been initialized const font = this._configHelper.getFont(); if (!font || !font.charWidth || !font.charHeight) { return null; } // The panel is minimized if (!height) { return TerminalInstance._lastKnownDimensions; } else { // Trigger scroll event manually so that the viewport's scroll area is synced. This // needs to happen otherwise its scrollTop value is invalid when the panel is toggled as // it gets removed and then added back to the DOM (resetting scrollTop to 0). // Upstream issue: https://github.com/sourcelair/xterm.js/issues/291 if (this._xterm) { this._xterm.emit('scroll', this._xterm.ydisp); } } const outerContainer = document.querySelector('.terminal-outer-container'); const outerContainerStyle = getComputedStyle(outerContainer); const padding = parseInt(outerContainerStyle.paddingLeft.split('px')[0], 10); const paddingBottom = parseInt(outerContainerStyle.paddingBottom.split('px')[0], 10); // Use left padding as right padding, right padding is not defined in CSS just in case // xterm.js causes an unexpected overflow. const innerWidth = width - padding * 2; const innerHeight = height - paddingBottom; TerminalInstance._lastKnownDimensions = new Dimension(innerWidth, innerHeight); return TerminalInstance._lastKnownDimensions; } /** * Create xterm.js instance and attach data listeners. */ protected _createXterm(): void { this._xterm = new XTermTerminal({ scrollback: this._configHelper.config.scrollback }); if (this._shellLaunchConfig.initialText) { this._xterm.writeln(this._shellLaunchConfig.initialText); } this._process.on('message', (message) => this._sendPtyDataToXterm(message)); this._xterm.on('data', (data) => { if (this._processId) { // Send data if the pty is ready this._process.send({ event: 'input', data }); } else { // If the pty is not ready, queue the data received from // xterm.js until the pty is ready this._preLaunchInputQueue += data; } return false; }); this._linkHandler = this._instantiationService.createInstance(TerminalLinkHandler, this._xterm, platform.platform, this._initialCwd); this._linkHandler.registerLocalLinkHandler(); } public attachToElement(container: HTMLElement): void { if (this._wrapperElement) { throw new Error('The terminal instance has already been attached to a container'); } this._container = container; this._wrapperElement = document.createElement('div'); dom.addClass(this._wrapperElement, 'terminal-wrapper'); this._xtermElement = document.createElement('div'); this._xterm.open(this._xtermElement); this._xterm.attachCustomKeyEventHandler((event: KeyboardEvent) => { // Disable all input if the terminal is exiting if (this._isExiting) { return false; } // Skip processing by xterm.js of keyboard events that resolve to commands described // within commandsToSkipShell const standardKeyboardEvent = new StandardKeyboardEvent(event); const resolveResult = this._keybindingService.softDispatch(standardKeyboardEvent, standardKeyboardEvent.target); if (resolveResult && this._skipTerminalCommands.some(k => k === resolveResult.commandId)) { event.preventDefault(); return false; } // If tab focus mode is on, tab is not passed to the terminal if (TabFocus.getTabFocusMode() && event.keyCode === 9) { return false; } return undefined; }); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'mouseup', (event: KeyboardEvent) => { // Wait until mouseup has propagated through the DOM before // evaluating the new selection state. setTimeout(() => this._refreshSelectionContextKey(), 0); })); // xterm.js currently drops selection on keyup as we need to handle this case. this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'keyup', (event: KeyboardEvent) => { // Wait until keyup has propagated through the DOM before evaluating // the new selection state. setTimeout(() => this._refreshSelectionContextKey(), 0); })); const xtermHelper: HTMLElement = <HTMLElement>this._xterm.element.querySelector('.xterm-helpers'); const focusTrap: HTMLElement = document.createElement('div'); focusTrap.setAttribute('tabindex', '0'); dom.addClass(focusTrap, 'focus-trap'); this._instanceDisposables.push(dom.addDisposableListener(focusTrap, 'focus', (event: FocusEvent) => { let currentElement = focusTrap; while (!dom.hasClass(currentElement, 'part')) { currentElement = currentElement.parentElement; } const hidePanelElement = <HTMLElement>currentElement.querySelector('.hide-panel-action'); hidePanelElement.focus(); })); xtermHelper.insertBefore(focusTrap, this._xterm.textarea); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'focus', (event: KeyboardEvent) => { this._terminalFocusContextKey.set(true); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'blur', (event: KeyboardEvent) => { this._terminalFocusContextKey.reset(); this._refreshSelectionContextKey(); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'focus', (event: KeyboardEvent) => { this._terminalFocusContextKey.set(true); })); this._instanceDisposables.push(dom.addDisposableListener(this._xterm.element, 'blur', (event: KeyboardEvent) => { this._terminalFocusContextKey.reset(); this._refreshSelectionContextKey(); })); this._wrapperElement.appendChild(this._xtermElement); this._widgetManager = new TerminalWidgetManager(this._configHelper, this._wrapperElement); this._linkHandler.setWidgetManager(this._widgetManager); this._container.appendChild(this._wrapperElement); const computedStyle = window.getComputedStyle(this._container); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this.layout(new Dimension(width, height)); this.setVisible(this._isVisible); this.updateConfig(); // If IShellLaunchConfig.waitOnExit was true and the process finished before the terminal // panel was initialized. if (this._xterm.getOption('disableStdin')) { this._attachPressAnyKeyToCloseListener(); } } public registerLinkMatcher(regex: RegExp, handler: (url: string) => void, matchIndex?: number, validationCallback?: (uri: string, element: HTMLElement, callback: (isValid: boolean) => void) => void): number { return this._linkHandler.registerCustomLinkHandler(regex, handler, matchIndex, validationCallback); } public deregisterLinkMatcher(linkMatcherId: number): void { this._xterm.deregisterLinkMatcher(linkMatcherId); } public hasSelection(): boolean { return this._xterm.hasSelection(); } public copySelection(): void { if (this.hasSelection()) { this._clipboardService.writeText(this._xterm.getSelection()); } else { this._messageService.show(Severity.Warning, nls.localize('terminal.integrated.copySelection.noSelection', 'The terminal has no selection to copy')); } } get selection(): string | undefined { return this.hasSelection() ? this._xterm.getSelection() : undefined; } public clearSelection(): void { this._xterm.clearSelection(); } public selectAll(): void { // Focus here to ensure the terminal context key is set this._xterm.focus(); this._xterm.selectAll(); } public findNext(term: string): boolean { return this._xterm.findNext(term); } public findPrevious(term: string): boolean { return this._xterm.findPrevious(term); } public notifyFindWidgetFocusChanged(isFocused: boolean): void { // In order to support escape to close the find widget when the terminal // is focused terminalFocus needs to be true when either the terminal or // the find widget are focused. this._terminalFocusContextKey.set(isFocused || document.activeElement === this._xterm.textarea); } public dispose(): void { if (this._windowsShellHelper) { this._windowsShellHelper.dispose(); } if (this._linkHandler) { this._linkHandler.dispose(); } if (this._xterm && this._xterm.element) { this._hadFocusOnExit = dom.hasClass(this._xterm.element, 'focus'); } if (this._wrapperElement) { this._container.removeChild(this._wrapperElement); this._wrapperElement = null; } if (this._xterm) { this._xterm.destroy(); this._xterm = null; } if (this._process) { if (this._process.connected) { // If the process was still connected this dispose came from // within VS Code, not the process, so mark the process as // killed by the user. this._processState = ProcessState.KILLED_BY_USER; this._process.send({ event: 'shutdown' }); } this._process = null; } if (!this._isDisposed) { this._isDisposed = true; this._onDisposed.fire(this); } this._processDisposables = lifecycle.dispose(this._processDisposables); this._instanceDisposables = lifecycle.dispose(this._instanceDisposables); } public focus(force?: boolean): void { if (!this._xterm) { return; } const text = window.getSelection().toString(); if (!text || force) { this._xterm.focus(); } } public paste(): void { this.focus(); document.execCommand('paste'); } public sendText(text: string, addNewLine: boolean): void { this._processReady.then(() => { // Normalize line endings to 'enter' press. text = text.replace(TerminalInstance.EOL_REGEX, '\r'); if (addNewLine && text.substr(text.length - 1) !== '\r') { text += '\r'; } this._process.send({ event: 'input', data: text }); }); } public setVisible(visible: boolean): void { this._isVisible = visible; if (this._wrapperElement) { dom.toggleClass(this._wrapperElement, 'active', visible); } if (visible && this._xterm) { // Trigger a manual scroll event which will sync the viewport and scroll bar. This is // necessary if the number of rows in the terminal has decreased while it was in the // background since scrollTop changes take no effect but the terminal's position does // change since the number of visible rows decreases. this._xterm.emit('scroll', this._xterm.ydisp); } } public scrollDownLine(): void { this._xterm.scrollDisp(1); } public scrollDownPage(): void { this._xterm.scrollPages(1); } public scrollToBottom(): void { this._xterm.scrollToBottom(); } public scrollUpLine(): void { this._xterm.scrollDisp(-1); } public scrollUpPage(): void { this._xterm.scrollPages(-1); } public scrollToTop(): void { this._xterm.scrollToTop(); } public clear(): void { this._xterm.clear(); } private _refreshSelectionContextKey() { const activePanel = this._panelService.getActivePanel(); const isActive = activePanel && activePanel.getId() === TERMINAL_PANEL_ID; this._terminalHasTextContextKey.set(isActive && this.hasSelection()); } protected _getCwd(shell: IShellLaunchConfig, root: Uri): string { if (shell.cwd) { return shell.cwd; } let cwd: string; // TODO: Handle non-existent customCwd if (!shell.ignoreConfigurationCwd) { // Evaluate custom cwd first const customCwd = this._configHelper.config.cwd; if (customCwd) { if (path.isAbsolute(customCwd)) { cwd = customCwd; } else if (root) { cwd = path.normalize(path.join(root.fsPath, customCwd)); } } } // If there was no custom cwd or it was relative with no workspace if (!cwd) { cwd = root ? root.fsPath : os.homedir(); } return TerminalInstance._sanitizeCwd(cwd); } protected _createProcess(shell: IShellLaunchConfig): void { const locale = this._configHelper.config.setLocaleVariables ? platform.locale : undefined; if (!shell.executable) { this._configHelper.mergeDefaultShellPathAndArgs(shell); } this._initialCwd = this._getCwd(this._shellLaunchConfig, this._historyService.getLastActiveWorkspaceRoot()); let envFromConfig: IStringDictionary<string>; if (platform.isWindows) { envFromConfig = { ...process.env }; for (let configKey in this._configHelper.config.env['windows']) { let actualKey = configKey; for (let envKey in envFromConfig) { if (configKey.toLowerCase() === envKey.toLowerCase()) { actualKey = envKey; break; } } envFromConfig[actualKey] = this._configHelper.config.env['windows'][configKey]; } } else { const platformKey = platform.isMacintosh ? 'osx' : 'linux'; envFromConfig = { ...process.env, ...this._configHelper.config.env[platformKey] }; } const env = TerminalInstance.createTerminalEnv(envFromConfig, shell, this._initialCwd, locale, this._cols, this._rows); this._process = cp.fork(Uri.parse(require.toUrl('bootstrap')).fsPath, ['--type=terminal'], { env, cwd: Uri.parse(path.dirname(require.toUrl('../node/terminalProcess'))).fsPath }); this._processState = ProcessState.LAUNCHING; if (shell.name) { this.setTitle(shell.name, false); } else { // Only listen for process title changes when a name is not provided this.setTitle(shell.executable, true); this._messageTitleListener = (message) => { if (message.type === 'title') { this.setTitle(message.content ? message.content : '', true); } }; this._process.on('message', this._messageTitleListener); } this._process.on('message', (message) => { if (message.type === 'pid') { this._processId = message.content; // Send any queued data that's waiting if (this._preLaunchInputQueue.length > 0) { this._process.send({ event: 'input', data: this._preLaunchInputQueue }); this._preLaunchInputQueue = null; } this._onProcessIdReady.fire(this); } }); this._process.on('exit', exitCode => this._onPtyProcessExit(exitCode)); setTimeout(() => { if (this._processState === ProcessState.LAUNCHING) { this._processState = ProcessState.RUNNING; } }, LAUNCHING_DURATION); } private _sendPtyDataToXterm(message: { type: string, content: string }): void { if (message.type === 'data') { if (this._widgetManager) { this._widgetManager.closeMessage(); } if (this._xterm) { this._xterm.write(message.content); } } } private _onPtyProcessExit(exitCode: number): void { // Prevent dispose functions being triggered multiple times if (this._isExiting) { return; } this._isExiting = true; this._process = null; let exitCodeMessage: string; if (exitCode) { exitCodeMessage = nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode); } // If the process is marked as launching then mark the process as killed // during launch. This typically means that there is a problem with the // shell and args. if (this._processState === ProcessState.LAUNCHING) { this._processState = ProcessState.KILLED_DURING_LAUNCH; } // If TerminalInstance did not know about the process exit then it was // triggered by the process, not on VS Code's side. if (this._processState === ProcessState.RUNNING) { this._processState = ProcessState.KILLED_BY_PROCESS; } // Only trigger wait on exit when the exit was triggered by the process, // not through the `workbench.action.terminal.kill` command if (this._processState === ProcessState.KILLED_BY_PROCESS && this._shellLaunchConfig.waitOnExit) { if (exitCode) { this._xterm.writeln(exitCodeMessage); } let message = typeof this._shellLaunchConfig.waitOnExit === 'string' ? this._shellLaunchConfig.waitOnExit : nls.localize('terminal.integrated.waitOnExit', 'Press any key to close the terminal'); // Bold the message and add an extra new line to make it stand out from the rest of the output message = `\n\x1b[1m${message}\x1b[0m`; this._xterm.writeln(message); // Disable all input if the terminal is exiting and listen for next keypress this._xterm.setOption('disableStdin', true); if (this._xterm.textarea) { this._attachPressAnyKeyToCloseListener(); } } else { this.dispose(); if (exitCode) { if (this._processState === ProcessState.KILLED_DURING_LAUNCH) { let args = ''; if (typeof this._shellLaunchConfig.args === 'string') { args = this._shellLaunchConfig.args; } else if (this._shellLaunchConfig.args && this._shellLaunchConfig.args.length) { args = ' ' + this._shellLaunchConfig.args.map(a => { if (typeof a === 'string' && a.indexOf(' ') !== -1) { return `'${a}'`; } return a; }).join(' '); } this._messageService.show(Severity.Error, nls.localize('terminal.integrated.launchFailed', 'The terminal process command `{0}{1}` failed to launch (exit code: {2})', this._shellLaunchConfig.executable, args, exitCode)); } else { this._messageService.show(Severity.Error, exitCodeMessage); } } } } private _attachPressAnyKeyToCloseListener() { this._processDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'keypress', (event: KeyboardEvent) => { this.dispose(); event.preventDefault(); })); } public reuseTerminal(shell?: IShellLaunchConfig): void { // Kill and clean up old process if (this._process) { this._process.removeAllListeners('exit'); if (this._process.connected) { this._process.kill(); } this._process = null; } lifecycle.dispose(this._processDisposables); this._processDisposables = []; // Ensure new processes' output starts at start of new line this._xterm.write('\n\x1b[G'); // Print initialText if specified if (shell.initialText) { this._xterm.writeln(shell.initialText); } // Initialize new process const oldTitle = this._title; this._createProcess(shell); if (oldTitle !== this._title) { this.setTitle(this._title, true); } this._process.on('message', (message) => this._sendPtyDataToXterm(message)); // Clean up waitOnExit state if (this._isExiting && this._shellLaunchConfig.waitOnExit) { this._xterm.setOption('disableStdin', false); this._isExiting = false; } // Set the new shell launch config this._shellLaunchConfig = shell; } // TODO: This should be private/protected // TODO: locale should not be optional public static createTerminalEnv(parentEnv: IStringDictionary<string>, shell: IShellLaunchConfig, cwd: string, locale?: string, cols?: number, rows?: number): IStringDictionary<string> { const env = shell.env ? shell.env : TerminalInstance._cloneEnv(parentEnv); env['PTYPID'] = process.pid.toString(); env['PTYSHELL'] = shell.executable; env['TERM_PROGRAM'] = 'vscode'; env['TERM_PROGRAM_VERSION'] = pkg.version; if (shell.args) { if (typeof shell.args === 'string') { env[`PTYSHELLCMDLINE`] = shell.args; } else { shell.args.forEach((arg, i) => env[`PTYSHELLARG${i}`] = arg); } } env['PTYCWD'] = cwd; env['LANG'] = TerminalInstance._getLangEnvVariable(locale); if (cols && rows) { env['PTYCOLS'] = cols.toString(); env['PTYROWS'] = rows.toString(); } env['AMD_ENTRYPOINT'] = 'vs/workbench/parts/terminal/node/terminalProcess'; return env; } public onData(listener: (data: string) => void): lifecycle.IDisposable { let callback = (message) => { if (message.type === 'data') { listener(message.content); } }; this._process.on('message', callback); return { dispose: () => { if (this._process) { this._process.removeListener('message', callback); } } }; } public onExit(listener: (exitCode: number) => void): lifecycle.IDisposable { if (this._process) { this._process.on('exit', listener); } return { dispose: () => { if (this._process) { this._process.removeListener('exit', listener); } } }; } private static _sanitizeCwd(cwd: string) { // Make the drive letter uppercase on Windows (see #9448) if (platform.platform === platform.Platform.Windows && cwd && cwd[1] === ':') { return cwd[0].toUpperCase() + cwd.substr(1); } return cwd; } private static _cloneEnv(env: IStringDictionary<string>): IStringDictionary<string> { const newEnv: IStringDictionary<string> = Object.create(null); Object.keys(env).forEach((key) => { newEnv[key] = env[key]; }); return newEnv; } private static _getLangEnvVariable(locale?: string) { const parts = locale ? locale.split('-') : []; const n = parts.length; if (n === 0) { // Fallback to en_US to prevent possible encoding issues. return 'en_US.UTF-8'; } if (n === 1) { // app.getLocale can return just a language without a variant, fill in the variant for // supported languages as many shells expect a 2-part locale. const languageVariants = { de: 'DE', en: 'US', es: 'ES', fr: 'FR', it: 'IT', ja: 'JP', ko: 'KR', ru: 'RU', zh: 'CN' }; if (parts[0] in languageVariants) { parts.push(languageVariants[parts[0]]); } } else { // Ensure the variant is uppercase parts[1] = parts[1].toUpperCase(); } return parts.join('_') + '.UTF-8'; } public updateConfig(): void { this._setCursorBlink(this._configHelper.config.cursorBlinking); this._setCursorStyle(this._configHelper.config.cursorStyle); this._setCommandsToSkipShell(this._configHelper.config.commandsToSkipShell); this._setScrollback(this._configHelper.config.scrollback); } private _setCursorBlink(blink: boolean): void { if (this._xterm && this._xterm.getOption('cursorBlink') !== blink) { this._xterm.setOption('cursorBlink', blink); this._xterm.refresh(0, this._xterm.rows - 1); } } private _setCursorStyle(style: string): void { if (this._xterm && this._xterm.getOption('cursorStyle') !== style) { // 'line' is used instead of bar in VS Code to be consistent with editor.cursorStyle const xtermOption = style === 'line' ? 'bar' : style; this._xterm.setOption('cursorStyle', xtermOption); } } private _setCommandsToSkipShell(commands: string[]): void { this._skipTerminalCommands = commands; } private _setScrollback(lineCount: number): void { if (this._xterm && this._xterm.getOption('scrollback') !== lineCount) { this._xterm.setOption('scrollback', lineCount); } } public layout(dimension: Dimension): void { const terminalWidth = this._evaluateColsAndRows(dimension.width, dimension.height); if (!terminalWidth) { return; } if (this._xterm) { this._xterm.resize(this._cols, this._rows); this._xterm.element.style.width = terminalWidth + 'px'; } this._processReady.then(() => { if (this._process && this._process.connected) { // The child process could aready be terminated try { this._process.send({ event: 'resize', cols: this._cols, rows: this._rows }); } catch (error) { // We tried to write to a closed pipe / channel. if (error.code !== 'EPIPE' && error.code !== 'ERR_IPC_CHANNEL_CLOSED') { throw (error); } } } }); } public static setTerminalProcessFactory(factory: ITerminalProcessFactory): void { this._terminalProcessFactory = factory; } public setTitle(title: string, eventFromProcess: boolean): void { if (!title) { return; } if (eventFromProcess) { title = path.basename(title); if (platform.isWindows) { // Remove the .exe extension title = title.split('.exe')[0]; } } else { // If the title has not been set by the API or the rename command, unregister the handler that // automatically updates the terminal name if (this._process && this._messageTitleListener) { this._process.removeListener('message', this._messageTitleListener); this._messageTitleListener = null; } } const didTitleChange = title !== this._title; this._title = title; if (didTitleChange) { this._onTitleChanged.fire(title); } } } registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { // Scrollbar const scrollbarSliderBackgroundColor = theme.getColor(scrollbarSliderBackground); if (scrollbarSliderBackgroundColor) { collector.addRule(` .monaco-workbench .panel.integrated-terminal .xterm.focus .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm:focus .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm:hover .xterm-viewport { background-color: ${scrollbarSliderBackgroundColor}; }` ); } const scrollbarSliderHoverBackgroundColor = theme.getColor(scrollbarSliderHoverBackground); if (scrollbarSliderHoverBackgroundColor) { collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:hover { background-color: ${scrollbarSliderHoverBackgroundColor}; }`); } const scrollbarSliderActiveBackgroundColor = theme.getColor(scrollbarSliderActiveBackground); if (scrollbarSliderActiveBackgroundColor) { collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:active { background-color: ${scrollbarSliderActiveBackgroundColor}; }`); } });
src/vs/workbench/parts/terminal/electron-browser/terminalInstance.ts
1
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.9989591836929321, 0.08150535076856613, 0.00016508086991962045, 0.00021327129798009992, 0.2587011158466339 ]
{ "id": 7, "code_window": [ "\tpublic _getCwd(shell: IShellLaunchConfig, root: Uri): string {\n", "\t\treturn super._getCwd(shell, root);\n", "\t}\n", "\n", "\tprotected _createProcess(shell: IShellLaunchConfig): void { }\n", "\tprotected _createXterm(): void { }\n", "}\n", "\n", "suite('Workbench - TerminalInstance', () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprotected _createProcess(): void { }\n" ], "file_path": "src/vs/workbench/parts/terminal/test/electron-browser/terminalInstance.test.ts", "type": "replace", "edit_start_line_idx": 27 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "hiddenMenuBar": "**Alt** 키를 눌러 메뉴 모음에 계속 액세스할 수 있습니다." }
i18n/kor/src/vs/code/electron-main/window.i18n.json
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.0001744644541759044, 0.0001744644541759044, 0.0001744644541759044, 0.0001744644541759044, 0 ]
{ "id": 7, "code_window": [ "\tpublic _getCwd(shell: IShellLaunchConfig, root: Uri): string {\n", "\t\treturn super._getCwd(shell, root);\n", "\t}\n", "\n", "\tprotected _createProcess(shell: IShellLaunchConfig): void { }\n", "\tprotected _createXterm(): void { }\n", "}\n", "\n", "suite('Workbench - TerminalInstance', () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprotected _createProcess(): void { }\n" ], "file_path": "src/vs/workbench/parts/terminal/test/electron-browser/terminalInstance.test.ts", "type": "replace", "edit_start_line_idx": 27 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "parseErrors": "Hiba a(z) {0} feldolgozása közben: {1}", "schema.openBracket": "A nyitó zárójelet definiáló karakter vagy karaktersorozat", "schema.closeBracket": "A záró zárójelet definiáló karakter vagy karaktersorozat", "schema.comments": "Meghatározza a megjegyzésszimbólumokat", "schema.blockComments": "Meghatározza, hogyan vannak jelölve a megjegyzésblokkok.", "schema.blockComment.begin": "A megjegyzésblokk kezdetét definiáló karaktersorozat.", "schema.blockComment.end": "A megjegyzésblokk végét definiáló karaktersorozat.", "schema.lineComment": "A megjegyzéssor kezdetét definiáló karaktersorozat.", "schema.brackets": "Meghatározza azokat a zárójelszimbólumokat, amelyek növeik vagy csökkentik az indentálást.", "schema.autoClosingPairs": "Meghatározza a zárójelpárokat. Ha egy nyitó zárójelet írnak be a szerkesztőbe, a záró párja automatikusan be lesz illesztve.", "schema.autoClosingPairs.notIn": "Azon hatókörök listája, ahol az automatikus zárójelek automatikus párosítása le van tiltve.", "schema.surroundingPairs": "Meghatározza azok zárójelpárok listáját, melyek használhatók a kijelölt szöveg körbezárására.", "schema.wordPattern": "A nyelvben található szavak definíciója.", "schema.wordPattern.pattern": "A szavak illesztésére használt reguláris kifejezés.", "schema.wordPattern.flags": "A szavak illesztésére használt reguláris kifejezés beállításai.", "schema.wordPattern.flags.errorMessage": "Illeszkednie kell a következő mintára: `/^([gimuy]+)$/`.", "schema.indentationRules": "A nyelv indentálási beállításai.", "schema.indentationRules.increaseIndentPattern": "Ha egy sor illeszkedik erre a mintára, akkor minden utána következő sor eggyel beljebb lesz indentálva (amíg egy újabb szabály nem illeszkedik).", "schema.indentationRules.increaseIndentPattern.pattern": "Az increaseIndentPatternhöz tartozó reguláris kifejezés.", "schema.indentationRules.increaseIndentPattern.flags": "Az increaseIndentPatternhöz tartozó reguláris kifejezés beállításai.", "schema.indentationRules.increaseIndentPattern.errorMessage": "Illeszkednie kell a következő mintára: `/^([gimuy]+)$/`.", "schema.indentationRules.decreaseIndentPattern": "Ha egy sor illeszkedik erre a mintára, akkor minden utána következő sor eggyel kijjebb lesz indentálva (amíg egy újabb szabály nem illeszkedik).", "schema.indentationRules.decreaseIndentPattern.pattern": "A decreaseIndentPatternhöz tartozó reguláris kifejezés.", "schema.indentationRules.decreaseIndentPattern.flags": "A decreaseIndentPatternhöz tartozó reguláris kifejezés beállításai.", "schema.indentationRules.decreaseIndentPattern.errorMessage": "Illeszkednie kell a következő mintára: `/^([gimuy]+)$/`.", "schema.indentationRules.indentNextLinePattern": "Ha egy sor illeszkedik erre a mintára, akkor **csak a következő sor** eggyel beljebb lesz indentálva.", "schema.indentationRules.indentNextLinePattern.pattern": "Az indentNextLinePatternhöz tartozó reguláris kifejezés.", "schema.indentationRules.indentNextLinePattern.flags": "Az indentNextLinePatternhöz tartozó reguláris kifejezés beállításai.", "schema.indentationRules.indentNextLinePattern.errorMessage": "Illeszkednie kell a következő mintára: `/^([gimuy]+)$/`.", "schema.indentationRules.unIndentedLinePattern": "Ha egy sor illeszkedik erre a mintára, akkor az indentálása nem változik, és nem lesz kiértékelve más szabályok alapján.", "schema.indentationRules.unIndentedLinePattern.pattern": "Az unIndentedLinePatternhöz tartozó reguláris kifejezés.", "schema.indentationRules.unIndentedLinePattern.flags": "Az unIndentedLinePatternhöz tartozó reguláris kifejezés beállításai.", "schema.indentationRules.unIndentedLinePattern.errorMessage": "Illeszkednie kell a következő mintára: `/^([gimuy]+)$/`." }
i18n/hun/src/vs/workbench/parts/codeEditor/electron-browser/languageConfiguration/languageConfigurationExtensionPoint.i18n.json
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.00017427773855160922, 0.00017087673768401146, 0.00016712077194824815, 0.0001703798188827932, 0.0000029400437142612645 ]
{ "id": 7, "code_window": [ "\tpublic _getCwd(shell: IShellLaunchConfig, root: Uri): string {\n", "\t\treturn super._getCwd(shell, root);\n", "\t}\n", "\n", "\tprotected _createProcess(shell: IShellLaunchConfig): void { }\n", "\tprotected _createXterm(): void { }\n", "}\n", "\n", "suite('Workbench - TerminalInstance', () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprotected _createProcess(): void { }\n" ], "file_path": "src/vs/workbench/parts/terminal/test/electron-browser/terminalInstance.test.ts", "type": "replace", "edit_start_line_idx": 27 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "overwritingExtension": "확장 {0}을(를) {1}(으)로 덮어쓰는 중입니다.", "extensionUnderDevelopment": "{0}에서 개발 확장 로드 중" }
i18n/kor/src/vs/workbench/api/node/mainThreadExtensionService.i18n.json
0
https://github.com/microsoft/vscode/commit/d5ac84dd0cb53354fdc1bafad1b42b6083a2e650
[ 0.0001758543512551114, 0.0001758543512551114, 0.0001758543512551114, 0.0001758543512551114, 0 ]
{ "id": 0, "code_window": [ " * Sanitizes the given unsafe, untrusted HTML fragment, and returns HTML text that is safe to add to\n", " * the DOM in a browser environment.\n", " */\n", "export function sanitizeHtml(unsafeHtml: string): string {\n", " try {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "export function sanitizeHtml(unsafeHtmlInput: string): string {\n" ], "file_path": "modules/@angular/platform-browser/src/security/html_sanitizer.ts", "type": "replace", "edit_start_line_idx": 233 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as t from '@angular/core/testing/testing_internal'; import {browserDetection} from '@angular/platform-browser/testing'; import {getDOM} from '../../src/dom/dom_adapter'; import {sanitizeHtml} from '../../src/security/html_sanitizer'; export function main() { t.describe('HTML sanitizer', () => { let originalLog: (msg: any) => any = null; let logMsgs: string[]; t.beforeEach(() => { logMsgs = []; originalLog = getDOM().log; // Monkey patch DOM.log. getDOM().log = (msg) => logMsgs.push(msg); }); t.afterEach(() => { getDOM().log = originalLog; }); t.it('serializes nested structures', () => { t.expect(sanitizeHtml('<div alt="x"><p>a</p>b<b>c<a alt="more">d</a></b>e</div>')) .toEqual('<div alt="x"><p>a</p>b<b>c<a alt="more">d</a></b>e</div>'); t.expect(logMsgs).toEqual([]); }); t.it('serializes self closing elements', () => { t.expect(sanitizeHtml('<p>Hello <br> World</p>')).toEqual('<p>Hello <br> World</p>'); }); t.it('supports namespaced elements', () => { t.expect(sanitizeHtml('a<my:hr/><my:div>b</my:div>c')).toEqual('abc'); }); t.it('supports namespaced attributes', () => { t.expect(sanitizeHtml('<a xlink:href="something">t</a>')) .toEqual('<a xlink:href="something">t</a>'); t.expect(sanitizeHtml('<a xlink:evil="something">t</a>')).toEqual('<a>t</a>'); t.expect(sanitizeHtml('<a xlink:href="javascript:foo()">t</a>')) .toEqual('<a xlink:href="unsafe:javascript:foo()">t</a>'); }); t.it('supports sanitizing plain text', () => { t.expect(sanitizeHtml('Hello, World')).toEqual('Hello, World'); }); t.it('ignores non-element, non-attribute nodes', () => { t.expect(sanitizeHtml('<!-- comments? -->no.')).toEqual('no.'); t.expect(sanitizeHtml('<?pi nodes?>no.')).toEqual('no.'); t.expect(logMsgs.join('\n')).toMatch(/sanitizing HTML stripped some content/); }); t.it('escapes entities', () => { t.expect(sanitizeHtml('<p>Hello &lt; World</p>')).toEqual('<p>Hello &lt; World</p>'); t.expect(sanitizeHtml('<p>Hello < World</p>')).toEqual('<p>Hello &lt; World</p>'); t.expect(sanitizeHtml('<p alt="% &amp; &quot; !">Hello</p>')) .toEqual('<p alt="% &amp; &#34; !">Hello</p>'); // NB: quote encoded as ASCII &#34;. }); t.describe('should strip dangerous elements', () => { let dangerousTags = [ 'frameset', 'form', 'param', 'object', 'embed', 'textarea', 'input', 'button', 'option', 'select', 'script', 'style', 'link', 'base', 'basefont' ]; for (let tag of dangerousTags) { t.it( `${tag}`, () => { t.expect(sanitizeHtml(`<${tag}>evil!</${tag}>`)).toEqual('evil!'); }); } t.it(`swallows frame entirely`, () => { t.expect(sanitizeHtml(`<frame>evil!</frame>`)).not.toContain('<frame>'); }); }); t.describe('should strip dangerous attributes', () => { let dangerousAttrs = ['id', 'name', 'style']; for (let attr of dangerousAttrs) { t.it(`${attr}`, () => { t.expect(sanitizeHtml(`<a ${attr}="x">evil!</a>`)).toEqual('<a>evil!</a>'); }); } }); if (browserDetection.isWebkit) { t.it('should prevent mXSS attacks', function() { t.expect(sanitizeHtml('<a href="&#x3000;javascript:alert(1)">CLICKME</a>')) .toEqual('<a href="unsafe:javascript:alert(1)">CLICKME</a>'); }); } }); }
modules/@angular/platform-browser/test/security/html_sanitizer_spec.ts
1
https://github.com/angular/angular/commit/98cef76931f1417c21bfaf8cbbdb3768a4b85fb5
[ 0.9992514252662659, 0.7990498542785645, 0.00017255049897357821, 0.9991083145141602, 0.3994392454624176 ]
{ "id": 0, "code_window": [ " * Sanitizes the given unsafe, untrusted HTML fragment, and returns HTML text that is safe to add to\n", " * the DOM in a browser environment.\n", " */\n", "export function sanitizeHtml(unsafeHtml: string): string {\n", " try {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "export function sanitizeHtml(unsafeHtmlInput: string): string {\n" ], "file_path": "modules/@angular/platform-browser/src/security/html_sanitizer.ts", "type": "replace", "edit_start_line_idx": 233 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal'; import {Component, Directive} from '@angular/core'; import {reflector} from '@angular/core/src/reflection/reflection'; export function main() { describe('es5 decorators', () => { it('should declare directive class', () => { var MyDirective = Directive({}).Class({constructor: function() { this.works = true; }}); expect(new MyDirective().works).toEqual(true); }); it('should declare Component class', () => { var MyComponent = Component({}).View({}).View({}).Class({constructor: function() { this.works = true; }}); expect(new MyComponent().works).toEqual(true); }); it('should create type in ES5', () => { function MyComponent(){}; var as: any /** TODO #9100 */; (<any>MyComponent).annotations = as = Component({}).View({}); expect(reflector.annotations(MyComponent)).toEqual(as.annotations); }); }); }
modules/@angular/core/test/metadata/decorators_spec.ts
0
https://github.com/angular/angular/commit/98cef76931f1417c21bfaf8cbbdb3768a4b85fb5
[ 0.00017632482922635972, 0.00017314220895059407, 0.0001691805518930778, 0.000173531734617427, 0.0000028883728191431146 ]
{ "id": 0, "code_window": [ " * Sanitizes the given unsafe, untrusted HTML fragment, and returns HTML text that is safe to add to\n", " * the DOM in a browser environment.\n", " */\n", "export function sanitizeHtml(unsafeHtml: string): string {\n", " try {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "export function sanitizeHtml(unsafeHtmlInput: string): string {\n" ], "file_path": "modules/@angular/platform-browser/src/security/html_sanitizer.ts", "type": "replace", "edit_start_line_idx": 233 }
name: angular2_benchmarks version: <%= packageJson.version %> authors: <%= Object.keys(packageJson.contributors).map(function(name) { return '- '+name+' <'+packageJson.contributors[name]+'>'; }).join('\n') %> description: Angular2 benchmarks homepage: <%= packageJson.homepage %> environment: sdk: '>=1.10.0 <2.0.0' dependencies: angular2: '^<%= packageJson.version %>' browser: '^0.10.0' dependency_overrides: angular2: path: ../angular2 transformers: - angular2/transform/codegen - angular2/transform/reflection_remover: $include: - web/src/compiler/compiler_benchmark.dart - web/src/costs/index.dart - web/src/di/di_benchmark.dart - web/src/element_injector/element_injector_benchmark.dart - web/src/largetable/largetable_benchmark.dart - web/src/naive_infinite_scroll/index.dart - web/src/static_tree/tree_benchmark.dart - web/src/tree/tree_benchmark.dart - web/src/page_load/page_load.dart - $dart2js: $include: web/src/** minify: false commandLineOptions: - --dump-info - --trust-type-annotations - --trust-primitives - --show-package-warnings - --fatal-warnings
modules/benchmarks/pubspec.yaml
0
https://github.com/angular/angular/commit/98cef76931f1417c21bfaf8cbbdb3768a4b85fb5
[ 0.00017117282550316304, 0.00017042484250850976, 0.00016894728469196707, 0.00017078964447136968, 8.683011287757836e-7 ]
{ "id": 0, "code_window": [ " * Sanitizes the given unsafe, untrusted HTML fragment, and returns HTML text that is safe to add to\n", " * the DOM in a browser environment.\n", " */\n", "export function sanitizeHtml(unsafeHtml: string): string {\n", " try {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "export function sanitizeHtml(unsafeHtmlInput: string): string {\n" ], "file_path": "modules/@angular/platform-browser/src/security/html_sanitizer.ts", "type": "replace", "edit_start_line_idx": 233 }
var data = module.exports = require('./protractor-shared.js'); var config = data.config; config.baseUrl = 'http://localhost:8003/';
protractor-ddc.conf.js
0
https://github.com/angular/angular/commit/98cef76931f1417c21bfaf8cbbdb3768a4b85fb5
[ 0.00017208780627697706, 0.00017208780627697706, 0.00017208780627697706, 0.00017208780627697706, 0 ]
{ "id": 1, "code_window": [ " try {\n", " let containerEl = getInertElement();\n", " // Make sure unsafeHtml is actually a string (TypeScript types are not enforced at runtime).\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " const containerEl = getInertElement();\n" ], "file_path": "modules/@angular/platform-browser/src/security/html_sanitizer.ts", "type": "replace", "edit_start_line_idx": 235 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as t from '@angular/core/testing/testing_internal'; import {browserDetection} from '@angular/platform-browser/testing'; import {getDOM} from '../../src/dom/dom_adapter'; import {sanitizeHtml} from '../../src/security/html_sanitizer'; export function main() { t.describe('HTML sanitizer', () => { let originalLog: (msg: any) => any = null; let logMsgs: string[]; t.beforeEach(() => { logMsgs = []; originalLog = getDOM().log; // Monkey patch DOM.log. getDOM().log = (msg) => logMsgs.push(msg); }); t.afterEach(() => { getDOM().log = originalLog; }); t.it('serializes nested structures', () => { t.expect(sanitizeHtml('<div alt="x"><p>a</p>b<b>c<a alt="more">d</a></b>e</div>')) .toEqual('<div alt="x"><p>a</p>b<b>c<a alt="more">d</a></b>e</div>'); t.expect(logMsgs).toEqual([]); }); t.it('serializes self closing elements', () => { t.expect(sanitizeHtml('<p>Hello <br> World</p>')).toEqual('<p>Hello <br> World</p>'); }); t.it('supports namespaced elements', () => { t.expect(sanitizeHtml('a<my:hr/><my:div>b</my:div>c')).toEqual('abc'); }); t.it('supports namespaced attributes', () => { t.expect(sanitizeHtml('<a xlink:href="something">t</a>')) .toEqual('<a xlink:href="something">t</a>'); t.expect(sanitizeHtml('<a xlink:evil="something">t</a>')).toEqual('<a>t</a>'); t.expect(sanitizeHtml('<a xlink:href="javascript:foo()">t</a>')) .toEqual('<a xlink:href="unsafe:javascript:foo()">t</a>'); }); t.it('supports sanitizing plain text', () => { t.expect(sanitizeHtml('Hello, World')).toEqual('Hello, World'); }); t.it('ignores non-element, non-attribute nodes', () => { t.expect(sanitizeHtml('<!-- comments? -->no.')).toEqual('no.'); t.expect(sanitizeHtml('<?pi nodes?>no.')).toEqual('no.'); t.expect(logMsgs.join('\n')).toMatch(/sanitizing HTML stripped some content/); }); t.it('escapes entities', () => { t.expect(sanitizeHtml('<p>Hello &lt; World</p>')).toEqual('<p>Hello &lt; World</p>'); t.expect(sanitizeHtml('<p>Hello < World</p>')).toEqual('<p>Hello &lt; World</p>'); t.expect(sanitizeHtml('<p alt="% &amp; &quot; !">Hello</p>')) .toEqual('<p alt="% &amp; &#34; !">Hello</p>'); // NB: quote encoded as ASCII &#34;. }); t.describe('should strip dangerous elements', () => { let dangerousTags = [ 'frameset', 'form', 'param', 'object', 'embed', 'textarea', 'input', 'button', 'option', 'select', 'script', 'style', 'link', 'base', 'basefont' ]; for (let tag of dangerousTags) { t.it( `${tag}`, () => { t.expect(sanitizeHtml(`<${tag}>evil!</${tag}>`)).toEqual('evil!'); }); } t.it(`swallows frame entirely`, () => { t.expect(sanitizeHtml(`<frame>evil!</frame>`)).not.toContain('<frame>'); }); }); t.describe('should strip dangerous attributes', () => { let dangerousAttrs = ['id', 'name', 'style']; for (let attr of dangerousAttrs) { t.it(`${attr}`, () => { t.expect(sanitizeHtml(`<a ${attr}="x">evil!</a>`)).toEqual('<a>evil!</a>'); }); } }); if (browserDetection.isWebkit) { t.it('should prevent mXSS attacks', function() { t.expect(sanitizeHtml('<a href="&#x3000;javascript:alert(1)">CLICKME</a>')) .toEqual('<a href="unsafe:javascript:alert(1)">CLICKME</a>'); }); } }); }
modules/@angular/platform-browser/test/security/html_sanitizer_spec.ts
1
https://github.com/angular/angular/commit/98cef76931f1417c21bfaf8cbbdb3768a4b85fb5
[ 0.0002246835792902857, 0.00017798581393435597, 0.00016944498929660767, 0.00017035414930433035, 0.00001614956090634223 ]
{ "id": 1, "code_window": [ " try {\n", " let containerEl = getInertElement();\n", " // Make sure unsafeHtml is actually a string (TypeScript types are not enforced at runtime).\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " const containerEl = getInertElement();\n" ], "file_path": "modules/@angular/platform-browser/src/security/html_sanitizer.ts", "type": "replace", "edit_start_line_idx": 235 }
var browserProvidersConf = require('./browser-providers.conf.js'); var internalAngularReporter = require('./tools/karma/reporter.js'); // Karma configuration // Generated on Thu Sep 25 2014 11:52:02 GMT-0700 (PDT) module.exports = function(config) { config.set({ frameworks: ['jasmine'], files: [ // Sources and specs. // Loaded through the System loader, in `test-main.js`. {pattern: 'dist/all/@angular/**/*.js', included: false, watched: true}, 'node_modules/es6-shim/es6-shim.js', // include Angular v1 for upgrade module testing 'node_modules/angular/angular.min.js', 'node_modules/zone.js/dist/zone.js', 'node_modules/zone.js/dist/long-stack-trace-zone.js', 'node_modules/zone.js/dist/jasmine-patch.js', 'node_modules/zone.js/dist/async-test.js', 'node_modules/zone.js/dist/fake-async-test.js', // Including systemjs because it defines `__eval`, which produces correct stack traces. 'shims_for_IE.js', 'node_modules/systemjs/dist/system.src.js', {pattern: 'node_modules/rxjs/**', included: false, watched: false, served: true}, 'node_modules/reflect-metadata/Reflect.js', 'tools/build/file2modulename.js', 'test-main.js', {pattern: 'dist/all/empty.*', included: false, watched: false}, {pattern: 'modules/@angular/platform-browser/test/static_assets/**', included: false, watched: false}, {pattern: 'modules/@angular/platform-browser/test/browser/static_assets/**', included: false, watched: false} ], exclude: [ 'dist/all/@angular/**/e2e_test/**', 'dist/all/@angular/examples/**', 'dist/all/@angular/compiler-cli/**', 'dist/all/angular1_router.js', 'dist/all/@angular/platform-browser/testing/e2e_util.js' ], customLaunchers: browserProvidersConf.customLaunchers, plugins: [ 'karma-jasmine', 'karma-browserstack-launcher', 'karma-sauce-launcher', 'karma-chrome-launcher', 'karma-sourcemap-loader', internalAngularReporter ], preprocessors: { '**/*.js': ['sourcemap'] }, reporters: ['internal-angular'], sauceLabs: { testName: 'Angular2', retryLimit: 3, startConnect: false, recordVideo: false, recordScreenshots: false, options: { 'selenium-version': '2.53.0', 'command-timeout': 600, 'idle-timeout': 600, 'max-duration': 5400 } }, browserStack: { project: 'Angular2', startTunnel: false, retryLimit: 3, timeout: 600, pollingTimeout: 10000 }, browsers: ['Chrome'], port: 9876, captureTimeout: 60000, browserDisconnectTimeout : 60000, browserDisconnectTolerance : 3, browserNoActivityTimeout : 60000, }); if (process.env.TRAVIS) { var buildId = 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')'; if (process.env.CI_MODE.startsWith('saucelabs')) { config.sauceLabs.build = buildId; config.sauceLabs.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER; // TODO(mlaval): remove once SauceLabs supports websockets. // This speeds up the capturing a bit, as browsers don't even try to use websocket. console.log('>>>> setting socket.io transport to polling <<<<'); config.transports = ['polling']; } if (process.env.CI_MODE.startsWith('browserstack')) { config.browserStack.build = buildId; config.browserStack.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER; } } };
karma-js.conf.js
0
https://github.com/angular/angular/commit/98cef76931f1417c21bfaf8cbbdb3768a4b85fb5
[ 0.00017744202341418713, 0.00016948150005191565, 0.00016423899796791375, 0.00016951884026639163, 0.0000029345399070734857 ]
{ "id": 1, "code_window": [ " try {\n", " let containerEl = getInertElement();\n", " // Make sure unsafeHtml is actually a string (TypeScript types are not enforced at runtime).\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " const containerEl = getInertElement();\n" ], "file_path": "modules/@angular/platform-browser/src/security/html_sanitizer.ts", "type": "replace", "edit_start_line_idx": 235 }
All of our npm dependencies are locked via the `npm-shrinkwrap.json` file for the following reasons: - our project has lots of dependencies which update at unpredictable times, so it's important that we update them explicitly once in a while rather than implicitly when any of us runs npm install - locked dependencies allow us to do reuse npm cache on travis, significantly speeding up our builds (by 5 minutes or more) - locked dependencies allow us to detect when node_modules folder is out of date after a branch switch which allows us to build the project with the correct dependencies every time We also generate `npm-shrinkwrap.clean.js` file which is used during code reviews or debugging to easily review what has actually changed without extra noise. To add a new dependency do the following: 1. if you are on linux or windows, then use MacOS or ask someone with MacOS to perform the installation. This is due to an optional `fsevents` dependency that is really required on MacOS to get good performance from file watching. 2. make sure you are in sync with `upstream/master` 3. ensure that your `node_modules` directory is not stale by running `npm install` 4. add a new dependency via `npm install --save-dev <packagename>` 5. run `./tools/npm/reshrinkwrap` 6. these steps should change 3 files: `package.json`, `npm-shrinkwrap.json` and `npm-shrinkwrap.clean.json` 7. commit changes to these three files and you are done To update existing dependency do the following: 1. if you are on linux or windows, then use MacOS or ask someone with MacOS to perform the installation. This is due to an optional `fsevents` dependency that is really required on MacOS to get good performance from file watching. 2. make sure you are in sync with `upstream/master`: `git fetch upstream && git rebase upstream/master` 3. ensure that your `node_modules` directory is not stale by running `npm install` 4. run `npm install --save-dev <packagename>@<version|latest>` or `npm update <packagename>` to update to the latest version that matches version constraint in `package.json` 5. run `./tools/npm/reshrinkwrap` 6. these steps should change 2 files: `npm-shrinkwrap.json` and `npm-shrinkwrap.clean.json`. Optionally if you used `npm install ...` in the first step, `package.json` might be modified as well. 7. commit changes to these three files and you are done To Remove an existing dependency do the following: 1. if you are on linux or windows, then use MacOS or ask someone with MacOS to perform the installation. This is due to an optional `fsevents` dependency that is really required on MacOS to get good performance from file watching. 2. make sure you are in sync with `upstream/master`: `git fetch upstream && git rebase upstream/master` 3. ensure that your `node_modules` directory is not stale by running `npm install` 4. run `npm uninstall --save-dev <packagename>@<version|latest>` 5. run `./tools/npm/reshrinkwrap` 6. these steps should change 3 files: `npm-shrinkwrap.json` and `npm-shrinkwrap.clean.json`. 7. commit changes to these three files and you are done
npm-shrinkwrap.readme.md
0
https://github.com/angular/angular/commit/98cef76931f1417c21bfaf8cbbdb3768a4b85fb5
[ 0.00017534184735268354, 0.00016735024109948426, 0.00016353953105863184, 0.00016619605594314635, 0.000003904336608684389 ]
{ "id": 1, "code_window": [ " try {\n", " let containerEl = getInertElement();\n", " // Make sure unsafeHtml is actually a string (TypeScript types are not enforced at runtime).\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " const containerEl = getInertElement();\n" ], "file_path": "modules/@angular/platform-browser/src/security/html_sanitizer.ts", "type": "replace", "edit_start_line_idx": 235 }
import 'rxjs/add/operator/map'; import {Location} from '@angular/common'; import {SpyLocation} from '@angular/common/testing'; import {ComponentFixture, TestComponentBuilder} from '@angular/compiler/testing'; import {Component, Injector} from '@angular/core'; import {ComponentResolver} from '@angular/core'; import {beforeEach, beforeEachProviders, ddescribe, describe, expect, fakeAsync, iit, inject, it, tick, xdescribe, xit} from '@angular/core/testing'; import {Observable} from 'rxjs/Observable'; import {of } from 'rxjs/observable/of'; import {ActivatedRoute, ActivatedRouteSnapshot, CanActivate, CanDeactivate, DefaultUrlSerializer, Event, NavigationCancel, NavigationEnd, NavigationError, NavigationStart, Params, ROUTER_DIRECTIVES, Router, RouterConfig, RouterOutletMap, RouterStateSnapshot, RoutesRecognized, UrlSerializer} from '../index'; describe('Integration', () => { beforeEachProviders(() => { let config: RouterConfig = [{path: '', component: BlankCmp}, {path: 'simple', component: SimpleCmp}]; return [ RouterOutletMap, {provide: UrlSerializer, useClass: DefaultUrlSerializer}, {provide: Location, useClass: SpyLocation}, { provide: Router, useFactory: (resolver: ComponentResolver, urlSerializer: UrlSerializer, outletMap: RouterOutletMap, location: Location, injector: Injector) => { const r = new Router(RootCmp, resolver, urlSerializer, outletMap, location, injector, config); r.initialNavigation(); return r; }, deps: [ComponentResolver, UrlSerializer, RouterOutletMap, Location, Injector] }, {provide: ActivatedRoute, useFactory: (r: Router) => r.routerState.root, deps: [Router]}, ]; }); it('should navigate with a provided config', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.navigateByUrl('/simple'); advance(fixture); expect(location.path()).toEqual('/simple'); }))); it('should update location when navigating', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{path: 'team/:id', component: TeamCmp}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); router.navigateByUrl('/team/33'); advance(fixture); expect(location.path()).toEqual('/team/33'); }))); it('should navigate back and forward', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: 'simple', component: SimpleCmp}, {path: 'user/:name', component: UserCmp} ] }]); router.navigateByUrl('/team/33/simple'); advance(fixture); expect(location.path()).toEqual('/team/33/simple'); router.navigateByUrl('/team/22/user/victor'); advance(fixture); location.back(); advance(fixture); expect(location.path()).toEqual('/team/33/simple'); location.forward(); advance(fixture); expect(location.path()).toEqual('/team/22/user/victor'); }))); it('should navigate when locations changes', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [{path: 'user/:name', component: UserCmp}] }]); router.navigateByUrl('/team/22/user/victor'); advance(fixture); (<any>location).simulateHashChange('/team/22/user/fedor'); advance(fixture); expect(fixture.debugElement.nativeElement).toHaveText('team 22 { user fedor, right: }'); }))); it('should update the location when the matched route does not change', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{path: '**', component: SimpleCmp}]); router.navigateByUrl('/one/two'); advance(fixture); expect(location.path()).toEqual('/one/two'); expect(fixture.debugElement.nativeElement).toHaveText('simple'); router.navigateByUrl('/three/four'); advance(fixture); expect(location.path()).toEqual('/three/four'); expect(fixture.debugElement.nativeElement).toHaveText('simple'); }))); it('should support secondary routes', fakeAsync( inject([Router, TestComponentBuilder], (router: Router, tcb: TestComponentBuilder) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: 'user/:name', component: UserCmp}, {path: 'simple', component: SimpleCmp, outlet: 'right'} ] }]); router.navigateByUrl('/team/22/(user/victor//right:simple)'); advance(fixture); expect(fixture.debugElement.nativeElement) .toHaveText('team 22 { user victor, right: simple }'); }))); it('should deactivate outlets', fakeAsync( inject([Router, TestComponentBuilder], (router: Router, tcb: TestComponentBuilder) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: 'user/:name', component: UserCmp}, {path: 'simple', component: SimpleCmp, outlet: 'right'} ] }]); router.navigateByUrl('/team/22/(user/victor//right:simple)'); advance(fixture); router.navigateByUrl('/team/22/user/victor'); advance(fixture); expect(fixture.debugElement.nativeElement) .toHaveText('team 22 { user victor, right: }'); }))); it('should deactivate nested outlets', fakeAsync( inject([Router, TestComponentBuilder], (router: Router, tcb: TestComponentBuilder) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ {path: 'user/:name', component: UserCmp}, {path: 'simple', component: SimpleCmp, outlet: 'right'} ] }, {path: '', component: BlankCmp} ]); router.navigateByUrl('/team/22/(user/victor//right:simple)'); advance(fixture); router.navigateByUrl('/'); advance(fixture); expect(fixture.debugElement.nativeElement).toHaveText(''); }))); it('should set query params and fragment', fakeAsync( inject([Router, TestComponentBuilder], (router: Router, tcb: TestComponentBuilder) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{path: 'query', component: QueryParamsAndFragmentCmp}]); router.navigateByUrl('/query?name=1#fragment1'); advance(fixture); expect(fixture.debugElement.nativeElement).toHaveText('query: 1 fragment: fragment1'); router.navigateByUrl('/query?name=2#fragment2'); advance(fixture); expect(fixture.debugElement.nativeElement).toHaveText('query: 2 fragment: fragment2'); }))); it('should push params only when they change', fakeAsync( inject([Router, TestComponentBuilder], (router: Router, tcb: TestComponentBuilder) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [{path: 'user/:name', component: UserCmp}] }]); router.navigateByUrl('/team/22/user/victor'); advance(fixture); const team = fixture.debugElement.children[1].componentInstance; const user = fixture.debugElement.children[1].children[1].componentInstance; expect(team.recordedParams).toEqual([{id: '22'}]); expect(user.recordedParams).toEqual([{name: 'victor'}]); router.navigateByUrl('/team/22/user/fedor'); advance(fixture); expect(team.recordedParams).toEqual([{id: '22'}]); expect(user.recordedParams).toEqual([{name: 'victor'}, {name: 'fedor'}]); }))); it('should work when navigating to /', fakeAsync( inject([Router, TestComponentBuilder], (router: Router, tcb: TestComponentBuilder) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([ {path: '', terminal: true, component: SimpleCmp}, {path: 'user/:name', component: UserCmp} ]); router.navigateByUrl('/user/victor'); advance(fixture); expect(fixture.debugElement.nativeElement).toHaveText('user victor'); router.navigateByUrl('/'); advance(fixture); expect(fixture.debugElement.nativeElement).toHaveText('simple'); }))); it('should cancel in-flight navigations', fakeAsync( inject([Router, TestComponentBuilder], (router: Router, tcb: TestComponentBuilder) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{path: 'user/:name', component: UserCmp}]); const recordedEvents: any = []; router.events.forEach(e => recordedEvents.push(e)); router.navigateByUrl('/user/init'); advance(fixture); const user = fixture.debugElement.children[1].componentInstance; let r1: any, r2: any; router.navigateByUrl('/user/victor').then(_ => r1 = _); router.navigateByUrl('/user/fedor').then(_ => r2 = _); advance(fixture); expect(r1).toEqual(false); // returns false because it was canceled expect(r2).toEqual(true); // returns true because it was successful expect(fixture.debugElement.nativeElement).toHaveText('user fedor'); expect(user.recordedParams).toEqual([{name: 'init'}, {name: 'fedor'}]); expectEvents(recordedEvents, [ [NavigationStart, '/user/init'], [RoutesRecognized, '/user/init'], [NavigationEnd, '/user/init'], [NavigationStart, '/user/victor'], [NavigationStart, '/user/fedor'], [NavigationCancel, '/user/victor'], [RoutesRecognized, '/user/fedor'], [NavigationEnd, '/user/fedor'] ]); }))); it('should handle failed navigations gracefully', fakeAsync( inject([Router, TestComponentBuilder], (router: Router, tcb: TestComponentBuilder) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{path: 'user/:name', component: UserCmp}]); const recordedEvents: any = []; router.events.forEach(e => recordedEvents.push(e)); let e: any; router.navigateByUrl('/invalid').catch(_ => e = _); advance(fixture); expect(e.message).toContain('Cannot match any routes'); router.navigateByUrl('/user/fedor'); advance(fixture); expect(fixture.debugElement.nativeElement).toHaveText('user fedor'); expectEvents(recordedEvents, [ [NavigationStart, '/invalid'], [NavigationError, '/invalid'], [NavigationStart, '/user/fedor'], [RoutesRecognized, '/user/fedor'], [NavigationEnd, '/user/fedor'] ]); }))); it('should replace state when path is equal to current path', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: 'simple', component: SimpleCmp}, {path: 'user/:name', component: UserCmp} ] }]); router.navigateByUrl('/team/33/simple'); advance(fixture); router.navigateByUrl('/team/22/user/victor'); advance(fixture); router.navigateByUrl('/team/22/user/victor'); advance(fixture); location.back(); advance(fixture); expect(location.path()).toEqual('/team/33/simple'); }))); it('should handle componentless paths', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmpWithTwoOutlets); advance(fixture); router.resetConfig([ { path: 'parent/:id', children: [ {path: 'simple', component: SimpleCmp}, {path: 'user/:name', component: UserCmp, outlet: 'right'} ] }, {path: 'user/:name', component: UserCmp} ]); // navigate to a componentless route router.navigateByUrl('/parent/11/(simple//right:user/victor)'); advance(fixture); expect(location.path()).toEqual('/parent/11/(simple//right:user/victor)'); expect(fixture.debugElement.nativeElement) .toHaveText('primary {simple} right {user victor}'); // navigate to the same route with different params (reuse) router.navigateByUrl('/parent/22/(simple//right:user/fedor)'); advance(fixture); expect(location.path()).toEqual('/parent/22/(simple//right:user/fedor)'); expect(fixture.debugElement.nativeElement) .toHaveText('primary {simple} right {user fedor}'); // navigate to a normal route (check deactivation) router.navigateByUrl('/user/victor'); advance(fixture); expect(location.path()).toEqual('/user/victor'); expect(fixture.debugElement.nativeElement).toHaveText('primary {user victor} right {}'); // navigate back to a componentless route router.navigateByUrl('/parent/11/(simple//right:user/victor)'); advance(fixture); expect(location.path()).toEqual('/parent/11/(simple//right:user/victor)'); expect(fixture.debugElement.nativeElement) .toHaveText('primary {simple} right {user victor}'); }))); describe('router links', () => { it('should support string router links', fakeAsync( inject([Router, TestComponentBuilder], (router: Router, tcb: TestComponentBuilder) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: 'link', component: StringLinkCmp}, {path: 'simple', component: SimpleCmp} ] }]); router.navigateByUrl('/team/22/link'); advance(fixture); expect(fixture.debugElement.nativeElement).toHaveText('team 22 { link, right: }'); const native = fixture.debugElement.nativeElement.querySelector('a'); expect(native.getAttribute('href')).toEqual('/team/33/simple'); native.click(); advance(fixture); expect(fixture.debugElement.nativeElement).toHaveText('team 33 { simple, right: }'); }))); it('should support absolute router links', fakeAsync( inject([Router, TestComponentBuilder], (router: Router, tcb: TestComponentBuilder) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: 'link', component: AbsoluteLinkCmp}, {path: 'simple', component: SimpleCmp} ] }]); router.navigateByUrl('/team/22/link'); advance(fixture); expect(fixture.debugElement.nativeElement).toHaveText('team 22 { link, right: }'); const native = fixture.debugElement.nativeElement.querySelector('a'); expect(native.getAttribute('href')).toEqual('/team/33/simple'); native.click(); advance(fixture); expect(fixture.debugElement.nativeElement).toHaveText('team 33 { simple, right: }'); }))); it('should support relative router links', fakeAsync( inject([Router, TestComponentBuilder], (router: Router, tcb: TestComponentBuilder) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: 'link', component: RelativeLinkCmp}, {path: 'simple', component: SimpleCmp} ] }]); router.navigateByUrl('/team/22/link'); advance(fixture); expect(fixture.debugElement.nativeElement).toHaveText('team 22 { link, right: }'); const native = fixture.debugElement.nativeElement.querySelector('a'); expect(native.getAttribute('href')).toEqual('/team/22/simple'); native.click(); advance(fixture); expect(fixture.debugElement.nativeElement).toHaveText('team 22 { simple, right: }'); }))); it('should support top-level link', fakeAsync( inject([Router, TestComponentBuilder], (router: Router, tcb: TestComponentBuilder) => { let fixture = tcb.createFakeAsync(AbsoluteLinkCmp); advance(fixture); expect(fixture.debugElement.nativeElement).toHaveText('link'); }))); it('should support query params and fragments', fakeAsync(inject( [Router, Location, TestComponentBuilder], (router: Router, location: Location, tcb: TestComponentBuilder) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: 'link', component: LinkWithQueryParamsAndFragment}, {path: 'simple', component: SimpleCmp} ] }]); router.navigateByUrl('/team/22/link'); advance(fixture); const native = fixture.debugElement.nativeElement.querySelector('a'); expect(native.getAttribute('href')).toEqual('/team/22/simple?q=1#f'); native.click(); advance(fixture); expect(fixture.debugElement.nativeElement).toHaveText('team 22 { simple, right: }'); expect(location.path()).toEqual('/team/22/simple?q=1#f'); }))); }); describe('redirects', () => { it('should work', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([ {path: 'old/team/:id', redirectTo: 'team/:id'}, {path: 'team/:id', component: TeamCmp} ]); router.navigateByUrl('old/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); }))); }); describe('guards', () => { describe('CanActivate', () => { describe('should not activate a route when CanActivate returns false', () => { beforeEachProviders(() => [{provide: 'alwaysFalse', useValue: (a: any, b: any) => false}]); it('works', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig( [{path: 'team/:id', component: TeamCmp, canActivate: ['alwaysFalse']}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/'); }))); }); describe( 'should not activate a route when CanActivate returns false (componentless route)', () => { beforeEachProviders( () => [{provide: 'alwaysFalse', useValue: (a: any, b: any) => false}]); it('works', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{ path: 'parent', canActivate: ['alwaysFalse'], children: [{path: 'team/:id', component: TeamCmp}] }]); router.navigateByUrl('parent/team/22'); advance(fixture); expect(location.path()).toEqual('/'); }))); }); describe('should activate a route when CanActivate returns true', () => { beforeEachProviders(() => [{ provide: 'alwaysTrue', useValue: (a: ActivatedRouteSnapshot, s: RouterStateSnapshot) => true }]); it('works', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig( [{path: 'team/:id', component: TeamCmp, canActivate: ['alwaysTrue']}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); }))); }); describe('should work when given a class', () => { class AlwaysTrue implements CanActivate { canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { return true; } } beforeEachProviders(() => [AlwaysTrue]); it('works', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig( [{path: 'team/:id', component: TeamCmp, canActivate: [AlwaysTrue]}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); }))); }); describe('should work when returns an observable', () => { beforeEachProviders(() => [{ provide: 'CanActivate', useValue: (a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { return of (false); } }]); it('works', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig( [{path: 'team/:id', component: TeamCmp, canActivate: ['CanActivate']}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/'); }))); }); }); describe('CanDeactivate', () => { describe('should not deactivate a route when CanDeactivate returns false', () => { beforeEachProviders( () => [{ provide: 'CanDeactivateParent', useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { return a.params['id'] === '22'; } }, { provide: 'CanDeactivateTeam', useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { return c.route.snapshot.params['id'] === '22'; } }, { provide: 'CanDeactivateUser', useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { return a.params['name'] === 'victor'; } }]); it('works', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([ {path: 'team/:id', component: TeamCmp, canDeactivate: ['CanDeactivateTeam']} ]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); router.navigateByUrl('/team/33'); advance(fixture); expect(location.path()).toEqual('/team/33'); router.navigateByUrl('/team/44'); advance(fixture); expect(location.path()).toEqual('/team/33'); }))); it('works (componentless route)', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{ path: 'parent/:id', canDeactivate: ['CanDeactivateParent'], children: [{path: 'simple', component: SimpleCmp}] }]); router.navigateByUrl('/parent/22/simple'); advance(fixture); expect(location.path()).toEqual('/parent/22/simple'); router.navigateByUrl('/parent/33/simple'); advance(fixture); expect(location.path()).toEqual('/parent/33/simple'); router.navigateByUrl('/parent/44/simple'); advance(fixture); expect(location.path()).toEqual('/parent/33/simple'); }))); it('works with a nested route', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: '', terminal: true, component: SimpleCmp}, { path: 'user/:name', component: UserCmp, canDeactivate: ['CanDeactivateUser'] } ] }]); router.navigateByUrl('/team/22/user/victor'); advance(fixture); // this works because we can deactivate victor router.navigateByUrl('/team/33'); advance(fixture); expect(location.path()).toEqual('/team/33'); router.navigateByUrl('/team/33/user/fedor'); advance(fixture); // this doesn't work cause we cannot deactivate fedor router.navigateByUrl('/team/44'); advance(fixture); expect(location.path()).toEqual('/team/33/user/fedor'); }))); }); describe('should work when given a class', () => { class AlwaysTrue implements CanDeactivate<TeamCmp> { canDeactivate( component: TeamCmp, route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { return true; } } beforeEachProviders(() => [AlwaysTrue]); it('works', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig( [{path: 'team/:id', component: TeamCmp, canDeactivate: [AlwaysTrue]}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); router.navigateByUrl('/team/33'); advance(fixture); expect(location.path()).toEqual('/team/33'); }))); }); }); describe('should work when returns an observable', () => { beforeEachProviders(() => [{ provide: 'CanDeactivate', useValue: (c: TeamCmp, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { return of (false); } }]); it('works', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig( [{path: 'team/:id', component: TeamCmp, canDeactivate: ['CanDeactivate']}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); router.navigateByUrl('/team/33'); advance(fixture); expect(location.path()).toEqual('/team/22'); }))); }); }); describe('routerActiveLink', () => { it('should set the class when the link is active (exact = true)', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [{ path: 'link', component: DummyLinkCmp, children: [{path: 'simple', component: SimpleCmp}, {path: '', component: BlankCmp}] }] }]); router.navigateByUrl('/team/22/link'); advance(fixture); expect(location.path()).toEqual('/team/22/link'); const native = fixture.debugElement.nativeElement.querySelector('a'); expect(native.className).toEqual('active'); router.navigateByUrl('/team/22/link/simple'); advance(fixture); expect(location.path()).toEqual('/team/22/link/simple'); expect(native.className).toEqual(''); }))); it('should set the class on a parent element when the link is active (exact = true)', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [{ path: 'link', component: DummyLinkWithParentCmp, children: [{path: 'simple', component: SimpleCmp}, {path: '', component: BlankCmp}] }] }]); router.navigateByUrl('/team/22/link'); advance(fixture); expect(location.path()).toEqual('/team/22/link'); const native = fixture.debugElement.nativeElement.querySelector('link-parent'); expect(native.className).toEqual('active'); router.navigateByUrl('/team/22/link/simple'); advance(fixture); expect(location.path()).toEqual('/team/22/link/simple'); expect(native.className).toEqual(''); }))); it('should set the class when the link is active (exact = false)', fakeAsync(inject( [Router, TestComponentBuilder, Location], (router: Router, tcb: TestComponentBuilder, location: Location) => { const fixture = tcb.createFakeAsync(RootCmp); advance(fixture); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [{ path: 'link', component: DummyLinkCmp, children: [{path: 'simple', component: SimpleCmp}, {path: '', component: BlankCmp}] }] }]); router.navigateByUrl('/team/22/link;exact=false'); advance(fixture); expect(location.path()).toEqual('/team/22/link;exact=false'); const native = fixture.debugElement.nativeElement.querySelector('a'); expect(native.className).toEqual('active'); router.navigateByUrl('/team/22/link/simple'); advance(fixture); expect(location.path()).toEqual('/team/22/link/simple'); expect(native.className).toEqual('active'); }))); }); }); function expectEvents(events: Event[], pairs: any[]) { for (let i = 0; i < events.length; ++i) { expect((<any>events[i].constructor).name).toBe(pairs[i][0].name); expect((<any>events[i]).url).toBe(pairs[i][1]); } } @Component({ selector: 'link-cmp', template: `<a routerLink="/team/33/simple">link</a>`, directives: ROUTER_DIRECTIVES }) class StringLinkCmp { } @Component({ selector: 'link-cmp', template: `<router-outlet></router-outlet><a [routerLink]="['/team/33/simple']">link</a>`, directives: ROUTER_DIRECTIVES }) class AbsoluteLinkCmp { } @Component({ selector: 'link-cmp', template: `<router-outlet></router-outlet><a routerLinkActive="active" [routerLinkActiveOptions]="{exact: exact}" [routerLink]="['./']">link</a>`, directives: ROUTER_DIRECTIVES }) class DummyLinkCmp { private exact: boolean; constructor(route: ActivatedRoute) { // convert 'false' into false this.exact = (<any>route.snapshot.params).exact !== 'false'; } } @Component({ selector: 'link-cmp', template: `<router-outlet></router-outlet><link-parent routerLinkActive="active"><a [routerLink]="['./']">link</a></link-parent>`, directives: ROUTER_DIRECTIVES }) class DummyLinkWithParentCmp { } @Component({ selector: 'link-cmp', template: `<a [routerLink]="['../simple']">link</a>`, directives: ROUTER_DIRECTIVES }) class RelativeLinkCmp { } @Component({ selector: 'link-cmp', template: `<a [routerLink]="['../simple']" [queryParams]="{q: '1'}" fragment="f">link</a>`, directives: ROUTER_DIRECTIVES }) class LinkWithQueryParamsAndFragment { } @Component({selector: 'simple-cmp', template: `simple`, directives: ROUTER_DIRECTIVES}) class SimpleCmp { } @Component({selector: 'blank-cmp', template: ``, directives: ROUTER_DIRECTIVES}) class BlankCmp { } @Component({ selector: 'team-cmp', template: `team {{id | async}} { <router-outlet></router-outlet>, right: <router-outlet name="right"></router-outlet> }`, directives: ROUTER_DIRECTIVES }) class TeamCmp { id: Observable<string>; recordedParams: Params[] = []; constructor(public route: ActivatedRoute) { this.id = route.params.map(p => p['id']); route.params.forEach(_ => this.recordedParams.push(_)); } } @Component( {selector: 'user-cmp', template: `user {{name | async}}`, directives: [ROUTER_DIRECTIVES]}) class UserCmp { name: Observable<string>; recordedParams: Params[] = []; constructor(route: ActivatedRoute) { this.name = route.params.map(p => p['name']); route.params.forEach(_ => this.recordedParams.push(_)); } } @Component({ selector: 'query-cmp', template: `query: {{name | async}} fragment: {{fragment | async}}`, directives: [ROUTER_DIRECTIVES] }) class QueryParamsAndFragmentCmp { name: Observable<string>; fragment: Observable<string>; constructor(router: Router) { this.name = router.routerState.queryParams.map(p => p['name']); this.fragment = router.routerState.fragment; } } @Component({ selector: 'root-cmp', template: `<router-outlet></router-outlet>`, directives: [ROUTER_DIRECTIVES] }) class RootCmp { } @Component({ selector: 'root-cmp', template: `primary {<router-outlet></router-outlet>} right {<router-outlet name="right"></router-outlet>}`, directives: [ROUTER_DIRECTIVES] }) class RootCmpWithTwoOutlets { } function advance(fixture: ComponentFixture<any>): void { tick(); fixture.detectChanges(); }
modules/@angular/router/test/router.spec.ts
0
https://github.com/angular/angular/commit/98cef76931f1417c21bfaf8cbbdb3768a4b85fb5
[ 0.0005275527946650982, 0.000174066168256104, 0.0001641647977521643, 0.00016982915985863656, 0.0000359913356078323 ]
{ "id": 2, "code_window": [ " // Make sure unsafeHtml is actually a string (TypeScript types are not enforced at runtime).\n", " unsafeHtml = unsafeHtml ? String(unsafeHtml) : '';\n", "\n", " // mXSS protection. Repeatedly parse the document to make sure it stabilizes, so that a browser\n", " // trying to auto-correct incorrect HTML cannot cause formerly inert HTML to become dangerous.\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " let unsafeHtml = unsafeHtmlInput ? String(unsafeHtmlInput) : '';\n" ], "file_path": "modules/@angular/platform-browser/src/security/html_sanitizer.ts", "type": "replace", "edit_start_line_idx": 237 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as t from '@angular/core/testing/testing_internal'; import {browserDetection} from '@angular/platform-browser/testing'; import {getDOM} from '../../src/dom/dom_adapter'; import {sanitizeHtml} from '../../src/security/html_sanitizer'; export function main() { t.describe('HTML sanitizer', () => { let originalLog: (msg: any) => any = null; let logMsgs: string[]; t.beforeEach(() => { logMsgs = []; originalLog = getDOM().log; // Monkey patch DOM.log. getDOM().log = (msg) => logMsgs.push(msg); }); t.afterEach(() => { getDOM().log = originalLog; }); t.it('serializes nested structures', () => { t.expect(sanitizeHtml('<div alt="x"><p>a</p>b<b>c<a alt="more">d</a></b>e</div>')) .toEqual('<div alt="x"><p>a</p>b<b>c<a alt="more">d</a></b>e</div>'); t.expect(logMsgs).toEqual([]); }); t.it('serializes self closing elements', () => { t.expect(sanitizeHtml('<p>Hello <br> World</p>')).toEqual('<p>Hello <br> World</p>'); }); t.it('supports namespaced elements', () => { t.expect(sanitizeHtml('a<my:hr/><my:div>b</my:div>c')).toEqual('abc'); }); t.it('supports namespaced attributes', () => { t.expect(sanitizeHtml('<a xlink:href="something">t</a>')) .toEqual('<a xlink:href="something">t</a>'); t.expect(sanitizeHtml('<a xlink:evil="something">t</a>')).toEqual('<a>t</a>'); t.expect(sanitizeHtml('<a xlink:href="javascript:foo()">t</a>')) .toEqual('<a xlink:href="unsafe:javascript:foo()">t</a>'); }); t.it('supports sanitizing plain text', () => { t.expect(sanitizeHtml('Hello, World')).toEqual('Hello, World'); }); t.it('ignores non-element, non-attribute nodes', () => { t.expect(sanitizeHtml('<!-- comments? -->no.')).toEqual('no.'); t.expect(sanitizeHtml('<?pi nodes?>no.')).toEqual('no.'); t.expect(logMsgs.join('\n')).toMatch(/sanitizing HTML stripped some content/); }); t.it('escapes entities', () => { t.expect(sanitizeHtml('<p>Hello &lt; World</p>')).toEqual('<p>Hello &lt; World</p>'); t.expect(sanitizeHtml('<p>Hello < World</p>')).toEqual('<p>Hello &lt; World</p>'); t.expect(sanitizeHtml('<p alt="% &amp; &quot; !">Hello</p>')) .toEqual('<p alt="% &amp; &#34; !">Hello</p>'); // NB: quote encoded as ASCII &#34;. }); t.describe('should strip dangerous elements', () => { let dangerousTags = [ 'frameset', 'form', 'param', 'object', 'embed', 'textarea', 'input', 'button', 'option', 'select', 'script', 'style', 'link', 'base', 'basefont' ]; for (let tag of dangerousTags) { t.it( `${tag}`, () => { t.expect(sanitizeHtml(`<${tag}>evil!</${tag}>`)).toEqual('evil!'); }); } t.it(`swallows frame entirely`, () => { t.expect(sanitizeHtml(`<frame>evil!</frame>`)).not.toContain('<frame>'); }); }); t.describe('should strip dangerous attributes', () => { let dangerousAttrs = ['id', 'name', 'style']; for (let attr of dangerousAttrs) { t.it(`${attr}`, () => { t.expect(sanitizeHtml(`<a ${attr}="x">evil!</a>`)).toEqual('<a>evil!</a>'); }); } }); if (browserDetection.isWebkit) { t.it('should prevent mXSS attacks', function() { t.expect(sanitizeHtml('<a href="&#x3000;javascript:alert(1)">CLICKME</a>')) .toEqual('<a href="unsafe:javascript:alert(1)">CLICKME</a>'); }); } }); }
modules/@angular/platform-browser/test/security/html_sanitizer_spec.ts
1
https://github.com/angular/angular/commit/98cef76931f1417c21bfaf8cbbdb3768a4b85fb5
[ 0.00037254710332490504, 0.0001992219767998904, 0.00016787700587883592, 0.00017147447215393186, 0.0000615707685938105 ]
{ "id": 2, "code_window": [ " // Make sure unsafeHtml is actually a string (TypeScript types are not enforced at runtime).\n", " unsafeHtml = unsafeHtml ? String(unsafeHtml) : '';\n", "\n", " // mXSS protection. Repeatedly parse the document to make sure it stabilizes, so that a browser\n", " // trying to auto-correct incorrect HTML cannot cause formerly inert HTML to become dangerous.\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " let unsafeHtml = unsafeHtmlInput ? String(unsafeHtmlInput) : '';\n" ], "file_path": "modules/@angular/platform-browser/src/security/html_sanitizer.ts", "type": "replace", "edit_start_line_idx": 237 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {verifyNoBrowserErrors} from '@angular/platform-browser/testing_e2e'; describe('WebWorkers Todo', function() { afterEach(() => { verifyNoBrowserErrors(); browser.ignoreSynchronization = false; }); var URL = 'all/playground/src/web_workers/todo/index.html'; it('should bootstrap', () => { // This test can't wait for Angular 2 as Testability is not available when using WebWorker browser.ignoreSynchronization = true; browser.get(URL); waitForBootstrap(); expect(element(by.css("#todoapp header")).getText()).toEqual("todos"); }); }); function waitForBootstrap(): void { browser.wait(protractor.until.elementLocated(by.css("todo-app #todoapp")), 15000); }
modules/playground/e2e_test/web_workers/todo/todo_spec.ts
0
https://github.com/angular/angular/commit/98cef76931f1417c21bfaf8cbbdb3768a4b85fb5
[ 0.0003102086193393916, 0.0002035334473475814, 0.00016493767907377332, 0.00016949372366070747, 0.0000616412507952191 ]
{ "id": 2, "code_window": [ " // Make sure unsafeHtml is actually a string (TypeScript types are not enforced at runtime).\n", " unsafeHtml = unsafeHtml ? String(unsafeHtml) : '';\n", "\n", " // mXSS protection. Repeatedly parse the document to make sure it stabilizes, so that a browser\n", " // trying to auto-correct incorrect HTML cannot cause formerly inert HTML to become dangerous.\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " let unsafeHtml = unsafeHtmlInput ? String(unsafeHtmlInput) : '';\n" ], "file_path": "modules/@angular/platform-browser/src/security/html_sanitizer.ts", "type": "replace", "edit_start_line_idx": 237 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {SelectorMatcher} from '@angular/compiler/src/selector'; import {CssSelector} from '@angular/compiler/src/selector'; import {beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {el} from '@angular/platform-browser/testing'; export function main() { describe('SelectorMatcher', () => { var matcher: any /** TODO #9100 */, selectableCollector: any /** TODO #9100 */, s1: any /** TODO #9100 */, s2: any /** TODO #9100 */, s3: any /** TODO #9100 */, s4: any /** TODO #9100 */; var matched: any[]; function reset() { matched = []; } beforeEach(() => { reset(); s1 = s2 = s3 = s4 = null; selectableCollector = (selector: any /** TODO #9100 */, context: any /** TODO #9100 */) => { matched.push(selector); matched.push(context); }; matcher = new SelectorMatcher(); }); it('should select by element name case sensitive', () => { matcher.addSelectables(s1 = CssSelector.parse('someTag'), 1); expect(matcher.match(CssSelector.parse('SOMEOTHERTAG')[0], selectableCollector)) .toEqual(false); expect(matched).toEqual([]); expect(matcher.match(CssSelector.parse('SOMETAG')[0], selectableCollector)).toEqual(false); expect(matched).toEqual([]); expect(matcher.match(CssSelector.parse('someTag')[0], selectableCollector)).toEqual(true); expect(matched).toEqual([s1[0], 1]); }); it('should select by class name case insensitive', () => { matcher.addSelectables(s1 = CssSelector.parse('.someClass'), 1); matcher.addSelectables(s2 = CssSelector.parse('.someClass.class2'), 2); expect(matcher.match(CssSelector.parse('.SOMEOTHERCLASS')[0], selectableCollector)) .toEqual(false); expect(matched).toEqual([]); expect(matcher.match(CssSelector.parse('.SOMECLASS')[0], selectableCollector)).toEqual(true); expect(matched).toEqual([s1[0], 1]); reset(); expect(matcher.match(CssSelector.parse('.someClass.class2')[0], selectableCollector)) .toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2]); }); it('should select by attr name case sensitive independent of the value', () => { matcher.addSelectables(s1 = CssSelector.parse('[someAttr]'), 1); matcher.addSelectables(s2 = CssSelector.parse('[someAttr][someAttr2]'), 2); expect(matcher.match(CssSelector.parse('[SOMEOTHERATTR]')[0], selectableCollector)) .toEqual(false); expect(matched).toEqual([]); expect(matcher.match(CssSelector.parse('[SOMEATTR]')[0], selectableCollector)).toEqual(false); expect(matched).toEqual([]); expect(matcher.match(CssSelector.parse('[SOMEATTR=someValue]')[0], selectableCollector)) .toEqual(false); expect(matched).toEqual([]); expect(matcher.match(CssSelector.parse('[someAttr][someAttr2]')[0], selectableCollector)) .toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2]); reset(); expect(matcher.match( CssSelector.parse('[someAttr=someValue][someAttr2]')[0], selectableCollector)) .toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2]); reset(); expect(matcher.match( CssSelector.parse('[someAttr2][someAttr=someValue]')[0], selectableCollector)) .toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2]); reset(); expect(matcher.match( CssSelector.parse('[someAttr2=someValue][someAttr]')[0], selectableCollector)) .toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2]); }); it('should select by attr name only once if the value is from the DOM', () => { matcher.addSelectables(s1 = CssSelector.parse('[some-decor]'), 1); var elementSelector = new CssSelector(); var element = el('<div attr></div>'); var empty = getDOM().getAttribute(element, 'attr'); elementSelector.addAttribute('some-decor', empty); matcher.match(elementSelector, selectableCollector); expect(matched).toEqual([s1[0], 1]); }); it('should select by attr name case sensitive and value case insensitive', () => { matcher.addSelectables(s1 = CssSelector.parse('[someAttr=someValue]'), 1); expect(matcher.match(CssSelector.parse('[SOMEATTR=SOMEOTHERATTR]')[0], selectableCollector)) .toEqual(false); expect(matched).toEqual([]); expect(matcher.match(CssSelector.parse('[SOMEATTR=SOMEVALUE]')[0], selectableCollector)) .toEqual(false); expect(matched).toEqual([]); expect(matcher.match(CssSelector.parse('[someAttr=SOMEVALUE]')[0], selectableCollector)) .toEqual(true); expect(matched).toEqual([s1[0], 1]); }); it('should select by element name, class name and attribute name with value', () => { matcher.addSelectables(s1 = CssSelector.parse('someTag.someClass[someAttr=someValue]'), 1); expect(matcher.match( CssSelector.parse('someOtherTag.someOtherClass[someOtherAttr]')[0], selectableCollector)) .toEqual(false); expect(matched).toEqual([]); expect( matcher.match( CssSelector.parse('someTag.someOtherClass[someOtherAttr]')[0], selectableCollector)) .toEqual(false); expect(matched).toEqual([]); expect(matcher.match( CssSelector.parse('someTag.someClass[someOtherAttr]')[0], selectableCollector)) .toEqual(false); expect(matched).toEqual([]); expect( matcher.match(CssSelector.parse('someTag.someClass[someAttr]')[0], selectableCollector)) .toEqual(false); expect(matched).toEqual([]); expect( matcher.match( CssSelector.parse('someTag.someClass[someAttr=someValue]')[0], selectableCollector)) .toEqual(true); expect(matched).toEqual([s1[0], 1]); }); it('should select by many attributes and independent of the value', () => { matcher.addSelectables(s1 = CssSelector.parse('input[type=text][control]'), 1); var cssSelector = new CssSelector(); cssSelector.setElement('input'); cssSelector.addAttribute('type', 'text'); cssSelector.addAttribute('control', 'one'); expect(matcher.match(cssSelector, selectableCollector)).toEqual(true); expect(matched).toEqual([s1[0], 1]); }); it('should select independent of the order in the css selector', () => { matcher.addSelectables(s1 = CssSelector.parse('[someAttr].someClass'), 1); matcher.addSelectables(s2 = CssSelector.parse('.someClass[someAttr]'), 2); matcher.addSelectables(s3 = CssSelector.parse('.class1.class2'), 3); matcher.addSelectables(s4 = CssSelector.parse('.class2.class1'), 4); expect(matcher.match(CssSelector.parse('[someAttr].someClass')[0], selectableCollector)) .toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2]); reset(); expect(matcher.match(CssSelector.parse('.someClass[someAttr]')[0], selectableCollector)) .toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2]); reset(); expect(matcher.match(CssSelector.parse('.class1.class2')[0], selectableCollector)) .toEqual(true); expect(matched).toEqual([s3[0], 3, s4[0], 4]); reset(); expect(matcher.match(CssSelector.parse('.class2.class1')[0], selectableCollector)) .toEqual(true); expect(matched).toEqual([s4[0], 4, s3[0], 3]); }); it('should not select with a matching :not selector', () => { matcher.addSelectables(CssSelector.parse('p:not(.someClass)'), 1); matcher.addSelectables(CssSelector.parse('p:not([someAttr])'), 2); matcher.addSelectables(CssSelector.parse(':not(.someClass)'), 3); matcher.addSelectables(CssSelector.parse(':not(p)'), 4); matcher.addSelectables(CssSelector.parse(':not(p[someAttr])'), 5); expect(matcher.match(CssSelector.parse('p.someClass[someAttr]')[0], selectableCollector)) .toEqual(false); expect(matched).toEqual([]); }); it('should select with a non matching :not selector', () => { matcher.addSelectables(s1 = CssSelector.parse('p:not(.someClass)'), 1); matcher.addSelectables(s2 = CssSelector.parse('p:not(.someOtherClass[someAttr])'), 2); matcher.addSelectables(s3 = CssSelector.parse(':not(.someClass)'), 3); matcher.addSelectables(s4 = CssSelector.parse(':not(.someOtherClass[someAttr])'), 4); expect(matcher.match( CssSelector.parse('p[someOtherAttr].someOtherClass')[0], selectableCollector)) .toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2, s3[0], 3, s4[0], 4]); }); it('should match with multiple :not selectors', () => { matcher.addSelectables(s1 = CssSelector.parse('div:not([a]):not([b])'), 1); expect(matcher.match(CssSelector.parse('div[a]')[0], selectableCollector)).toBe(false); expect(matcher.match(CssSelector.parse('div[b]')[0], selectableCollector)).toBe(false); expect(matcher.match(CssSelector.parse('div[c]')[0], selectableCollector)).toBe(true); }); it('should select with one match in a list', () => { matcher.addSelectables(s1 = CssSelector.parse('input[type=text], textbox'), 1); expect(matcher.match(CssSelector.parse('textbox')[0], selectableCollector)).toEqual(true); expect(matched).toEqual([s1[1], 1]); reset(); expect(matcher.match(CssSelector.parse('input[type=text]')[0], selectableCollector)) .toEqual(true); expect(matched).toEqual([s1[0], 1]); }); it('should not select twice with two matches in a list', () => { matcher.addSelectables(s1 = CssSelector.parse('input, .someClass'), 1); expect(matcher.match(CssSelector.parse('input.someclass')[0], selectableCollector)) .toEqual(true); expect(matched.length).toEqual(2); expect(matched).toEqual([s1[0], 1]); }); }); describe('CssSelector.parse', () => { it('should detect element names', () => { var cssSelector = CssSelector.parse('sometag')[0]; expect(cssSelector.element).toEqual('sometag'); expect(cssSelector.toString()).toEqual('sometag'); }); it('should detect class names', () => { var cssSelector = CssSelector.parse('.someClass')[0]; expect(cssSelector.classNames).toEqual(['someclass']); expect(cssSelector.toString()).toEqual('.someclass'); }); it('should detect attr names', () => { var cssSelector = CssSelector.parse('[attrname]')[0]; expect(cssSelector.attrs).toEqual(['attrname', '']); expect(cssSelector.toString()).toEqual('[attrname]'); }); it('should detect attr values', () => { var cssSelector = CssSelector.parse('[attrname=attrvalue]')[0]; expect(cssSelector.attrs).toEqual(['attrname', 'attrvalue']); expect(cssSelector.toString()).toEqual('[attrname=attrvalue]'); }); it('should detect multiple parts', () => { var cssSelector = CssSelector.parse('sometag[attrname=attrvalue].someclass')[0]; expect(cssSelector.element).toEqual('sometag'); expect(cssSelector.attrs).toEqual(['attrname', 'attrvalue']); expect(cssSelector.classNames).toEqual(['someclass']); expect(cssSelector.toString()).toEqual('sometag.someclass[attrname=attrvalue]'); }); it('should detect multiple attributes', () => { var cssSelector = CssSelector.parse('input[type=text][control]')[0]; expect(cssSelector.element).toEqual('input'); expect(cssSelector.attrs).toEqual(['type', 'text', 'control', '']); expect(cssSelector.toString()).toEqual('input[type=text][control]'); }); it('should detect :not', () => { var cssSelector = CssSelector.parse('sometag:not([attrname=attrvalue].someclass)')[0]; expect(cssSelector.element).toEqual('sometag'); expect(cssSelector.attrs.length).toEqual(0); expect(cssSelector.classNames.length).toEqual(0); var notSelector = cssSelector.notSelectors[0]; expect(notSelector.element).toEqual(null); expect(notSelector.attrs).toEqual(['attrname', 'attrvalue']); expect(notSelector.classNames).toEqual(['someclass']); expect(cssSelector.toString()).toEqual('sometag:not(.someclass[attrname=attrvalue])'); }); it('should detect :not without truthy', () => { var cssSelector = CssSelector.parse(':not([attrname=attrvalue].someclass)')[0]; expect(cssSelector.element).toEqual('*'); var notSelector = cssSelector.notSelectors[0]; expect(notSelector.attrs).toEqual(['attrname', 'attrvalue']); expect(notSelector.classNames).toEqual(['someclass']); expect(cssSelector.toString()).toEqual('*:not(.someclass[attrname=attrvalue])'); }); it('should throw when nested :not', () => { expect(() => { CssSelector.parse('sometag:not(:not([attrname=attrvalue].someclass))')[0]; }).toThrowError('Nesting :not is not allowed in a selector'); }); it('should throw when multiple selectors in :not', () => { expect(() => { CssSelector.parse('sometag:not(a,b)'); }).toThrowError('Multiple selectors in :not are not supported'); }); it('should detect lists of selectors', () => { var cssSelectors = CssSelector.parse('.someclass,[attrname=attrvalue], sometag'); expect(cssSelectors.length).toEqual(3); expect(cssSelectors[0].classNames).toEqual(['someclass']); expect(cssSelectors[1].attrs).toEqual(['attrname', 'attrvalue']); expect(cssSelectors[2].element).toEqual('sometag'); }); it('should detect lists of selectors with :not', () => { var cssSelectors = CssSelector.parse('input[type=text], :not(textarea), textbox:not(.special)'); expect(cssSelectors.length).toEqual(3); expect(cssSelectors[0].element).toEqual('input'); expect(cssSelectors[0].attrs).toEqual(['type', 'text']); expect(cssSelectors[1].element).toEqual('*'); expect(cssSelectors[1].notSelectors[0].element).toEqual('textarea'); expect(cssSelectors[2].element).toEqual('textbox'); expect(cssSelectors[2].notSelectors[0].classNames).toEqual(['special']); }); }); describe('CssSelector.getMatchingElementTemplate', () => { it('should create an element with a tagName, classes, and attributes with the correct casing', () => { let selector = CssSelector.parse('Blink.neon.hotpink[Sweet][Dismissable=false]')[0]; let template = selector.getMatchingElementTemplate(); expect(template).toEqual('<Blink class="neon hotpink" Sweet Dismissable="false"></Blink>'); }); it('should create an element without a tag name', () => { let selector = CssSelector.parse('[fancy]')[0]; let template = selector.getMatchingElementTemplate(); expect(template).toEqual('<div fancy></div>'); }); it('should ignore :not selectors', () => { let selector = CssSelector.parse('grape:not(.red)')[0]; let template = selector.getMatchingElementTemplate(); expect(template).toEqual('<grape></grape>'); }); }); }
modules/@angular/compiler/test/selector_spec.ts
0
https://github.com/angular/angular/commit/98cef76931f1417c21bfaf8cbbdb3768a4b85fb5
[ 0.00017679434677120298, 0.00017211576050613075, 0.0001667195319896564, 0.0001719902065815404, 0.0000025141578134935116 ]
{ "id": 2, "code_window": [ " // Make sure unsafeHtml is actually a string (TypeScript types are not enforced at runtime).\n", " unsafeHtml = unsafeHtml ? String(unsafeHtml) : '';\n", "\n", " // mXSS protection. Repeatedly parse the document to make sure it stabilizes, so that a browser\n", " // trying to auto-correct incorrect HTML cannot cause formerly inert HTML to become dangerous.\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " let unsafeHtml = unsafeHtmlInput ? String(unsafeHtmlInput) : '';\n" ], "file_path": "modules/@angular/platform-browser/src/security/html_sanitizer.ts", "type": "replace", "edit_start_line_idx": 237 }
// Unique place to configure the browsers which are used in the different CI jobs in Sauce Labs (SL) and BrowserStack (BS). // If the target is set to null, then the browser is not run anywhere during CI. // If a category becomes empty (e.g. BS and required), then the corresponding job must be commented out in Travis configuration. var CIconfiguration = { 'Chrome': { unitTest: {target: 'SL', required: true}, e2e: {target: null, required: true}}, 'Firefox': { unitTest: {target: 'SL', required: true}, e2e: {target: null, required: true}}, // FirefoxBeta and ChromeBeta should be target:'BS' or target:'SL', and required:true // Currently deactivated due to https://github.com/angular/angular/issues/7560 'ChromeBeta': { unitTest: {target: null, required: true}, e2e: {target: null, required: false}}, 'FirefoxBeta': { unitTest: {target: null, required: false}, e2e: {target: null, required: false}}, 'ChromeDev': { unitTest: {target: null, required: true}, e2e: {target: null, required: true}}, 'FirefoxDev': { unitTest: {target: null, required: true}, e2e: {target: null, required: true}}, 'IE9': { unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}}, 'IE10': { unitTest: {target: 'SL', required: true}, e2e: {target: null, required: true}}, 'IE11': { unitTest: {target: 'SL', required: true}, e2e: {target: null, required: true}}, 'Edge': { unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}}, 'Android4.1': { unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}}, 'Android4.2': { unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}}, 'Android4.3': { unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}}, 'Android4.4': { unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}}, 'Android5': { unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}}, 'Safari7': { unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}}, 'Safari8': { unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}}, 'Safari9': { unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}}, 'iOS7': { unitTest: {target: 'BS', required: true}, e2e: {target: null, required: true}}, 'iOS8': { unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}}, 'iOS9': { unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}}, 'WindowsPhone': { unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}} }; var customLaunchers = { 'DartiumWithWebPlatform': { base: 'Dartium', flags: ['--enable-experimental-web-platform-features'] }, 'ChromeNoSandbox': { base: 'Chrome', flags: ['--no-sandbox'] }, 'SL_CHROME': { base: 'SauceLabs', browserName: 'chrome', version: '50' }, 'SL_CHROMEBETA': { base: 'SauceLabs', browserName: 'chrome', version: 'beta' }, 'SL_CHROMEDEV': { base: 'SauceLabs', browserName: 'chrome', version: 'dev' }, 'SL_FIREFOX': { base: 'SauceLabs', browserName: 'firefox', version: '45' }, 'SL_FIREFOXBETA': { base: 'SauceLabs', browserName: 'firefox', version: 'beta' }, 'SL_FIREFOXDEV': { base: 'SauceLabs', browserName: 'firefox', version: 'dev' }, 'SL_SAFARI7': { base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.9', version: '7' }, 'SL_SAFARI8': { base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.10', version: '8' }, 'SL_SAFARI9': { base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.11', version: '9.0' }, 'SL_IOS7': { base: 'SauceLabs', browserName: 'iphone', platform: 'OS X 10.10', version: '7.1' }, 'SL_IOS8': { base: 'SauceLabs', browserName: 'iphone', platform: 'OS X 10.10', version: '8.4' }, 'SL_IOS9': { base: 'SauceLabs', browserName: 'iphone', platform: 'OS X 10.10', version: '9.1' }, 'SL_IE9': { base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 2008', version: '9' }, 'SL_IE10': { base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 2012', version: '10' }, 'SL_IE11': { base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 8.1', version: '11' }, 'SL_EDGE': { base: 'SauceLabs', browserName: 'MicrosoftEdge', platform: 'Windows 10', version: '13.10586' }, 'SL_ANDROID4.1': { base: 'SauceLabs', browserName: 'android', platform: 'Linux', version: '4.1' }, 'SL_ANDROID4.2': { base: 'SauceLabs', browserName: 'android', platform: 'Linux', version: '4.2' }, 'SL_ANDROID4.3': { base: 'SauceLabs', browserName: 'android', platform: 'Linux', version: '4.3' }, 'SL_ANDROID4.4': { base: 'SauceLabs', browserName: 'android', platform: 'Linux', version: '4.4' }, 'SL_ANDROID5': { base: 'SauceLabs', browserName: 'android', platform: 'Linux', version: '5.1' }, 'BS_CHROME': { base: 'BrowserStack', browser: 'chrome', os: 'OS X', os_version: 'Yosemite' }, 'BS_FIREFOX': { base: 'BrowserStack', browser: 'firefox', os: 'Windows', os_version: '10' }, 'BS_SAFARI7': { base: 'BrowserStack', browser: 'safari', os: 'OS X', os_version: 'Mavericks' }, 'BS_SAFARI8': { base: 'BrowserStack', browser: 'safari', os: 'OS X', os_version: 'Yosemite' }, 'BS_SAFARI9': { base: 'BrowserStack', browser: 'safari', os: 'OS X', os_version: 'El Capitan' }, 'BS_IOS7': { base: 'BrowserStack', device: 'iPhone 5S', os: 'ios', os_version: '7.0' }, 'BS_IOS8': { base: 'BrowserStack', device: 'iPhone 6', os: 'ios', os_version: '8.3' }, 'BS_IOS9': { base: 'BrowserStack', device: 'iPhone 6S', os: 'ios', os_version: '9.0' }, 'BS_IE9': { base: 'BrowserStack', browser: 'ie', browser_version: '9.0', os: 'Windows', os_version: '7' }, 'BS_IE10': { base: 'BrowserStack', browser: 'ie', browser_version: '10.0', os: 'Windows', os_version: '8' }, 'BS_IE11': { base: 'BrowserStack', browser: 'ie', browser_version: '11.0', os: 'Windows', os_version: '10' }, 'BS_EDGE': { base: 'BrowserStack', browser: 'edge', os: 'Windows', os_version: '10' }, 'BS_WINDOWSPHONE' : { base: 'BrowserStack', device: 'Nokia Lumia 930', os: 'winphone', os_version: '8.1' }, 'BS_ANDROID5': { base: 'BrowserStack', device: 'Google Nexus 5', os: 'android', os_version: '5.0' }, 'BS_ANDROID4.4': { base: 'BrowserStack', device: 'HTC One M8', os: 'android', os_version: '4.4' }, 'BS_ANDROID4.3': { base: 'BrowserStack', device: 'Samsung Galaxy S4', os: 'android', os_version: '4.3' }, 'BS_ANDROID4.2': { base: 'BrowserStack', device: 'Google Nexus 4', os: 'android', os_version: '4.2' }, 'BS_ANDROID4.1': { base: 'BrowserStack', device: 'Google Nexus 7', os: 'android', os_version: '4.1' } }; var sauceAliases = { 'ALL': Object.keys(customLaunchers).filter(function(item) {return customLaunchers[item].base == 'SauceLabs';}), 'DESKTOP': ['SL_CHROME', 'SL_FIREFOX', 'SL_IE9', 'SL_IE10', 'SL_IE11', 'SL_EDGE', 'SL_SAFARI7', 'SL_SAFARI8', 'SL_SAFARI9'], 'MOBILE': ['SL_ANDROID4.1', 'SL_ANDROID4.2', 'SL_ANDROID4.3', 'SL_ANDROID4.4', 'SL_ANDROID5', 'SL_IOS7', 'SL_IOS8', 'SL_IOS9'], 'ANDROID': ['SL_ANDROID4.1', 'SL_ANDROID4.2', 'SL_ANDROID4.3', 'SL_ANDROID4.4', 'SL_ANDROID5'], 'IE': ['SL_IE9', 'SL_IE10', 'SL_IE11'], 'IOS': ['SL_IOS7', 'SL_IOS8', 'SL_IOS9'], 'SAFARI': ['SL_SAFARI7', 'SL_SAFARI8', 'SL_SAFARI9'], 'BETA': ['SL_CHROMEBETA', 'SL_FIREFOXBETA'], 'DEV': ['SL_CHROMEDEV', 'SL_FIREFOXDEV'], 'CI_REQUIRED': buildConfiguration('unitTest', 'SL', true), 'CI_OPTIONAL': buildConfiguration('unitTest', 'SL', false) }; var browserstackAliases = { 'ALL': Object.keys(customLaunchers).filter(function(item) {return customLaunchers[item].base == 'BrowserStack';}), 'DESKTOP': ['BS_CHROME', 'BS_FIREFOX', 'BS_IE9', 'BS_IE10', 'BS_IE11', 'BS_EDGE', 'BS_SAFARI7', 'BS_SAFARI8', 'BS_SAFARI9'], 'MOBILE': ['BS_ANDROID4.3', 'BS_ANDROID4.4', 'BS_IOS7', 'BS_IOS8', 'BS_IOS9', 'BS_WINDOWSPHONE'], 'ANDROID': ['BS_ANDROID4.3', 'BS_ANDROID4.4'], 'IE': ['BS_IE9', 'BS_IE10', 'BS_IE11'], 'IOS': ['BS_IOS7', 'BS_IOS8', 'BS_IOS9'], 'SAFARI': ['BS_SAFARI7', 'BS_SAFARI8', 'BS_SAFARI9'], 'CI_REQUIRED': buildConfiguration('unitTest', 'BS', true), 'CI_OPTIONAL': buildConfiguration('unitTest', 'BS', false) }; module.exports = { customLaunchers: customLaunchers, sauceAliases: sauceAliases, browserstackAliases: browserstackAliases }; function buildConfiguration(type, target, required) { return Object.keys(CIconfiguration) .filter((item) => { var conf = CIconfiguration[item][type]; return conf.required === required && conf.target === target; }) .map((item) => { return target + '_' + item.toUpperCase(); }); }
browser-providers.conf.js
0
https://github.com/angular/angular/commit/98cef76931f1417c21bfaf8cbbdb3768a4b85fb5
[ 0.00018817542877513915, 0.00017022888641804457, 0.00016523645899724215, 0.0001698730484349653, 0.00000431375974585535 ]
{ "id": 3, "code_window": [ " for (let child of DOM.childNodesAsList(parent)) {\n", " DOM.removeChild(parent, child);\n", " }\n", "\n", " if (isDevMode() && safeHtml !== unsafeHtml) {\n", " DOM.log('WARNING: sanitizing HTML stripped some content.');\n", " }\n", "\n", " return safeHtml;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (isDevMode() && safeHtml !== unsafeHtmlInput) {\n" ], "file_path": "modules/@angular/platform-browser/src/security/html_sanitizer.ts", "type": "replace", "edit_start_line_idx": 268 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {isDevMode} from '@angular/core'; import {DomAdapter, getDOM} from '../dom/dom_adapter'; import {sanitizeUrl} from './url_sanitizer'; /** A <body> element that can be safely used to parse untrusted HTML. Lazily initialized below. */ let inertElement: HTMLElement = null; /** Lazily initialized to make sure the DOM adapter gets set before use. */ let DOM: DomAdapter = null; /** Returns an HTML element that is guaranteed to not execute code when creating elements in it. */ function getInertElement() { if (inertElement) return inertElement; DOM = getDOM(); // Prefer using <template> element if supported. let templateEl = DOM.createElement('template'); if ('content' in templateEl) return templateEl; let doc = DOM.createHtmlDocument(); inertElement = DOM.querySelector(doc, 'body'); if (inertElement == null) { // usually there should be only one body element in the document, but IE doesn't have any, so we // need to create one. let html = DOM.createElement('html', doc); inertElement = DOM.createElement('body', doc); DOM.appendChild(html, inertElement); DOM.appendChild(doc, html); } return inertElement; } function tagSet(tags: string): {[k: string]: boolean} { let res: {[k: string]: boolean} = {}; for (let t of tags.split(',')) res[t.toLowerCase()] = true; return res; } function merge(...sets: {[k: string]: boolean}[]): {[k: string]: boolean} { let res: {[k: string]: boolean} = {}; for (let s of sets) { for (let v in s) { if (s.hasOwnProperty(v)) res[v] = true; } } return res; } // Good source of info about elements and attributes // http://dev.w3.org/html5/spec/Overview.html#semantics // http://simon.html5.org/html-elements // Safe Void Elements - HTML5 // http://dev.w3.org/html5/spec/Overview.html#void-elements const VOID_ELEMENTS = tagSet('area,br,col,hr,img,wbr'); // Elements that you can, intentionally, leave open (and which close themselves) // http://dev.w3.org/html5/spec/Overview.html#optional-tags const OPTIONAL_END_TAG_BLOCK_ELEMENTS = tagSet('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr'); const OPTIONAL_END_TAG_INLINE_ELEMENTS = tagSet('rp,rt'); const OPTIONAL_END_TAG_ELEMENTS = merge(OPTIONAL_END_TAG_INLINE_ELEMENTS, OPTIONAL_END_TAG_BLOCK_ELEMENTS); // Safe Block Elements - HTML5 const BLOCK_ELEMENTS = merge( OPTIONAL_END_TAG_BLOCK_ELEMENTS, tagSet( 'address,article,' + 'aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' + 'h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul')); // Inline Elements - HTML5 const INLINE_ELEMENTS = merge( OPTIONAL_END_TAG_INLINE_ELEMENTS, tagSet( 'a,abbr,acronym,b,' + 'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,' + 'samp,small,span,strike,strong,sub,sup,time,tt,u,var')); const VALID_ELEMENTS = merge(VOID_ELEMENTS, BLOCK_ELEMENTS, INLINE_ELEMENTS, OPTIONAL_END_TAG_ELEMENTS); // Attributes that have href and hence need to be sanitized const URI_ATTRS = tagSet('background,cite,href,longdesc,src,xlink:href'); const HTML_ATTRS = tagSet( 'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' + 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' + 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' + 'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' + 'valign,value,vspace,width'); // NB: This currently conciously doesn't support SVG. SVG sanitization has had several security // issues in the past, so it seems safer to leave it out if possible. If support for binding SVG via // innerHTML is required, SVG attributes should be added here. // NB: Sanitization does not allow <form> elements or other active elements (<button> etc). Those // can be sanitized, but they increase security surface area without a legitimate use case, so they // are left out here. const VALID_ATTRS = merge(URI_ATTRS, HTML_ATTRS); /** * SanitizingHtmlSerializer serializes a DOM fragment, stripping out any unsafe elements and unsafe * attributes. */ class SanitizingHtmlSerializer { private buf: string[] = []; sanitizeChildren(el: Element): string { // This cannot use a TreeWalker, as it has to run on Angular's various DOM adapters. // However this code never accesses properties off of `document` before deleting its contents // again, so it shouldn't be vulnerable to DOM clobbering. let current: Node = el.firstChild; while (current) { if (DOM.isElementNode(current)) { this.startElement(current); } else if (DOM.isTextNode(current)) { this.chars(DOM.nodeValue(current)); } if (DOM.firstChild(current)) { current = DOM.firstChild(current); continue; } while (current) { // Leaving the element. Walk up and to the right, closing tags as we go. if (DOM.isElementNode(current)) { this.endElement(DOM.nodeName(current).toLowerCase()); } if (DOM.nextSibling(current)) { current = DOM.nextSibling(current); break; } current = DOM.parentElement(current); } } return this.buf.join(''); } private startElement(element: any) { let tagName = DOM.nodeName(element).toLowerCase(); tagName = tagName.toLowerCase(); if (VALID_ELEMENTS.hasOwnProperty(tagName)) { this.buf.push('<'); this.buf.push(tagName); DOM.attributeMap(element).forEach((value: string, attrName: string) => { let lower = attrName.toLowerCase(); if (!VALID_ATTRS.hasOwnProperty(lower)) return; // TODO(martinprobst): Special case image URIs for data:image/... if (URI_ATTRS[lower]) value = sanitizeUrl(value); this.buf.push(' '); this.buf.push(attrName); this.buf.push('="'); this.buf.push(encodeEntities(value)); this.buf.push('"'); }); this.buf.push('>'); } } private endElement(tagName: string) { tagName = tagName.toLowerCase(); if (VALID_ELEMENTS.hasOwnProperty(tagName) && !VOID_ELEMENTS.hasOwnProperty(tagName)) { this.buf.push('</'); this.buf.push(tagName); this.buf.push('>'); } } private chars(chars: any /** TODO #9100 */) { this.buf.push(encodeEntities(chars)); } } // Regular Expressions for parsing tags and attributes const SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; // ! to ~ is the ASCII range. const NON_ALPHANUMERIC_REGEXP = /([^\#-~ |!])/g; /** * Escapes all potentially dangerous characters, so that the * resulting string can be safely inserted into attribute or * element text. * @param value * @returns {string} escaped text */ function encodeEntities(value: any /** TODO #9100 */) { return value.replace(/&/g, '&amp;') .replace( SURROGATE_PAIR_REGEXP, function(match: any /** TODO #9100 */) { let hi = match.charCodeAt(0); let low = match.charCodeAt(1); return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';'; }) .replace( NON_ALPHANUMERIC_REGEXP, function(match: any /** TODO #9100 */) { return '&#' + match.charCodeAt(0) + ';'; }) .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); } /** * When IE9-11 comes across an unknown namespaced attribute e.g. 'xlink:foo' it adds 'xmlns:ns1' * attribute to declare ns1 namespace and prefixes the attribute with 'ns1' (e.g. 'ns1:xlink:foo'). * * This is undesirable since we don't want to allow any of these custom attributes. This method * strips them all. */ function stripCustomNsAttrs(el: any) { DOM.attributeMap(el).forEach((_, attrName) => { if (attrName === 'xmlns:ns1' || attrName.indexOf('ns1:') === 0) { DOM.removeAttribute(el, attrName); } }); for (let n of DOM.childNodesAsList(el)) { if (DOM.isElementNode(n)) stripCustomNsAttrs(n); } } /** * Sanitizes the given unsafe, untrusted HTML fragment, and returns HTML text that is safe to add to * the DOM in a browser environment. */ export function sanitizeHtml(unsafeHtml: string): string { try { let containerEl = getInertElement(); // Make sure unsafeHtml is actually a string (TypeScript types are not enforced at runtime). unsafeHtml = unsafeHtml ? String(unsafeHtml) : ''; // mXSS protection. Repeatedly parse the document to make sure it stabilizes, so that a browser // trying to auto-correct incorrect HTML cannot cause formerly inert HTML to become dangerous. let mXSSAttempts = 5; let parsedHtml = unsafeHtml; do { if (mXSSAttempts === 0) { throw new Error('Failed to sanitize html because the input is unstable'); } mXSSAttempts--; unsafeHtml = parsedHtml; DOM.setInnerHTML(containerEl, unsafeHtml); if ((DOM.defaultDoc() as any).documentMode) { // strip custom-namespaced attributes on IE<=11 stripCustomNsAttrs(containerEl); } parsedHtml = DOM.getInnerHTML(containerEl); } while (unsafeHtml !== parsedHtml); let sanitizer = new SanitizingHtmlSerializer(); let safeHtml = sanitizer.sanitizeChildren(DOM.getTemplateContent(containerEl) || containerEl); // Clear out the body element. let parent = DOM.getTemplateContent(containerEl) || containerEl; for (let child of DOM.childNodesAsList(parent)) { DOM.removeChild(parent, child); } if (isDevMode() && safeHtml !== unsafeHtml) { DOM.log('WARNING: sanitizing HTML stripped some content.'); } return safeHtml; } catch (e) { // In case anything goes wrong, clear out inertElement to reset the entire DOM structure. inertElement = null; throw e; } }
modules/@angular/platform-browser/src/security/html_sanitizer.ts
1
https://github.com/angular/angular/commit/98cef76931f1417c21bfaf8cbbdb3768a4b85fb5
[ 0.9978219270706177, 0.07914246618747711, 0.00016319355927407742, 0.00025819201255217195, 0.242628812789917 ]
{ "id": 3, "code_window": [ " for (let child of DOM.childNodesAsList(parent)) {\n", " DOM.removeChild(parent, child);\n", " }\n", "\n", " if (isDevMode() && safeHtml !== unsafeHtml) {\n", " DOM.log('WARNING: sanitizing HTML stripped some content.');\n", " }\n", "\n", " return safeHtml;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (isDevMode() && safeHtml !== unsafeHtmlInput) {\n" ], "file_path": "modules/@angular/platform-browser/src/security/html_sanitizer.ts", "type": "replace", "edit_start_line_idx": 268 }
class RollupNG2 { resolveId(id, from){ if(id.startsWith('@angular/')){ return `${__dirname}/../../packages-dist/${id.split('/')[1]}/esm/index.js`; } // if(id.startsWith('rxjs/')){ // return `${__dirname}/../../../node_modules/rxjs-es/${id.replace('rxjs/', '')}.js`; // } } } export default { entry: 'test.js', format: 'es6', plugins: [ new RollupNG2(), ] }
tools/tree-shaking-test/rollup.config.js
0
https://github.com/angular/angular/commit/98cef76931f1417c21bfaf8cbbdb3768a4b85fb5
[ 0.00017674682021606714, 0.00017318455502390862, 0.00016766249609645456, 0.00017514434875920415, 0.000003959110017603962 ]
{ "id": 3, "code_window": [ " for (let child of DOM.childNodesAsList(parent)) {\n", " DOM.removeChild(parent, child);\n", " }\n", "\n", " if (isDevMode() && safeHtml !== unsafeHtml) {\n", " DOM.log('WARNING: sanitizing HTML stripped some content.');\n", " }\n", "\n", " return safeHtml;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (isDevMode() && safeHtml !== unsafeHtmlInput) {\n" ], "file_path": "modules/@angular/platform-browser/src/security/html_sanitizer.ts", "type": "replace", "edit_start_line_idx": 268 }
import * as fs from 'fs'; import * as ts from 'typescript'; import {Evaluator} from '../src/evaluator'; import {Symbols} from '../src/symbols'; import {Directory, Host, expectNoDiagnostics, findVar} from './typescript.mocks'; describe('Evaluator', () => { let documentRegistry = ts.createDocumentRegistry(); let host: ts.LanguageServiceHost; let service: ts.LanguageService; let program: ts.Program; let typeChecker: ts.TypeChecker; let symbols: Symbols; let evaluator: Evaluator; beforeEach(() => { host = new Host(FILES, [ 'expressions.ts', 'consts.ts', 'const_expr.ts', 'forwardRef.ts', 'classes.ts', 'newExpression.ts', 'errors.ts' ]); service = ts.createLanguageService(host, documentRegistry); program = service.getProgram(); typeChecker = program.getTypeChecker(); symbols = new Symbols(null); evaluator = new Evaluator(symbols); }); it('should not have typescript errors in test data', () => { expectNoDiagnostics(service.getCompilerOptionsDiagnostics()); for (const sourceFile of program.getSourceFiles()) { expectNoDiagnostics(service.getSyntacticDiagnostics(sourceFile.fileName)); if (sourceFile.fileName != 'errors.ts') { // Skip errors.ts because we it has intentional semantic errors that we are testing for. expectNoDiagnostics(service.getSemanticDiagnostics(sourceFile.fileName)); } } }); it('should be able to fold literal expressions', () => { var consts = program.getSourceFile('consts.ts'); expect(evaluator.isFoldable(findVar(consts, 'someName').initializer)).toBeTruthy(); expect(evaluator.isFoldable(findVar(consts, 'someBool').initializer)).toBeTruthy(); expect(evaluator.isFoldable(findVar(consts, 'one').initializer)).toBeTruthy(); expect(evaluator.isFoldable(findVar(consts, 'two').initializer)).toBeTruthy(); }); it('should be able to fold expressions with foldable references', () => { var expressions = program.getSourceFile('expressions.ts'); symbols.define('someName', 'some-name'); symbols.define('someBool', true); symbols.define('one', 1); symbols.define('two', 2); expect(evaluator.isFoldable(findVar(expressions, 'three').initializer)).toBeTruthy(); expect(evaluator.isFoldable(findVar(expressions, 'four').initializer)).toBeTruthy(); symbols.define('three', 3); symbols.define('four', 4); expect(evaluator.isFoldable(findVar(expressions, 'obj').initializer)).toBeTruthy(); expect(evaluator.isFoldable(findVar(expressions, 'arr').initializer)).toBeTruthy(); }); it('should be able to evaluate literal expressions', () => { var consts = program.getSourceFile('consts.ts'); expect(evaluator.evaluateNode(findVar(consts, 'someName').initializer)).toBe('some-name'); expect(evaluator.evaluateNode(findVar(consts, 'someBool').initializer)).toBe(true); expect(evaluator.evaluateNode(findVar(consts, 'one').initializer)).toBe(1); expect(evaluator.evaluateNode(findVar(consts, 'two').initializer)).toBe(2); }); it('should be able to evaluate expressions', () => { var expressions = program.getSourceFile('expressions.ts'); symbols.define('someName', 'some-name'); symbols.define('someBool', true); symbols.define('one', 1); symbols.define('two', 2); expect(evaluator.evaluateNode(findVar(expressions, 'three').initializer)).toBe(3); symbols.define('three', 3); expect(evaluator.evaluateNode(findVar(expressions, 'four').initializer)).toBe(4); symbols.define('four', 4); expect(evaluator.evaluateNode(findVar(expressions, 'obj').initializer)) .toEqual({one: 1, two: 2, three: 3, four: 4}); expect(evaluator.evaluateNode(findVar(expressions, 'arr').initializer)).toEqual([1, 2, 3, 4]); expect(evaluator.evaluateNode(findVar(expressions, 'bTrue').initializer)).toEqual(true); expect(evaluator.evaluateNode(findVar(expressions, 'bFalse').initializer)).toEqual(false); expect(evaluator.evaluateNode(findVar(expressions, 'bAnd').initializer)).toEqual(true); expect(evaluator.evaluateNode(findVar(expressions, 'bOr').initializer)).toEqual(true); expect(evaluator.evaluateNode(findVar(expressions, 'nDiv').initializer)).toEqual(2); expect(evaluator.evaluateNode(findVar(expressions, 'nMod').initializer)).toEqual(1); expect(evaluator.evaluateNode(findVar(expressions, 'bLOr').initializer)).toEqual(false || true); expect(evaluator.evaluateNode(findVar(expressions, 'bLAnd').initializer)).toEqual(true && true); expect(evaluator.evaluateNode(findVar(expressions, 'bBOr').initializer)).toEqual(0x11 | 0x22); expect(evaluator.evaluateNode(findVar(expressions, 'bBAnd').initializer)).toEqual(0x11 & 0x03); expect(evaluator.evaluateNode(findVar(expressions, 'bXor').initializer)).toEqual(0x11 ^ 0x21); expect(evaluator.evaluateNode(findVar(expressions, 'bEqual').initializer)) .toEqual(1 == <any>'1'); expect(evaluator.evaluateNode(findVar(expressions, 'bNotEqual').initializer)) .toEqual(1 != <any>'1'); expect(evaluator.evaluateNode(findVar(expressions, 'bIdentical').initializer)) .toEqual(1 === <any>'1'); expect(evaluator.evaluateNode(findVar(expressions, 'bNotIdentical').initializer)) .toEqual(1 !== <any>'1'); expect(evaluator.evaluateNode(findVar(expressions, 'bLessThan').initializer)).toEqual(1 < 2); expect(evaluator.evaluateNode(findVar(expressions, 'bGreaterThan').initializer)).toEqual(1 > 2); expect(evaluator.evaluateNode(findVar(expressions, 'bLessThanEqual').initializer)) .toEqual(1 <= 2); expect(evaluator.evaluateNode(findVar(expressions, 'bGreaterThanEqual').initializer)) .toEqual(1 >= 2); expect(evaluator.evaluateNode(findVar(expressions, 'bShiftLeft').initializer)).toEqual(1 << 2); expect(evaluator.evaluateNode(findVar(expressions, 'bShiftRight').initializer)) .toEqual(-1 >> 2); expect(evaluator.evaluateNode(findVar(expressions, 'bShiftRightU').initializer)) .toEqual(-1 >>> 2); }); it('should report recursive references as symbolic', () => { var expressions = program.getSourceFile('expressions.ts'); expect(evaluator.evaluateNode(findVar(expressions, 'recursiveA').initializer)) .toEqual({__symbolic: 'reference', name: 'recursiveB'}); expect(evaluator.evaluateNode(findVar(expressions, 'recursiveB').initializer)) .toEqual({__symbolic: 'reference', name: 'recursiveA'}); }); it('should correctly handle special cases for CONST_EXPR', () => { var const_expr = program.getSourceFile('const_expr.ts'); expect(evaluator.evaluateNode(findVar(const_expr, 'bTrue').initializer)).toEqual(true); expect(evaluator.evaluateNode(findVar(const_expr, 'bFalse').initializer)).toEqual(false); }); it('should resolve a forwardRef', () => { var forwardRef = program.getSourceFile('forwardRef.ts'); expect(evaluator.evaluateNode(findVar(forwardRef, 'bTrue').initializer)).toEqual(true); expect(evaluator.evaluateNode(findVar(forwardRef, 'bFalse').initializer)).toEqual(false); }); it('should return new expressions', () => { symbols.define('Value', {__symbolic: 'reference', module: './classes', name: 'Value'}); evaluator = new Evaluator(symbols); var newExpression = program.getSourceFile('newExpression.ts'); expect(evaluator.evaluateNode(findVar(newExpression, 'someValue').initializer)).toEqual({ __symbolic: 'new', expression: {__symbolic: 'reference', name: 'Value', module: './classes'}, arguments: ['name', 12] }); expect(evaluator.evaluateNode(findVar(newExpression, 'complex').initializer)).toEqual({ __symbolic: 'new', expression: {__symbolic: 'reference', name: 'Value', module: './classes'}, arguments: ['name', 12] }); }); it('should return errors for unsupported expressions', () => { let errors = program.getSourceFile('errors.ts'); let aDecl = findVar(errors, 'a'); expect(evaluator.evaluateNode(aDecl.type)).toEqual({ __symbolic: 'error', message: 'Qualified type names not supported', line: 5, character: 10 }); let fDecl = findVar(errors, 'f'); expect(evaluator.evaluateNode(fDecl.initializer)) .toEqual( {__symbolic: 'error', message: 'Function call not supported', line: 6, character: 11}); let eDecl = findVar(errors, 'e'); expect(evaluator.evaluateNode(eDecl.type)).toEqual({ __symbolic: 'error', message: 'Could not resolve type', line: 7, character: 10, context: {typeName: 'NotFound'} }); let sDecl = findVar(errors, 's'); expect(evaluator.evaluateNode(sDecl.initializer)).toEqual({ __symbolic: 'error', message: 'Name expected', line: 8, character: 13, context: {received: '1'} }); let tDecl = findVar(errors, 't'); expect(evaluator.evaluateNode(tDecl.initializer)).toEqual({ __symbolic: 'error', message: 'Expression form not supported', line: 9, character: 11 }); }); it('should be able to fold an array spread', () => { let expressions = program.getSourceFile('expressions.ts'); symbols.define('arr', [1, 2, 3, 4]); let arrSpread = findVar(expressions, 'arrSpread'); expect(evaluator.evaluateNode(arrSpread.initializer)).toEqual([0, 1, 2, 3, 4, 5]); }); it('should be able to produce a spread expression', () => { let expressions = program.getSourceFile('expressions.ts'); let arrSpreadRef = findVar(expressions, 'arrSpreadRef'); expect(evaluator.evaluateNode(arrSpreadRef.initializer)).toEqual([ 0, {__symbolic: 'spread', expression: {__symbolic: 'reference', name: 'arrImport'}}, 5 ]); }); }); const FILES: Directory = { 'directives.ts': ` export function Pipe(options: { name?: string, pure?: boolean}) { return function(fn: Function) { } } `, 'classes.ts': ` export class Value { constructor(public name: string, public value: any) {} } `, 'consts.ts': ` export var someName = 'some-name'; export var someBool = true; export var one = 1; export var two = 2; export var arrImport = [1, 2, 3, 4]; `, 'expressions.ts': ` import {arrImport} from './consts'; export var someName = 'some-name'; export var someBool = true; export var one = 1; export var two = 2; export var three = one + two; export var four = two * two; export var obj = { one: one, two: two, three: three, four: four }; export var arr = [one, two, three, four]; export var bTrue = someBool; export var bFalse = !someBool; export var bAnd = someBool && someBool; export var bOr = someBool || someBool; export var nDiv = four / two; export var nMod = (four + one) % two; export var bLOr = false || true; // true export var bLAnd = true && true; // true export var bBOr = 0x11 | 0x22; // 0x33 export var bBAnd = 0x11 & 0x03; // 0x01 export var bXor = 0x11 ^ 0x21; // 0x20 export var bEqual = 1 == <any>"1"; // true export var bNotEqual = 1 != <any>"1"; // false export var bIdentical = 1 === <any>"1"; // false export var bNotIdentical = 1 !== <any>"1"; // true export var bLessThan = 1 < 2; // true export var bGreaterThan = 1 > 2; // false export var bLessThanEqual = 1 <= 2; // true export var bGreaterThanEqual = 1 >= 2; // false export var bShiftLeft = 1 << 2; // 0x04 export var bShiftRight = -1 >> 2; // -1 export var bShiftRightU = -1 >>> 2; // 0x3fffffff export var arrSpread = [0, ...arr, 5]; export var arrSpreadRef = [0, ...arrImport, 5]; export var recursiveA = recursiveB; export var recursiveB = recursiveA; `, 'A.ts': ` import {Pipe} from './directives'; @Pipe({name: 'A', pure: false}) export class A {}`, 'B.ts': ` import {Pipe} from './directives'; import {someName, someBool} from './consts'; @Pipe({name: someName, pure: someBool}) export class B {}`, 'const_expr.ts': ` function CONST_EXPR(value: any) { return value; } export var bTrue = CONST_EXPR(true); export var bFalse = CONST_EXPR(false); `, 'forwardRef.ts': ` function forwardRef(value: any) { return value; } export var bTrue = forwardRef(() => true); export var bFalse = forwardRef(() => false); `, 'newExpression.ts': ` import {Value} from './classes'; function CONST_EXPR(value: any) { return value; } function forwardRef(value: any) { return value; } export const someValue = new Value("name", 12); export const complex = CONST_EXPR(new Value("name", forwardRef(() => 12))); `, 'errors.ts': ` declare namespace Foo { type A = string; } let a: Foo.A = 'some value'; let f = () => 1; let e: NotFound; let s = { 1: 1, 2: 2 }; let t = typeof 12; `, };
tools/@angular/tsc-wrapped/test/evaluator.spec.ts
0
https://github.com/angular/angular/commit/98cef76931f1417c21bfaf8cbbdb3768a4b85fb5
[ 0.0001787132932804525, 0.00017620068683754653, 0.0001726601185509935, 0.00017657804710324854, 0.0000016647446727802162 ]
{ "id": 3, "code_window": [ " for (let child of DOM.childNodesAsList(parent)) {\n", " DOM.removeChild(parent, child);\n", " }\n", "\n", " if (isDevMode() && safeHtml !== unsafeHtml) {\n", " DOM.log('WARNING: sanitizing HTML stripped some content.');\n", " }\n", "\n", " return safeHtml;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (isDevMode() && safeHtml !== unsafeHtmlInput) {\n" ], "file_path": "modules/@angular/platform-browser/src/security/html_sanitizer.ts", "type": "replace", "edit_start_line_idx": 268 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Location} from '@angular/common'; import {ComponentFixture, TestComponentBuilder} from '@angular/compiler/testing'; import {Component} from '@angular/core'; import {beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter} from '@angular/core/testing/testing_internal'; import {By} from '@angular/platform-browser/src/dom/debug/by'; import {AuxRoute, ROUTER_DIRECTIVES, Route, RouteConfig, Router} from '@angular/router-deprecated'; import {BaseException} from '../../../src/facade/exceptions'; import {clickOnElement, compile, getHref, specs} from '../util'; function getLinkElement(rtc: ComponentFixture<any>, linkIndex: number = 0) { return rtc.debugElement.queryAll(By.css('a'))[linkIndex].nativeElement; } function auxRoutes() { var tcb: TestComponentBuilder; var fixture: ComponentFixture<any>; var rtr: any /** TODO #9100 */; beforeEach(inject( [TestComponentBuilder, Router], (tcBuilder: any /** TODO #9100 */, router: any /** TODO #9100 */) => { tcb = tcBuilder; rtr = router; })); it('should recognize and navigate from the URL', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { compile( tcb, `main {<router-outlet></router-outlet>} | aux {<router-outlet name="modal"></router-outlet>}`) .then((rtc) => {fixture = rtc}) .then((_) => rtr.config([ new Route({path: '/hello', component: HelloCmp, name: 'Hello'}), new AuxRoute({path: '/modal', component: ModalCmp, name: 'Aux'}) ])) .then((_) => rtr.navigateByUrl('/(modal)')) .then((_) => { fixture.detectChanges(); expect(fixture.debugElement.nativeElement).toHaveText('main {} | aux {modal}'); async.done(); }); })); it('should navigate via the link DSL', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { compile( tcb, `main {<router-outlet></router-outlet>} | aux {<router-outlet name="modal"></router-outlet>}`) .then((rtc) => {fixture = rtc}) .then((_) => rtr.config([ new Route({path: '/hello', component: HelloCmp, name: 'Hello'}), new AuxRoute({path: '/modal', component: ModalCmp, name: 'Modal'}) ])) .then((_) => rtr.navigate(['/', ['Modal']])) .then((_) => { fixture.detectChanges(); expect(fixture.debugElement.nativeElement).toHaveText('main {} | aux {modal}'); async.done(); }); })); it('should generate a link URL', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { compile( tcb, `<a [routerLink]="['/', ['Modal']]">open modal</a> | main {<router-outlet></router-outlet>} | aux {<router-outlet name="modal"></router-outlet>}`) .then((rtc) => {fixture = rtc}) .then((_) => rtr.config([ new Route({path: '/hello', component: HelloCmp, name: 'Hello'}), new AuxRoute({path: '/modal', component: ModalCmp, name: 'Modal'}) ])) .then((_) => { fixture.detectChanges(); expect(getHref(getLinkElement(fixture))).toEqual('/(modal)'); async.done(); }); })); it('should navigate from a link click', inject( [AsyncTestCompleter, Location], (async: AsyncTestCompleter, location: any /** TODO #9100 */) => { compile( tcb, `<a [routerLink]="['/', ['Modal']]">open modal</a> | <a [routerLink]="['/Hello']">hello</a> | main {<router-outlet></router-outlet>} | aux {<router-outlet name="modal"></router-outlet>}`) .then((rtc) => {fixture = rtc}) .then((_) => rtr.config([ new Route({path: '/hello', component: HelloCmp, name: 'Hello'}), new AuxRoute({path: '/modal', component: ModalCmp, name: 'Modal'}) ])) .then((_) => { fixture.detectChanges(); expect(fixture.debugElement.nativeElement) .toHaveText('open modal | hello | main {} | aux {}'); var navCount = 0; rtr.subscribe((_: any /** TODO #9100 */) => { navCount += 1; fixture.detectChanges(); if (navCount == 1) { expect(fixture.debugElement.nativeElement) .toHaveText('open modal | hello | main {} | aux {modal}'); expect(location.urlChanges).toEqual(['/(modal)']); expect(getHref(getLinkElement(fixture, 0))).toEqual('/(modal)'); expect(getHref(getLinkElement(fixture, 1))).toEqual('/hello(modal)'); // click on primary route link clickOnElement(getLinkElement(fixture, 1)); } else if (navCount == 2) { expect(fixture.debugElement.nativeElement) .toHaveText('open modal | hello | main {hello} | aux {modal}'); expect(location.urlChanges).toEqual(['/(modal)', '/hello(modal)']); expect(getHref(getLinkElement(fixture, 0))).toEqual('/hello(modal)'); expect(getHref(getLinkElement(fixture, 1))).toEqual('/hello(modal)'); async.done(); } else { throw new BaseException(`Unexpected route change #${navCount}`); } }); clickOnElement(getLinkElement(fixture)); }); })); } function auxRoutesWithAPrimaryRoute() { var tcb: TestComponentBuilder; var fixture: ComponentFixture<any>; var rtr: any /** TODO #9100 */; beforeEach(inject( [TestComponentBuilder, Router], (tcBuilder: any /** TODO #9100 */, router: any /** TODO #9100 */) => { tcb = tcBuilder; rtr = router; })); it('should recognize and navigate from the URL', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { compile( tcb, `main {<router-outlet></router-outlet>} | aux {<router-outlet name="modal"></router-outlet>}`) .then((rtc) => {fixture = rtc}) .then((_) => rtr.config([ new Route({path: '/hello', component: HelloCmp, name: 'Hello'}), new AuxRoute({path: '/modal', component: ModalCmp, name: 'Aux'}) ])) .then((_) => rtr.navigateByUrl('/hello(modal)')) .then((_) => { fixture.detectChanges(); expect(fixture.debugElement.nativeElement).toHaveText('main {hello} | aux {modal}'); async.done(); }); })); it('should navigate via the link DSL', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { compile( tcb, `main {<router-outlet></router-outlet>} | aux {<router-outlet name="modal"></router-outlet>}`) .then((rtc) => {fixture = rtc}) .then((_) => rtr.config([ new Route({path: '/hello', component: HelloCmp, name: 'Hello'}), new AuxRoute({path: '/modal', component: ModalCmp, name: 'Modal'}) ])) .then((_) => rtr.navigate(['/Hello', ['Modal']])) .then((_) => { fixture.detectChanges(); expect(fixture.debugElement.nativeElement).toHaveText('main {hello} | aux {modal}'); async.done(); }); })); it('should generate a link URL', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { compile( tcb, `<a [routerLink]="['/Hello', ['Modal']]">open modal</a> | main {<router-outlet></router-outlet>} | aux {<router-outlet name="modal"></router-outlet>}`) .then((rtc) => {fixture = rtc}) .then((_) => rtr.config([ new Route({path: '/hello', component: HelloCmp, name: 'Hello'}), new AuxRoute({path: '/modal', component: ModalCmp, name: 'Modal'}) ])) .then((_) => { fixture.detectChanges(); expect(getHref(getLinkElement(fixture))).toEqual('/hello(modal)'); async.done(); }); })); it('should navigate from a link click', inject( [AsyncTestCompleter, Location], (async: AsyncTestCompleter, location: any /** TODO #9100 */) => { compile( tcb, `<a [routerLink]="['/Hello', ['Modal']]">open modal</a> | main {<router-outlet></router-outlet>} | aux {<router-outlet name="modal"></router-outlet>}`) .then((rtc) => {fixture = rtc}) .then((_) => rtr.config([ new Route({path: '/hello', component: HelloCmp, name: 'Hello'}), new AuxRoute({path: '/modal', component: ModalCmp, name: 'Modal'}) ])) .then((_) => { fixture.detectChanges(); expect(fixture.debugElement.nativeElement) .toHaveText('open modal | main {} | aux {}'); rtr.subscribe((_: any /** TODO #9100 */) => { fixture.detectChanges(); expect(fixture.debugElement.nativeElement) .toHaveText('open modal | main {hello} | aux {modal}'); expect(location.urlChanges).toEqual(['/hello(modal)']); async.done(); }); clickOnElement(getLinkElement(fixture)); }); })); } export function registerSpecs() { (specs as any /** TODO #9100 */)['auxRoutes'] = auxRoutes; (specs as any /** TODO #9100 */)['auxRoutesWithAPrimaryRoute'] = auxRoutesWithAPrimaryRoute; } @Component({selector: 'hello-cmp', template: `{{greeting}}`}) class HelloCmp { greeting: string; constructor() { this.greeting = 'hello'; } } @Component({selector: 'modal-cmp', template: `modal`}) class ModalCmp { } @Component({ selector: 'aux-cmp', template: 'main {<router-outlet></router-outlet>} | ' + 'aux {<router-outlet name="modal"></router-outlet>}', directives: [ROUTER_DIRECTIVES], }) @RouteConfig([ new Route({path: '/hello', component: HelloCmp, name: 'Hello'}), new AuxRoute({path: '/modal', component: ModalCmp, name: 'Aux'}) ]) class AuxCmp { }
modules/@angular/router-deprecated/test/integration/impl/aux_route_spec_impl.ts
0
https://github.com/angular/angular/commit/98cef76931f1417c21bfaf8cbbdb3768a4b85fb5
[ 0.00017847181879915297, 0.00017483624105807394, 0.00016895246517378837, 0.00017541812849231064, 0.000002172645508835558 ]
{ "id": 4, "code_window": [ " t.expect(sanitizeHtml('<?pi nodes?>no.')).toEqual('no.');\n", " t.expect(logMsgs.join('\\n')).toMatch(/sanitizing HTML stripped some content/);\n", " });\n", " t.it('escapes entities', () => {\n", " t.expect(sanitizeHtml('<p>Hello &lt; World</p>')).toEqual('<p>Hello &lt; World</p>');\n", " t.expect(sanitizeHtml('<p>Hello < World</p>')).toEqual('<p>Hello &lt; World</p>');\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " t.it('supports sanitizing escaped entities', () => {\n", " t.expect(sanitizeHtml('&#128640;')).toEqual('&#128640;');\n", " t.expect(logMsgs).toEqual([]);\n", " });\n" ], "file_path": "modules/@angular/platform-browser/test/security/html_sanitizer_spec.ts", "type": "add", "edit_start_line_idx": 53 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {isDevMode} from '@angular/core'; import {DomAdapter, getDOM} from '../dom/dom_adapter'; import {sanitizeUrl} from './url_sanitizer'; /** A <body> element that can be safely used to parse untrusted HTML. Lazily initialized below. */ let inertElement: HTMLElement = null; /** Lazily initialized to make sure the DOM adapter gets set before use. */ let DOM: DomAdapter = null; /** Returns an HTML element that is guaranteed to not execute code when creating elements in it. */ function getInertElement() { if (inertElement) return inertElement; DOM = getDOM(); // Prefer using <template> element if supported. let templateEl = DOM.createElement('template'); if ('content' in templateEl) return templateEl; let doc = DOM.createHtmlDocument(); inertElement = DOM.querySelector(doc, 'body'); if (inertElement == null) { // usually there should be only one body element in the document, but IE doesn't have any, so we // need to create one. let html = DOM.createElement('html', doc); inertElement = DOM.createElement('body', doc); DOM.appendChild(html, inertElement); DOM.appendChild(doc, html); } return inertElement; } function tagSet(tags: string): {[k: string]: boolean} { let res: {[k: string]: boolean} = {}; for (let t of tags.split(',')) res[t.toLowerCase()] = true; return res; } function merge(...sets: {[k: string]: boolean}[]): {[k: string]: boolean} { let res: {[k: string]: boolean} = {}; for (let s of sets) { for (let v in s) { if (s.hasOwnProperty(v)) res[v] = true; } } return res; } // Good source of info about elements and attributes // http://dev.w3.org/html5/spec/Overview.html#semantics // http://simon.html5.org/html-elements // Safe Void Elements - HTML5 // http://dev.w3.org/html5/spec/Overview.html#void-elements const VOID_ELEMENTS = tagSet('area,br,col,hr,img,wbr'); // Elements that you can, intentionally, leave open (and which close themselves) // http://dev.w3.org/html5/spec/Overview.html#optional-tags const OPTIONAL_END_TAG_BLOCK_ELEMENTS = tagSet('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr'); const OPTIONAL_END_TAG_INLINE_ELEMENTS = tagSet('rp,rt'); const OPTIONAL_END_TAG_ELEMENTS = merge(OPTIONAL_END_TAG_INLINE_ELEMENTS, OPTIONAL_END_TAG_BLOCK_ELEMENTS); // Safe Block Elements - HTML5 const BLOCK_ELEMENTS = merge( OPTIONAL_END_TAG_BLOCK_ELEMENTS, tagSet( 'address,article,' + 'aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' + 'h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul')); // Inline Elements - HTML5 const INLINE_ELEMENTS = merge( OPTIONAL_END_TAG_INLINE_ELEMENTS, tagSet( 'a,abbr,acronym,b,' + 'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,' + 'samp,small,span,strike,strong,sub,sup,time,tt,u,var')); const VALID_ELEMENTS = merge(VOID_ELEMENTS, BLOCK_ELEMENTS, INLINE_ELEMENTS, OPTIONAL_END_TAG_ELEMENTS); // Attributes that have href and hence need to be sanitized const URI_ATTRS = tagSet('background,cite,href,longdesc,src,xlink:href'); const HTML_ATTRS = tagSet( 'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' + 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' + 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' + 'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' + 'valign,value,vspace,width'); // NB: This currently conciously doesn't support SVG. SVG sanitization has had several security // issues in the past, so it seems safer to leave it out if possible. If support for binding SVG via // innerHTML is required, SVG attributes should be added here. // NB: Sanitization does not allow <form> elements or other active elements (<button> etc). Those // can be sanitized, but they increase security surface area without a legitimate use case, so they // are left out here. const VALID_ATTRS = merge(URI_ATTRS, HTML_ATTRS); /** * SanitizingHtmlSerializer serializes a DOM fragment, stripping out any unsafe elements and unsafe * attributes. */ class SanitizingHtmlSerializer { private buf: string[] = []; sanitizeChildren(el: Element): string { // This cannot use a TreeWalker, as it has to run on Angular's various DOM adapters. // However this code never accesses properties off of `document` before deleting its contents // again, so it shouldn't be vulnerable to DOM clobbering. let current: Node = el.firstChild; while (current) { if (DOM.isElementNode(current)) { this.startElement(current); } else if (DOM.isTextNode(current)) { this.chars(DOM.nodeValue(current)); } if (DOM.firstChild(current)) { current = DOM.firstChild(current); continue; } while (current) { // Leaving the element. Walk up and to the right, closing tags as we go. if (DOM.isElementNode(current)) { this.endElement(DOM.nodeName(current).toLowerCase()); } if (DOM.nextSibling(current)) { current = DOM.nextSibling(current); break; } current = DOM.parentElement(current); } } return this.buf.join(''); } private startElement(element: any) { let tagName = DOM.nodeName(element).toLowerCase(); tagName = tagName.toLowerCase(); if (VALID_ELEMENTS.hasOwnProperty(tagName)) { this.buf.push('<'); this.buf.push(tagName); DOM.attributeMap(element).forEach((value: string, attrName: string) => { let lower = attrName.toLowerCase(); if (!VALID_ATTRS.hasOwnProperty(lower)) return; // TODO(martinprobst): Special case image URIs for data:image/... if (URI_ATTRS[lower]) value = sanitizeUrl(value); this.buf.push(' '); this.buf.push(attrName); this.buf.push('="'); this.buf.push(encodeEntities(value)); this.buf.push('"'); }); this.buf.push('>'); } } private endElement(tagName: string) { tagName = tagName.toLowerCase(); if (VALID_ELEMENTS.hasOwnProperty(tagName) && !VOID_ELEMENTS.hasOwnProperty(tagName)) { this.buf.push('</'); this.buf.push(tagName); this.buf.push('>'); } } private chars(chars: any /** TODO #9100 */) { this.buf.push(encodeEntities(chars)); } } // Regular Expressions for parsing tags and attributes const SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; // ! to ~ is the ASCII range. const NON_ALPHANUMERIC_REGEXP = /([^\#-~ |!])/g; /** * Escapes all potentially dangerous characters, so that the * resulting string can be safely inserted into attribute or * element text. * @param value * @returns {string} escaped text */ function encodeEntities(value: any /** TODO #9100 */) { return value.replace(/&/g, '&amp;') .replace( SURROGATE_PAIR_REGEXP, function(match: any /** TODO #9100 */) { let hi = match.charCodeAt(0); let low = match.charCodeAt(1); return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';'; }) .replace( NON_ALPHANUMERIC_REGEXP, function(match: any /** TODO #9100 */) { return '&#' + match.charCodeAt(0) + ';'; }) .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); } /** * When IE9-11 comes across an unknown namespaced attribute e.g. 'xlink:foo' it adds 'xmlns:ns1' * attribute to declare ns1 namespace and prefixes the attribute with 'ns1' (e.g. 'ns1:xlink:foo'). * * This is undesirable since we don't want to allow any of these custom attributes. This method * strips them all. */ function stripCustomNsAttrs(el: any) { DOM.attributeMap(el).forEach((_, attrName) => { if (attrName === 'xmlns:ns1' || attrName.indexOf('ns1:') === 0) { DOM.removeAttribute(el, attrName); } }); for (let n of DOM.childNodesAsList(el)) { if (DOM.isElementNode(n)) stripCustomNsAttrs(n); } } /** * Sanitizes the given unsafe, untrusted HTML fragment, and returns HTML text that is safe to add to * the DOM in a browser environment. */ export function sanitizeHtml(unsafeHtml: string): string { try { let containerEl = getInertElement(); // Make sure unsafeHtml is actually a string (TypeScript types are not enforced at runtime). unsafeHtml = unsafeHtml ? String(unsafeHtml) : ''; // mXSS protection. Repeatedly parse the document to make sure it stabilizes, so that a browser // trying to auto-correct incorrect HTML cannot cause formerly inert HTML to become dangerous. let mXSSAttempts = 5; let parsedHtml = unsafeHtml; do { if (mXSSAttempts === 0) { throw new Error('Failed to sanitize html because the input is unstable'); } mXSSAttempts--; unsafeHtml = parsedHtml; DOM.setInnerHTML(containerEl, unsafeHtml); if ((DOM.defaultDoc() as any).documentMode) { // strip custom-namespaced attributes on IE<=11 stripCustomNsAttrs(containerEl); } parsedHtml = DOM.getInnerHTML(containerEl); } while (unsafeHtml !== parsedHtml); let sanitizer = new SanitizingHtmlSerializer(); let safeHtml = sanitizer.sanitizeChildren(DOM.getTemplateContent(containerEl) || containerEl); // Clear out the body element. let parent = DOM.getTemplateContent(containerEl) || containerEl; for (let child of DOM.childNodesAsList(parent)) { DOM.removeChild(parent, child); } if (isDevMode() && safeHtml !== unsafeHtml) { DOM.log('WARNING: sanitizing HTML stripped some content.'); } return safeHtml; } catch (e) { // In case anything goes wrong, clear out inertElement to reset the entire DOM structure. inertElement = null; throw e; } }
modules/@angular/platform-browser/src/security/html_sanitizer.ts
1
https://github.com/angular/angular/commit/98cef76931f1417c21bfaf8cbbdb3768a4b85fb5
[ 0.004373137839138508, 0.0006717824144288898, 0.00016360878362320364, 0.00017421926895622164, 0.0011154377134516835 ]
{ "id": 4, "code_window": [ " t.expect(sanitizeHtml('<?pi nodes?>no.')).toEqual('no.');\n", " t.expect(logMsgs.join('\\n')).toMatch(/sanitizing HTML stripped some content/);\n", " });\n", " t.it('escapes entities', () => {\n", " t.expect(sanitizeHtml('<p>Hello &lt; World</p>')).toEqual('<p>Hello &lt; World</p>');\n", " t.expect(sanitizeHtml('<p>Hello < World</p>')).toEqual('<p>Hello &lt; World</p>');\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " t.it('supports sanitizing escaped entities', () => {\n", " t.expect(sanitizeHtml('&#128640;')).toEqual('&#128640;');\n", " t.expect(logMsgs).toEqual([]);\n", " });\n" ], "file_path": "modules/@angular/platform-browser/test/security/html_sanitizer_spec.ts", "type": "add", "edit_start_line_idx": 53 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {CompilerConfig} from '@angular/compiler/src/config'; import {AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, ChangeDetectionStrategy, Component, Directive, DoCheck, Injectable, OnChanges, OnDestroy, OnInit, SimpleChanges, ViewEncapsulation} from '@angular/core'; import {LIFECYCLE_HOOKS_VALUES} from '@angular/core/src/metadata/lifecycle_hooks'; import {afterEach, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal'; import {IS_DART, stringify} from '../src/facade/lang'; import {CompileMetadataResolver} from '../src/metadata_resolver'; import {MalformedStylesComponent} from './metadata_resolver_fixture'; import {TEST_PROVIDERS} from './test_bindings'; export function main() { describe('CompileMetadataResolver', () => { beforeEachProviders(() => TEST_PROVIDERS); describe('getMetadata', () => { it('should read metadata', inject([CompileMetadataResolver], (resolver: CompileMetadataResolver) => { var meta = resolver.getDirectiveMetadata(ComponentWithEverything); expect(meta.selector).toEqual('someSelector'); expect(meta.exportAs).toEqual('someExportAs'); expect(meta.isComponent).toBe(true); expect(meta.type.runtime).toBe(ComponentWithEverything); expect(meta.type.name).toEqual(stringify(ComponentWithEverything)); expect(meta.lifecycleHooks).toEqual(LIFECYCLE_HOOKS_VALUES); expect(meta.changeDetection).toBe(ChangeDetectionStrategy.CheckAlways); expect(meta.inputs).toEqual({'someProp': 'someProp'}); expect(meta.outputs).toEqual({'someEvent': 'someEvent'}); expect(meta.hostListeners).toEqual({'someHostListener': 'someHostListenerExpr'}); expect(meta.hostProperties).toEqual({'someHostProp': 'someHostPropExpr'}); expect(meta.hostAttributes).toEqual({'someHostAttr': 'someHostAttrValue'}); expect(meta.template.encapsulation).toBe(ViewEncapsulation.Emulated); expect(meta.template.styles).toEqual(['someStyle']); expect(meta.template.styleUrls).toEqual(['someStyleUrl']); expect(meta.template.template).toEqual('someTemplate'); expect(meta.template.templateUrl).toEqual('someTemplateUrl'); expect(meta.template.interpolation).toEqual(['{{', '}}']); })); it('should use the moduleUrl from the reflector if none is given', inject([CompileMetadataResolver], (resolver: CompileMetadataResolver) => { var value: string = resolver.getDirectiveMetadata(ComponentWithoutModuleId).type.moduleUrl; var expectedEndValue = IS_DART ? 'test/compiler/metadata_resolver_spec.dart' : './ComponentWithoutModuleId'; expect(value.endsWith(expectedEndValue)).toBe(true); })); it('should throw when metadata is incorrectly typed', inject([CompileMetadataResolver], (resolver: CompileMetadataResolver) => { expect(() => resolver.getDirectiveMetadata(MalformedStylesComponent)) .toThrowError(`Expected 'styles' to be an array of strings.`); })); it('should throw with descriptive error message when provider token can not be resolved', inject([CompileMetadataResolver], (resolver: CompileMetadataResolver) => { expect(() => resolver.getDirectiveMetadata(MyBrokenComp1)) .toThrowError(`Can't resolve all parameters for MyBrokenComp1: (?).`); })); it('should throw with descriptive error message when a param token of a dependency is undefined', inject([CompileMetadataResolver], (resolver: CompileMetadataResolver) => { expect(() => resolver.getDirectiveMetadata(MyBrokenComp2)) .toThrowError(`Can't resolve all parameters for NonAnnotatedService: (?).`); })); it('should throw with descriptive error message when one of providers is not present', inject([CompileMetadataResolver], (resolver: CompileMetadataResolver) => { expect(() => resolver.getDirectiveMetadata(MyBrokenComp3)) .toThrowError( `One or more of providers for "MyBrokenComp3" were not defined: [?, SimpleService, ?].`); })); it('should throw with descriptive error message when one of viewProviders is not present', inject([CompileMetadataResolver], (resolver: CompileMetadataResolver) => { expect(() => resolver.getDirectiveMetadata(MyBrokenComp4)) .toThrowError( `One or more of viewProviders for "MyBrokenComp4" were not defined: [?, SimpleService, ?].`); })); it('should throw an error when the interpolation config has invalid symbols', inject([CompileMetadataResolver], (resolver: CompileMetadataResolver) => { expect(() => resolver.getDirectiveMetadata(ComponentWithInvalidInterpolation1)) .toThrowError(`[' ', ' '] contains unusable interpolation symbol.`); expect(() => resolver.getDirectiveMetadata(ComponentWithInvalidInterpolation2)) .toThrowError(`['{', '}'] contains unusable interpolation symbol.`); expect(() => resolver.getDirectiveMetadata(ComponentWithInvalidInterpolation3)) .toThrowError(`['<%', '%>'] contains unusable interpolation symbol.`); expect(() => resolver.getDirectiveMetadata(ComponentWithInvalidInterpolation4)) .toThrowError(`['&#', '}}'] contains unusable interpolation symbol.`); expect(() => resolver.getDirectiveMetadata(ComponentWithInvalidInterpolation5)) .toThrowError(`['&lbrace;', '}}'] contains unusable interpolation symbol.`); })); }); describe('getViewDirectivesMetadata', () => { it('should return the directive metadatas', inject([CompileMetadataResolver], (resolver: CompileMetadataResolver) => { expect(resolver.getViewDirectivesMetadata(ComponentWithEverything)) .toContain(resolver.getDirectiveMetadata(SomeDirective)); })); describe('platform directives', () => { beforeEachProviders(() => [{ provide: CompilerConfig, useValue: new CompilerConfig( {genDebugInfo: true, platformDirectives: [ADirective]}) }]); it('should include platform directives when available', inject([CompileMetadataResolver], (resolver: CompileMetadataResolver) => { expect(resolver.getViewDirectivesMetadata(ComponentWithEverything)) .toContain(resolver.getDirectiveMetadata(ADirective)); expect(resolver.getViewDirectivesMetadata(ComponentWithEverything)) .toContain(resolver.getDirectiveMetadata(SomeDirective)); })); }); }); }); } @Directive({selector: 'a-directive'}) class ADirective { } @Directive({selector: 'someSelector'}) class SomeDirective { } @Component({selector: 'someComponent', template: ''}) class ComponentWithoutModuleId { } @Component({ selector: 'someSelector', inputs: ['someProp'], outputs: ['someEvent'], host: { '[someHostProp]': 'someHostPropExpr', '(someHostListener)': 'someHostListenerExpr', 'someHostAttr': 'someHostAttrValue' }, exportAs: 'someExportAs', moduleId: 'someModuleId', changeDetection: ChangeDetectionStrategy.CheckAlways, template: 'someTemplate', templateUrl: 'someTemplateUrl', encapsulation: ViewEncapsulation.Emulated, styles: ['someStyle'], styleUrls: ['someStyleUrl'], directives: [SomeDirective], interpolation: ['{{', '}}'] }) class ComponentWithEverything implements OnChanges, OnInit, DoCheck, OnDestroy, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked { ngOnChanges(changes: SimpleChanges): void {} ngOnInit(): void {} ngDoCheck(): void {} ngOnDestroy(): void {} ngAfterContentInit(): void {} ngAfterContentChecked(): void {} ngAfterViewInit(): void {} ngAfterViewChecked(): void {} } @Component({selector: 'my-broken-comp', template: ''}) class MyBrokenComp1 { constructor(public dependency: any) {} } class NonAnnotatedService { constructor(dep: any) {} } @Component({selector: 'my-broken-comp', template: '', providers: [NonAnnotatedService]}) class MyBrokenComp2 { constructor(dependency: NonAnnotatedService) {} } @Injectable() class SimpleService { } @Component({selector: 'my-broken-comp', template: '', providers: [null, SimpleService, [null]]}) class MyBrokenComp3 { } @Component({selector: 'my-broken-comp', template: '', viewProviders: [null, SimpleService, [null]]}) class MyBrokenComp4 { } @Component({selector: 'someSelector', template: '', interpolation: [' ', ' ']}) class ComponentWithInvalidInterpolation1 { } @Component({selector: 'someSelector', template: '', interpolation: ['{', '}']}) class ComponentWithInvalidInterpolation2 { } @Component({selector: 'someSelector', template: '', interpolation: ['<%', '%>']}) class ComponentWithInvalidInterpolation3 { } @Component({selector: 'someSelector', template: '', interpolation: ['&#', '}}']}) class ComponentWithInvalidInterpolation4 { } @Component({selector: 'someSelector', template: '', interpolation: ['&lbrace;', '}}']}) class ComponentWithInvalidInterpolation5 { }
modules/@angular/compiler/test/metadata_resolver_spec.ts
0
https://github.com/angular/angular/commit/98cef76931f1417c21bfaf8cbbdb3768a4b85fb5
[ 0.00017853171448223293, 0.00017415526963304728, 0.00016457762103527784, 0.00017488034791313112, 0.0000028240467599971453 ]
{ "id": 4, "code_window": [ " t.expect(sanitizeHtml('<?pi nodes?>no.')).toEqual('no.');\n", " t.expect(logMsgs.join('\\n')).toMatch(/sanitizing HTML stripped some content/);\n", " });\n", " t.it('escapes entities', () => {\n", " t.expect(sanitizeHtml('<p>Hello &lt; World</p>')).toEqual('<p>Hello &lt; World</p>');\n", " t.expect(sanitizeHtml('<p>Hello < World</p>')).toEqual('<p>Hello &lt; World</p>');\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " t.it('supports sanitizing escaped entities', () => {\n", " t.expect(sanitizeHtml('&#128640;')).toEqual('&#128640;');\n", " t.expect(logMsgs).toEqual([]);\n", " });\n" ], "file_path": "modules/@angular/platform-browser/test/security/html_sanitizer_spec.ts", "type": "add", "edit_start_line_idx": 53 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {AbstractControl} from '../model'; import {AsyncValidatorFn, Validator, ValidatorFn} from './validators'; export function normalizeValidator(validator: ValidatorFn | Validator): ValidatorFn { if ((<Validator>validator).validate !== undefined) { return (c: AbstractControl) => (<Validator>validator).validate(c); } else { return <ValidatorFn>validator; } } export function normalizeAsyncValidator(validator: AsyncValidatorFn | Validator): AsyncValidatorFn { if ((<Validator>validator).validate !== undefined) { return (c: AbstractControl) => Promise.resolve((<Validator>validator).validate(c)); } else { return <AsyncValidatorFn>validator; } }
modules/@angular/forms/src/directives/normalize_validator.ts
0
https://github.com/angular/angular/commit/98cef76931f1417c21bfaf8cbbdb3768a4b85fb5
[ 0.00032457479392178357, 0.00022054857981856912, 0.00016181835962925106, 0.00017525258590467274, 0.0000737618247512728 ]
{ "id": 4, "code_window": [ " t.expect(sanitizeHtml('<?pi nodes?>no.')).toEqual('no.');\n", " t.expect(logMsgs.join('\\n')).toMatch(/sanitizing HTML stripped some content/);\n", " });\n", " t.it('escapes entities', () => {\n", " t.expect(sanitizeHtml('<p>Hello &lt; World</p>')).toEqual('<p>Hello &lt; World</p>');\n", " t.expect(sanitizeHtml('<p>Hello < World</p>')).toEqual('<p>Hello &lt; World</p>');\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " t.it('supports sanitizing escaped entities', () => {\n", " t.expect(sanitizeHtml('&#128640;')).toEqual('&#128640;');\n", " t.expect(logMsgs).toEqual([]);\n", " });\n" ], "file_path": "modules/@angular/platform-browser/test/security/html_sanitizer_spec.ts", "type": "add", "edit_start_line_idx": 53 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ListWrapper, StringMapWrapper} from '../facade/collection'; import {isArray, isPresent} from '../facade/lang'; import {FILL_STYLE_FLAG} from './animation_constants'; import {AUTO_STYLE} from './metadata'; export function prepareFinalAnimationStyles( previousStyles: {[key: string]: string | number}, newStyles: {[key: string]: string | number}, nullValue: string = null): {[key: string]: string} { var finalStyles: {[key: string]: string} = {}; StringMapWrapper.forEach(newStyles, (value: string, prop: string) => { finalStyles[prop] = value == AUTO_STYLE ? nullValue : value.toString(); }); StringMapWrapper.forEach(previousStyles, (value: string, prop: string) => { if (!isPresent(finalStyles[prop])) { finalStyles[prop] = nullValue; } }); return finalStyles; } export function balanceAnimationKeyframes( collectedStyles: {[key: string]: string | number}, finalStateStyles: {[key: string]: string | number}, keyframes: any[]): any[] { var limit = keyframes.length - 1; var firstKeyframe = keyframes[0]; // phase 1: copy all the styles from the first keyframe into the lookup map var flatenedFirstKeyframeStyles = flattenStyles(firstKeyframe.styles.styles); var extraFirstKeyframeStyles: {[key: string]: string} = {}; var hasExtraFirstStyles = false; StringMapWrapper.forEach(collectedStyles, (value: string, prop: string) => { // if the style is already defined in the first keyframe then // we do not replace it. if (!flatenedFirstKeyframeStyles[prop]) { flatenedFirstKeyframeStyles[prop] = value; extraFirstKeyframeStyles[prop] = value; hasExtraFirstStyles = true; } }); var keyframeCollectedStyles = StringMapWrapper.merge({}, flatenedFirstKeyframeStyles); // phase 2: normalize the final keyframe var finalKeyframe = keyframes[limit]; ListWrapper.insert(finalKeyframe.styles.styles, 0, finalStateStyles); var flatenedFinalKeyframeStyles = flattenStyles(finalKeyframe.styles.styles); var extraFinalKeyframeStyles: {[key: string]: string} = {}; var hasExtraFinalStyles = false; StringMapWrapper.forEach(keyframeCollectedStyles, (value: string, prop: string) => { if (!isPresent(flatenedFinalKeyframeStyles[prop])) { extraFinalKeyframeStyles[prop] = AUTO_STYLE; hasExtraFinalStyles = true; } }); if (hasExtraFinalStyles) { finalKeyframe.styles.styles.push(extraFinalKeyframeStyles); } StringMapWrapper.forEach(flatenedFinalKeyframeStyles, (value: string, prop: string) => { if (!isPresent(flatenedFirstKeyframeStyles[prop])) { extraFirstKeyframeStyles[prop] = AUTO_STYLE; hasExtraFirstStyles = true; } }); if (hasExtraFirstStyles) { firstKeyframe.styles.styles.push(extraFirstKeyframeStyles); } return keyframes; } export function clearStyles(styles: {[key: string]: string | number}): {[key: string]: string} { var finalStyles: {[key: string]: string} = {}; StringMapWrapper.keys(styles).forEach(key => { finalStyles[key] = null; }); return finalStyles; } export function collectAndResolveStyles( collection: {[key: string]: string | number}, styles: {[key: string]: string | number}[]) { return styles.map(entry => { var stylesObj: {[key: string]: string | number} = {}; StringMapWrapper.forEach(entry, (value: string | number, prop: string) => { if (value == FILL_STYLE_FLAG) { value = collection[prop]; if (!isPresent(value)) { value = AUTO_STYLE; } } collection[prop] = value; stylesObj[prop] = value; }); return stylesObj; }); } export function renderStyles( element: any, renderer: any, styles: {[key: string]: string | number}): void { StringMapWrapper.forEach( styles, (value: string, prop: string) => { renderer.setElementStyle(element, prop, value); }); } export function flattenStyles(styles: {[key: string]: string | number}[]): {[key: string]: string} { var finalStyles: {[key: string]: string} = {}; styles.forEach(entry => { StringMapWrapper.forEach( entry, (value: string, prop: string) => { finalStyles[prop] = value; }); }); return finalStyles; }
modules/@angular/core/src/animation/animation_style_util.ts
0
https://github.com/angular/angular/commit/98cef76931f1417c21bfaf8cbbdb3768a4b85fb5
[ 0.00017782498616725206, 0.0001732339442241937, 0.00016894456348381937, 0.00017333361029159278, 0.0000025011272555275355 ]
{ "id": 0, "code_window": [ "} from '../utils'\n", "import { toAbsoluteGlob } from './importMetaGlob'\n", "import { hasViteIgnoreRE } from './importAnalysis'\n", "\n", "export const dynamicImportHelperId = '\\0vite/dynamic-import-helper'\n", "\n", "const relativePathRE = /^\\.{1,2}\\//\n", "// fast path to check if source contains a dynamic import. we check for a\n", "// trailing slash too as a dynamic import statement can have comments between\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const dynamicImportHelperId = '\\0vite/dynamic-import-helper.js'\n" ], "file_path": "packages/vite/src/node/plugins/dynamicImportVars.ts", "type": "replace", "edit_start_line_idx": 21 }
import { posix } from 'node:path' import MagicString from 'magic-string' import { init, parse as parseImports } from 'es-module-lexer' import type { ImportSpecifier } from 'es-module-lexer' import { parse as parseJS } from 'acorn' import { dynamicImportToGlob } from '@rollup/plugin-dynamic-import-vars' import type { KnownAsTypeMap } from 'types/importGlob' import type { Plugin } from '../plugin' import type { ResolvedConfig } from '../config' import { CLIENT_ENTRY } from '../constants' import { createFilter, normalizePath, parseRequest, removeComments, requestQuerySplitRE, transformStableResult, } from '../utils' import { toAbsoluteGlob } from './importMetaGlob' import { hasViteIgnoreRE } from './importAnalysis' export const dynamicImportHelperId = '\0vite/dynamic-import-helper' const relativePathRE = /^\.{1,2}\// // fast path to check if source contains a dynamic import. we check for a // trailing slash too as a dynamic import statement can have comments between // the `import` and the `(`. const hasDynamicImportRE = /\bimport\s*[(/]/ interface DynamicImportRequest { as?: keyof KnownAsTypeMap } interface DynamicImportPattern { globParams: DynamicImportRequest | null userPattern: string rawPattern: string } const dynamicImportHelper = (glob: Record<string, any>, path: string) => { const v = glob[path] if (v) { return typeof v === 'function' ? v() : Promise.resolve(v) } return new Promise((_, reject) => { ;(typeof queueMicrotask === 'function' ? queueMicrotask : setTimeout)( reject.bind(null, new Error('Unknown variable dynamic import: ' + path)), ) }) } function parseDynamicImportPattern( strings: string, ): DynamicImportPattern | null { const filename = strings.slice(1, -1) const rawQuery = parseRequest(filename) let globParams: DynamicImportRequest | null = null const ast = ( parseJS(strings, { ecmaVersion: 'latest', sourceType: 'module', }) as any ).body[0].expression const userPatternQuery = dynamicImportToGlob(ast, filename) if (!userPatternQuery) { return null } const [userPattern] = userPatternQuery.split(requestQuerySplitRE, 2) const [rawPattern] = filename.split(requestQuerySplitRE, 2) if (rawQuery?.raw !== undefined) { globParams = { as: 'raw' } } if (rawQuery?.url !== undefined) { globParams = { as: 'url' } } if (rawQuery?.worker !== undefined) { globParams = { as: 'worker' } } return { globParams, userPattern, rawPattern, } } export async function transformDynamicImport( importSource: string, importer: string, resolve: ( url: string, importer?: string, ) => Promise<string | undefined> | string | undefined, root: string, ): Promise<{ glob: string pattern: string rawPattern: string } | null> { if (importSource[1] !== '.' && importSource[1] !== '/') { const resolvedFileName = await resolve(importSource.slice(1, -1), importer) if (!resolvedFileName) { return null } const relativeFileName = posix.relative( posix.dirname(normalizePath(importer)), normalizePath(resolvedFileName), ) importSource = normalizePath( '`' + (relativeFileName[0] === '.' ? '' : './') + relativeFileName + '`', ) } const dynamicImportPattern = parseDynamicImportPattern(importSource) if (!dynamicImportPattern) { return null } const { globParams, rawPattern, userPattern } = dynamicImportPattern const params = globParams ? `, ${JSON.stringify({ ...globParams, import: '*' })}` : '' let newRawPattern = posix.relative( posix.dirname(importer), await toAbsoluteGlob(rawPattern, root, importer, resolve), ) if (!relativePathRE.test(newRawPattern)) { newRawPattern = `./${newRawPattern}` } const exp = `(import.meta.glob(${JSON.stringify(userPattern)}${params}))` return { rawPattern: newRawPattern, pattern: userPattern, glob: exp, } } export function dynamicImportVarsPlugin(config: ResolvedConfig): Plugin { const resolve = config.createResolver({ preferRelative: true, tryIndex: false, extensions: [], }) const { include, exclude, warnOnError } = config.build.dynamicImportVarsOptions const filter = createFilter(include, exclude) return { name: 'vite:dynamic-import-vars', resolveId(id) { if (id === dynamicImportHelperId) { return id } }, load(id) { if (id === dynamicImportHelperId) { return 'export default ' + dynamicImportHelper.toString() } }, async transform(source, importer) { if ( !filter(importer) || importer === CLIENT_ENTRY || !hasDynamicImportRE.test(source) ) { return } await init let imports: readonly ImportSpecifier[] = [] try { imports = parseImports(source)[0] } catch (e: any) { // ignore as it might not be a JS file, the subsequent plugins will catch the error return null } if (!imports.length) { return null } let s: MagicString | undefined let needDynamicImportHelper = false for (let index = 0; index < imports.length; index++) { const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, } = imports[index] if (dynamicIndex === -1 || source[start] !== '`') { continue } if (hasViteIgnoreRE.test(source.slice(expStart, expEnd))) { continue } s ||= new MagicString(source) let result try { // When import string is using backticks, es-module-lexer `end` captures // until the closing parenthesis, instead of the closing backtick. // There may be inline comments between the backtick and the closing // parenthesis, so we manually remove them for now. // See https://github.com/guybedford/es-module-lexer/issues/118 const importSource = removeComments(source.slice(start, end)).trim() result = await transformDynamicImport( importSource, importer, resolve, config.root, ) } catch (error) { if (warnOnError) { this.warn(error) } else { this.error(error) } } if (!result) { continue } const { rawPattern, glob } = result needDynamicImportHelper = true s.overwrite( expStart, expEnd, `__variableDynamicImportRuntimeHelper(${glob}, \`${rawPattern}\`)`, ) } if (s) { if (needDynamicImportHelper) { s.prepend( `import __variableDynamicImportRuntimeHelper from "${dynamicImportHelperId}";`, ) } return transformStableResult(s, importer, config) } }, } }
packages/vite/src/node/plugins/dynamicImportVars.ts
1
https://github.com/vitejs/vite/commit/9594c7021bba606ab423fc9e18d638615a111360
[ 0.9992331266403198, 0.2185889482498169, 0.00016873575805220753, 0.002445791382342577, 0.39425531029701233 ]
{ "id": 0, "code_window": [ "} from '../utils'\n", "import { toAbsoluteGlob } from './importMetaGlob'\n", "import { hasViteIgnoreRE } from './importAnalysis'\n", "\n", "export const dynamicImportHelperId = '\\0vite/dynamic-import-helper'\n", "\n", "const relativePathRE = /^\\.{1,2}\\//\n", "// fast path to check if source contains a dynamic import. we check for a\n", "// trailing slash too as a dynamic import statement can have comments between\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const dynamicImportHelperId = '\\0vite/dynamic-import-helper.js'\n" ], "file_path": "packages/vite/src/node/plugins/dynamicImportVars.ts", "type": "replace", "edit_start_line_idx": 21 }
# Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw?
packages/create-vite/template-qwik-ts/_gitignore
0
https://github.com/vitejs/vite/commit/9594c7021bba606ab423fc9e18d638615a111360
[ 0.00017056138312909752, 0.00017031060997396708, 0.00017017035861499608, 0.00017020005907397717, 1.7774431171346805e-7 ]
{ "id": 0, "code_window": [ "} from '../utils'\n", "import { toAbsoluteGlob } from './importMetaGlob'\n", "import { hasViteIgnoreRE } from './importAnalysis'\n", "\n", "export const dynamicImportHelperId = '\\0vite/dynamic-import-helper'\n", "\n", "const relativePathRE = /^\\.{1,2}\\//\n", "// fast path to check if source contains a dynamic import. we check for a\n", "// trailing slash too as a dynamic import statement can have comments between\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const dynamicImportHelperId = '\\0vite/dynamic-import-helper.js'\n" ], "file_path": "packages/vite/src/node/plugins/dynamicImportVars.ts", "type": "replace", "edit_start_line_idx": 21 }
import a22 from './a22' import a23 from './a23' import a24 from './a24' export const that = () => import('./a20.js') export function other() { return a22() + a23() + a24() } export default function () { return 123 }
playground/multiple-entrypoints/entrypoints/a21.js
0
https://github.com/vitejs/vite/commit/9594c7021bba606ab423fc9e18d638615a111360
[ 0.000294376426609233, 0.00023193698143586516, 0.00016949752171058208, 0.00023193698143586516, 0.00006243945244932547 ]
{ "id": 0, "code_window": [ "} from '../utils'\n", "import { toAbsoluteGlob } from './importMetaGlob'\n", "import { hasViteIgnoreRE } from './importAnalysis'\n", "\n", "export const dynamicImportHelperId = '\\0vite/dynamic-import-helper'\n", "\n", "const relativePathRE = /^\\.{1,2}\\//\n", "// fast path to check if source contains a dynamic import. we check for a\n", "// trailing slash too as a dynamic import statement can have comments between\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const dynamicImportHelperId = '\\0vite/dynamic-import-helper.js'\n" ], "file_path": "packages/vite/src/node/plugins/dynamicImportVars.ts", "type": "replace", "edit_start_line_idx": 21 }
import fs from 'node:fs' import path from 'node:path' import { describe, expect, test, vi } from 'vitest' import { resolveConfig } from '../../config' import type { InlineConfig } from '../../config' import { convertTargets, cssPlugin, cssUrlRE, hoistAtRules, } from '../../plugins/css' describe('search css url function', () => { test('some spaces before it', () => { expect( cssUrlRE.test("list-style-image: url('../images/bullet.jpg');"), ).toBe(true) }) test('no space after colon', () => { expect(cssUrlRE.test("list-style-image:url('../images/bullet.jpg');")).toBe( true, ) }) test('at the beginning of line', () => { expect(cssUrlRE.test("url('../images/bullet.jpg');")).toBe(true) }) test('as suffix of a function name', () => { expect( cssUrlRE.test(`@function svg-url($string) { @return ""; }`), ).toBe(false) }) test('after parenthesis', () => { expect( cssUrlRE.test( 'mask-image: image(url(mask.png), skyblue, linear-gradient(rgba(0, 0, 0, 1.0), transparent));', ), ).toBe(true) }) test('after comma', () => { expect( cssUrlRE.test( 'mask-image: image(skyblue,url(mask.png), linear-gradient(rgba(0, 0, 0, 1.0), transparent));', ), ).toBe(true) }) }) describe('css modules', () => { test('css module compose/from path resolutions', async () => { const mockedProjectPath = path.join(process.cwd(), '/foo/bar/project') const { transform, resetMock } = await createCssPluginTransform( { [path.join(mockedProjectPath, '/css/bar.module.css')]: `\ .bar { display: block; background: #f0f; }`, }, { resolve: { alias: [ { find: '@', replacement: mockedProjectPath, }, ], }, }, ) const result = await transform( `\ .foo { position: fixed; composes: bar from '@/css/bar.module.css'; }`, '/css/foo.module.css', ) expect(result.code).toBe( `\ ._bar_1csqm_1 { display: block; background: #f0f; } ._foo_86148_1 { position: fixed; }`, ) resetMock() }) test('custom generateScopedName', async () => { const { transform, resetMock } = await createCssPluginTransform(undefined, { css: { modules: { generateScopedName: 'custom__[hash:base64:5]', }, }, }) const css = `\ .foo { color: red; }` const result1 = await transform(css, '/foo.module.css') // server const result2 = await transform(css, '/foo.module.css?direct') // client expect(result1.code).toBe(result2.code) resetMock() }) }) describe('hoist @ rules', () => { test('hoist @import', async () => { const css = `.foo{color:red;}@import "bla";` const result = await hoistAtRules(css) expect(result).toBe(`@import "bla";.foo{color:red;}`) }) test('hoist @import url with semicolon', async () => { const css = `.foo{color:red;}@import url("bla;bla");` const result = await hoistAtRules(css) expect(result).toBe(`@import url("bla;bla");.foo{color:red;}`) }) test('hoist @import url data with semicolon', async () => { const css = `.foo{color:red;}@import url(data:image/png;base64,iRxVB0);` const result = await hoistAtRules(css) expect(result).toBe( `@import url(data:image/png;base64,iRxVB0);.foo{color:red;}`, ) }) test('hoist @import with semicolon in quotes', async () => { const css = `.foo{color:red;}@import "bla;bar";` const result = await hoistAtRules(css) expect(result).toBe(`@import "bla;bar";.foo{color:red;}`) }) test('hoist @charset', async () => { const css = `.foo{color:red;}@charset "utf-8";` const result = await hoistAtRules(css) expect(result).toBe(`@charset "utf-8";.foo{color:red;}`) }) test('hoist one @charset only', async () => { const css = `.foo{color:red;}@charset "utf-8";@charset "utf-8";` const result = await hoistAtRules(css) expect(result).toBe(`@charset "utf-8";.foo{color:red;}`) }) test('hoist @import and @charset', async () => { const css = `.foo{color:red;}@import "bla";@charset "utf-8";.bar{color:green;}@import "baz";` const result = await hoistAtRules(css) expect(result).toBe( `@charset "utf-8";@import "bla";@import "baz";.foo{color:red;}.bar{color:green;}`, ) }) test('dont hoist @import in comments', async () => { const css = `.foo{color:red;}/* @import "bla"; */@import "bar";` const result = await hoistAtRules(css) expect(result).toBe(`@import "bar";.foo{color:red;}/* @import "bla"; */`) }) test('dont hoist @charset in comments', async () => { const css = `.foo{color:red;}/* @charset "utf-8"; */@charset "utf-8";` const result = await hoistAtRules(css) expect(result).toBe( `@charset "utf-8";.foo{color:red;}/* @charset "utf-8"; */`, ) }) test('dont hoist @import and @charset in comments', async () => { const css = ` .foo{color:red;} /* @import "bla"; */ @charset "utf-8"; /* @charset "utf-8"; @import "bar"; */ @import "baz";` const result = await hoistAtRules(css) expect(result).toMatchInlineSnapshot(` "@charset \\"utf-8\\";@import \\"baz\\"; .foo{color:red;} /* @import \\"bla\\"; */ /* @charset \\"utf-8\\"; @import \\"bar\\"; */ " `) }) }) async function createCssPluginTransform( files?: Record<string, string>, inlineConfig: InlineConfig = {}, ) { const config = await resolveConfig(inlineConfig, 'serve') const { transform, buildStart } = cssPlugin(config) // @ts-expect-error buildStart is function await buildStart.call({}) const mockFs = vi .spyOn(fs, 'readFile') // @ts-expect-error vi.spyOn not recognize override `fs.readFile` definition. .mockImplementationOnce((p, encoding, callback) => { callback(null, Buffer.from(files?.[p] ?? '')) }) return { async transform(code: string, id: string) { // @ts-expect-error transform is function return await transform.call( { addWatchFile() { return }, }, code, id, ) }, resetMock() { mockFs.mockReset() }, } } describe('convertTargets', () => { test('basic cases', () => { expect(convertTargets('es2018')).toStrictEqual({ chrome: 4128768, edge: 5177344, firefox: 3801088, safari: 786432, opera: 3276800, }) expect(convertTargets(['safari13.1', 'ios13', 'node14'])).toStrictEqual({ ios_saf: 851968, safari: 852224, }) }) })
packages/vite/src/node/__tests__/plugins/css.spec.ts
0
https://github.com/vitejs/vite/commit/9594c7021bba606ab423fc9e18d638615a111360
[ 0.0001785041531547904, 0.00017348800611216575, 0.00016711503849364817, 0.00017286914226133376, 0.000003286553919679136 ]
{ "id": 1, "code_window": [ "export const preloadMarker = `__VITE_PRELOAD__`\n", "export const preloadBaseMarker = `__VITE_PRELOAD_BASE__`\n", "\n", "export const preloadHelperId = '\\0vite/preload-helper'\n", "const preloadMarkerWithQuote = new RegExp(`['\"]${preloadMarker}['\"]`)\n", "\n", "const dynamicImportPrefixRE = /import\\s*\\(/\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const preloadHelperId = '\\0vite/preload-helper.js'\n" ], "file_path": "packages/vite/src/node/plugins/importAnalysisBuild.ts", "type": "replace", "edit_start_line_idx": 40 }
import type { ResolvedConfig } from '../config' import type { Plugin } from '../plugin' import { fileToUrl } from './asset' const wasmHelperId = '\0vite/wasm-helper' const wasmHelper = async (opts = {}, url: string) => { let result if (url.startsWith('data:')) { const urlContent = url.replace(/^data:.*?base64,/, '') let bytes if (typeof Buffer === 'function' && typeof Buffer.from === 'function') { bytes = Buffer.from(urlContent, 'base64') } else if (typeof atob === 'function') { const binaryString = atob(urlContent) bytes = new Uint8Array(binaryString.length) for (let i = 0; i < binaryString.length; i++) { bytes[i] = binaryString.charCodeAt(i) } } else { throw new Error( 'Failed to decode base64-encoded data URL, Buffer and atob are not supported', ) } result = await WebAssembly.instantiate(bytes, opts) } else { // https://github.com/mdn/webassembly-examples/issues/5 // WebAssembly.instantiateStreaming requires the server to provide the // correct MIME type for .wasm files, which unfortunately doesn't work for // a lot of static file servers, so we just work around it by getting the // raw buffer. const response = await fetch(url) const contentType = response.headers.get('Content-Type') || '' if ( 'instantiateStreaming' in WebAssembly && contentType.startsWith('application/wasm') ) { result = await WebAssembly.instantiateStreaming(response, opts) } else { const buffer = await response.arrayBuffer() result = await WebAssembly.instantiate(buffer, opts) } } return result.instance } const wasmHelperCode = wasmHelper.toString() export const wasmHelperPlugin = (config: ResolvedConfig): Plugin => { return { name: 'vite:wasm-helper', resolveId(id) { if (id === wasmHelperId) { return id } }, async load(id) { if (id === wasmHelperId) { return `export default ${wasmHelperCode}` } if (!id.endsWith('.wasm?init')) { return } const url = await fileToUrl(id, config, this) return ` import initWasm from "${wasmHelperId}" export default opts => initWasm(opts, ${JSON.stringify(url)}) ` }, } } export const wasmFallbackPlugin = (): Plugin => { return { name: 'vite:wasm-fallback', async load(id) { if (!id.endsWith('.wasm')) { return } throw new Error( '"ESM integration proposal for Wasm" is not supported currently. ' + 'Use vite-plugin-wasm or other community plugins to handle this. ' + 'Alternatively, you can use `.wasm?init` or `.wasm?url`. ' + 'See https://vitejs.dev/guide/features.html#webassembly for more details.', ) }, } }
packages/vite/src/node/plugins/wasm.ts
1
https://github.com/vitejs/vite/commit/9594c7021bba606ab423fc9e18d638615a111360
[ 0.03298579528927803, 0.004632260650396347, 0.0001672431972110644, 0.00019789609359577298, 0.009666896425187588 ]
{ "id": 1, "code_window": [ "export const preloadMarker = `__VITE_PRELOAD__`\n", "export const preloadBaseMarker = `__VITE_PRELOAD_BASE__`\n", "\n", "export const preloadHelperId = '\\0vite/preload-helper'\n", "const preloadMarkerWithQuote = new RegExp(`['\"]${preloadMarker}['\"]`)\n", "\n", "const dynamicImportPrefixRE = /import\\s*\\(/\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const preloadHelperId = '\\0vite/preload-helper.js'\n" ], "file_path": "packages/vite/src/node/plugins/importAnalysisBuild.ts", "type": "replace", "edit_start_line_idx": 40 }
# Releases Vite releases follow [Semantic Versioning](https://semver.org/). You can see the latest stable version of Vite in the [Vite npm package page](https://www.npmjs.com/package/vite). A full changelog of past releases is [available on GitHub](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md). ::: tip note The next Vite Major release will happen after the Node 16 EOL in September. Check out the [Vite 5 discussion](https://github.com/vitejs/vite/discussions/12466) for more information. ::: ## Release Cycle​ Vite does not have a fixed release cycle. - **Patch** releases are released as needed. - **Minor** releases always contain new features and are also released as needed. Minor releases always go through a beta pre-release phase. - **Major** releases generally align with [Node.js EOL schedule](https://endoflife.date/nodejs), and will be announced ahead of time. These releases will go through an early discussion phase, and both alpha and beta pre-release phases. The previous Vite Major will keep receiving important fixes and security patches. After that, it would only get updates if there are security concerns. We recommend updating Vite regularly. Check out the [Migration Guides](https://vitejs.dev/guide/migration.html) when you update to each Major. The Vite team partners with the main projects in the ecosystem to test new Vite versions before they are released through the [vite-ecosystem-ci project](https://github.com/vitejs/vite-ecosystem-ci). Most projects using Vite should be able to quickly offer support or migrate to new versions as soon as they are released. ## Semantic Versioning Edge Cases ### TypeScript Definitions​ We may ship incompatible changes to TypeScript definitions between minor versions. This is because: - Sometimes TypeScript itself ships incompatible changes between minor versions, and we may have to adjust types to support newer versions of TypeScript. - Occasionally we may need to adopt features that are only available in a newer version of TypeScript, raising the minimum required version of TypeScript. - If you are using TypeScript, you can use a semver range that locks the current minor and manually upgrade when a new minor version of Vite is released. ### esbuild [esbuild](https://esbuild.github.io/) is pre-1.0.0 and sometimes it has a breaking change we may need to include to have access to newer features and performance improvements. We may bump the esbuild's version in a Vite Minor. ### Node.js non-LTS versions Non-LTS Node.js versions (odd-numbered) are not tested as part of Vite's CI, but they should still work before their [EOL](https://endoflife.date/nodejs). ## Pre Releases​ Minor releases typically go through a non-fixed number of beta releases. Major releases will go through an alpha phase and a beta phase. Pre-releases allow early adopters and maintainers from the Ecosystem to do integration and stability testing, and provide feedback. Do not use pre-releases in production. All pre-releases are considered unstable and may ship breaking changes in between. Always pin to exact versions when using pre-releases. ## Deprecations​ We periodically deprecate features that have been superseded by better alternatives in Minor releases. Deprecated features will continue to work with a type or logged warning. They will be removed in the next major release after entering deprecated status. The [Migration Guide](https://vitejs.dev/guide/migration.html) for each major will list these removals and document an upgrade path for them. ## Experimental Features​ Some features are marked as experimental when released in a stable version of Vite. Experimental features allows us to gather real-world experience to influence their final design. The goal is to let users provide feedback by testing them in production. Experimental features themselves are considered unstable, and should only be used in a controlled manner. These features may change between Minors, so users must pin their Vite version when they rely on them.
docs/releases.md
0
https://github.com/vitejs/vite/commit/9594c7021bba606ab423fc9e18d638615a111360
[ 0.00017147422477137297, 0.0001674191007623449, 0.00016144802793860435, 0.000168355560163036, 0.000003280182681919541 ]
{ "id": 1, "code_window": [ "export const preloadMarker = `__VITE_PRELOAD__`\n", "export const preloadBaseMarker = `__VITE_PRELOAD_BASE__`\n", "\n", "export const preloadHelperId = '\\0vite/preload-helper'\n", "const preloadMarkerWithQuote = new RegExp(`['\"]${preloadMarker}['\"]`)\n", "\n", "const dynamicImportPrefixRE = /import\\s*\\(/\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const preloadHelperId = '\\0vite/preload-helper.js'\n" ], "file_path": "packages/vite/src/node/plugins/importAnalysisBuild.ts", "type": "replace", "edit_start_line_idx": 40 }
name: Lock Closed Issues on: schedule: - cron: "0 0 * * *" permissions: issues: write jobs: action: if: github.repository == 'vitejs/vite' runs-on: ubuntu-latest steps: - uses: dessant/lock-threads@v4 with: github-token: ${{ secrets.GITHUB_TOKEN }} issue-inactive-days: "14" #issue-comment: | # This issue has been locked since it has been closed for more than 14 days. # # If you have found a concrete bug or regression related to it, please open a new [bug report](https://github.com/vitejs/vite/issues/new/choose) with a reproduction against the latest Vite version. If you have any other comments you should join the chat at [Vite Land](https://chat.vitejs.dev) or create a new [discussion](https://github.com/vitejs/vite/discussions). issue-lock-reason: "" process-only: "issues"
.github/workflows/lock-closed-issues.yml
0
https://github.com/vitejs/vite/commit/9594c7021bba606ab423fc9e18d638615a111360
[ 0.0001730558433337137, 0.00017203029710799456, 0.0001710330107016489, 0.0001720020081847906, 8.26060045255872e-7 ]
{ "id": 1, "code_window": [ "export const preloadMarker = `__VITE_PRELOAD__`\n", "export const preloadBaseMarker = `__VITE_PRELOAD_BASE__`\n", "\n", "export const preloadHelperId = '\\0vite/preload-helper'\n", "const preloadMarkerWithQuote = new RegExp(`['\"]${preloadMarker}['\"]`)\n", "\n", "const dynamicImportPrefixRE = /import\\s*\\(/\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const preloadHelperId = '\\0vite/preload-helper.js'\n" ], "file_path": "packages/vite/src/node/plugins/importAnalysisBuild.ts", "type": "replace", "edit_start_line_idx": 40 }
import path from 'node:path' import MagicString from 'magic-string' import { stripLiteral } from 'strip-literal' import type { Plugin } from '../plugin' import type { ResolvedConfig } from '../config' import type { ResolveFn } from '../' import { injectQuery, isParentDirectory, normalizePath, slash, transformStableResult, } from '../utils' import { CLIENT_ENTRY } from '../constants' import { fileToUrl } from './asset' import { preloadHelperId } from './importAnalysisBuild' import type { InternalResolveOptions } from './resolve' import { tryFsResolve } from './resolve' /** * Convert `new URL('./foo.png', import.meta.url)` to its resolved built URL * * Supports template string with dynamic segments: * ``` * new URL(`./dir/${name}.png`, import.meta.url) * // transformed to * import.meta.glob('./dir/**.png', { eager: true, import: 'default' })[`./dir/${name}.png`] * ``` */ export function assetImportMetaUrlPlugin(config: ResolvedConfig): Plugin { const normalizedPublicDir = normalizePath(config.publicDir) let assetResolver: ResolveFn const fsResolveOptions: InternalResolveOptions = { ...config.resolve, root: config.root, isProduction: config.isProduction, isBuild: config.command === 'build', packageCache: config.packageCache, ssrConfig: config.ssr, asSrc: true, } return { name: 'vite:asset-import-meta-url', async transform(code, id, options) { if ( !options?.ssr && id !== preloadHelperId && id !== CLIENT_ENTRY && code.includes('new URL') && code.includes(`import.meta.url`) ) { let s: MagicString | undefined const assetImportMetaUrlRE = /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\)/g const cleanString = stripLiteral(code) let match: RegExpExecArray | null while ((match = assetImportMetaUrlRE.exec(cleanString))) { const { 0: exp, 1: emptyUrl, index } = match const urlStart = cleanString.indexOf(emptyUrl, index) const urlEnd = urlStart + emptyUrl.length const rawUrl = code.slice(urlStart, urlEnd) if (!s) s = new MagicString(code) // potential dynamic template string if (rawUrl[0] === '`' && rawUrl.includes('${')) { const queryDelimiterIndex = getQueryDelimiterIndex(rawUrl) const hasQueryDelimiter = queryDelimiterIndex !== -1 const pureUrl = hasQueryDelimiter ? rawUrl.slice(0, queryDelimiterIndex) + '`' : rawUrl const queryString = hasQueryDelimiter ? rawUrl.slice(queryDelimiterIndex, -1) : '' const ast = this.parse(pureUrl) const templateLiteral = (ast as any).body[0].expression if (templateLiteral.expressions.length) { const pattern = buildGlobPattern(templateLiteral) if (pattern.startsWith('**')) { // don't transform for patterns like this // because users won't intend to do that in most cases continue } const globOptions = { eager: true, import: 'default', // A hack to allow 'as' & 'query' exist at the same time query: injectQuery(queryString, 'url'), } // Note: native import.meta.url is not supported in the baseline // target so we use the global location here. It can be // window.location or self.location in case it is used in a Web Worker. // @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self s.update( index, index + exp.length, `new URL((import.meta.glob(${JSON.stringify( pattern, )}, ${JSON.stringify( globOptions, )}))[${pureUrl}], self.location)`, ) continue } } const url = rawUrl.slice(1, -1) let file: string | undefined if (url[0] === '.') { file = slash(path.resolve(path.dirname(id), url)) file = tryFsResolve(file, fsResolveOptions) ?? file } else { assetResolver ??= config.createResolver({ extensions: [], mainFields: [], tryIndex: false, preferRelative: true, }) file = await assetResolver(url, id) file ??= url[0] === '/' ? slash(path.join(config.publicDir, url)) : slash(path.resolve(path.dirname(id), url)) } // Get final asset URL. If the file does not exist, // we fall back to the initial URL and let it resolve in runtime let builtUrl: string | undefined if (file) { try { if (isParentDirectory(normalizedPublicDir, file)) { const publicPath = '/' + path.posix.relative(normalizedPublicDir, file) builtUrl = await fileToUrl(publicPath, config, this) } else { builtUrl = await fileToUrl(file, config, this) } } catch { // do nothing, we'll log a warning after this } } if (!builtUrl) { const rawExp = code.slice(index, index + exp.length) config.logger.warnOnce( `\n${rawExp} doesn't exist at build time, it will remain unchanged to be resolved at runtime`, ) builtUrl = url } s.update( index, index + exp.length, `new URL(${JSON.stringify(builtUrl)}, self.location)`, ) } if (s) { return transformStableResult(s, id, config) } } return null }, } } function buildGlobPattern(ast: any) { let pattern = '' let lastElementIndex = -1 for (const exp of ast.expressions) { for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) { const el = ast.quasis[i] if (el.end < exp.start) { pattern += el.value.raw lastElementIndex = i } } pattern += '**' } for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) { pattern += ast.quasis[i].value.raw } return pattern } function getQueryDelimiterIndex(rawUrl: string): number { let bracketsStack = 0 for (let i = 0; i < rawUrl.length; i++) { if (rawUrl[i] === '{') { bracketsStack++ } else if (rawUrl[i] === '}') { bracketsStack-- } else if (rawUrl[i] === '?' && bracketsStack === 0) { return i } } return -1 }
packages/vite/src/node/plugins/assetImportMetaUrl.ts
0
https://github.com/vitejs/vite/commit/9594c7021bba606ab423fc9e18d638615a111360
[ 0.998637855052948, 0.0952497199177742, 0.0001655982923693955, 0.00017276417929679155, 0.29300522804260254 ]
{ "id": 2, "code_window": [ "import { isModernFlag } from './importAnalysisBuild'\n", "\n", "export const modulePreloadPolyfillId = 'vite/modulepreload-polyfill'\n", "const resolvedModulePreloadPolyfillId = '\\0' + modulePreloadPolyfillId\n", "\n", "export function modulePreloadPolyfillPlugin(config: ResolvedConfig): Plugin {\n", " // `isModernFlag` is only available during build since it is resolved by `vite:build-import-analysis`\n", " const skip = config.command !== 'build' || config.build.ssr\n", " let polyfillString: string | undefined\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const resolvedModulePreloadPolyfillId = '\\0' + modulePreloadPolyfillId + '.js'\n" ], "file_path": "packages/vite/src/node/plugins/modulePreloadPolyfill.ts", "type": "replace", "edit_start_line_idx": 5 }
import { posix } from 'node:path' import MagicString from 'magic-string' import { init, parse as parseImports } from 'es-module-lexer' import type { ImportSpecifier } from 'es-module-lexer' import { parse as parseJS } from 'acorn' import { dynamicImportToGlob } from '@rollup/plugin-dynamic-import-vars' import type { KnownAsTypeMap } from 'types/importGlob' import type { Plugin } from '../plugin' import type { ResolvedConfig } from '../config' import { CLIENT_ENTRY } from '../constants' import { createFilter, normalizePath, parseRequest, removeComments, requestQuerySplitRE, transformStableResult, } from '../utils' import { toAbsoluteGlob } from './importMetaGlob' import { hasViteIgnoreRE } from './importAnalysis' export const dynamicImportHelperId = '\0vite/dynamic-import-helper' const relativePathRE = /^\.{1,2}\// // fast path to check if source contains a dynamic import. we check for a // trailing slash too as a dynamic import statement can have comments between // the `import` and the `(`. const hasDynamicImportRE = /\bimport\s*[(/]/ interface DynamicImportRequest { as?: keyof KnownAsTypeMap } interface DynamicImportPattern { globParams: DynamicImportRequest | null userPattern: string rawPattern: string } const dynamicImportHelper = (glob: Record<string, any>, path: string) => { const v = glob[path] if (v) { return typeof v === 'function' ? v() : Promise.resolve(v) } return new Promise((_, reject) => { ;(typeof queueMicrotask === 'function' ? queueMicrotask : setTimeout)( reject.bind(null, new Error('Unknown variable dynamic import: ' + path)), ) }) } function parseDynamicImportPattern( strings: string, ): DynamicImportPattern | null { const filename = strings.slice(1, -1) const rawQuery = parseRequest(filename) let globParams: DynamicImportRequest | null = null const ast = ( parseJS(strings, { ecmaVersion: 'latest', sourceType: 'module', }) as any ).body[0].expression const userPatternQuery = dynamicImportToGlob(ast, filename) if (!userPatternQuery) { return null } const [userPattern] = userPatternQuery.split(requestQuerySplitRE, 2) const [rawPattern] = filename.split(requestQuerySplitRE, 2) if (rawQuery?.raw !== undefined) { globParams = { as: 'raw' } } if (rawQuery?.url !== undefined) { globParams = { as: 'url' } } if (rawQuery?.worker !== undefined) { globParams = { as: 'worker' } } return { globParams, userPattern, rawPattern, } } export async function transformDynamicImport( importSource: string, importer: string, resolve: ( url: string, importer?: string, ) => Promise<string | undefined> | string | undefined, root: string, ): Promise<{ glob: string pattern: string rawPattern: string } | null> { if (importSource[1] !== '.' && importSource[1] !== '/') { const resolvedFileName = await resolve(importSource.slice(1, -1), importer) if (!resolvedFileName) { return null } const relativeFileName = posix.relative( posix.dirname(normalizePath(importer)), normalizePath(resolvedFileName), ) importSource = normalizePath( '`' + (relativeFileName[0] === '.' ? '' : './') + relativeFileName + '`', ) } const dynamicImportPattern = parseDynamicImportPattern(importSource) if (!dynamicImportPattern) { return null } const { globParams, rawPattern, userPattern } = dynamicImportPattern const params = globParams ? `, ${JSON.stringify({ ...globParams, import: '*' })}` : '' let newRawPattern = posix.relative( posix.dirname(importer), await toAbsoluteGlob(rawPattern, root, importer, resolve), ) if (!relativePathRE.test(newRawPattern)) { newRawPattern = `./${newRawPattern}` } const exp = `(import.meta.glob(${JSON.stringify(userPattern)}${params}))` return { rawPattern: newRawPattern, pattern: userPattern, glob: exp, } } export function dynamicImportVarsPlugin(config: ResolvedConfig): Plugin { const resolve = config.createResolver({ preferRelative: true, tryIndex: false, extensions: [], }) const { include, exclude, warnOnError } = config.build.dynamicImportVarsOptions const filter = createFilter(include, exclude) return { name: 'vite:dynamic-import-vars', resolveId(id) { if (id === dynamicImportHelperId) { return id } }, load(id) { if (id === dynamicImportHelperId) { return 'export default ' + dynamicImportHelper.toString() } }, async transform(source, importer) { if ( !filter(importer) || importer === CLIENT_ENTRY || !hasDynamicImportRE.test(source) ) { return } await init let imports: readonly ImportSpecifier[] = [] try { imports = parseImports(source)[0] } catch (e: any) { // ignore as it might not be a JS file, the subsequent plugins will catch the error return null } if (!imports.length) { return null } let s: MagicString | undefined let needDynamicImportHelper = false for (let index = 0; index < imports.length; index++) { const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, } = imports[index] if (dynamicIndex === -1 || source[start] !== '`') { continue } if (hasViteIgnoreRE.test(source.slice(expStart, expEnd))) { continue } s ||= new MagicString(source) let result try { // When import string is using backticks, es-module-lexer `end` captures // until the closing parenthesis, instead of the closing backtick. // There may be inline comments between the backtick and the closing // parenthesis, so we manually remove them for now. // See https://github.com/guybedford/es-module-lexer/issues/118 const importSource = removeComments(source.slice(start, end)).trim() result = await transformDynamicImport( importSource, importer, resolve, config.root, ) } catch (error) { if (warnOnError) { this.warn(error) } else { this.error(error) } } if (!result) { continue } const { rawPattern, glob } = result needDynamicImportHelper = true s.overwrite( expStart, expEnd, `__variableDynamicImportRuntimeHelper(${glob}, \`${rawPattern}\`)`, ) } if (s) { if (needDynamicImportHelper) { s.prepend( `import __variableDynamicImportRuntimeHelper from "${dynamicImportHelperId}";`, ) } return transformStableResult(s, importer, config) } }, } }
packages/vite/src/node/plugins/dynamicImportVars.ts
1
https://github.com/vitejs/vite/commit/9594c7021bba606ab423fc9e18d638615a111360
[ 0.0004379570600576699, 0.00019195002096239477, 0.00016439144383184612, 0.0001717569975880906, 0.00006425265019061044 ]
{ "id": 2, "code_window": [ "import { isModernFlag } from './importAnalysisBuild'\n", "\n", "export const modulePreloadPolyfillId = 'vite/modulepreload-polyfill'\n", "const resolvedModulePreloadPolyfillId = '\\0' + modulePreloadPolyfillId\n", "\n", "export function modulePreloadPolyfillPlugin(config: ResolvedConfig): Plugin {\n", " // `isModernFlag` is only available during build since it is resolved by `vite:build-import-analysis`\n", " const skip = config.command !== 'build' || config.build.ssr\n", " let polyfillString: string | undefined\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const resolvedModulePreloadPolyfillId = '\\0' + modulePreloadPolyfillId + '.js'\n" ], "file_path": "packages/vite/src/node/plugins/modulePreloadPolyfill.ts", "type": "replace", "edit_start_line_idx": 5 }
module.exports = { defined: __STRINGIFIED_OBJ__, importMetaEnvUndefined: 'import.meta.env.UNDEFINED', processEnvUndefined: 'process.env.UNDEFINED', }
playground/define/commonjs-dep/index.js
0
https://github.com/vitejs/vite/commit/9594c7021bba606ab423fc9e18d638615a111360
[ 0.00017078628297895193, 0.00017078628297895193, 0.00017078628297895193, 0.00017078628297895193, 0 ]
{ "id": 2, "code_window": [ "import { isModernFlag } from './importAnalysisBuild'\n", "\n", "export const modulePreloadPolyfillId = 'vite/modulepreload-polyfill'\n", "const resolvedModulePreloadPolyfillId = '\\0' + modulePreloadPolyfillId\n", "\n", "export function modulePreloadPolyfillPlugin(config: ResolvedConfig): Plugin {\n", " // `isModernFlag` is only available during build since it is resolved by `vite:build-import-analysis`\n", " const skip = config.command !== 'build' || config.build.ssr\n", " let polyfillString: string | undefined\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const resolvedModulePreloadPolyfillId = '\\0' + modulePreloadPolyfillId + '.js'\n" ], "file_path": "packages/vite/src/node/plugins/modulePreloadPolyfill.ts", "type": "replace", "edit_start_line_idx": 5 }
/// <reference types="svelte" /> /// <reference types="vite/client" />
packages/create-vite/template-svelte-ts/src/vite-env.d.ts
0
https://github.com/vitejs/vite/commit/9594c7021bba606ab423fc9e18d638615a111360
[ 0.0001711173536023125, 0.0001711173536023125, 0.0001711173536023125, 0.0001711173536023125, 0 ]
{ "id": 2, "code_window": [ "import { isModernFlag } from './importAnalysisBuild'\n", "\n", "export const modulePreloadPolyfillId = 'vite/modulepreload-polyfill'\n", "const resolvedModulePreloadPolyfillId = '\\0' + modulePreloadPolyfillId\n", "\n", "export function modulePreloadPolyfillPlugin(config: ResolvedConfig): Plugin {\n", " // `isModernFlag` is only available during build since it is resolved by `vite:build-import-analysis`\n", " const skip = config.command !== 'build' || config.build.ssr\n", " let polyfillString: string | undefined\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const resolvedModulePreloadPolyfillId = '\\0' + modulePreloadPolyfillId + '.js'\n" ], "file_path": "packages/vite/src/node/plugins/modulePreloadPolyfill.ts", "type": "replace", "edit_start_line_idx": 5 }
const relative = import.meta.glob('./**/*.js', { eager: true }) const alias = import.meta.glob('@escape_[brackets]_mod/**/*.js', { eager: true, }) export { relative, alias }
playground/glob-import/escape/[brackets]/glob.js
0
https://github.com/vitejs/vite/commit/9594c7021bba606ab423fc9e18d638615a111360
[ 0.00017497125372756273, 0.00017497125372756273, 0.00017497125372756273, 0.00017497125372756273, 0 ]
{ "id": 3, "code_window": [ "import type { ResolvedConfig } from '../config'\n", "import type { Plugin } from '../plugin'\n", "import { fileToUrl } from './asset'\n", "\n", "const wasmHelperId = '\\0vite/wasm-helper'\n", "\n", "const wasmHelper = async (opts = {}, url: string) => {\n", " let result\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "const wasmHelperId = '\\0vite/wasm-helper.js'\n" ], "file_path": "packages/vite/src/node/plugins/wasm.ts", "type": "replace", "edit_start_line_idx": 4 }
import type { ResolvedConfig } from '../config' import type { Plugin } from '../plugin' import { fileToUrl } from './asset' const wasmHelperId = '\0vite/wasm-helper' const wasmHelper = async (opts = {}, url: string) => { let result if (url.startsWith('data:')) { const urlContent = url.replace(/^data:.*?base64,/, '') let bytes if (typeof Buffer === 'function' && typeof Buffer.from === 'function') { bytes = Buffer.from(urlContent, 'base64') } else if (typeof atob === 'function') { const binaryString = atob(urlContent) bytes = new Uint8Array(binaryString.length) for (let i = 0; i < binaryString.length; i++) { bytes[i] = binaryString.charCodeAt(i) } } else { throw new Error( 'Failed to decode base64-encoded data URL, Buffer and atob are not supported', ) } result = await WebAssembly.instantiate(bytes, opts) } else { // https://github.com/mdn/webassembly-examples/issues/5 // WebAssembly.instantiateStreaming requires the server to provide the // correct MIME type for .wasm files, which unfortunately doesn't work for // a lot of static file servers, so we just work around it by getting the // raw buffer. const response = await fetch(url) const contentType = response.headers.get('Content-Type') || '' if ( 'instantiateStreaming' in WebAssembly && contentType.startsWith('application/wasm') ) { result = await WebAssembly.instantiateStreaming(response, opts) } else { const buffer = await response.arrayBuffer() result = await WebAssembly.instantiate(buffer, opts) } } return result.instance } const wasmHelperCode = wasmHelper.toString() export const wasmHelperPlugin = (config: ResolvedConfig): Plugin => { return { name: 'vite:wasm-helper', resolveId(id) { if (id === wasmHelperId) { return id } }, async load(id) { if (id === wasmHelperId) { return `export default ${wasmHelperCode}` } if (!id.endsWith('.wasm?init')) { return } const url = await fileToUrl(id, config, this) return ` import initWasm from "${wasmHelperId}" export default opts => initWasm(opts, ${JSON.stringify(url)}) ` }, } } export const wasmFallbackPlugin = (): Plugin => { return { name: 'vite:wasm-fallback', async load(id) { if (!id.endsWith('.wasm')) { return } throw new Error( '"ESM integration proposal for Wasm" is not supported currently. ' + 'Use vite-plugin-wasm or other community plugins to handle this. ' + 'Alternatively, you can use `.wasm?init` or `.wasm?url`. ' + 'See https://vitejs.dev/guide/features.html#webassembly for more details.', ) }, } }
packages/vite/src/node/plugins/wasm.ts
1
https://github.com/vitejs/vite/commit/9594c7021bba606ab423fc9e18d638615a111360
[ 0.9992050528526306, 0.639184832572937, 0.00017488034791313112, 0.9751238226890564, 0.44740450382232666 ]
{ "id": 3, "code_window": [ "import type { ResolvedConfig } from '../config'\n", "import type { Plugin } from '../plugin'\n", "import { fileToUrl } from './asset'\n", "\n", "const wasmHelperId = '\\0vite/wasm-helper'\n", "\n", "const wasmHelper = async (opts = {}, url: string) => {\n", " let result\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "const wasmHelperId = '\\0vite/wasm-helper.js'\n" ], "file_path": "packages/vite/src/node/plugins/wasm.ts", "type": "replace", "edit_start_line_idx": 4 }
export default 5
playground/resolve/exports-legacy-fallback/index.js
0
https://github.com/vitejs/vite/commit/9594c7021bba606ab423fc9e18d638615a111360
[ 0.0001768860820448026, 0.0001768860820448026, 0.0001768860820448026, 0.0001768860820448026, 0 ]
{ "id": 3, "code_window": [ "import type { ResolvedConfig } from '../config'\n", "import type { Plugin } from '../plugin'\n", "import { fileToUrl } from './asset'\n", "\n", "const wasmHelperId = '\\0vite/wasm-helper'\n", "\n", "const wasmHelper = async (opts = {}, url: string) => {\n", " let result\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "const wasmHelperId = '\\0vite/wasm-helper.js'\n" ], "file_path": "packages/vite/src/node/plugins/wasm.ts", "type": "replace", "edit_start_line_idx": 4 }
<svg viewBox="0 0 1440 495" fill="none" xmlns="http://www.w3.org/2000/svg"> <rect y="191" width="315" height="146" rx="10" fill="#C3E88C"/> <text fill="#15505C" xml:space="preserve" style="white-space: pre" font-family="Inter" font-size="40" font-weight="600" letter-spacing="0em"><tspan x="105.5" y="278.545">Entry</tspan></text> <rect x="556" width="360" height="141" rx="10" fill="#C3E88C"/> <text fill="#15505C" xml:space="preserve" style="white-space: pre" font-family="Inter" font-size="40" font-weight="600" letter-spacing="0em"><tspan x="594" y="85.0455">async chunk A</tspan></text> <rect x="1080" y="169" width="360" height="141" rx="10" fill="#C3E88C"/> <text fill="#15505C" xml:space="preserve" style="white-space: pre" font-family="Inter" font-size="40" font-weight="600" letter-spacing="0em"><tspan x="1091.5" y="254.045">common chunk C</tspan></text> <rect x="556" y="354" width="360" height="141" rx="10" fill="#C3E88C"/> <text fill="#15505C" xml:space="preserve" style="white-space: pre" font-family="Inter" font-size="40" font-weight="600" letter-spacing="0em"><tspan x="595.5" y="439.045">async chunk B</tspan></text> <path d="M546.44 71.5452C546.741 70.1977 545.893 68.8613 544.545 68.5602L522.587 63.6533C521.239 63.3522 519.903 64.2004 519.602 65.5479C519.301 66.8954 520.149 68.2318 521.496 68.5329L541.015 72.8946L536.653 92.4132C536.352 93.7607 537.2 95.0971 538.548 95.3983C539.895 95.6994 541.232 94.8511 541.533 93.5036L546.44 71.5452ZM326.34 212.111L334.161 207.146L331.482 202.925L323.66 207.889L326.34 212.111ZM349.804 197.218L365.447 187.289L362.767 183.068L347.125 192.996L349.804 197.218ZM381.09 177.361L396.733 167.432L394.053 163.211L378.41 173.139L381.09 177.361ZM412.375 157.504L428.018 147.575L425.339 143.354L409.696 153.282L412.375 157.504ZM443.661 137.646L459.304 127.718L456.625 123.496L440.982 133.425L443.661 137.646ZM474.947 117.789L490.59 107.861L487.91 103.639L472.267 113.568L474.947 117.789ZM506.233 97.9322L521.875 88.0036L519.196 83.7821L503.553 93.7107L506.233 97.9322ZM537.518 78.075L545.34 73.1107L542.66 68.8893L534.839 73.8536L537.518 78.075ZM548.88 72.0904C549.482 69.3955 547.785 66.7226 545.09 66.1204L501.174 56.3065C498.479 55.7043 495.806 57.4008 495.203 60.0958C494.601 62.7907 496.298 65.4636 498.993 66.0658L538.03 74.7892L529.307 113.826C528.704 116.521 530.401 119.194 533.096 119.796C535.791 120.399 538.464 118.702 539.066 116.007L548.88 72.0904ZM327.679 214.221L335.501 209.257L330.142 200.814L322.321 205.779L327.679 214.221ZM351.144 199.329L366.787 189.4L361.428 180.957L345.785 190.886L351.144 199.329ZM382.429 179.471L398.072 169.543L392.713 161.1L377.071 171.029L382.429 179.471ZM413.715 159.614L429.358 149.686L423.999 141.243L408.356 151.171L413.715 159.614ZM445.001 139.757L460.644 129.829L455.285 121.386L439.642 131.314L445.001 139.757ZM476.287 119.9L491.929 109.971L486.571 101.529L470.928 111.457L476.287 119.9ZM507.572 100.043L523.215 90.1143L517.856 81.6714L502.213 91.6L507.572 100.043ZM538.858 80.1858L546.679 75.2215L541.321 66.7785L533.499 71.7428L538.858 80.1858Z" fill="#0B7285"/> <path d="M544.718 442.395C546.04 441.998 546.791 440.605 546.395 439.282L539.935 417.729C539.539 416.407 538.145 415.656 536.823 416.052C535.5 416.449 534.749 417.842 535.146 419.165L540.888 438.323L521.729 444.065C520.407 444.461 519.656 445.855 520.052 447.177C520.449 448.5 521.842 449.251 523.165 448.854L544.718 442.395ZM323.814 324.201L331.636 328.415L334.007 324.013L326.186 319.799L323.814 324.201ZM347.278 336.844L362.921 345.272L365.293 340.871L349.65 332.442L347.278 336.844ZM378.564 353.701L394.207 362.129L396.579 357.728L380.936 349.299L378.564 353.701ZM409.85 370.558L425.493 378.987L427.864 374.585L412.222 366.156L409.85 370.558ZM441.136 387.415L456.778 395.844L459.15 391.442L443.507 383.013L441.136 387.415ZM472.421 404.272L488.064 412.701L490.436 408.299L474.793 399.871L472.421 404.272ZM503.707 421.129L519.35 429.558L521.722 425.156L506.079 416.728L503.707 421.129ZM534.993 437.987L542.814 442.201L545.186 437.799L537.364 433.585L534.993 437.987ZM545.435 444.79C548.081 443.997 549.582 441.21 548.79 438.565L535.871 395.459C535.078 392.814 532.291 391.312 529.646 392.105C527 392.898 525.499 395.685 526.292 398.33L537.775 436.646L499.459 448.129C496.814 448.922 495.312 451.709 496.105 454.354C496.898 457 499.685 458.501 502.33 457.708L545.435 444.79ZM322.628 326.402L330.45 330.616L335.193 321.813L327.372 317.598L322.628 326.402ZM346.093 339.045L361.735 347.473L366.479 338.67L350.836 330.241L346.093 339.045ZM377.378 355.902L393.021 364.33L397.765 355.527L382.122 347.098L377.378 355.902ZM408.664 372.759L424.307 381.187L429.05 372.384L413.407 363.955L408.664 372.759ZM439.95 389.616L455.593 398.045L460.336 389.241L444.693 380.813L439.95 389.616ZM471.235 406.473L486.878 414.902L491.622 406.098L475.979 397.67L471.235 406.473ZM502.521 423.33L518.164 431.759L522.907 422.955L507.265 414.527L502.521 423.33ZM533.807 440.187L541.628 444.402L546.372 435.598L538.55 431.384L533.807 440.187Z" fill="#0B7285"/> <text fill="#0B7285" xml:space="preserve" style="white-space: pre" font-family="Inter" font-size="35" letter-spacing="0em"><tspan x="172" y="98.7273">dynamic import</tspan></text> <text fill="#1864AB" xml:space="preserve" style="white-space: pre" font-family="Inter" font-size="35" letter-spacing="0em"><tspan x="1013" y="83.7273">direct import</tspan></text> <path d="M1071.89 171.899C1074.05 171.404 1075.39 169.258 1074.9 167.105L1066.85 132.017C1066.35 129.864 1064.21 128.519 1062.05 129.014C1059.9 129.508 1058.55 131.654 1059.05 133.807L1066.21 164.996L1035.02 172.154C1032.86 172.648 1031.52 174.795 1032.01 176.948C1032.51 179.101 1034.65 180.446 1036.81 179.952L1071.89 171.899ZM918.876 77.3895L1068.88 171.389L1073.12 164.611L923.124 70.6105L918.876 77.3895Z" fill="#1864AB"/> <path d="M1074.95 317.66C1075.31 315.481 1073.84 313.419 1071.66 313.055L1036.15 307.114C1033.97 306.75 1031.91 308.22 1031.55 310.399C1031.18 312.578 1032.65 314.64 1034.83 315.004L1066.39 320.285L1061.11 351.846C1060.75 354.025 1062.22 356.087 1064.4 356.452C1066.58 356.816 1068.64 355.345 1069 353.167L1074.95 317.66ZM923.323 427.256L1073.32 320.256L1068.68 313.744L918.677 420.744L923.323 427.256Z" fill="#1864AB"/> </svg>
docs/images/graph.svg
0
https://github.com/vitejs/vite/commit/9594c7021bba606ab423fc9e18d638615a111360
[ 0.0002534468949306756, 0.00021124986233189702, 0.00016905284428503364, 0.00021124986233189702, 0.00004219702532282099 ]
{ "id": 3, "code_window": [ "import type { ResolvedConfig } from '../config'\n", "import type { Plugin } from '../plugin'\n", "import { fileToUrl } from './asset'\n", "\n", "const wasmHelperId = '\\0vite/wasm-helper'\n", "\n", "const wasmHelper = async (opts = {}, url: string) => {\n", " let result\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "const wasmHelperId = '\\0vite/wasm-helper.js'\n" ], "file_path": "packages/vite/src/node/plugins/wasm.ts", "type": "replace", "edit_start_line_idx": 4 }
{ "name": "@vitejs/test-dep-not-js", "private": true, "version": "1.0.0", "main": "index.notjs" }
playground/optimize-deps/dep-not-js/package.json
0
https://github.com/vitejs/vite/commit/9594c7021bba606ab423fc9e18d638615a111360
[ 0.0001748955255607143, 0.0001748955255607143, 0.0001748955255607143, 0.0001748955255607143, 0 ]
{ "id": 0, "code_window": [ "\tflex: 1 1 auto;\n", "\tdisplay: -ms-flexbox;\n", "\tdisplay: flex;\n", "}\n", "\n", ".monaco-menu .monaco-action-bar.vertical .action-label {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\theight: 2.6em;\n", "\talign-items: center;\n" ], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "add", "edit_start_line_idx": 42 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-shell { height: 100%; width: 100%; margin: 0; padding: 0; overflow: hidden; font-size: 11px; user-select: none; } /* Font Families (with CJK support) */ .monaco-shell { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Ubuntu", "Droid Sans", sans-serif; } .monaco-shell:lang(zh-Hans) { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Microsoft YaHei", "PingFang SC", "Hiragino Sans GB", "Source Han Sans SC", "Source Han Sans CN", "Source Han Sans", sans-serif; } .monaco-shell:lang(zh-Hant) { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Microsoft Jhenghei", "PingFang TC", "Source Han Sans TC", "Source Han Sans", "Source Han Sans TW", sans-serif; } .monaco-shell:lang(ja) { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Meiryo", "Hiragino Kaku Gothic Pro", "Source Han Sans J", "Source Han Sans JP", "Source Han Sans", "Sazanami Gothic", "IPA Gothic", sans-serif; } .monaco-shell:lang(ko) { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Malgun Gothic", "Nanum Gothic", "Dotom", "Apple SD Gothic Neo", "AppleGothic", "Source Han Sans K", "Source Han Sans JR", "Source Han Sans", "UnDotum", "FBaekmuk Gulim", sans-serif; } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .monaco-shell img { border: 0; } .monaco-shell label { cursor: pointer; } .monaco-shell a { text-decoration: none; } .monaco-shell a:active { color: inherit; background-color: inherit; } .monaco-shell a.plain { color: inherit; text-decoration: none; } .monaco-shell a.plain:hover, .monaco-shell a.plain.hover { color: inherit; text-decoration: none; } .monaco-shell input { color: inherit; font-family: inherit; font-size: 100%; } .monaco-shell select { font-family: inherit; } .monaco-shell .pointer { cursor: pointer; } .monaco-shell .monaco-menu .monaco-action-bar.vertical { padding: .5em 0; } .monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label:not(.separator), .monaco-shell .monaco-menu .monaco-action-bar.vertical .keybinding { padding: 0.5em 2em; } .monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label.separator { padding: 0.2em 0 0 0; margin-bottom: 0.2em; } .monaco-shell .monaco-menu .monaco-action-bar.vertical .submenu-indicator { padding: 0.5em 1em; } .monaco-shell .monaco-menu .action-item { cursor: default; } /* START Keyboard Focus Indication Styles */ .monaco-shell [tabindex="0"]:focus, .monaco-shell .synthetic-focus, .monaco-shell select:focus, .monaco-shell input[type="button"]:focus, .monaco-shell input[type="text"]:focus, .monaco-shell textarea:focus, .monaco-shell input[type="checkbox"]:focus { outline-width: 1px; outline-style: solid; outline-offset: -1px; opacity: 1 !important; } .monaco-shell [tabindex="0"]:active, .monaco-shell select:active, .monaco-shell input[type="button"]:active, .monaco-shell input[type="checkbox"]:active, .monaco-shell .monaco-tree .monaco-tree-row .monaco-shell .monaco-tree.focused.no-focused-item:active:before { outline: 0 !important; /* fixes some flashing outlines from showing up when clicking */ } .monaco-shell .mac select:focus { border: none; /* outline is a square, but border has a radius, so we avoid this glitch when focused (https://github.com/Microsoft/vscode/issues/26045) */ } .monaco-shell .monaco-tree.focused .monaco-tree-row.focused [tabindex="0"]:focus { outline-width: 1px; /* higher contrast color for focusable elements in a row that shows focus feedback */ outline-style: solid; } .monaco-shell .monaco-tree.focused.no-focused-item:focus:before, .monaco-shell .monaco-list:not(.element-focused):focus:before { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 5; /* make sure we are on top of the tree items */ content: ""; pointer-events: none; /* enable click through */ outline: 1px solid; /* we still need to handle the empty tree or no focus item case */ outline-width: 1px; outline-style: solid; outline-offset: -1px; } .monaco-shell .synthetic-focus :focus { outline: 0 !important; /* elements within widgets that draw synthetic-focus should never show focus */ } .monaco-shell .monaco-inputbox.info.synthetic-focus, .monaco-shell .monaco-inputbox.warning.synthetic-focus, .monaco-shell .monaco-inputbox.error.synthetic-focus, .monaco-shell .monaco-inputbox.info input[type="text"]:focus, .monaco-shell .monaco-inputbox.warning input[type="text"]:focus, .monaco-shell .monaco-inputbox.error input[type="text"]:focus { outline: 0 !important; /* outline is not going well with decoration */ } .monaco-shell .monaco-tree.focused:focus, .monaco-shell .monaco-list:focus { outline: 0 !important; /* tree indicates focus not via outline but through the focused item */ }
src/vs/workbench/electron-browser/media/shell.css
1
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.004828605800867081, 0.0008993846131488681, 0.00016657842206768692, 0.00031096162274479866, 0.001290213200263679 ]
{ "id": 0, "code_window": [ "\tflex: 1 1 auto;\n", "\tdisplay: -ms-flexbox;\n", "\tdisplay: flex;\n", "}\n", "\n", ".monaco-menu .monaco-action-bar.vertical .action-label {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\theight: 2.6em;\n", "\talign-items: center;\n" ], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "add", "edit_start_line_idx": 42 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "label.close": "닫기" }
i18n/kor/src/vs/editor/contrib/referenceSearch/peekViewWidget.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00017923564882948995, 0.00017757972818799317, 0.00017592379299458116, 0.00017757972818799317, 0.0000016559279174543917 ]
{ "id": 0, "code_window": [ "\tflex: 1 1 auto;\n", "\tdisplay: -ms-flexbox;\n", "\tdisplay: flex;\n", "}\n", "\n", ".monaco-menu .monaco-action-bar.vertical .action-label {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\theight: 2.6em;\n", "\talign-items: center;\n" ], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "add", "edit_start_line_idx": 42 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { TPromise } from 'vs/base/common/winjs.base'; import { IChannel } from 'vs/base/parts/ipc/common/ipc'; import { Event, Emitter } from 'vs/base/common/event'; import { onUnexpectedError } from 'vs/base/common/errors'; import { IUpdateService, State } from './update'; export interface IUpdateChannel extends IChannel { listen(event: 'onStateChange'): Event<State>; listen<T>(command: string, arg?: any): Event<T>; call(command: 'checkForUpdates', arg: any): TPromise<void>; call(command: 'downloadUpdate'): TPromise<void>; call(command: 'applyUpdate'): TPromise<void>; call(command: 'quitAndInstall'): TPromise<void>; call(command: '_getInitialState'): TPromise<State>; call(command: 'isLatestVersion'): TPromise<boolean>; call(command: string, arg?: any): TPromise<any>; } export class UpdateChannel implements IUpdateChannel { constructor(private service: IUpdateService) { } listen<T>(event: string, arg?: any): Event<any> { switch (event) { case 'onStateChange': return this.service.onStateChange; } throw new Error('No event found'); } call(command: string, arg?: any): TPromise<any> { switch (command) { case 'checkForUpdates': return this.service.checkForUpdates(arg); case 'downloadUpdate': return this.service.downloadUpdate(); case 'applyUpdate': return this.service.applyUpdate(); case 'quitAndInstall': return this.service.quitAndInstall(); case '_getInitialState': return TPromise.as(this.service.state); case 'isLatestVersion': return this.service.isLatestVersion(); } return undefined; } } export class UpdateChannelClient implements IUpdateService { _serviceBrand: any; private _onStateChange = new Emitter<State>(); get onStateChange(): Event<State> { return this._onStateChange.event; } private _state: State = State.Uninitialized; get state(): State { return this._state; } constructor(private channel: IUpdateChannel) { // always set this._state as the state changes this.onStateChange(state => this._state = state); channel.call('_getInitialState').done(state => { // fire initial state this._onStateChange.fire(state); // fire subsequent states as they come in from remote this.channel.listen('onStateChange')(state => this._onStateChange.fire(state)); }, onUnexpectedError); } checkForUpdates(context: any): TPromise<void> { return this.channel.call('checkForUpdates', context); } downloadUpdate(): TPromise<void> { return this.channel.call('downloadUpdate'); } applyUpdate(): TPromise<void> { return this.channel.call('applyUpdate'); } quitAndInstall(): TPromise<void> { return this.channel.call('quitAndInstall'); } isLatestVersion(): TPromise<boolean> { return this.channel.call('isLatestVersion'); } }
src/vs/platform/update/common/updateIpc.ts
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.0001756653218762949, 0.000171622697962448, 0.00016660956316627562, 0.00017193364328704774, 0.0000029589803034468787 ]
{ "id": 0, "code_window": [ "\tflex: 1 1 auto;\n", "\tdisplay: -ms-flexbox;\n", "\tdisplay: flex;\n", "}\n", "\n", ".monaco-menu .monaco-action-bar.vertical .action-label {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\theight: 2.6em;\n", "\talign-items: center;\n" ], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "add", "edit_start_line_idx": 42 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "displayName": "C# Sprachgrundlagen", "description": "Bietet Ausschnitte, Syntaxhervorhebung, Klammernpaare und Falten in C#-Dateien." }
i18n/deu/extensions/csharp/package.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00017918780213221908, 0.0001771067181834951, 0.00017502563423477113, 0.0001771067181834951, 0.000002081083948723972 ]
{ "id": 1, "code_window": [ "\n", ".monaco-menu .monaco-action-bar.vertical .action-label {\n", "\t-ms-flex: 1 1 auto;\n", "\tflex: 1 1 auto;\n", "\ttext-decoration: none;\n", "\tpadding: 0.8em 1em;\n", "\tline-height: 1.1em;\n", "\tbackground: none;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "\tpadding: 0 1em;\n" ], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "replace", "edit_start_line_idx": 48 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .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; -ms-transform: none; -webkit-transform: none; -moz-transform: none; -o-transform: none; transform: none; display: -ms-flexbox; display: flex; } .monaco-menu .monaco-action-bar.vertical .action-item.active { -ms-transform: none; -webkit-transform: none; -moz-transform: none; -o-transform: none; transform: none; } .monaco-menu .monaco-action-bar.vertical .action-item.focused { background-color: #E4E4E4; } .monaco-menu .monaco-action-bar.vertical .action-menu-item { -ms-flex: 1 1 auto; flex: 1 1 auto; display: -ms-flexbox; display: flex; } .monaco-menu .monaco-action-bar.vertical .action-label { -ms-flex: 1 1 auto; flex: 1 1 auto; text-decoration: none; padding: 0.8em 1em; line-height: 1.1em; background: none; } .monaco-menu .monaco-action-bar.vertical .keybinding, .monaco-menu .monaco-action-bar.vertical .submenu-indicator { display: inline-block; -ms-flex: 2 1 auto; flex: 2 1 auto; padding: 0.8em 1em; line-height: 1.1em; font-size: 12px; text-align: right; } .monaco-menu .monaco-action-bar.vertical .submenu-indicator { padding: 0.8em .5em; } .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; -webkit-box-sizing: border-box; -o-box-sizing: border-box; -moz-box-sizing: border-box; -ms-box-sizing: border-box; box-sizing: border-box; margin: 0; } .monaco-menu .monaco-action-bar.vertical .action-label.separator { padding: 0.5em 0 0 0; margin-bottom: 0.5em; width: 100%; } .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 .action-label.checked:after { content: ' \2713'; } /* Context Menu */ .context-view.monaco-menu-container { font-family: "Segoe WPC", "Segoe UI", ".SFNSDisplay-Light", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; outline: 0; box-shadow: 0 2px 8px #A8A8A8; border: none; color: #646465; background-color: white; -webkit-animation: fadeIn 0.083s linear; -o-animation: fadeIn 0.083s linear; -moz-animation: fadeIn 0.083s linear; -ms-animation: fadeIn 0.083s linear; animation: fadeIn 0.083s linear; } .context-view.monaco-menu-container :focus { outline: 0; } .monaco-menu .monaco-action-bar.vertical .action-item { border: 1px solid transparent; /* prevents jumping behaviour on hover or focus */ } /* Dark theme */ .vs-dark .monaco-menu .monaco-action-bar.vertical .action-item.focused { background-color: #4B4C4D; } .vs-dark .context-view.monaco-menu-container { box-shadow: 0 2px 8px #000; color: #BBB; background-color: #2D2F31; } /* High Contrast Theming */ .hc-black .context-view.monaco-menu-container { border: 2px solid #6FC3DF; color: white; background-color: #0C141F; box-shadow: none; } .hc-black .monaco-menu .monaco-action-bar.vertical .action-item.focused { background: none; border: 1px dotted #f38518; }
src/vs/base/browser/ui/menu/menu.css
1
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.9874516129493713, 0.06422543525695801, 0.00017259723972529173, 0.0017429650761187077, 0.23839221894741058 ]
{ "id": 1, "code_window": [ "\n", ".monaco-menu .monaco-action-bar.vertical .action-label {\n", "\t-ms-flex: 1 1 auto;\n", "\tflex: 1 1 auto;\n", "\ttext-decoration: none;\n", "\tpadding: 0.8em 1em;\n", "\tline-height: 1.1em;\n", "\tbackground: none;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "\tpadding: 0 1em;\n" ], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "replace", "edit_start_line_idx": 48 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "lines.copyUp": "向上复制行", "lines.copyDown": "向下复制行", "lines.moveUp": "向上移动行", "lines.moveDown": "向下移动行", "lines.sortAscending": "按升序排列行", "lines.sortDescending": "按降序排列行", "lines.trimTrailingWhitespace": "裁剪尾随空格", "lines.delete": "删除行", "lines.indent": "行缩进", "lines.outdent": "行减少缩进", "lines.insertBefore": "在上面插入行", "lines.insertAfter": "在下面插入行", "lines.deleteAllLeft": "删除左侧所有内容", "lines.deleteAllRight": "删除右侧所有内容", "lines.joinLines": "合并行", "editor.transpose": "转置游标处的字符", "editor.transformToUppercase": "转换为大写", "editor.transformToLowercase": "转换为小写" }
i18n/chs/src/vs/editor/contrib/linesOperations/common/linesOperations.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.0001728907518554479, 0.00017074908828362823, 0.00016916668391786516, 0.00017018984362948686, 0.0000015709318859080668 ]
{ "id": 1, "code_window": [ "\n", ".monaco-menu .monaco-action-bar.vertical .action-label {\n", "\t-ms-flex: 1 1 auto;\n", "\tflex: 1 1 auto;\n", "\ttext-decoration: none;\n", "\tpadding: 0.8em 1em;\n", "\tline-height: 1.1em;\n", "\tbackground: none;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "\tpadding: 0 1em;\n" ], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "replace", "edit_start_line_idx": 48 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "commit": "Commit" }
i18n/hun/extensions/git/out/scmProvider.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00017575043602846563, 0.00017575043602846563, 0.00017575043602846563, 0.00017575043602846563, 0 ]
{ "id": 1, "code_window": [ "\n", ".monaco-menu .monaco-action-bar.vertical .action-label {\n", "\t-ms-flex: 1 1 auto;\n", "\tflex: 1 1 auto;\n", "\ttext-decoration: none;\n", "\tpadding: 0.8em 1em;\n", "\tline-height: 1.1em;\n", "\tbackground: none;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "\tpadding: 0 1em;\n" ], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "replace", "edit_start_line_idx": 48 }
{ "comments": { "lineComment": "//", "blockComment": [ "/*", "*/" ] }, "brackets": [ ["{", "}"], ["[", "]"], ["(", ")"] ], "autoClosingPairs": [ ["{", "}"], ["[", "]"], ["(", ")"], ["\"", "\""] ], "surroundingPairs": [ ["{", "}"], ["[", "]"], ["(", ")"], ["\"", "\""], ["'", "'"] ] }
extensions/rust/language-configuration.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00017292634584009647, 0.00017169675265904516, 0.0001699835411272943, 0.0001721803710097447, 0.0000012491169627537602 ]
{ "id": 2, "code_window": [ "\tbackground: none;\n", "}\n", "\n", ".monaco-menu .monaco-action-bar.vertical .keybinding,\n", ".monaco-menu .monaco-action-bar.vertical .submenu-indicator {\n", "\tdisplay: inline-block;\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tfont-size: inherit;\n", "\tline-height: 1;\n" ], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "add", "edit_start_line_idx": 51 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-shell { height: 100%; width: 100%; margin: 0; padding: 0; overflow: hidden; font-size: 11px; user-select: none; } /* Font Families (with CJK support) */ .monaco-shell { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Ubuntu", "Droid Sans", sans-serif; } .monaco-shell:lang(zh-Hans) { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Microsoft YaHei", "PingFang SC", "Hiragino Sans GB", "Source Han Sans SC", "Source Han Sans CN", "Source Han Sans", sans-serif; } .monaco-shell:lang(zh-Hant) { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Microsoft Jhenghei", "PingFang TC", "Source Han Sans TC", "Source Han Sans", "Source Han Sans TW", sans-serif; } .monaco-shell:lang(ja) { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Meiryo", "Hiragino Kaku Gothic Pro", "Source Han Sans J", "Source Han Sans JP", "Source Han Sans", "Sazanami Gothic", "IPA Gothic", sans-serif; } .monaco-shell:lang(ko) { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Malgun Gothic", "Nanum Gothic", "Dotom", "Apple SD Gothic Neo", "AppleGothic", "Source Han Sans K", "Source Han Sans JR", "Source Han Sans", "UnDotum", "FBaekmuk Gulim", sans-serif; } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .monaco-shell img { border: 0; } .monaco-shell label { cursor: pointer; } .monaco-shell a { text-decoration: none; } .monaco-shell a:active { color: inherit; background-color: inherit; } .monaco-shell a.plain { color: inherit; text-decoration: none; } .monaco-shell a.plain:hover, .monaco-shell a.plain.hover { color: inherit; text-decoration: none; } .monaco-shell input { color: inherit; font-family: inherit; font-size: 100%; } .monaco-shell select { font-family: inherit; } .monaco-shell .pointer { cursor: pointer; } .monaco-shell .monaco-menu .monaco-action-bar.vertical { padding: .5em 0; } .monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label:not(.separator), .monaco-shell .monaco-menu .monaco-action-bar.vertical .keybinding { padding: 0.5em 2em; } .monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label.separator { padding: 0.2em 0 0 0; margin-bottom: 0.2em; } .monaco-shell .monaco-menu .monaco-action-bar.vertical .submenu-indicator { padding: 0.5em 1em; } .monaco-shell .monaco-menu .action-item { cursor: default; } /* START Keyboard Focus Indication Styles */ .monaco-shell [tabindex="0"]:focus, .monaco-shell .synthetic-focus, .monaco-shell select:focus, .monaco-shell input[type="button"]:focus, .monaco-shell input[type="text"]:focus, .monaco-shell textarea:focus, .monaco-shell input[type="checkbox"]:focus { outline-width: 1px; outline-style: solid; outline-offset: -1px; opacity: 1 !important; } .monaco-shell [tabindex="0"]:active, .monaco-shell select:active, .monaco-shell input[type="button"]:active, .monaco-shell input[type="checkbox"]:active, .monaco-shell .monaco-tree .monaco-tree-row .monaco-shell .monaco-tree.focused.no-focused-item:active:before { outline: 0 !important; /* fixes some flashing outlines from showing up when clicking */ } .monaco-shell .mac select:focus { border: none; /* outline is a square, but border has a radius, so we avoid this glitch when focused (https://github.com/Microsoft/vscode/issues/26045) */ } .monaco-shell .monaco-tree.focused .monaco-tree-row.focused [tabindex="0"]:focus { outline-width: 1px; /* higher contrast color for focusable elements in a row that shows focus feedback */ outline-style: solid; } .monaco-shell .monaco-tree.focused.no-focused-item:focus:before, .monaco-shell .monaco-list:not(.element-focused):focus:before { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 5; /* make sure we are on top of the tree items */ content: ""; pointer-events: none; /* enable click through */ outline: 1px solid; /* we still need to handle the empty tree or no focus item case */ outline-width: 1px; outline-style: solid; outline-offset: -1px; } .monaco-shell .synthetic-focus :focus { outline: 0 !important; /* elements within widgets that draw synthetic-focus should never show focus */ } .monaco-shell .monaco-inputbox.info.synthetic-focus, .monaco-shell .monaco-inputbox.warning.synthetic-focus, .monaco-shell .monaco-inputbox.error.synthetic-focus, .monaco-shell .monaco-inputbox.info input[type="text"]:focus, .monaco-shell .monaco-inputbox.warning input[type="text"]:focus, .monaco-shell .monaco-inputbox.error input[type="text"]:focus { outline: 0 !important; /* outline is not going well with decoration */ } .monaco-shell .monaco-tree.focused:focus, .monaco-shell .monaco-list:focus { outline: 0 !important; /* tree indicates focus not via outline but through the focused item */ }
src/vs/workbench/electron-browser/media/shell.css
1
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00614556111395359, 0.001272719819098711, 0.00016683831927366555, 0.0004701262805610895, 0.0015989776002243161 ]
{ "id": 2, "code_window": [ "\tbackground: none;\n", "}\n", "\n", ".monaco-menu .monaco-action-bar.vertical .keybinding,\n", ".monaco-menu .monaco-action-bar.vertical .submenu-indicator {\n", "\tdisplay: inline-block;\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tfont-size: inherit;\n", "\tline-height: 1;\n" ], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "add", "edit_start_line_idx": 51 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-workbench > .part.activitybar { width: 50px; } .monaco-workbench > .activitybar > .content { height: 100%; display: flex; flex-direction: column; justify-content: space-between; } .monaco-workbench > .activitybar > .content .monaco-action-bar { text-align: left; background-color: inherit; } .monaco-workbench > .activitybar .action-item:focus { outline: 0 !important; /* activity bar indicates focus custom */ } .monaco-workbench .activitybar > .content > .composite-bar > .monaco-action-bar .action-label.toggle-more { -webkit-mask: url('ellipsis-global.svg') no-repeat 50% 50%; }
src/vs/workbench/browser/parts/activitybar/media/activitybarpart.css
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.0034960550256073475, 0.0015428332844749093, 0.00016575452173128724, 0.0009666902478784323, 0.0014193146489560604 ]
{ "id": 2, "code_window": [ "\tbackground: none;\n", "}\n", "\n", ".monaco-menu .monaco-action-bar.vertical .keybinding,\n", ".monaco-menu .monaco-action-bar.vertical .submenu-indicator {\n", "\tdisplay: inline-block;\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tfont-size: inherit;\n", "\tline-height: 1;\n" ], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "add", "edit_start_line_idx": 51 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "htmlserver.name": "Serveur de langage HTML", "folding.start": "Début de la région repliable", "folding.end": "Fin de la région repliable" }
i18n/fra/extensions/html/client/out/htmlMain.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.0001760019949870184, 0.00017542524437885731, 0.00017484849377069622, 0.00017542524437885731, 5.767506081610918e-7 ]
{ "id": 2, "code_window": [ "\tbackground: none;\n", "}\n", "\n", ".monaco-menu .monaco-action-bar.vertical .keybinding,\n", ".monaco-menu .monaco-action-bar.vertical .submenu-indicator {\n", "\tdisplay: inline-block;\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tfont-size: inherit;\n", "\tline-height: 1;\n" ], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "add", "edit_start_line_idx": 51 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "invalid.language": "Ismeretlen nyelv található a következőben: `contributes.{0}.language`. A megadott érték: {1}", "invalid.scopeName": "Hiányzó karakterlánc a `contributes.{0}.scopeName`-ben. A megadott érték: {1}", "invalid.path.0": "Hiányzó karakterlánc a `contributes.{0}.path`-ban. A megadott érték: {1}", "invalid.injectTo": "A `contributes.{0}.injectTo` értéke érvénytelen. Az értéke egy tömb lehet, ami nyelvhatókörök neveit tartalmazza. A megadott érték: {1}", "invalid.embeddedLanguages": "A `contributes.{0}.embeddedLanguages` értéke érvénytelen. Az értéke egy hatókörnév-nyelv kulcs-érték párokat tartalmazó objektum lehet. A megadott érték: {1}", "invalid.path.1": "A `contributes.{0}.path` ({1}) nem a kiegészítő mappáján belül található ({2}). Emiatt előfordulhat, hogy a kiegészítő nem lesz hordozható.", "no-tm-grammar": "Nincs TM Grammar regisztrálva ehhez a nyelvhez." }
i18n/hun/src/vs/editor/electron-browser/textMate/TMSyntax.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00017192740051541477, 0.00017077583470381796, 0.00016962426889222115, 0.00017077583470381796, 0.0000011515658115968108 ]
{ "id": 3, "code_window": [ "\tdisplay: inline-block;\n", "\t-ms-flex: 2 1 auto;\n", "\tflex: 2 1 auto;\n", "\tpadding: 0.8em 1em;\n", "\tline-height: 1.1em;\n", "\tfont-size: 12px;\n", "\ttext-align: right;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\tpadding: 0 1em;\n" ], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "replace", "edit_start_line_idx": 58 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-shell { height: 100%; width: 100%; margin: 0; padding: 0; overflow: hidden; font-size: 11px; user-select: none; } /* Font Families (with CJK support) */ .monaco-shell { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Ubuntu", "Droid Sans", sans-serif; } .monaco-shell:lang(zh-Hans) { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Microsoft YaHei", "PingFang SC", "Hiragino Sans GB", "Source Han Sans SC", "Source Han Sans CN", "Source Han Sans", sans-serif; } .monaco-shell:lang(zh-Hant) { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Microsoft Jhenghei", "PingFang TC", "Source Han Sans TC", "Source Han Sans", "Source Han Sans TW", sans-serif; } .monaco-shell:lang(ja) { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Meiryo", "Hiragino Kaku Gothic Pro", "Source Han Sans J", "Source Han Sans JP", "Source Han Sans", "Sazanami Gothic", "IPA Gothic", sans-serif; } .monaco-shell:lang(ko) { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Malgun Gothic", "Nanum Gothic", "Dotom", "Apple SD Gothic Neo", "AppleGothic", "Source Han Sans K", "Source Han Sans JR", "Source Han Sans", "UnDotum", "FBaekmuk Gulim", sans-serif; } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .monaco-shell img { border: 0; } .monaco-shell label { cursor: pointer; } .monaco-shell a { text-decoration: none; } .monaco-shell a:active { color: inherit; background-color: inherit; } .monaco-shell a.plain { color: inherit; text-decoration: none; } .monaco-shell a.plain:hover, .monaco-shell a.plain.hover { color: inherit; text-decoration: none; } .monaco-shell input { color: inherit; font-family: inherit; font-size: 100%; } .monaco-shell select { font-family: inherit; } .monaco-shell .pointer { cursor: pointer; } .monaco-shell .monaco-menu .monaco-action-bar.vertical { padding: .5em 0; } .monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label:not(.separator), .monaco-shell .monaco-menu .monaco-action-bar.vertical .keybinding { padding: 0.5em 2em; } .monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label.separator { padding: 0.2em 0 0 0; margin-bottom: 0.2em; } .monaco-shell .monaco-menu .monaco-action-bar.vertical .submenu-indicator { padding: 0.5em 1em; } .monaco-shell .monaco-menu .action-item { cursor: default; } /* START Keyboard Focus Indication Styles */ .monaco-shell [tabindex="0"]:focus, .monaco-shell .synthetic-focus, .monaco-shell select:focus, .monaco-shell input[type="button"]:focus, .monaco-shell input[type="text"]:focus, .monaco-shell textarea:focus, .monaco-shell input[type="checkbox"]:focus { outline-width: 1px; outline-style: solid; outline-offset: -1px; opacity: 1 !important; } .monaco-shell [tabindex="0"]:active, .monaco-shell select:active, .monaco-shell input[type="button"]:active, .monaco-shell input[type="checkbox"]:active, .monaco-shell .monaco-tree .monaco-tree-row .monaco-shell .monaco-tree.focused.no-focused-item:active:before { outline: 0 !important; /* fixes some flashing outlines from showing up when clicking */ } .monaco-shell .mac select:focus { border: none; /* outline is a square, but border has a radius, so we avoid this glitch when focused (https://github.com/Microsoft/vscode/issues/26045) */ } .monaco-shell .monaco-tree.focused .monaco-tree-row.focused [tabindex="0"]:focus { outline-width: 1px; /* higher contrast color for focusable elements in a row that shows focus feedback */ outline-style: solid; } .monaco-shell .monaco-tree.focused.no-focused-item:focus:before, .monaco-shell .monaco-list:not(.element-focused):focus:before { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 5; /* make sure we are on top of the tree items */ content: ""; pointer-events: none; /* enable click through */ outline: 1px solid; /* we still need to handle the empty tree or no focus item case */ outline-width: 1px; outline-style: solid; outline-offset: -1px; } .monaco-shell .synthetic-focus :focus { outline: 0 !important; /* elements within widgets that draw synthetic-focus should never show focus */ } .monaco-shell .monaco-inputbox.info.synthetic-focus, .monaco-shell .monaco-inputbox.warning.synthetic-focus, .monaco-shell .monaco-inputbox.error.synthetic-focus, .monaco-shell .monaco-inputbox.info input[type="text"]:focus, .monaco-shell .monaco-inputbox.warning input[type="text"]:focus, .monaco-shell .monaco-inputbox.error input[type="text"]:focus { outline: 0 !important; /* outline is not going well with decoration */ } .monaco-shell .monaco-tree.focused:focus, .monaco-shell .monaco-list:focus { outline: 0 !important; /* tree indicates focus not via outline but through the focused item */ }
src/vs/workbench/electron-browser/media/shell.css
1
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00017265255155507475, 0.00016819355369079858, 0.00016441370826214552, 0.00016789278015494347, 0.0000025848914901871467 ]
{ "id": 3, "code_window": [ "\tdisplay: inline-block;\n", "\t-ms-flex: 2 1 auto;\n", "\tflex: 2 1 auto;\n", "\tpadding: 0.8em 1em;\n", "\tline-height: 1.1em;\n", "\tfont-size: 12px;\n", "\ttext-align: right;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\tpadding: 0 1em;\n" ], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "replace", "edit_start_line_idx": 58 }
declare module 'gc-signals' { export interface GCSignal { } /** * Create a new GC signal. When being garbage collected the passed * value is stored for later consumption. */ export const GCSignal: { new(id: number): GCSignal; }; /** * Consume ids of garbage collected signals. */ export function consumeSignals(): number[]; export function onDidGarbageCollectSignals(callback: (ids: number[]) => any): { dispose(): void; }; export function trackGarbageCollection(obj: any, id: number): number; }
src/typings/gc-signals.d.ts
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00017476714856456965, 0.00017238450527656823, 0.00017000186198856682, 0.00017238450527656823, 0.000002382643288001418 ]
{ "id": 3, "code_window": [ "\tdisplay: inline-block;\n", "\t-ms-flex: 2 1 auto;\n", "\tflex: 2 1 auto;\n", "\tpadding: 0.8em 1em;\n", "\tline-height: 1.1em;\n", "\tfont-size: 12px;\n", "\ttext-align: right;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\tpadding: 0 1em;\n" ], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "replace", "edit_start_line_idx": 58 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "nextSearchIncludePattern": "Következő bele foglalt keresési minta megjelenítése", "previousSearchIncludePattern": "Előző bele foglalt keresési minta megjelenítése", "nextSearchExcludePattern": "Következő kizáró keresési minta megjelenítése", "previousSearchExcludePattern": "Előző kizáró keresési minta megjelenítése", "nextSearchTerm": "Következő keresőkifejezés megjelenítése", "previousSearchTerm": "Előző keresőkifejezés megjelenítése", "nextReplaceTerm": "Következő keresési cserekifejezés megjelenítése", "previousReplaceTerm": "Előző keresési cserekifejezés megjelenítése", "findInFiles": "Keresés a fájlokban", "replaceInFiles": "Csere a fájlokban", "RefreshAction.label": "Frissítés", "CollapseDeepestExpandedLevelAction.label": "Összes bezárása", "ClearSearchResultsAction.label": "Törlés", "CancelSearchAction.label": "Keresés megszakítása", "FocusNextSearchResult.label": "Váltás a következő keresési eredményre", "FocusPreviousSearchResult.label": "Váltás az előző keresési eredményre", "RemoveAction.label": "Elvetés", "file.replaceAll.label": "Összes cseréje", "match.replace.label": "Csere" }
i18n/hun/src/vs/workbench/parts/search/browser/searchActions.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00017518142703920603, 0.00017260295862797648, 0.00017016875790432096, 0.0001724587200442329, 0.000002048954002020764 ]
{ "id": 3, "code_window": [ "\tdisplay: inline-block;\n", "\t-ms-flex: 2 1 auto;\n", "\tflex: 2 1 auto;\n", "\tpadding: 0.8em 1em;\n", "\tline-height: 1.1em;\n", "\tfont-size: 12px;\n", "\ttext-align: right;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\tpadding: 0 1em;\n" ], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "replace", "edit_start_line_idx": 58 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "closeWindow": "Fenster schließen", "closeWorkspace": "Arbeitsbereich schließen", "noWorkspaceOpened": "Zurzeit ist kein Arbeitsbereich in dieser Instanz geöffnet, der geschlossen werden kann.", "newWindow": "Neues Fenster", "toggleFullScreen": "Vollbild umschalten", "toggleMenuBar": "Menüleiste umschalten", "toggleDevTools": "Entwicklertools umschalten", "zoomIn": "Vergrößern", "zoomOut": "Verkleinern", "zoomReset": "Zoom zurücksetzen", "appPerf": "Startleistung", "reloadWindow": "Fenster erneut laden", "reloadWindowWithExntesionsDisabled": "Fenster mit deaktivierten Erweiterungen erneut laden", "switchWindowPlaceHolder": "Fenster auswählen, zu dem Sie wechseln möchten", "current": "Aktuelles Fenster", "close": "Fenster schließen", "switchWindow": "Fenster wechseln...", "quickSwitchWindow": "Fenster schnell wechseln...", "workspaces": "Arbeitsbereiche", "files": "Dateien", "openRecentPlaceHolderMac": "Zum Öffnen auswählen (zum Öffnen in einem neuen Fenster die BEFEHLSTASTE gedrückt halten)", "openRecentPlaceHolder": "Zum Öffnen auswählen (zum Öffnen in einem neuen Fenster die STRG-TASTE gedrückt halten)", "remove": "Aus zuletzt geöffneten entfernen", "openRecent": "Zuletzt benutzt...", "quickOpenRecent": "Zuletzt benutzte schnell öffnen...", "reportIssueInEnglish": "Problem melden", "openProcessExplorer": "Prozess-Explorer öffnen", "reportPerformanceIssue": "Leistungsproblem melden", "keybindingsReference": "Referenz für Tastenkombinationen", "openDocumentationUrl": "Dokumentation", "openIntroductoryVideosUrl": "Einführungsvideos", "openTipsAndTricksUrl": "Tipps und Tricks", "toggleSharedProcess": "Freigegebenen Prozess umschalten", "navigateLeft": "Zur Ansicht auf der linken Seite navigieren", "navigateRight": "Zur Ansicht auf der rechten Seite navigieren", "navigateUp": "Zur Ansicht darüber navigieren", "navigateDown": "Zur Ansicht darunter navigieren", "increaseViewSize": "Aktuelle Ansicht vergrößern", "decreaseViewSize": "Aktuelle Ansicht verkleinern", "showPreviousTab": "Vorherige Fensterregisterkarte anzeigen", "showNextWindowTab": "Nächste Fensterregisterkarte anzeigen", "moveWindowTabToNewWindow": "Fensterregisterkarte in neues Fenster verschieben", "mergeAllWindowTabs": "Alle Fenster zusammenführen", "toggleWindowTabsBar": "Fensterregisterkarten-Leiste umschalten", "about": "Informationen zu {0}", "inspect context keys": "Kontextschlüssel prüfen" }
i18n/deu/src/vs/workbench/electron-browser/actions.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.0001754769909894094, 0.00017004874825943261, 0.00016662290727254003, 0.00016912040882743895, 0.0000029511063530662796 ]
{ "id": 4, "code_window": [ "\ttext-align: right;\n", "}\n", "\n" ], "labels": [ "add", "keep", "keep" ], "after_edit": [ "\tfont-size: inherit;\n", "\tline-height: 1;\n" ], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "add", "edit_start_line_idx": 62 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-shell { height: 100%; width: 100%; margin: 0; padding: 0; overflow: hidden; font-size: 11px; user-select: none; } /* Font Families (with CJK support) */ .monaco-shell { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Ubuntu", "Droid Sans", sans-serif; } .monaco-shell:lang(zh-Hans) { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Microsoft YaHei", "PingFang SC", "Hiragino Sans GB", "Source Han Sans SC", "Source Han Sans CN", "Source Han Sans", sans-serif; } .monaco-shell:lang(zh-Hant) { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Microsoft Jhenghei", "PingFang TC", "Source Han Sans TC", "Source Han Sans", "Source Han Sans TW", sans-serif; } .monaco-shell:lang(ja) { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Meiryo", "Hiragino Kaku Gothic Pro", "Source Han Sans J", "Source Han Sans JP", "Source Han Sans", "Sazanami Gothic", "IPA Gothic", sans-serif; } .monaco-shell:lang(ko) { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Malgun Gothic", "Nanum Gothic", "Dotom", "Apple SD Gothic Neo", "AppleGothic", "Source Han Sans K", "Source Han Sans JR", "Source Han Sans", "UnDotum", "FBaekmuk Gulim", sans-serif; } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .monaco-shell img { border: 0; } .monaco-shell label { cursor: pointer; } .monaco-shell a { text-decoration: none; } .monaco-shell a:active { color: inherit; background-color: inherit; } .monaco-shell a.plain { color: inherit; text-decoration: none; } .monaco-shell a.plain:hover, .monaco-shell a.plain.hover { color: inherit; text-decoration: none; } .monaco-shell input { color: inherit; font-family: inherit; font-size: 100%; } .monaco-shell select { font-family: inherit; } .monaco-shell .pointer { cursor: pointer; } .monaco-shell .monaco-menu .monaco-action-bar.vertical { padding: .5em 0; } .monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label:not(.separator), .monaco-shell .monaco-menu .monaco-action-bar.vertical .keybinding { padding: 0.5em 2em; } .monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label.separator { padding: 0.2em 0 0 0; margin-bottom: 0.2em; } .monaco-shell .monaco-menu .monaco-action-bar.vertical .submenu-indicator { padding: 0.5em 1em; } .monaco-shell .monaco-menu .action-item { cursor: default; } /* START Keyboard Focus Indication Styles */ .monaco-shell [tabindex="0"]:focus, .monaco-shell .synthetic-focus, .monaco-shell select:focus, .monaco-shell input[type="button"]:focus, .monaco-shell input[type="text"]:focus, .monaco-shell textarea:focus, .monaco-shell input[type="checkbox"]:focus { outline-width: 1px; outline-style: solid; outline-offset: -1px; opacity: 1 !important; } .monaco-shell [tabindex="0"]:active, .monaco-shell select:active, .monaco-shell input[type="button"]:active, .monaco-shell input[type="checkbox"]:active, .monaco-shell .monaco-tree .monaco-tree-row .monaco-shell .monaco-tree.focused.no-focused-item:active:before { outline: 0 !important; /* fixes some flashing outlines from showing up when clicking */ } .monaco-shell .mac select:focus { border: none; /* outline is a square, but border has a radius, so we avoid this glitch when focused (https://github.com/Microsoft/vscode/issues/26045) */ } .monaco-shell .monaco-tree.focused .monaco-tree-row.focused [tabindex="0"]:focus { outline-width: 1px; /* higher contrast color for focusable elements in a row that shows focus feedback */ outline-style: solid; } .monaco-shell .monaco-tree.focused.no-focused-item:focus:before, .monaco-shell .monaco-list:not(.element-focused):focus:before { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 5; /* make sure we are on top of the tree items */ content: ""; pointer-events: none; /* enable click through */ outline: 1px solid; /* we still need to handle the empty tree or no focus item case */ outline-width: 1px; outline-style: solid; outline-offset: -1px; } .monaco-shell .synthetic-focus :focus { outline: 0 !important; /* elements within widgets that draw synthetic-focus should never show focus */ } .monaco-shell .monaco-inputbox.info.synthetic-focus, .monaco-shell .monaco-inputbox.warning.synthetic-focus, .monaco-shell .monaco-inputbox.error.synthetic-focus, .monaco-shell .monaco-inputbox.info input[type="text"]:focus, .monaco-shell .monaco-inputbox.warning input[type="text"]:focus, .monaco-shell .monaco-inputbox.error input[type="text"]:focus { outline: 0 !important; /* outline is not going well with decoration */ } .monaco-shell .monaco-tree.focused:focus, .monaco-shell .monaco-list:focus { outline: 0 !important; /* tree indicates focus not via outline but through the focused item */ }
src/vs/workbench/electron-browser/media/shell.css
1
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.0002528900222387165, 0.00018354179337620735, 0.00016517659241799265, 0.00017715984722599387, 0.000020424497051863 ]
{ "id": 4, "code_window": [ "\ttext-align: right;\n", "}\n", "\n" ], "labels": [ "add", "keep", "keep" ], "after_edit": [ "\tfont-size: inherit;\n", "\tline-height: 1;\n" ], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "add", "edit_start_line_idx": 62 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "binaryFileEditor": "二進位檔案檢視器" }
i18n/cht/src/vs/workbench/parts/files/browser/editors/binaryFileEditor.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00018335101776756346, 0.0001796077995095402, 0.00017586459580343217, 0.0001796077995095402, 0.000003743210982065648 ]
{ "id": 4, "code_window": [ "\ttext-align: right;\n", "}\n", "\n" ], "labels": [ "add", "keep", "keep" ], "after_edit": [ "\tfont-size: inherit;\n", "\tline-height: 1;\n" ], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "add", "edit_start_line_idx": 62 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "publishBranch": "Опубликовать ветвь", "syncBranch": "Синхронизировать изменения", "gitNotEnabled": "GIT недоступен в этой рабочей области." }
i18n/rus/src/vs/workbench/parts/git/browser/gitWidgets.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00018335101776756346, 0.000176912551978603, 0.00017047407163772732, 0.000176912551978603, 0.000006438473064918071 ]
{ "id": 4, "code_window": [ "\ttext-align: right;\n", "}\n", "\n" ], "labels": [ "add", "keep", "keep" ], "after_edit": [ "\tfont-size: inherit;\n", "\tline-height: 1;\n" ], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "add", "edit_start_line_idx": 62 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "console.title": "VS Code コンソール", "mac.terminal.script.failed": "スクリプト '{0}' が終了コード {1} で失敗しました", "mac.terminal.type.not.supported": "'{0}' はサポートされていません", "press.any.key": "続行するには、任意のキーを押してください...", "linux.term.failed": "'{0}' が終了コード {1} で失敗しました" }
i18n/jpn/src/vs/workbench/parts/debug/node/terminals.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00017488034791313112, 0.0001712417579255998, 0.00016760318248998374, 0.0001712417579255998, 0.00000363858271157369 ]
{ "id": 5, "code_window": [ "}\n", "\n", ".monaco-menu .monaco-action-bar.vertical .submenu-indicator {\n", "\tpadding: 0.8em .5em;\n", "}\n", "\n", ".monaco-menu .monaco-action-bar.vertical .action-item.disabled .keybinding,\n", ".monaco-menu .monaco-action-bar.vertical .action-item.disabled .submenu-indicator {\n", "\topacity: 0.4;\n", "}\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "replace", "edit_start_line_idx": 64 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-shell { height: 100%; width: 100%; margin: 0; padding: 0; overflow: hidden; font-size: 11px; user-select: none; } /* Font Families (with CJK support) */ .monaco-shell { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Ubuntu", "Droid Sans", sans-serif; } .monaco-shell:lang(zh-Hans) { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Microsoft YaHei", "PingFang SC", "Hiragino Sans GB", "Source Han Sans SC", "Source Han Sans CN", "Source Han Sans", sans-serif; } .monaco-shell:lang(zh-Hant) { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Microsoft Jhenghei", "PingFang TC", "Source Han Sans TC", "Source Han Sans", "Source Han Sans TW", sans-serif; } .monaco-shell:lang(ja) { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Meiryo", "Hiragino Kaku Gothic Pro", "Source Han Sans J", "Source Han Sans JP", "Source Han Sans", "Sazanami Gothic", "IPA Gothic", sans-serif; } .monaco-shell:lang(ko) { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Malgun Gothic", "Nanum Gothic", "Dotom", "Apple SD Gothic Neo", "AppleGothic", "Source Han Sans K", "Source Han Sans JR", "Source Han Sans", "UnDotum", "FBaekmuk Gulim", sans-serif; } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .monaco-shell img { border: 0; } .monaco-shell label { cursor: pointer; } .monaco-shell a { text-decoration: none; } .monaco-shell a:active { color: inherit; background-color: inherit; } .monaco-shell a.plain { color: inherit; text-decoration: none; } .monaco-shell a.plain:hover, .monaco-shell a.plain.hover { color: inherit; text-decoration: none; } .monaco-shell input { color: inherit; font-family: inherit; font-size: 100%; } .monaco-shell select { font-family: inherit; } .monaco-shell .pointer { cursor: pointer; } .monaco-shell .monaco-menu .monaco-action-bar.vertical { padding: .5em 0; } .monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label:not(.separator), .monaco-shell .monaco-menu .monaco-action-bar.vertical .keybinding { padding: 0.5em 2em; } .monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label.separator { padding: 0.2em 0 0 0; margin-bottom: 0.2em; } .monaco-shell .monaco-menu .monaco-action-bar.vertical .submenu-indicator { padding: 0.5em 1em; } .monaco-shell .monaco-menu .action-item { cursor: default; } /* START Keyboard Focus Indication Styles */ .monaco-shell [tabindex="0"]:focus, .monaco-shell .synthetic-focus, .monaco-shell select:focus, .monaco-shell input[type="button"]:focus, .monaco-shell input[type="text"]:focus, .monaco-shell textarea:focus, .monaco-shell input[type="checkbox"]:focus { outline-width: 1px; outline-style: solid; outline-offset: -1px; opacity: 1 !important; } .monaco-shell [tabindex="0"]:active, .monaco-shell select:active, .monaco-shell input[type="button"]:active, .monaco-shell input[type="checkbox"]:active, .monaco-shell .monaco-tree .monaco-tree-row .monaco-shell .monaco-tree.focused.no-focused-item:active:before { outline: 0 !important; /* fixes some flashing outlines from showing up when clicking */ } .monaco-shell .mac select:focus { border: none; /* outline is a square, but border has a radius, so we avoid this glitch when focused (https://github.com/Microsoft/vscode/issues/26045) */ } .monaco-shell .monaco-tree.focused .monaco-tree-row.focused [tabindex="0"]:focus { outline-width: 1px; /* higher contrast color for focusable elements in a row that shows focus feedback */ outline-style: solid; } .monaco-shell .monaco-tree.focused.no-focused-item:focus:before, .monaco-shell .monaco-list:not(.element-focused):focus:before { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 5; /* make sure we are on top of the tree items */ content: ""; pointer-events: none; /* enable click through */ outline: 1px solid; /* we still need to handle the empty tree or no focus item case */ outline-width: 1px; outline-style: solid; outline-offset: -1px; } .monaco-shell .synthetic-focus :focus { outline: 0 !important; /* elements within widgets that draw synthetic-focus should never show focus */ } .monaco-shell .monaco-inputbox.info.synthetic-focus, .monaco-shell .monaco-inputbox.warning.synthetic-focus, .monaco-shell .monaco-inputbox.error.synthetic-focus, .monaco-shell .monaco-inputbox.info input[type="text"]:focus, .monaco-shell .monaco-inputbox.warning input[type="text"]:focus, .monaco-shell .monaco-inputbox.error input[type="text"]:focus { outline: 0 !important; /* outline is not going well with decoration */ } .monaco-shell .monaco-tree.focused:focus, .monaco-shell .monaco-list:focus { outline: 0 !important; /* tree indicates focus not via outline but through the focused item */ }
src/vs/workbench/electron-browser/media/shell.css
1
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.0068335081450641155, 0.0013271607458591461, 0.0001668548648012802, 0.00026295590214431286, 0.0022763721644878387 ]
{ "id": 5, "code_window": [ "}\n", "\n", ".monaco-menu .monaco-action-bar.vertical .submenu-indicator {\n", "\tpadding: 0.8em .5em;\n", "}\n", "\n", ".monaco-menu .monaco-action-bar.vertical .action-item.disabled .keybinding,\n", ".monaco-menu .monaco-action-bar.vertical .action-item.disabled .submenu-indicator {\n", "\topacity: 0.4;\n", "}\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "replace", "edit_start_line_idx": 64 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "displayName": "TypeScript- und JavaScript-Sprachfeatures", "description": "Bietet umfangreiche Sprachunterstützung für JavaScript und TypeScript.", "typescript.reloadProjects.title": "Projekt erneut laden", "javascript.reloadProjects.title": "Projekt erneut laden", "configuration.typescript": "TypeScript", "typescript.useCodeSnippetsOnMethodSuggest.dec": "Vervollständigen Sie Funktionen mit deren Parametersignatur.", "typescript.tsdk.desc": "Gibt den Ordnerpfad mit den zu verwendenden tsserver- und lib*.d.ts-Dateien an.", "typescript.disableAutomaticTypeAcquisition": "Deaktiviert die automatische Typerfassung. Erfordert TypeScript >= 2.0.6.", "typescript.tsserver.log": "Aktiviert die Protokollierung des TS-Servers in eine Datei. Mithilfe der Protokolldatei lassen sich Probleme beim TS-Server diagnostizieren. Die Protokolldatei kann Dateipfade, Quellcode und weitere potenziell sensible Informationen aus Ihrem Projekt enthalten.", "typescript.tsserver.trace": "Aktiviert die Ablaufverfolgung von an den TS-Server gesendeten Nachrichten. Mithilfe der Ablaufverfolgung lassen sich Probleme beim TS-Server diagnostizieren. Die Ablaufverfolgung kann Dateipfade, Quellcode und weitere potenziell sensible Informationen aus Ihrem Projekt enthalten.", "typescript.validate.enable": "TypeScript-Überprüfung aktivieren/deaktivieren.", "typescript.format.enable": "Standardmäßigen TypeScript-Formatierer aktivieren/deaktivieren.", "javascript.format.enable": "Standardmäßigen JavaScript-Formatierer aktivieren/deaktivieren.", "format.insertSpaceAfterCommaDelimiter": "Definiert die Verarbeitung von Leerzeichen nach einem Kommatrennzeichen.", "format.insertSpaceAfterConstructor": "Definiert die Verarbeitung von Leerzeichen nach dem Konstruktor-Schlüsselwort. Erfordert TypeScript 2.3.0 oder höher.", "format.insertSpaceAfterSemicolonInForStatements": " Definiert die Verarbeitung von Leerzeichen nach einem Semikolon in einer for-Anweisung.", "format.insertSpaceBeforeAndAfterBinaryOperators": "Definiert die Verarbeitung von Leerzeichen nach einem binären Operator.", "format.insertSpaceAfterKeywordsInControlFlowStatements": "Definiert die Verarbeitung von Leerzeichen nach Schlüsselwörtern in einer Flusssteuerungsanweisung.", "format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": "Definiert die Verarbeitung von Leerzeichen nach einem Funktionsschlüsselwort für anonyme Funktionen.", "format.insertSpaceBeforeFunctionParenthesis": "Definiert die Verarbeitung von Leerzeichen vor Funktionsargumentklammern. Erfordert TypeScript >= 2.1.5.", "format.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis": "Definiert die Verarbeitung von Leerzeichen nach öffnenden und vor schließenden nicht leeren runden Klammern.", "format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets": "Definiert die Verarbeitung von Leerzeichen nach öffnenden und vor schließenden nicht leeren eckigen Klammern.", "format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": "Definiert die Verarbeitung von Leerzeichen nach öffnenden und vor schließenden geschweiften Klammern. Erfordert TypeScript 2.3.0 oder höher.", "format.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces": "Definiert die Verarbeitung von Leerzeichen nach öffnenden und vor schließenden geschweiften Klammern für Vorlagenzeichenfolgen. Erfordert TypeScript >= 2.0.6.", "format.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces": "Definiert die Verarbeitung von Leerzeichen nach öffnenden und vor schließenden geschweiften Klammern für JSX-Ausdrücke. Erfordert TypeScript >= 2.0.6.", "format.insertSpaceAfterTypeAssertion": "Definiert die Verarbeitung von Leerzeichen nach Typassertionen in TypeScript. Erfordert TypeScript >= 2.4.", "format.placeOpenBraceOnNewLineForFunctions": "Definiert, ob eine öffnende geschweifte Klammer für Funktionen in eine neue Zeile eingefügt wird.", "format.placeOpenBraceOnNewLineForControlBlocks": "Definiert, ob eine öffnende geschweifte Klammer für Kontrollblöcke in eine neue Zeile eingefügt wird.", "javascript.validate.enable": "JavaScript-Überprüfung aktivieren/deaktivieren.", "typescript.goToProjectConfig.title": "Zur Projektkonfiguration wechseln", "javascript.goToProjectConfig.title": "Zur Projektkonfiguration wechseln", "javascript.referencesCodeLens.enabled": "Aktiviert oder deaktiviert CodeLens-Verweise in JavaScript Dateien. Erfordert TypeScript 2.0.6 oder höher.", "typescript.referencesCodeLens.enabled": "Aktiviert oder deaktiviert CodeLens-Verweise in TypeScript Dateien. Erfordert TypeScript 2.0.6 oder höher.", "typescript.implementationsCodeLens.enabled": "Aktiviert oder deaktiviert CodeLens-Implementierungen. Erfordert TypeScript 2.2.0 oder höher.", "typescript.openTsServerLog.title": "TS Server-Protokolldatei öffnen", "typescript.restartTsServer": "TS Server neu starten", "typescript.selectTypeScriptVersion.title": "TypeScript-Version wählen", "typescript.reportStyleChecksAsWarnings": "Formatvorlagenprüfungen als Warnungen melden", "jsDocCompletion.enabled": "Automatische JSDoc-Kommentare aktivieren/deaktivieren", "javascript.implicitProjectConfig.checkJs": "Aktiviert/deaktiviert die Semantikprüfung bei JavaScript-Dateien. Diese Einstellung wird von vorhandenen \"jsconfig.json\"- oder \"tsconfig.json\"-Dateien außer Kraft gesetzt. Erfordert TypeScript 2.3.1 oder höher.", "typescript.npm": "Gibt den Pfad zur ausführbaren NPM-Datei an, die für die automatische Typerfassung verwendet wird. Hierfür ist TypeScript 2.3.4 oder höher erforderlich.", "typescript.check.npmIsInstalled": "Überprüfen Sie, ob NPM für die automatische Typerfassung installiert ist.", "javascript.nameSuggestions": "Das Einbeziehen eindeutiger Namen von der Datei in der JavaScript-Vorschlagsliste aktivieren/deaktivieren.", "typescript.tsc.autoDetect": "Steuert die automatische Erkennung von TSC-Aufgaben. \"Aus\" deaktiviert diese Funktion. \"Build\" erstellt nur Kompilierungsaufgaben mit einer Ausführung. \"Überwachen\" erstellt nur Kompilierungs- und Überwachungsaufgaben. \"Ein\" erstellt sowohl Build- als auch Überwachungsaufgaben. Der Standardwert ist \"Ein\".", "typescript.problemMatchers.tsc.label": "TypeScript-Probleme", "typescript.problemMatchers.tscWatch.label": "TypeScript-Probleme (Überwachungsmodus)", "typescript.quickSuggestionsForPaths": "Aktiviert oder deaktiviert Schnellvorschläge, wenn Sie einen Importpfad ausschreiben.", "typescript.locale": "Legt das zum Melden von TypeScript-Fehlern verwendete Gebietsschema fest. Erfordert TypeScript 2.6.0 oder höher. Der Standardwert \"null\" verwendet für TypeScript-Fehler das Gebietsschema von VS Code.", "javascript.implicitProjectConfig.experimentalDecorators": "Aktiviert oder deaktiviert \"experimentalDecorators\" für JavaScript-Dateien, die nicht Teil eines Projekts sind. Vorhandene jsconfig.json- oder tsconfig.json-Dateien setzen diese Einstellung außer Kraft. Erfordert TypeScript 2.3.1 oder höher.", "typescript.autoImportSuggestions.enabled": "Aktiviert oder deaktiviert Vorschläge für den automatischen Import. Erfordert TypeScript 2.6.1 oder höher.", "typescript.experimental.syntaxFolding": "Aktiviert bzw. deaktiviert die syntaxabhängigen Faltungsmarkierungen.", "taskDefinition.tsconfig.description": "Die \"tsconfig\"-Datei, die den TS-Build definiert." }
i18n/deu/extensions/typescript/package.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00017560386913828552, 0.00016806037456262857, 0.00016324834723491222, 0.00016719695122446865, 0.00000410076609114185 ]