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": 1, "code_window": [ " currentParent.attrsMap.placeholder === text) {\n", " return\n", " }\n", " const children = currentParent.children\n", " text = inPre || text.trim()\n", " ? decodeHTMLCached(text)\n", " // only preserve whitespace if its not right after a starting tag\n", " : preserveWhitespace && children.length ? ' ' : ''\n", " if (text) {\n", " let expression\n", " if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " ? isTextTag(currentParent) ? text : decodeHTMLCached(text)\n" ], "file_path": "src/compiler/parser/index.js", "type": "replace", "edit_start_line_idx": 254 }
import Vue from 'vue' import { MAX_UPDATE_COUNT, queueWatcher as _queueWatcher } from 'core/observer/scheduler' function queueWatcher (watcher) { watcher.vm = {} // mock vm _queueWatcher(watcher) } describe('Scheduler', () => { let spy beforeEach(() => { spy = jasmine.createSpy('scheduler') }) it('queueWatcher', done => { queueWatcher({ run: spy }) waitForUpdate(() => { expect(spy.calls.count()).toBe(1) }).then(done) }) it('dedup', done => { queueWatcher({ id: 1, run: spy }) queueWatcher({ id: 1, run: spy }) waitForUpdate(() => { expect(spy.calls.count()).toBe(1) }).then(done) }) it('allow duplicate when flushing', done => { const job = { id: 1, run: spy } queueWatcher(job) queueWatcher({ id: 2, run () { queueWatcher(job) } }) waitForUpdate(() => { expect(spy.calls.count()).toBe(2) }).then(done) }) it('call user watchers before component re-render', done => { const calls = [] const vm = new Vue({ data: { a: 1 }, template: '<div>{{ a }}</div>', watch: { a () { calls.push(1) } }, beforeUpdate () { calls.push(2) } }).$mount() vm.a = 2 waitForUpdate(() => { expect(calls).toEqual([1, 2]) }).then(done) }) it('call user watcher triggered by component re-render immediately', done => { // this happens when a component re-render updates the props of a child const calls = [] const vm = new Vue({ data: { a: 1 }, watch: { a () { calls.push(1) } }, beforeUpdate () { calls.push(2) }, template: '<div><test :a="a"></test></div>', components: { test: { props: ['a'], template: '<div>{{ a }}</div>', watch: { a () { calls.push(3) } }, beforeUpdate () { calls.push(4) } } } }).$mount() vm.a = 2 waitForUpdate(() => { expect(calls).toEqual([1, 2, 3, 4]) }).then(done) }) it('warn against infinite update loops', function (done) { let count = 0 const job = { id: 1, run () { count++ queueWatcher(job) } } queueWatcher(job) waitForUpdate(() => { expect(count).toBe(MAX_UPDATE_COUNT + 1) expect('infinite update loop').toHaveBeenWarned() }).then(done) }) it('should call newly pushed watcher after current watcher is done', done => { const callOrder = [] queueWatcher({ id: 1, user: true, run () { callOrder.push(1) queueWatcher({ id: 2, run () { callOrder.push(3) } }) callOrder.push(2) } }) waitForUpdate(() => { expect(callOrder).toEqual([1, 2, 3]) }).then(done) }) // Github issue #5191 it('emit should work when updated hook called', done => { const el = document.createElement('div') const vm = new Vue({ template: `<div><child @change="bar" :foo="foo"></child></div>`, data: { foo: 0 }, methods: { bar: spy }, components: { child: { template: `<div>{{foo}}</div>`, props: ['foo'], updated () { this.$emit('change') } } } }).$mount(el) vm.$nextTick(() => { vm.foo = 1 vm.$nextTick(() => { expect(vm.$el.innerHTML).toBe('<div>1</div>') expect(spy).toHaveBeenCalled() done() }) }) }) })
test/unit/modules/observer/scheduler.spec.js
0
https://github.com/vuejs/vue/commit/d8315c42ef5b6b739100fad5f20e8b0c41f78eef
[ 0.0001775459386408329, 0.00017412651504855603, 0.0001662529684836045, 0.00017441539966966957, 0.000002947514076367952 ]
{ "id": 1, "code_window": [ " currentParent.attrsMap.placeholder === text) {\n", " return\n", " }\n", " const children = currentParent.children\n", " text = inPre || text.trim()\n", " ? decodeHTMLCached(text)\n", " // only preserve whitespace if its not right after a starting tag\n", " : preserveWhitespace && children.length ? ' ' : ''\n", " if (text) {\n", " let expression\n", " if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " ? isTextTag(currentParent) ? text : decodeHTMLCached(text)\n" ], "file_path": "src/compiler/parser/index.js", "type": "replace", "edit_start_line_idx": 254 }
/* @flow */ import { emptyNode } from 'core/vdom/patch' import { resolveAsset, handleError } from 'core/util/index' import { mergeVNodeHook } from 'core/vdom/helpers/index' export default { create: updateDirectives, update: updateDirectives, destroy: function unbindDirectives (vnode: VNodeWithData) { updateDirectives(vnode, emptyNode) } } function updateDirectives (oldVnode: VNodeWithData, vnode: VNodeWithData) { if (oldVnode.data.directives || vnode.data.directives) { _update(oldVnode, vnode) } } function _update (oldVnode, vnode) { const isCreate = oldVnode === emptyNode const isDestroy = vnode === emptyNode const oldDirs = normalizeDirectives(oldVnode.data.directives, oldVnode.context) const newDirs = normalizeDirectives(vnode.data.directives, vnode.context) const dirsWithInsert = [] const dirsWithPostpatch = [] let key, oldDir, dir for (key in newDirs) { oldDir = oldDirs[key] dir = newDirs[key] if (!oldDir) { // new directive, bind callHook(dir, 'bind', vnode, oldVnode) if (dir.def && dir.def.inserted) { dirsWithInsert.push(dir) } } else { // existing directive, update dir.oldValue = oldDir.value callHook(dir, 'update', vnode, oldVnode) if (dir.def && dir.def.componentUpdated) { dirsWithPostpatch.push(dir) } } } if (dirsWithInsert.length) { const callInsert = () => { for (let i = 0; i < dirsWithInsert.length; i++) { callHook(dirsWithInsert[i], 'inserted', vnode, oldVnode) } } if (isCreate) { mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', callInsert) } else { callInsert() } } if (dirsWithPostpatch.length) { mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'postpatch', () => { for (let i = 0; i < dirsWithPostpatch.length; i++) { callHook(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode) } }) } if (!isCreate) { for (key in oldDirs) { if (!newDirs[key]) { // no longer present, unbind callHook(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy) } } } } const emptyModifiers = Object.create(null) function normalizeDirectives ( dirs: ?Array<VNodeDirective>, vm: Component ): { [key: string]: VNodeDirective } { const res = Object.create(null) if (!dirs) { return res } let i, dir for (i = 0; i < dirs.length; i++) { dir = dirs[i] if (!dir.modifiers) { dir.modifiers = emptyModifiers } res[getRawDirName(dir)] = dir dir.def = resolveAsset(vm.$options, 'directives', dir.name, true) } return res } function getRawDirName (dir: VNodeDirective): string { return dir.rawName || `${dir.name}.${Object.keys(dir.modifiers || {}).join('.')}` } function callHook (dir, hook, vnode, oldVnode, isDestroy) { const fn = dir.def && dir.def[hook] if (fn) { try { fn(vnode.elm, dir, vnode, oldVnode, isDestroy) } catch (e) { handleError(e, vnode.context, `directive ${dir.name} ${hook} hook`) } } }
src/core/vdom/modules/directives.js
0
https://github.com/vuejs/vue/commit/d8315c42ef5b6b739100fad5f20e8b0c41f78eef
[ 0.0001767389039741829, 0.00017399521311745048, 0.00017122588178608567, 0.0001739555737003684, 0.000001711352069833083 ]
{ "id": 2, "code_window": [ " return map\n", "}\n", "\n", "function isForbiddenTag (el): boolean {\n", " return (\n", " el.tag === 'style' ||\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "// for script (e.g. type=\"x/template\") or style, do not decode content\n", "function isTextTag (el): boolean {\n", " return el.tag === 'script' || el.tag === 'style'\n", "}\n", "\n" ], "file_path": "src/compiler/parser/index.js", "type": "add", "edit_start_line_idx": 546 }
import { parse } from 'compiler/parser/index' import { extend } from 'shared/util' import { baseOptions } from 'web/compiler/index' import { isIE, isEdge } from 'core/util/env' describe('parser', () => { it('simple element', () => { const ast = parse('<h1>hello world</h1>', baseOptions) expect(ast.tag).toBe('h1') expect(ast.plain).toBe(true) expect(ast.children[0].text).toBe('hello world') }) it('interpolation in element', () => { const ast = parse('<h1>{{msg}}</h1>', baseOptions) expect(ast.tag).toBe('h1') expect(ast.plain).toBe(true) expect(ast.children[0].expression).toBe('_s(msg)') }) it('child elements', () => { const ast = parse('<ul><li>hello world</li></ul>', baseOptions) expect(ast.tag).toBe('ul') expect(ast.plain).toBe(true) expect(ast.children[0].tag).toBe('li') expect(ast.children[0].plain).toBe(true) expect(ast.children[0].children[0].text).toBe('hello world') expect(ast.children[0].parent).toBe(ast) }) it('unary element', () => { const ast = parse('<hr>', baseOptions) expect(ast.tag).toBe('hr') expect(ast.plain).toBe(true) expect(ast.children.length).toBe(0) }) it('svg element', () => { const ast = parse('<svg><text>hello world</text></svg>', baseOptions) expect(ast.tag).toBe('svg') expect(ast.ns).toBe('svg') expect(ast.plain).toBe(true) expect(ast.children[0].tag).toBe('text') expect(ast.children[0].children[0].text).toBe('hello world') expect(ast.children[0].parent).toBe(ast) }) it('camelCase element', () => { const ast = parse('<MyComponent><p>hello world</p></MyComponent>', baseOptions) expect(ast.tag).toBe('MyComponent') expect(ast.plain).toBe(true) expect(ast.children[0].tag).toBe('p') expect(ast.children[0].plain).toBe(true) expect(ast.children[0].children[0].text).toBe('hello world') expect(ast.children[0].parent).toBe(ast) }) it('forbidden element', () => { // style const styleAst = parse('<style>error { color: red; }</style>', baseOptions) expect(styleAst.tag).toBe('style') expect(styleAst.plain).toBe(true) expect(styleAst.forbidden).toBe(true) expect(styleAst.children[0].text).toBe('error { color: red; }') expect('Templates should only be responsible for mapping the state').toHaveBeenWarned() // script const scriptAst = parse('<script type="text/javascript">alert("hello world!")</script>', baseOptions) expect(scriptAst.tag).toBe('script') expect(scriptAst.plain).toBe(false) expect(scriptAst.forbidden).toBe(true) expect(scriptAst.children[0].text).toBe('alert("hello world!")') expect('Templates should only be responsible for mapping the state').toHaveBeenWarned() }) it('not contain root element', () => { parse('hello world', baseOptions) expect('Component template requires a root element, rather than just text').toHaveBeenWarned() }) it('warn text before root element', () => { parse('before root {{ interpolation }}<div></div>', baseOptions) expect('text "before root {{ interpolation }}" outside root element will be ignored.').toHaveBeenWarned() }) it('warn text after root element', () => { parse('<div></div>after root {{ interpolation }}', baseOptions) expect('text "after root {{ interpolation }}" outside root element will be ignored.').toHaveBeenWarned() }) it('warn multiple root elements', () => { parse('<div></div><div></div>', baseOptions) expect('Component template should contain exactly one root element').toHaveBeenWarned() }) it('remove duplicate whitespace text nodes caused by comments', () => { const ast = parse(`<div><a></a> <!----> <a></a></div>`, baseOptions) expect(ast.children.length).toBe(3) expect(ast.children[0].tag).toBe('a') expect(ast.children[1].text).toBe(' ') expect(ast.children[2].tag).toBe('a') }) it('remove text nodes between v-if conditions', () => { const ast = parse(`<div><div v-if="1"></div> <div v-else-if="2"></div> <div v-else></div> <span></span></div>`, baseOptions) expect(ast.children.length).toBe(3) expect(ast.children[0].tag).toBe('div') expect(ast.children[0].ifConditions.length).toBe(3) expect(ast.children[1].text).toBe(' ') // text expect(ast.children[2].tag).toBe('span') }) it('warn non whitespace text between v-if conditions', () => { parse(`<div><div v-if="1"></div> foo <div v-else></div></div>`, baseOptions) expect(`text "foo" between v-if and v-else(-if) will be ignored`).toHaveBeenWarned() }) it('not warn 2 root elements with v-if and v-else', () => { parse('<div v-if="1"></div><div v-else></div>', baseOptions) expect('Component template should contain exactly one root element') .not.toHaveBeenWarned() }) it('not warn 3 root elements with v-if, v-else-if and v-else', () => { parse('<div v-if="1"></div><div v-else-if="2"></div><div v-else></div>', baseOptions) expect('Component template should contain exactly one root element') .not.toHaveBeenWarned() }) it('not warn 2 root elements with v-if and v-else on separate lines', () => { parse(` <div v-if="1"></div> <div v-else></div> `, baseOptions) expect('Component template should contain exactly one root element') .not.toHaveBeenWarned() }) it('not warn 3 or more root elements with v-if, v-else-if and v-else on separate lines', () => { parse(` <div v-if="1"></div> <div v-else-if="2"></div> <div v-else></div> `, baseOptions) expect('Component template should contain exactly one root element') .not.toHaveBeenWarned() parse(` <div v-if="1"></div> <div v-else-if="2"></div> <div v-else-if="3"></div> <div v-else-if="4"></div> <div v-else></div> `, baseOptions) expect('Component template should contain exactly one root element') .not.toHaveBeenWarned() }) it('generate correct ast for 2 root elements with v-if and v-else on separate lines', () => { const ast = parse(` <div v-if="1"></div> <p v-else></p> `, baseOptions) expect(ast.tag).toBe('div') expect(ast.ifConditions[1].block.tag).toBe('p') }) it('generate correct ast for 3 or more root elements with v-if and v-else on separate lines', () => { const ast = parse(` <div v-if="1"></div> <span v-else-if="2"></span> <p v-else></p> `, baseOptions) expect(ast.tag).toBe('div') expect(ast.ifConditions[0].block.tag).toBe('div') expect(ast.ifConditions[1].block.tag).toBe('span') expect(ast.ifConditions[2].block.tag).toBe('p') const astMore = parse(` <div v-if="1"></div> <span v-else-if="2"></span> <div v-else-if="3"></div> <span v-else-if="4"></span> <p v-else></p> `, baseOptions) expect(astMore.tag).toBe('div') expect(astMore.ifConditions[0].block.tag).toBe('div') expect(astMore.ifConditions[1].block.tag).toBe('span') expect(astMore.ifConditions[2].block.tag).toBe('div') expect(astMore.ifConditions[3].block.tag).toBe('span') expect(astMore.ifConditions[4].block.tag).toBe('p') }) it('warn 2 root elements with v-if', () => { parse('<div v-if="1"></div><div v-if="2"></div>', baseOptions) expect('Component template should contain exactly one root element').toHaveBeenWarned() }) it('warn 3 root elements with v-if and v-else on first 2', () => { parse('<div v-if="1"></div><div v-else></div><div></div>', baseOptions) expect('Component template should contain exactly one root element').toHaveBeenWarned() }) it('warn 3 root elements with v-if and v-else-if on first 2', () => { parse('<div v-if="1"></div><div v-else-if></div><div></div>', baseOptions) expect('Component template should contain exactly one root element').toHaveBeenWarned() }) it('warn 4 root elements with v-if, v-else-if and v-else on first 2', () => { parse('<div v-if="1"></div><div v-else-if></div><div v-else></div><div></div>', baseOptions) expect('Component template should contain exactly one root element').toHaveBeenWarned() }) it('warn 2 root elements with v-if and v-else with v-for on 2nd', () => { parse('<div v-if="1"></div><div v-else v-for="i in [1]"></div>', baseOptions) expect('Cannot use v-for on stateful component root element because it renders multiple elements') .toHaveBeenWarned() }) it('warn 2 root elements with v-if and v-else-if with v-for on 2nd', () => { parse('<div v-if="1"></div><div v-else-if="2" v-for="i in [1]"></div>', baseOptions) expect('Cannot use v-for on stateful component root element because it renders multiple elements') .toHaveBeenWarned() }) it('warn <template> as root element', () => { parse('<template></template>', baseOptions) expect('Cannot use <template> as component root element').toHaveBeenWarned() }) it('warn <slot> as root element', () => { parse('<slot></slot>', baseOptions) expect('Cannot use <slot> as component root element').toHaveBeenWarned() }) it('warn v-for on root element', () => { parse('<div v-for="item in items"></div>', baseOptions) expect('Cannot use v-for on stateful component root element').toHaveBeenWarned() }) it('warn <template> key', () => { parse('<div><template v-for="i in 10" :key="i"></template></div>', baseOptions) expect('<template> cannot be keyed').toHaveBeenWarned() }) it('v-pre directive', () => { const ast = parse('<div v-pre id="message1"><p>{{msg}}</p></div>', baseOptions) expect(ast.pre).toBe(true) expect(ast.attrs[0].name).toBe('id') expect(ast.attrs[0].value).toBe('"message1"') expect(ast.children[0].children[0].text).toBe('{{msg}}') }) it('v-for directive basic syntax', () => { const ast = parse('<ul><li v-for="item in items"></li></ul>', baseOptions) const liAst = ast.children[0] expect(liAst.for).toBe('items') expect(liAst.alias).toBe('item') }) it('v-for directive iteration syntax', () => { const ast = parse('<ul><li v-for="(item, index) in items"></li></ul>', baseOptions) const liAst = ast.children[0] expect(liAst.for).toBe('items') expect(liAst.alias).toBe('item') expect(liAst.iterator1).toBe('index') expect(liAst.iterator2).toBeUndefined() }) it('v-for directive iteration syntax (multiple)', () => { const ast = parse('<ul><li v-for="(item, key, index) in items"></li></ul>', baseOptions) const liAst = ast.children[0] expect(liAst.for).toBe('items') expect(liAst.alias).toBe('item') expect(liAst.iterator1).toBe('key') expect(liAst.iterator2).toBe('index') }) it('v-for directive key', () => { const ast = parse('<ul><li v-for="item in items" :key="item.uid"></li></ul>', baseOptions) const liAst = ast.children[0] expect(liAst.for).toBe('items') expect(liAst.alias).toBe('item') expect(liAst.key).toBe('item.uid') }) it('v-for directive invalid syntax', () => { parse('<ul><li v-for="item into items"></li></ul>', baseOptions) expect('Invalid v-for expression').toHaveBeenWarned() }) it('v-if directive syntax', () => { const ast = parse('<p v-if="show">hello world</p>', baseOptions) expect(ast.if).toBe('show') expect(ast.ifConditions[0].exp).toBe('show') }) it('v-else-if directive syntax', () => { const ast = parse('<div><p v-if="show">hello</p><span v-else-if="2">elseif</span><p v-else>world</p></div>', baseOptions) const ifAst = ast.children[0] const conditionsAst = ifAst.ifConditions expect(conditionsAst.length).toBe(3) expect(conditionsAst[1].block.children[0].text).toBe('elseif') expect(conditionsAst[1].block.parent).toBe(ast) expect(conditionsAst[2].block.children[0].text).toBe('world') expect(conditionsAst[2].block.parent).toBe(ast) }) it('v-else directive syntax', () => { const ast = parse('<div><p v-if="show">hello</p><p v-else>world</p></div>', baseOptions) const ifAst = ast.children[0] const conditionsAst = ifAst.ifConditions expect(conditionsAst.length).toBe(2) expect(conditionsAst[1].block.children[0].text).toBe('world') expect(conditionsAst[1].block.parent).toBe(ast) }) it('v-else-if directive invalid syntax', () => { parse('<div><p v-else-if="1">world</p></div>', baseOptions) expect('v-else-if="1" used on element').toHaveBeenWarned() }) it('v-else directive invalid syntax', () => { parse('<div><p v-else>world</p></div>', baseOptions) expect('v-else used on element').toHaveBeenWarned() }) it('v-once directive syntax', () => { const ast = parse('<p v-once>world</p>', baseOptions) expect(ast.once).toBe(true) }) it('slot tag single syntax', () => { const ast = parse('<div><slot></slot></div>', baseOptions) expect(ast.children[0].tag).toBe('slot') expect(ast.children[0].slotName).toBeUndefined() }) it('slot tag named syntax', () => { const ast = parse('<div><slot name="one">hello world</slot></div>', baseOptions) expect(ast.children[0].tag).toBe('slot') expect(ast.children[0].slotName).toBe('"one"') }) it('slot target', () => { const ast = parse('<p slot="one">hello world</p>', baseOptions) expect(ast.slotTarget).toBe('"one"') }) it('component properties', () => { const ast = parse('<my-component :msg="hello"></my-component>', baseOptions) expect(ast.attrs[0].name).toBe('msg') expect(ast.attrs[0].value).toBe('hello') }) it('component "is" attribute', () => { const ast = parse('<my-component is="component1"></my-component>', baseOptions) expect(ast.component).toBe('"component1"') }) it('component "inline-template" attribute', () => { const ast = parse('<my-component inline-template>hello world</my-component>', baseOptions) expect(ast.inlineTemplate).toBe(true) }) it('class binding', () => { // static const ast1 = parse('<p class="class1">hello world</p>', baseOptions) expect(ast1.staticClass).toBe('"class1"') // dynamic const ast2 = parse('<p :class="class1">hello world</p>', baseOptions) expect(ast2.classBinding).toBe('class1') // interpolation warning parse('<p class="{{error}}">hello world</p>', baseOptions) expect('Interpolation inside attributes has been removed').toHaveBeenWarned() }) it('style binding', () => { const ast = parse('<p :style="error">hello world</p>', baseOptions) expect(ast.styleBinding).toBe('error') }) it('attribute with v-bind', () => { const ast = parse('<input type="text" name="field1" :value="msg">', baseOptions) expect(ast.attrsList[0].name).toBe('type') expect(ast.attrsList[0].value).toBe('text') expect(ast.attrsList[1].name).toBe('name') expect(ast.attrsList[1].value).toBe('field1') expect(ast.attrsMap['type']).toBe('text') expect(ast.attrsMap['name']).toBe('field1') expect(ast.attrs[0].name).toBe('type') expect(ast.attrs[0].value).toBe('"text"') expect(ast.attrs[1].name).toBe('name') expect(ast.attrs[1].value).toBe('"field1"') expect(ast.props[0].name).toBe('value') expect(ast.props[0].value).toBe('msg') }) it('attribute with v-on', () => { const ast = parse('<input type="text" name="field1" :value="msg" @input="onInput">', baseOptions) expect(ast.events.input.value).toBe('onInput') }) it('attribute with directive', () => { const ast = parse('<input type="text" name="field1" :value="msg" v-validate:field1="required">', baseOptions) expect(ast.directives[0].name).toBe('validate') expect(ast.directives[0].value).toBe('required') expect(ast.directives[0].arg).toBe('field1') }) it('attribute with modifiered directive', () => { const ast = parse('<input type="text" name="field1" :value="msg" v-validate.on.off>', baseOptions) expect(ast.directives[0].modifiers.on).toBe(true) expect(ast.directives[0].modifiers.off).toBe(true) }) it('literal attribute', () => { // basic const ast1 = parse('<input type="text" name="field1" value="hello world">', baseOptions) expect(ast1.attrsList[0].name).toBe('type') expect(ast1.attrsList[0].value).toBe('text') expect(ast1.attrsList[1].name).toBe('name') expect(ast1.attrsList[1].value).toBe('field1') expect(ast1.attrsList[2].name).toBe('value') expect(ast1.attrsList[2].value).toBe('hello world') expect(ast1.attrsMap['type']).toBe('text') expect(ast1.attrsMap['name']).toBe('field1') expect(ast1.attrsMap['value']).toBe('hello world') expect(ast1.attrs[0].name).toBe('type') expect(ast1.attrs[0].value).toBe('"text"') expect(ast1.attrs[1].name).toBe('name') expect(ast1.attrs[1].value).toBe('"field1"') expect(ast1.attrs[2].name).toBe('value') expect(ast1.attrs[2].value).toBe('"hello world"') // interpolation warning parse('<input type="text" name="field1" value="{{msg}}">', baseOptions) expect('Interpolation inside attributes has been removed').toHaveBeenWarned() }) if (!isIE && !isEdge) { it('duplicate attribute', () => { parse('<p class="class1" class="class1">hello world</p>', baseOptions) expect('duplicate attribute').toHaveBeenWarned() }) } it('custom delimiter', () => { const ast = parse('<p>{msg}</p>', extend({ delimiters: ['{', '}'] }, baseOptions)) expect(ast.children[0].expression).toBe('_s(msg)') }) it('not specified getTagNamespace option', () => { const options = extend({}, baseOptions) delete options.getTagNamespace const ast = parse('<svg><text>hello world</text></svg>', options) expect(ast.tag).toBe('svg') expect(ast.ns).toBeUndefined() }) it('not specified mustUseProp', () => { const options = extend({}, baseOptions) delete options.mustUseProp const ast = parse('<input type="text" name="field1" :value="msg">', options) expect(ast.props).toBeUndefined() }) it('pre/post transforms', () => { const options = extend({}, baseOptions) const spy1 = jasmine.createSpy('preTransform') const spy2 = jasmine.createSpy('postTransform') options.modules = options.modules.concat([{ preTransformNode (el) { spy1(el.tag) }, postTransformNode (el) { expect(el.attrs.length).toBe(1) spy2(el.tag) } }]) parse('<img v-pre src="hi">', options) expect(spy1).toHaveBeenCalledWith('img') expect(spy2).toHaveBeenCalledWith('img') }) it('preserve whitespace in <pre> tag', function () { const options = extend({}, baseOptions) const ast = parse('<pre><code> \n<span>hi</span>\n </code><span> </span></pre>', options) const code = ast.children[0] expect(code.children[0].type).toBe(3) expect(code.children[0].text).toBe(' \n') expect(code.children[2].type).toBe(3) expect(code.children[2].text).toBe('\n ') const span = ast.children[1] expect(span.children[0].type).toBe(3) expect(span.children[0].text).toBe(' ') }) it('forgivingly handle < in plain text', () => { const options = extend({}, baseOptions) const ast = parse('<p>1 < 2 < 3</p>', options) expect(ast.tag).toBe('p') expect(ast.children.length).toBe(1) expect(ast.children[0].type).toBe(3) expect(ast.children[0].text).toBe('1 < 2 < 3') }) it('IE conditional comments', () => { const options = extend({}, baseOptions) const ast = parse(` <div> <!--[if lte IE 8]> <p>Test 1</p> <![endif]--> </div> `, options) expect(ast.tag).toBe('div') expect(ast.children.length).toBe(0) }) it('parse content in textarea as text', () => { const options = extend({}, baseOptions) const whitespace = parse(` <textarea> <p>Test 1</p> test2 </textarea> `, options) expect(whitespace.tag).toBe('textarea') expect(whitespace.children.length).toBe(1) expect(whitespace.children[0].type).toBe(3) // textarea is whitespace sensitive expect(whitespace.children[0].text).toBe(` <p>Test 1</p> test2 `) const comment = parse('<textarea><!--comment--></textarea>', options) expect(comment.tag).toBe('textarea') expect(comment.children.length).toBe(1) expect(comment.children[0].type).toBe(3) expect(comment.children[0].text).toBe('<!--comment-->') }) })
test/unit/modules/compiler/parser.spec.js
1
https://github.com/vuejs/vue/commit/d8315c42ef5b6b739100fad5f20e8b0c41f78eef
[ 0.9188723564147949, 0.03218689560890198, 0.0001671367062954232, 0.00017101653793361038, 0.1642441749572754 ]
{ "id": 2, "code_window": [ " return map\n", "}\n", "\n", "function isForbiddenTag (el): boolean {\n", " return (\n", " el.tag === 'style' ||\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "// for script (e.g. type=\"x/template\") or style, do not decode content\n", "function isTextTag (el): boolean {\n", " return el.tag === 'script' || el.tag === 'style'\n", "}\n", "\n" ], "file_path": "src/compiler/parser/index.js", "type": "add", "edit_start_line_idx": 546 }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Vue benchmark</title> <style type="text/css"> html, body { margin: 0; padding: 0 10px; font-family: sans-serif; } #fps { position: fixed; top: 0px; right: 0px; padding: 32px; font-size: 32px; text-align: right; } * { box-sizing: border-box; } .server-uptime { display: block; overflow: hidden; margin: 0 auto; width: 50%; } .server-uptime + .server-uptime { margin: 20px auto 0 auto; border-top: 1px solid #999; } .days { display: flex; flex-direction: row; flex-flow: wrap; } .uptime-day { display: flex; } span.uptime-day-status { width: 10px; height: 10px; margin: 1px; } .hover { display: none; } .uptime-day-status:hover + .hover { display: flex; position: absolute; margin-top: -35px; margin-left: -30px; border-radius: 4px; color: #eee; background-color: #333; padding: 10px; font-size: 11px; } </style> </head> <body> <p>Reference: <a href="https://github.com/tildeio/glimmer/blob/master/packages/glimmer-demos/lib/uptime.ts">Ember Glimmer 2 demo</a></p> <div id="app"> <p>FPS: {{ fps }}</p> <button @click="toggle">{{ playing ? 'pause' : 'play' }}</button> <server-uptime v-for="server in servers" :key="server.name" :name="server.name" :days="server.days"> </server-uptime> </div> <script src="../../dist/vue.min.js"></script> <script> // functional components are prefect for small, presentational components // and they are much more efficient than stateful ones. Vue.component('uptime-day', { props: ['day'], functional: true, render (h, ctx) { var day = ctx.props.day return h('div', { staticClass: 'uptime-day'}, [ h('span', { staticClass: 'uptime-day-status', style: { backgroundColor: day.up ? '#8cc665' : '#ccc' } }), h('span', { staticClass: 'hover' }, [day.number + ': ' + day.up ? 'Servers operational!' : 'Red alert!']) ]) } }) Vue.component('server-uptime', { props: ['name', 'days'], computed: { upDays () { return this.days.reduce(function (upDays, day) { return upDays += (day.up ? 1 : 0) }, 0) }, maxStreak () { var streak = this.days.reduce(([max, streak], day) => { if (day.up && streak + 1 > max) { return [streak + 1, streak + 1] } else if (day.up) { return [max, streak + 1] } else { return [max, 0] } }, [0, 0]) return streak.max } }, template: ` <div class="server-uptime"> <h1>{{name}}</h1> <h2>{{upDays}} Days Up</h2> <h2>Biggest Streak: {{maxStreak}}</h2> <div class="days"> <uptime-day v-for="day in days" :key="day.number" :day="day"> </uptime-day> </div> </div> ` }) function generateServer (name) { var days = [] for (var i=0; i<=364; i++) { var up = Math.random() > 0.2 days.push({ number: i, up }) } return { name, days } } function generateServers () { return [ generateServer("Stefan's Server"), generateServer("Godfrey's Server"), generateServer("Yehuda's Server") ] } var s = window.performance.now() var app = new Vue({ el: '#app', data: { fps: 0, playing: false, servers: Object.freeze(generateServers()) }, methods: { toggle () { this.playing = !this.playing if (this.playing) { update() } else { clearTimeout(timeoutId) } } } }) console.log('initial render: ' + (window.performance.now() - s) + 'ms') var fpsMeter = { alpha: 2/121, lastValue: null, push (dataPoint) { if (this.lastValue) { return this.lastValue = this.lastValue + this.alpha * (dataPoint - this.lastValue) } else { return this.lastValue = dataPoint } } } var timeoutId var lastFrame = null function update () { var thisFrame = window.performance.now() if (lastFrame) { app.fps = Math.round(fpsMeter.push(1000 / (thisFrame - lastFrame))) } app.servers = Object.freeze(generateServers()) timeoutId = setTimeout(update, 0) // not using rAF because that limits us to 60fps! lastFrame = thisFrame } </script> </body> </html>
benchmarks/uptime/index.html
0
https://github.com/vuejs/vue/commit/d8315c42ef5b6b739100fad5f20e8b0c41f78eef
[ 0.0006828779587522149, 0.00021592162374872714, 0.0001666219613980502, 0.0001709728385321796, 0.0001152278928202577 ]
{ "id": 2, "code_window": [ " return map\n", "}\n", "\n", "function isForbiddenTag (el): boolean {\n", " return (\n", " el.tag === 'style' ||\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "// for script (e.g. type=\"x/template\") or style, do not decode content\n", "function isTextTag (el): boolean {\n", " return el.tag === 'script' || el.tag === 'style'\n", "}\n", "\n" ], "file_path": "src/compiler/parser/index.js", "type": "add", "edit_start_line_idx": 546 }
import { patch } from 'web/runtime/patch' import VNode from 'core/vdom/vnode' describe('vdom events module', () => { it('should attach event handler to element', () => { const click = jasmine.createSpy() const vnode = new VNode('a', { on: { click }}) const elm = patch(null, vnode) document.body.appendChild(elm) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(1) }) it('should not duplicate the same listener', () => { const click = jasmine.createSpy() const vnode1 = new VNode('a', { on: { click }}) const vnode2 = new VNode('a', { on: { click }}) const elm = patch(null, vnode1) patch(vnode1, vnode2) document.body.appendChild(elm) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(1) }) it('should update different listener', () => { const click = jasmine.createSpy() const click2 = jasmine.createSpy() const vnode1 = new VNode('a', { on: { click }}) const vnode2 = new VNode('a', { on: { click: click2 }}) const elm = patch(null, vnode1) document.body.appendChild(elm) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(1) expect(click2.calls.count()).toBe(0) patch(vnode1, vnode2) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(1) expect(click2.calls.count()).toBe(1) }) it('should attach Array of multiple handlers', () => { const click = jasmine.createSpy() const vnode = new VNode('a', { on: { click: [click, click] }}) const elm = patch(null, vnode) document.body.appendChild(elm) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(2) }) it('should update Array of multiple handlers', () => { const click = jasmine.createSpy() const click2 = jasmine.createSpy() const vnode1 = new VNode('a', { on: { click: [click, click2] }}) const vnode2 = new VNode('a', { on: { click: [click] }}) const elm = patch(null, vnode1) document.body.appendChild(elm) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(1) expect(click2.calls.count()).toBe(1) patch(vnode1, vnode2) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(2) expect(click2.calls.count()).toBe(1) }) it('should remove handlers that are no longer present', () => { const click = jasmine.createSpy() const vnode1 = new VNode('a', { on: { click }}) const vnode2 = new VNode('a', {}) const elm = patch(null, vnode1) document.body.appendChild(elm) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(1) patch(vnode1, vnode2) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(1) }) it('should remove Array handlers that are no longer present', () => { const click = jasmine.createSpy() const vnode1 = new VNode('a', { on: { click: [click, click] }}) const vnode2 = new VNode('a', {}) const elm = patch(null, vnode1) document.body.appendChild(elm) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(2) patch(vnode1, vnode2) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(2) }) // #4650 it('should handle single -> array or array -> single handler changes', () => { const click = jasmine.createSpy() const click2 = jasmine.createSpy() const click3 = jasmine.createSpy() const vnode0 = new VNode('a', { on: { click: click }}) const vnode1 = new VNode('a', { on: { click: [click, click2] }}) const vnode2 = new VNode('a', { on: { click: click }}) const vnode3 = new VNode('a', { on: { click: [click2, click3] }}) const elm = patch(null, vnode0) document.body.appendChild(elm) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(1) expect(click2.calls.count()).toBe(0) patch(vnode0, vnode1) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(2) expect(click2.calls.count()).toBe(1) patch(vnode1, vnode2) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(3) expect(click2.calls.count()).toBe(1) patch(vnode2, vnode3) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(3) expect(click2.calls.count()).toBe(2) expect(click3.calls.count()).toBe(1) }) })
test/unit/modules/vdom/modules/events.spec.js
0
https://github.com/vuejs/vue/commit/d8315c42ef5b6b739100fad5f20e8b0c41f78eef
[ 0.0001723396999295801, 0.00016915242304094136, 0.00016754359239712358, 0.00016878804308362305, 0.000001309468075305631 ]
{ "id": 2, "code_window": [ " return map\n", "}\n", "\n", "function isForbiddenTag (el): boolean {\n", " return (\n", " el.tag === 'style' ||\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "// for script (e.g. type=\"x/template\") or style, do not decode content\n", "function isTextTag (el): boolean {\n", " return el.tag === 'script' || el.tag === 'style'\n", "}\n", "\n" ], "file_path": "src/compiler/parser/index.js", "type": "add", "edit_start_line_idx": 546 }
import Vue from 'vue' describe('Instance methods lifecycle', () => { describe('$mount', () => { it('empty mount', () => { const vm = new Vue({ data: { msg: 'hi' }, template: '<div>{{ msg }}</div>' }).$mount() expect(vm.$el.tagName).toBe('DIV') expect(vm.$el.textContent).toBe('hi') }) it('mount to existing element', () => { const el = document.createElement('div') el.innerHTML = '{{ msg }}' const vm = new Vue({ data: { msg: 'hi' } }).$mount(el) expect(vm.$el.tagName).toBe('DIV') expect(vm.$el.textContent).toBe('hi') }) it('mount to id', () => { const el = document.createElement('div') el.id = 'mount-test' el.innerHTML = '{{ msg }}' document.body.appendChild(el) const vm = new Vue({ data: { msg: 'hi' } }).$mount('#mount-test') expect(vm.$el.tagName).toBe('DIV') expect(vm.$el.textContent).toBe('hi') }) }) describe('$destroy', () => { it('remove self from parent', () => { const vm = new Vue({ template: '<test></test>', components: { test: { template: '<div></div>' } } }).$mount() vm.$children[0].$destroy() expect(vm.$children.length).toBe(0) }) it('teardown watchers', () => { const vm = new Vue({ data: { a: 123 }, template: '<div></div>' }).$mount() vm.$watch('a', () => {}) vm.$destroy() expect(vm._watcher.active).toBe(false) expect(vm._watchers.every(w => !w.active)).toBe(true) }) it('remove self from data observer', () => { const vm = new Vue({ data: { a: 1 }}) vm.$destroy() expect(vm.$data.__ob__.vmCount).toBe(0) }) it('avoid duplicate calls', () => { const spy = jasmine.createSpy('destroy') const vm = new Vue({ beforeDestroy: spy }) vm.$destroy() vm.$destroy() expect(spy.calls.count()).toBe(1) }) }) describe('$forceUpdate', () => { it('should force update', done => { const vm = new Vue({ data: { a: {} }, template: '<div>{{ a.b }}</div>' }).$mount() expect(vm.$el.textContent).toBe('') vm.a.b = 'foo' waitForUpdate(() => { // should not work because adding new property expect(vm.$el.textContent).toBe('') vm.$forceUpdate() }).then(() => { expect(vm.$el.textContent).toBe('foo') }).then(done) }) }) describe('$nextTick', () => { it('should be called after DOM update in correct context', done => { const vm = new Vue({ template: '<div>{{ msg }}</div>', data: { msg: 'foo' } }).$mount() vm.msg = 'bar' vm.$nextTick(function () { expect(this).toBe(vm) expect(vm.$el.textContent).toBe('bar') done() }) }) if (typeof Promise !== 'undefined') { it('should be called after DOM update in correct context, when using Promise syntax', done => { const vm = new Vue({ template: '<div>{{ msg }}</div>', data: { msg: 'foo' } }).$mount() vm.msg = 'bar' vm.$nextTick().then(ctx => { expect(ctx).toBe(vm) expect(vm.$el.textContent).toBe('bar') done() }) }) } }) })
test/unit/features/instance/methods-lifecycle.spec.js
0
https://github.com/vuejs/vue/commit/d8315c42ef5b6b739100fad5f20e8b0c41f78eef
[ 0.001512568793259561, 0.00032158204703591764, 0.00016803588368929923, 0.00018588329839985818, 0.0003571949782781303 ]
{ "id": 3, "code_window": [ " expect(comment.children[0].type).toBe(3)\n", " expect(comment.children[0].text).toBe('<!--comment-->')\n", " })\n", "})" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " // #5526\n", " it('should not decode text in script tags', () => {\n", " const options = extend({}, baseOptions)\n", " const ast = parse(`<script type=\"x/template\">&gt;<foo>&lt;</script>`, options)\n", " expect(ast.children[0].text).toBe(`&gt;<foo>&lt;`)\n", " })\n" ], "file_path": "test/unit/modules/compiler/parser.spec.js", "type": "add", "edit_start_line_idx": 543 }
import { parse } from 'compiler/parser/index' import { extend } from 'shared/util' import { baseOptions } from 'web/compiler/index' import { isIE, isEdge } from 'core/util/env' describe('parser', () => { it('simple element', () => { const ast = parse('<h1>hello world</h1>', baseOptions) expect(ast.tag).toBe('h1') expect(ast.plain).toBe(true) expect(ast.children[0].text).toBe('hello world') }) it('interpolation in element', () => { const ast = parse('<h1>{{msg}}</h1>', baseOptions) expect(ast.tag).toBe('h1') expect(ast.plain).toBe(true) expect(ast.children[0].expression).toBe('_s(msg)') }) it('child elements', () => { const ast = parse('<ul><li>hello world</li></ul>', baseOptions) expect(ast.tag).toBe('ul') expect(ast.plain).toBe(true) expect(ast.children[0].tag).toBe('li') expect(ast.children[0].plain).toBe(true) expect(ast.children[0].children[0].text).toBe('hello world') expect(ast.children[0].parent).toBe(ast) }) it('unary element', () => { const ast = parse('<hr>', baseOptions) expect(ast.tag).toBe('hr') expect(ast.plain).toBe(true) expect(ast.children.length).toBe(0) }) it('svg element', () => { const ast = parse('<svg><text>hello world</text></svg>', baseOptions) expect(ast.tag).toBe('svg') expect(ast.ns).toBe('svg') expect(ast.plain).toBe(true) expect(ast.children[0].tag).toBe('text') expect(ast.children[0].children[0].text).toBe('hello world') expect(ast.children[0].parent).toBe(ast) }) it('camelCase element', () => { const ast = parse('<MyComponent><p>hello world</p></MyComponent>', baseOptions) expect(ast.tag).toBe('MyComponent') expect(ast.plain).toBe(true) expect(ast.children[0].tag).toBe('p') expect(ast.children[0].plain).toBe(true) expect(ast.children[0].children[0].text).toBe('hello world') expect(ast.children[0].parent).toBe(ast) }) it('forbidden element', () => { // style const styleAst = parse('<style>error { color: red; }</style>', baseOptions) expect(styleAst.tag).toBe('style') expect(styleAst.plain).toBe(true) expect(styleAst.forbidden).toBe(true) expect(styleAst.children[0].text).toBe('error { color: red; }') expect('Templates should only be responsible for mapping the state').toHaveBeenWarned() // script const scriptAst = parse('<script type="text/javascript">alert("hello world!")</script>', baseOptions) expect(scriptAst.tag).toBe('script') expect(scriptAst.plain).toBe(false) expect(scriptAst.forbidden).toBe(true) expect(scriptAst.children[0].text).toBe('alert("hello world!")') expect('Templates should only be responsible for mapping the state').toHaveBeenWarned() }) it('not contain root element', () => { parse('hello world', baseOptions) expect('Component template requires a root element, rather than just text').toHaveBeenWarned() }) it('warn text before root element', () => { parse('before root {{ interpolation }}<div></div>', baseOptions) expect('text "before root {{ interpolation }}" outside root element will be ignored.').toHaveBeenWarned() }) it('warn text after root element', () => { parse('<div></div>after root {{ interpolation }}', baseOptions) expect('text "after root {{ interpolation }}" outside root element will be ignored.').toHaveBeenWarned() }) it('warn multiple root elements', () => { parse('<div></div><div></div>', baseOptions) expect('Component template should contain exactly one root element').toHaveBeenWarned() }) it('remove duplicate whitespace text nodes caused by comments', () => { const ast = parse(`<div><a></a> <!----> <a></a></div>`, baseOptions) expect(ast.children.length).toBe(3) expect(ast.children[0].tag).toBe('a') expect(ast.children[1].text).toBe(' ') expect(ast.children[2].tag).toBe('a') }) it('remove text nodes between v-if conditions', () => { const ast = parse(`<div><div v-if="1"></div> <div v-else-if="2"></div> <div v-else></div> <span></span></div>`, baseOptions) expect(ast.children.length).toBe(3) expect(ast.children[0].tag).toBe('div') expect(ast.children[0].ifConditions.length).toBe(3) expect(ast.children[1].text).toBe(' ') // text expect(ast.children[2].tag).toBe('span') }) it('warn non whitespace text between v-if conditions', () => { parse(`<div><div v-if="1"></div> foo <div v-else></div></div>`, baseOptions) expect(`text "foo" between v-if and v-else(-if) will be ignored`).toHaveBeenWarned() }) it('not warn 2 root elements with v-if and v-else', () => { parse('<div v-if="1"></div><div v-else></div>', baseOptions) expect('Component template should contain exactly one root element') .not.toHaveBeenWarned() }) it('not warn 3 root elements with v-if, v-else-if and v-else', () => { parse('<div v-if="1"></div><div v-else-if="2"></div><div v-else></div>', baseOptions) expect('Component template should contain exactly one root element') .not.toHaveBeenWarned() }) it('not warn 2 root elements with v-if and v-else on separate lines', () => { parse(` <div v-if="1"></div> <div v-else></div> `, baseOptions) expect('Component template should contain exactly one root element') .not.toHaveBeenWarned() }) it('not warn 3 or more root elements with v-if, v-else-if and v-else on separate lines', () => { parse(` <div v-if="1"></div> <div v-else-if="2"></div> <div v-else></div> `, baseOptions) expect('Component template should contain exactly one root element') .not.toHaveBeenWarned() parse(` <div v-if="1"></div> <div v-else-if="2"></div> <div v-else-if="3"></div> <div v-else-if="4"></div> <div v-else></div> `, baseOptions) expect('Component template should contain exactly one root element') .not.toHaveBeenWarned() }) it('generate correct ast for 2 root elements with v-if and v-else on separate lines', () => { const ast = parse(` <div v-if="1"></div> <p v-else></p> `, baseOptions) expect(ast.tag).toBe('div') expect(ast.ifConditions[1].block.tag).toBe('p') }) it('generate correct ast for 3 or more root elements with v-if and v-else on separate lines', () => { const ast = parse(` <div v-if="1"></div> <span v-else-if="2"></span> <p v-else></p> `, baseOptions) expect(ast.tag).toBe('div') expect(ast.ifConditions[0].block.tag).toBe('div') expect(ast.ifConditions[1].block.tag).toBe('span') expect(ast.ifConditions[2].block.tag).toBe('p') const astMore = parse(` <div v-if="1"></div> <span v-else-if="2"></span> <div v-else-if="3"></div> <span v-else-if="4"></span> <p v-else></p> `, baseOptions) expect(astMore.tag).toBe('div') expect(astMore.ifConditions[0].block.tag).toBe('div') expect(astMore.ifConditions[1].block.tag).toBe('span') expect(astMore.ifConditions[2].block.tag).toBe('div') expect(astMore.ifConditions[3].block.tag).toBe('span') expect(astMore.ifConditions[4].block.tag).toBe('p') }) it('warn 2 root elements with v-if', () => { parse('<div v-if="1"></div><div v-if="2"></div>', baseOptions) expect('Component template should contain exactly one root element').toHaveBeenWarned() }) it('warn 3 root elements with v-if and v-else on first 2', () => { parse('<div v-if="1"></div><div v-else></div><div></div>', baseOptions) expect('Component template should contain exactly one root element').toHaveBeenWarned() }) it('warn 3 root elements with v-if and v-else-if on first 2', () => { parse('<div v-if="1"></div><div v-else-if></div><div></div>', baseOptions) expect('Component template should contain exactly one root element').toHaveBeenWarned() }) it('warn 4 root elements with v-if, v-else-if and v-else on first 2', () => { parse('<div v-if="1"></div><div v-else-if></div><div v-else></div><div></div>', baseOptions) expect('Component template should contain exactly one root element').toHaveBeenWarned() }) it('warn 2 root elements with v-if and v-else with v-for on 2nd', () => { parse('<div v-if="1"></div><div v-else v-for="i in [1]"></div>', baseOptions) expect('Cannot use v-for on stateful component root element because it renders multiple elements') .toHaveBeenWarned() }) it('warn 2 root elements with v-if and v-else-if with v-for on 2nd', () => { parse('<div v-if="1"></div><div v-else-if="2" v-for="i in [1]"></div>', baseOptions) expect('Cannot use v-for on stateful component root element because it renders multiple elements') .toHaveBeenWarned() }) it('warn <template> as root element', () => { parse('<template></template>', baseOptions) expect('Cannot use <template> as component root element').toHaveBeenWarned() }) it('warn <slot> as root element', () => { parse('<slot></slot>', baseOptions) expect('Cannot use <slot> as component root element').toHaveBeenWarned() }) it('warn v-for on root element', () => { parse('<div v-for="item in items"></div>', baseOptions) expect('Cannot use v-for on stateful component root element').toHaveBeenWarned() }) it('warn <template> key', () => { parse('<div><template v-for="i in 10" :key="i"></template></div>', baseOptions) expect('<template> cannot be keyed').toHaveBeenWarned() }) it('v-pre directive', () => { const ast = parse('<div v-pre id="message1"><p>{{msg}}</p></div>', baseOptions) expect(ast.pre).toBe(true) expect(ast.attrs[0].name).toBe('id') expect(ast.attrs[0].value).toBe('"message1"') expect(ast.children[0].children[0].text).toBe('{{msg}}') }) it('v-for directive basic syntax', () => { const ast = parse('<ul><li v-for="item in items"></li></ul>', baseOptions) const liAst = ast.children[0] expect(liAst.for).toBe('items') expect(liAst.alias).toBe('item') }) it('v-for directive iteration syntax', () => { const ast = parse('<ul><li v-for="(item, index) in items"></li></ul>', baseOptions) const liAst = ast.children[0] expect(liAst.for).toBe('items') expect(liAst.alias).toBe('item') expect(liAst.iterator1).toBe('index') expect(liAst.iterator2).toBeUndefined() }) it('v-for directive iteration syntax (multiple)', () => { const ast = parse('<ul><li v-for="(item, key, index) in items"></li></ul>', baseOptions) const liAst = ast.children[0] expect(liAst.for).toBe('items') expect(liAst.alias).toBe('item') expect(liAst.iterator1).toBe('key') expect(liAst.iterator2).toBe('index') }) it('v-for directive key', () => { const ast = parse('<ul><li v-for="item in items" :key="item.uid"></li></ul>', baseOptions) const liAst = ast.children[0] expect(liAst.for).toBe('items') expect(liAst.alias).toBe('item') expect(liAst.key).toBe('item.uid') }) it('v-for directive invalid syntax', () => { parse('<ul><li v-for="item into items"></li></ul>', baseOptions) expect('Invalid v-for expression').toHaveBeenWarned() }) it('v-if directive syntax', () => { const ast = parse('<p v-if="show">hello world</p>', baseOptions) expect(ast.if).toBe('show') expect(ast.ifConditions[0].exp).toBe('show') }) it('v-else-if directive syntax', () => { const ast = parse('<div><p v-if="show">hello</p><span v-else-if="2">elseif</span><p v-else>world</p></div>', baseOptions) const ifAst = ast.children[0] const conditionsAst = ifAst.ifConditions expect(conditionsAst.length).toBe(3) expect(conditionsAst[1].block.children[0].text).toBe('elseif') expect(conditionsAst[1].block.parent).toBe(ast) expect(conditionsAst[2].block.children[0].text).toBe('world') expect(conditionsAst[2].block.parent).toBe(ast) }) it('v-else directive syntax', () => { const ast = parse('<div><p v-if="show">hello</p><p v-else>world</p></div>', baseOptions) const ifAst = ast.children[0] const conditionsAst = ifAst.ifConditions expect(conditionsAst.length).toBe(2) expect(conditionsAst[1].block.children[0].text).toBe('world') expect(conditionsAst[1].block.parent).toBe(ast) }) it('v-else-if directive invalid syntax', () => { parse('<div><p v-else-if="1">world</p></div>', baseOptions) expect('v-else-if="1" used on element').toHaveBeenWarned() }) it('v-else directive invalid syntax', () => { parse('<div><p v-else>world</p></div>', baseOptions) expect('v-else used on element').toHaveBeenWarned() }) it('v-once directive syntax', () => { const ast = parse('<p v-once>world</p>', baseOptions) expect(ast.once).toBe(true) }) it('slot tag single syntax', () => { const ast = parse('<div><slot></slot></div>', baseOptions) expect(ast.children[0].tag).toBe('slot') expect(ast.children[0].slotName).toBeUndefined() }) it('slot tag named syntax', () => { const ast = parse('<div><slot name="one">hello world</slot></div>', baseOptions) expect(ast.children[0].tag).toBe('slot') expect(ast.children[0].slotName).toBe('"one"') }) it('slot target', () => { const ast = parse('<p slot="one">hello world</p>', baseOptions) expect(ast.slotTarget).toBe('"one"') }) it('component properties', () => { const ast = parse('<my-component :msg="hello"></my-component>', baseOptions) expect(ast.attrs[0].name).toBe('msg') expect(ast.attrs[0].value).toBe('hello') }) it('component "is" attribute', () => { const ast = parse('<my-component is="component1"></my-component>', baseOptions) expect(ast.component).toBe('"component1"') }) it('component "inline-template" attribute', () => { const ast = parse('<my-component inline-template>hello world</my-component>', baseOptions) expect(ast.inlineTemplate).toBe(true) }) it('class binding', () => { // static const ast1 = parse('<p class="class1">hello world</p>', baseOptions) expect(ast1.staticClass).toBe('"class1"') // dynamic const ast2 = parse('<p :class="class1">hello world</p>', baseOptions) expect(ast2.classBinding).toBe('class1') // interpolation warning parse('<p class="{{error}}">hello world</p>', baseOptions) expect('Interpolation inside attributes has been removed').toHaveBeenWarned() }) it('style binding', () => { const ast = parse('<p :style="error">hello world</p>', baseOptions) expect(ast.styleBinding).toBe('error') }) it('attribute with v-bind', () => { const ast = parse('<input type="text" name="field1" :value="msg">', baseOptions) expect(ast.attrsList[0].name).toBe('type') expect(ast.attrsList[0].value).toBe('text') expect(ast.attrsList[1].name).toBe('name') expect(ast.attrsList[1].value).toBe('field1') expect(ast.attrsMap['type']).toBe('text') expect(ast.attrsMap['name']).toBe('field1') expect(ast.attrs[0].name).toBe('type') expect(ast.attrs[0].value).toBe('"text"') expect(ast.attrs[1].name).toBe('name') expect(ast.attrs[1].value).toBe('"field1"') expect(ast.props[0].name).toBe('value') expect(ast.props[0].value).toBe('msg') }) it('attribute with v-on', () => { const ast = parse('<input type="text" name="field1" :value="msg" @input="onInput">', baseOptions) expect(ast.events.input.value).toBe('onInput') }) it('attribute with directive', () => { const ast = parse('<input type="text" name="field1" :value="msg" v-validate:field1="required">', baseOptions) expect(ast.directives[0].name).toBe('validate') expect(ast.directives[0].value).toBe('required') expect(ast.directives[0].arg).toBe('field1') }) it('attribute with modifiered directive', () => { const ast = parse('<input type="text" name="field1" :value="msg" v-validate.on.off>', baseOptions) expect(ast.directives[0].modifiers.on).toBe(true) expect(ast.directives[0].modifiers.off).toBe(true) }) it('literal attribute', () => { // basic const ast1 = parse('<input type="text" name="field1" value="hello world">', baseOptions) expect(ast1.attrsList[0].name).toBe('type') expect(ast1.attrsList[0].value).toBe('text') expect(ast1.attrsList[1].name).toBe('name') expect(ast1.attrsList[1].value).toBe('field1') expect(ast1.attrsList[2].name).toBe('value') expect(ast1.attrsList[2].value).toBe('hello world') expect(ast1.attrsMap['type']).toBe('text') expect(ast1.attrsMap['name']).toBe('field1') expect(ast1.attrsMap['value']).toBe('hello world') expect(ast1.attrs[0].name).toBe('type') expect(ast1.attrs[0].value).toBe('"text"') expect(ast1.attrs[1].name).toBe('name') expect(ast1.attrs[1].value).toBe('"field1"') expect(ast1.attrs[2].name).toBe('value') expect(ast1.attrs[2].value).toBe('"hello world"') // interpolation warning parse('<input type="text" name="field1" value="{{msg}}">', baseOptions) expect('Interpolation inside attributes has been removed').toHaveBeenWarned() }) if (!isIE && !isEdge) { it('duplicate attribute', () => { parse('<p class="class1" class="class1">hello world</p>', baseOptions) expect('duplicate attribute').toHaveBeenWarned() }) } it('custom delimiter', () => { const ast = parse('<p>{msg}</p>', extend({ delimiters: ['{', '}'] }, baseOptions)) expect(ast.children[0].expression).toBe('_s(msg)') }) it('not specified getTagNamespace option', () => { const options = extend({}, baseOptions) delete options.getTagNamespace const ast = parse('<svg><text>hello world</text></svg>', options) expect(ast.tag).toBe('svg') expect(ast.ns).toBeUndefined() }) it('not specified mustUseProp', () => { const options = extend({}, baseOptions) delete options.mustUseProp const ast = parse('<input type="text" name="field1" :value="msg">', options) expect(ast.props).toBeUndefined() }) it('pre/post transforms', () => { const options = extend({}, baseOptions) const spy1 = jasmine.createSpy('preTransform') const spy2 = jasmine.createSpy('postTransform') options.modules = options.modules.concat([{ preTransformNode (el) { spy1(el.tag) }, postTransformNode (el) { expect(el.attrs.length).toBe(1) spy2(el.tag) } }]) parse('<img v-pre src="hi">', options) expect(spy1).toHaveBeenCalledWith('img') expect(spy2).toHaveBeenCalledWith('img') }) it('preserve whitespace in <pre> tag', function () { const options = extend({}, baseOptions) const ast = parse('<pre><code> \n<span>hi</span>\n </code><span> </span></pre>', options) const code = ast.children[0] expect(code.children[0].type).toBe(3) expect(code.children[0].text).toBe(' \n') expect(code.children[2].type).toBe(3) expect(code.children[2].text).toBe('\n ') const span = ast.children[1] expect(span.children[0].type).toBe(3) expect(span.children[0].text).toBe(' ') }) it('forgivingly handle < in plain text', () => { const options = extend({}, baseOptions) const ast = parse('<p>1 < 2 < 3</p>', options) expect(ast.tag).toBe('p') expect(ast.children.length).toBe(1) expect(ast.children[0].type).toBe(3) expect(ast.children[0].text).toBe('1 < 2 < 3') }) it('IE conditional comments', () => { const options = extend({}, baseOptions) const ast = parse(` <div> <!--[if lte IE 8]> <p>Test 1</p> <![endif]--> </div> `, options) expect(ast.tag).toBe('div') expect(ast.children.length).toBe(0) }) it('parse content in textarea as text', () => { const options = extend({}, baseOptions) const whitespace = parse(` <textarea> <p>Test 1</p> test2 </textarea> `, options) expect(whitespace.tag).toBe('textarea') expect(whitespace.children.length).toBe(1) expect(whitespace.children[0].type).toBe(3) // textarea is whitespace sensitive expect(whitespace.children[0].text).toBe(` <p>Test 1</p> test2 `) const comment = parse('<textarea><!--comment--></textarea>', options) expect(comment.tag).toBe('textarea') expect(comment.children.length).toBe(1) expect(comment.children[0].type).toBe(3) expect(comment.children[0].text).toBe('<!--comment-->') }) })
test/unit/modules/compiler/parser.spec.js
1
https://github.com/vuejs/vue/commit/d8315c42ef5b6b739100fad5f20e8b0c41f78eef
[ 0.9954373240470886, 0.018338341265916824, 0.0001646526507101953, 0.0001695835089776665, 0.13296718895435333 ]
{ "id": 3, "code_window": [ " expect(comment.children[0].type).toBe(3)\n", " expect(comment.children[0].text).toBe('<!--comment-->')\n", " })\n", "})" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " // #5526\n", " it('should not decode text in script tags', () => {\n", " const options = extend({}, baseOptions)\n", " const ast = parse(`<script type=\"x/template\">&gt;<foo>&lt;</script>`, options)\n", " expect(ast.children[0].text).toBe(`&gt;<foo>&lt;`)\n", " })\n" ], "file_path": "test/unit/modules/compiler/parser.spec.js", "type": "add", "edit_start_line_idx": 543 }
import Transition from './transition' import TransitionGroup from './transition-group' export default { Transition, TransitionGroup }
src/platforms/web/runtime/components/index.js
0
https://github.com/vuejs/vue/commit/d8315c42ef5b6b739100fad5f20e8b0c41f78eef
[ 0.00017116287199314684, 0.00017116287199314684, 0.00017116287199314684, 0.00017116287199314684, 0 ]
{ "id": 3, "code_window": [ " expect(comment.children[0].type).toBe(3)\n", " expect(comment.children[0].text).toBe('<!--comment-->')\n", " })\n", "})" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " // #5526\n", " it('should not decode text in script tags', () => {\n", " const options = extend({}, baseOptions)\n", " const ast = parse(`<script type=\"x/template\">&gt;<foo>&lt;</script>`, options)\n", " expect(ast.children[0].text).toBe(`&gt;<foo>&lt;`)\n", " })\n" ], "file_path": "test/unit/modules/compiler/parser.spec.js", "type": "add", "edit_start_line_idx": 543 }
import { parseStyleText } from 'web/util/style' const base64ImgUrl = 'url("data:image/webp;base64,UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA==")' const logoUrl = 'url(https://vuejs.org/images/logo.png)' it('should parse normal static style', () => { const staticStyle = `font-size: 12px;background: ${logoUrl};color:red` const res = parseStyleText(staticStyle) expect(res.background).toBe(logoUrl) expect(res.color).toBe('red') expect(res['font-size']).toBe('12px') }) it('should parse base64 background', () => { const staticStyle = `background: ${base64ImgUrl}` const res = parseStyleText(staticStyle) expect(res.background).toBe(base64ImgUrl) }) it('should parse multiple background images ', () => { let staticStyle = `background: ${logoUrl}, ${logoUrl};` let res = parseStyleText(staticStyle) expect(res.background).toBe(`${logoUrl}, ${logoUrl}`) staticStyle = `background: ${base64ImgUrl}, ${base64ImgUrl}` res = parseStyleText(staticStyle) expect(res.background).toBe(`${base64ImgUrl}, ${base64ImgUrl}`) }) it('should parse other images ', () => { let staticStyle = `shape-outside: ${logoUrl}` let res = parseStyleText(staticStyle) expect(res['shape-outside']).toBe(logoUrl) staticStyle = `list-style-image: ${logoUrl}` res = parseStyleText(staticStyle) expect(res['list-style-image']).toBe(logoUrl) staticStyle = `border-image: ${logoUrl} 30 30 repeat` res = parseStyleText(staticStyle) expect(res['border-image']).toBe(`${logoUrl} 30 30 repeat`) })
test/unit/features/directives/static-style-parser.spec.js
0
https://github.com/vuejs/vue/commit/d8315c42ef5b6b739100fad5f20e8b0c41f78eef
[ 0.00017959541582968086, 0.00017504276183899492, 0.00017077504890039563, 0.00017494423082098365, 0.0000029027658001723466 ]
{ "id": 3, "code_window": [ " expect(comment.children[0].type).toBe(3)\n", " expect(comment.children[0].text).toBe('<!--comment-->')\n", " })\n", "})" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " // #5526\n", " it('should not decode text in script tags', () => {\n", " const options = extend({}, baseOptions)\n", " const ast = parse(`<script type=\"x/template\">&gt;<foo>&lt;</script>`, options)\n", " expect(ast.children[0].text).toBe(`&gt;<foo>&lt;`)\n", " })\n" ], "file_path": "test/unit/modules/compiler/parser.spec.js", "type": "add", "edit_start_line_idx": 543 }
import { compileAndStringify, prepareRuntime, resetRuntime, createInstance, syncPromise, checkRefresh } from '../helpers/index' describe('node in render function', () => { let runtime beforeAll(() => { runtime = prepareRuntime() }) afterAll(() => { resetRuntime() runtime = null }) it('should be generated', () => { const instance = createInstance(runtime, ` new Vue({ render: function (createElement) { return createElement('div', {}, [ createElement('text', { attrs: { value: 'Hello' }}, []) ]) }, el: "body" }) `) expect(instance.getRealRoot()).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: 'Hello' }} ] }) }) it('should be generated with all types of text', () => { const instance = createInstance(runtime, ` new Vue({ render: function (createElement) { return createElement('div', {}, [ createElement('text', { attrs: { value: 'Hello' }}, []), 'World', createElement('text', {}, ['Weex']) ]) }, el: "body" }) `) expect(instance.getRealRoot()).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: 'Hello' }}, { type: 'text', attr: { value: 'World' }}, { type: 'text', attr: { value: 'Weex' }} ] }) }) it('should be generated with comments', () => { // todo }) it('should be generated with module diff', (done) => { const instance = createInstance(runtime, ` new Vue({ data: { counter: 0 }, methods: { foo: function () {} }, render: function (createElement) { switch (this.counter) { case 1: return createElement('div', {}, [ createElement('text', { attrs: { value: 'World' }}, []) ]) case 2: return createElement('div', {}, [ createElement('text', { attrs: { value: 'World' }, style: { fontSize: 100 }}, []) ]) case 3: return createElement('div', {}, [ createElement('text', { attrs: { value: 'World' }, style: { fontSize: 100 }, on: { click: this.foo } }, []) ]) case 4: return createElement('div', {}, [ createElement('text', { attrs: { value: 'Weex' }, style: { color: '#ff0000' } }, []) ]) default: return createElement('div', {}, [ createElement('text', { attrs: { value: 'Hello' }}, []) ]) } }, el: "body" }) `) expect(instance.getRealRoot()).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: 'Hello' }} ] }) syncPromise([ checkRefresh(instance, { counter: 1 }, result => { expect(result).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: 'World' }} ] }) }), checkRefresh(instance, { counter: 2 }, result => { expect(result).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: 'World' }, style: { fontSize: 100 }} ] }) }), checkRefresh(instance, { counter: 3 }, result => { expect(result).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: 'World' }, style: { fontSize: 100 }, event: ['click'] } ] }) }), checkRefresh(instance, { counter: 4 }, result => { expect(result).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: 'Weex' }, style: { fontSize: '', color: '#ff0000' }} ] }) done() }) ]) }) it('should be generated with sub components', () => { const instance = createInstance(runtime, ` new Vue({ render: function (createElement) { return createElement('div', {}, [ createElement('text', { attrs: { value: 'Hello' }}, []), createElement('foo', { props: { x: 'Weex' }}) ]) }, components: { foo: { props: { x: { default: 'World' } }, render: function (createElement) { return createElement('text', { attrs: { value: this.x }}, []) } } }, el: "body" }) `) expect(instance.getRealRoot()).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: 'Hello' }}, { type: 'text', attr: { value: 'Weex' }} ] }) }) it('should be generated with if/for diff', (done) => { const { render, staticRenderFns } = compileAndStringify(` <div> <text v-for="item in list" v-if="item.x">{{item.v}}</text> </div> `) const instance = createInstance(runtime, ` new Vue({ data: { list: [ { v: 'Hello', x: true }, { v: 'World', x: false }, { v: 'Weex', x: true } ] }, computed: { x: { get: function () { return 0 }, set: function (v) { switch (v) { case 1: this.list[1].x = true break case 2: this.list.push({ v: 'v-if' }) break case 3: this.list.push({ v: 'v-for', x: true }) break case 4: this.list.splice(1, 2) break } } } }, render: ${render}, staticRenderFns: ${staticRenderFns}, el: "body" }) `) expect(instance.getRealRoot()).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: 'Hello' }}, { type: 'text', attr: { value: 'Weex' }} ] }) syncPromise([ checkRefresh(instance, { x: 1 }, result => { expect(result).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: 'Hello' }}, { type: 'text', attr: { value: 'World' }}, { type: 'text', attr: { value: 'Weex' }} ] }) }), checkRefresh(instance, { x: 2 }, result => { expect(result).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: 'Hello' }}, { type: 'text', attr: { value: 'World' }}, { type: 'text', attr: { value: 'Weex' }} ] }) }), checkRefresh(instance, { x: 3 }, result => { expect(result).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: 'Hello' }}, { type: 'text', attr: { value: 'World' }}, { type: 'text', attr: { value: 'Weex' }}, { type: 'text', attr: { value: 'v-for' }} ] }) }), checkRefresh(instance, { x: 4 }, result => { expect(result).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: 'Hello' }}, { type: 'text', attr: { value: 'v-for' }} ] }) done() }) ]) }) it('should be generated with node structure diff', (done) => { const instance = createInstance(runtime, ` new Vue({ data: { counter: 0 }, render: function (createElement) { switch (this.counter) { case 1: return createElement('div', {}, [ createElement('text', { attrs: { value: 'Hello' }}, []), createElement('text', { attrs: { value: 'World' }}, []) ]) case 2: return createElement('div', {}, [ createElement('text', { attrs: { value: 'Hello' }}, []), createElement('text', { attrs: { value: 'World' }}, []), createElement('text', { attrs: { value: 'Weex' }}, []) ]) case 3: return createElement('div', {}, [ createElement('text', { attrs: { value: 'Hello' }}, []), createElement('text', { attrs: { value: 'Weex' }}, []) ]) case 4: return createElement('div', {}, [ createElement('text', { attrs: { value: 'Weex' }}, []) ]) case 5: return createElement('div', {}, [ createElement('text', { attrs: { value: 'Hello' }}, []), createElement('text', { attrs: { value: 'Weex' }}, []) ]) case 6: return createElement('div', {}, [ createElement('input', { attrs: { value: 'Hello' }}, []), createElement('text', { attrs: { value: 'Weex' }}, []) ]) default: return createElement('div', {}, [ createElement('text', { attrs: { value: 'Hello' }}, []), ]) } }, el: "body" }) `) expect(instance.getRealRoot()).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: 'Hello' }} ] }) syncPromise([ checkRefresh(instance, { counter: 1 }, result => { expect(result).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: 'Hello' }}, { type: 'text', attr: { value: 'World' }} ] }) }), checkRefresh(instance, { counter: 2 }, result => { expect(result).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: 'Hello' }}, { type: 'text', attr: { value: 'World' }}, { type: 'text', attr: { value: 'Weex' }} ] }) }), checkRefresh(instance, { counter: 3 }, result => { expect(result).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: 'Hello' }}, { type: 'text', attr: { value: 'Weex' }} ] }) }), checkRefresh(instance, { counter: 4 }, result => { expect(result).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: 'Weex' }} ] }) }), checkRefresh(instance, { counter: 5 }, result => { expect(result).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: 'Hello' }}, { type: 'text', attr: { value: 'Weex' }} ] }) }), checkRefresh(instance, { counter: 6 }, result => { expect(result).toEqual({ type: 'div', children: [ { type: 'input', attr: { value: 'Hello' }}, { type: 'text', attr: { value: 'Weex' }} ] }) done() }) ]) }) it('should be generated with component diff', (done) => { const instance = createInstance(runtime, ` new Vue({ data: { counter: 0 }, components: { foo: { props: { a: { default: '1' }, b: { default: '2' }}, render: function (createElement) { return createElement('text', { attrs: { value: this.a + '-' + this.b }}, []) } }, bar: { render: function (createElement) { return createElement('text', { attrs: { value: 'Bar' }, style: { fontSize: 100 }}) } }, baz: { render: function (createElement) { return createElement('image', { attrs: { src: 'http://example.com/favicon.ico' }}) } } }, render: function (createElement) { switch (this.counter) { case 1: return createElement('div', {}, [ createElement('foo', { props: { a: '111', b: '222' }}, []) ]) case 2: return createElement('div', {}, [ createElement('foo', {}, []) ]) case 3: return createElement('div', {}, [ createElement('bar', {}, []) ]) case 4: return createElement('div', {}, [ createElement('baz', {}, []) ]) case 5: return createElement('div', {}, [ createElement('foo', {}, []), createElement('bar', {}, []), createElement('baz', {}, []) ]) default: return createElement('div', {}, [ createElement('foo', { props: { a: '111' }}, []) ]) } }, el: "body" }) `) expect(instance.getRealRoot()).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: '111-2' }} ] }) syncPromise([ checkRefresh(instance, { counter: 1 }, result => { expect(result).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: '111-222' }} ] }) }), checkRefresh(instance, { counter: 2 }, result => { expect(result).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: '1-2' }} ] }) }), checkRefresh(instance, { counter: 3 }, result => { expect(result).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: 'Bar' }, style: { fontSize: 100 }} ] }) }), checkRefresh(instance, { counter: 4 }, result => { expect(result).toEqual({ type: 'div', children: [ { type: 'image', attr: { src: 'http://example.com/favicon.ico' }} ] }) }), checkRefresh(instance, { counter: 5 }, result => { expect(result).toEqual({ type: 'div', children: [ { type: 'text', attr: { value: '1-2' }}, { type: 'text', attr: { value: 'Bar' }, style: { fontSize: 100 }}, { type: 'image', attr: { src: 'http://example.com/favicon.ico' }} ] }) done() }) ]) }) })
test/weex/runtime/node.spec.js
0
https://github.com/vuejs/vue/commit/d8315c42ef5b6b739100fad5f20e8b0c41f78eef
[ 0.00029571709455922246, 0.00018856288807000965, 0.00016613681509625167, 0.0001742712629493326, 0.000026895104383584112 ]
{ "id": 0, "code_window": [ " const ret = body[0] as ts.ReturnStatement;\n", "\n", " const args = this.evaluateFunctionArguments(node, context);\n", " const newScope: Scope = new Map<ts.ParameterDeclaration, ResolvedValue>();\n", " fn.parameters.forEach((param, index) => {\n", " let arg = args[index];\n", " if (param.node.dotDotDotToken !== undefined) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const calleeContext = {...context, scope: newScope};\n" ], "file_path": "packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts", "type": "add", "edit_start_line_idx": 429 }
/** * @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 ts from 'typescript'; import {Reference} from '../../imports'; import {TypeScriptReflectionHost} from '../../reflection'; import {getDeclaration, makeProgram} from '../../testing/in_memory_typescript'; import {DynamicValue} from '../src/dynamic'; import {ForeignFunctionResolver, PartialEvaluator} from '../src/interface'; import {EnumValue, ResolvedValue} from '../src/result'; function makeExpression( code: string, expr: string, supportingFiles: {name: string, contents: string}[] = []): { expression: ts.Expression, host: ts.CompilerHost, checker: ts.TypeChecker, program: ts.Program, options: ts.CompilerOptions } { const {program, options, host} = makeProgram( [{name: 'entry.ts', contents: `${code}; const target$ = ${expr};`}, ...supportingFiles]); const checker = program.getTypeChecker(); const decl = getDeclaration(program, 'entry.ts', 'target$', ts.isVariableDeclaration); return { expression: decl.initializer !, host, options, checker, program, }; } function makeEvaluator(checker: ts.TypeChecker): PartialEvaluator { const reflectionHost = new TypeScriptReflectionHost(checker); return new PartialEvaluator(reflectionHost, checker); } function evaluate<T extends ResolvedValue>( code: string, expr: string, supportingFiles: {name: string, contents: string}[] = [], foreignFunctionResolver?: ForeignFunctionResolver): T { const {expression, checker} = makeExpression(code, expr, supportingFiles); const evaluator = makeEvaluator(checker); return evaluator.evaluate(expression, foreignFunctionResolver) as T; } describe('ngtsc metadata', () => { it('reads a file correctly', () => { const value = evaluate( ` import {Y} from './other'; const A = Y; `, 'A', [ { name: 'other.ts', contents: ` export const Y = 'test'; ` }, ]); expect(value).toEqual('test'); }); it('map access works', () => { expect(evaluate('const obj = {a: "test"};', 'obj.a')).toEqual('test'); }); it('function calls work', () => { expect(evaluate(`function foo(bar) { return bar; }`, 'foo("test")')).toEqual('test'); }); it('function call spread works', () => { expect(evaluate(`function foo(a, ...b) { return [a, b]; }`, 'foo(1, ...[2, 3])')).toEqual([ 1, [2, 3] ]); }); it('conditionals work', () => { expect(evaluate(`const x = false; const y = x ? 'true' : 'false';`, 'y')).toEqual('false'); }); it('addition works', () => { expect(evaluate(`const x = 1 + 2;`, 'x')).toEqual(3); }); it('static property on class works', () => { expect(evaluate(`class Foo { static bar = 'test'; }`, 'Foo.bar')).toEqual('test'); }); it('static property call works', () => { expect(evaluate(`class Foo { static bar(test) { return test; } }`, 'Foo.bar("test")')) .toEqual('test'); }); it('indirected static property call works', () => { expect( evaluate( `class Foo { static bar(test) { return test; } }; const fn = Foo.bar;`, 'fn("test")')) .toEqual('test'); }); it('array works', () => { expect(evaluate(`const x = 'test'; const y = [1, x, 2];`, 'y')).toEqual([1, 'test', 2]); }); it('array spread works', () => { expect(evaluate(`const a = [1, 2]; const b = [4, 5]; const c = [...a, 3, ...b];`, 'c')) .toEqual([1, 2, 3, 4, 5]); }); it('&& operations work', () => { expect(evaluate(`const a = 'hello', b = 'world';`, 'a && b')).toEqual('world'); expect(evaluate(`const a = false, b = 'world';`, 'a && b')).toEqual(false); expect(evaluate(`const a = 'hello', b = 0;`, 'a && b')).toEqual(0); }); it('|| operations work', () => { expect(evaluate(`const a = 'hello', b = 'world';`, 'a || b')).toEqual('hello'); expect(evaluate(`const a = false, b = 'world';`, 'a || b')).toEqual('world'); expect(evaluate(`const a = 'hello', b = 0;`, 'a || b')).toEqual('hello'); }); it('parentheticals work', () => { expect(evaluate(`const a = 3, b = 4;`, 'a * (a + b)')).toEqual(21); }); it('array access works', () => { expect(evaluate(`const a = [1, 2, 3];`, 'a[1] + a[0]')).toEqual(3); }); it('array `length` property access works', () => { expect(evaluate(`const a = [1, 2, 3];`, 'a[\'length\'] + 1')).toEqual(4); }); it('array `slice` function works', () => { expect(evaluate(`const a = [1, 2, 3];`, 'a[\'slice\']()')).toEqual([1, 2, 3]); }); it('array `concat` function works', () => { expect(evaluate(`const a = [1, 2], b = [3, 4];`, 'a[\'concat\'](b)')).toEqual([1, 2, 3, 4]); expect(evaluate(`const a = [1, 2], b = 3;`, 'a[\'concat\'](b)')).toEqual([1, 2, 3]); expect(evaluate(`const a = [1, 2], b = 3, c = [4, 5];`, 'a[\'concat\'](b, c)')).toEqual([ 1, 2, 3, 4, 5 ]); expect(evaluate(`const a = [1, 2], b = [3, 4]`, 'a[\'concat\'](...b)')).toEqual([1, 2, 3, 4]); }); it('negation works', () => { expect(evaluate(`const x = 3;`, '!x')).toEqual(false); expect(evaluate(`const x = 3;`, '!!x')).toEqual(true); }); it('imports work', () => { const {program, options, host} = makeProgram([ {name: 'second.ts', contents: 'export function foo(bar) { return bar; }'}, { name: 'entry.ts', contents: ` import {foo} from './second'; const target$ = foo; ` }, ]); const checker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(checker); const result = getDeclaration(program, 'entry.ts', 'target$', ts.isVariableDeclaration); const expr = result.initializer !; const evaluator = new PartialEvaluator(reflectionHost, checker); const resolved = evaluator.evaluate(expr); if (!(resolved instanceof Reference)) { return fail('Expected expression to resolve to a reference'); } expect(ts.isFunctionDeclaration(resolved.node)).toBe(true); const reference = resolved.getIdentityIn(program.getSourceFile('entry.ts') !); if (reference === null) { return fail('Expected to get an identifier'); } expect(reference.getSourceFile()).toEqual(program.getSourceFile('entry.ts') !); }); it('absolute imports work', () => { const {program, options, host} = makeProgram([ {name: 'node_modules/some_library/index.d.ts', contents: 'export declare function foo(bar);'}, { name: 'entry.ts', contents: ` import {foo} from 'some_library'; const target$ = foo; ` }, ]); const checker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(checker); const result = getDeclaration(program, 'entry.ts', 'target$', ts.isVariableDeclaration); const expr = result.initializer !; const evaluator = new PartialEvaluator(reflectionHost, checker); const resolved = evaluator.evaluate(expr); if (!(resolved instanceof Reference)) { return fail('Expected expression to resolve to an absolute reference'); } expect(owningModuleOf(resolved)).toBe('some_library'); expect(ts.isFunctionDeclaration(resolved.node)).toBe(true); const reference = resolved.getIdentityIn(program.getSourceFile('entry.ts') !); expect(reference).not.toBeNull(); expect(reference !.getSourceFile()).toEqual(program.getSourceFile('entry.ts') !); }); it('reads values from default exports', () => { const value = evaluate( ` import mod from './second'; `, 'mod.property', [ {name: 'second.ts', contents: 'export default {property: "test"}'}, ]); expect(value).toEqual('test'); }); it('reads values from named exports', () => { const value = evaluate(`import * as mod from './second';`, 'mod.a.property', [ {name: 'second.ts', contents: 'export const a = {property: "test"};'}, ]); expect(value).toEqual('test'); }); it('chain of re-exports works', () => { const value = evaluate(`import * as mod from './direct-reexport';`, 'mod.value.property', [ {name: 'const.ts', contents: 'export const value = {property: "test"};'}, {name: 'def.ts', contents: `import {value} from './const'; export default value;`}, {name: 'indirect-reexport.ts', contents: `import value from './def'; export {value};`}, {name: 'direct-reexport.ts', contents: `export {value} from './indirect-reexport';`}, ]); expect(value).toEqual('test'); }); it('map spread works', () => { const map: Map<string, number> = evaluate<Map<string, number>>( `const a = {a: 1}; const b = {b: 2, c: 1}; const c = {...a, ...b, c: 3};`, 'c'); const obj: {[key: string]: number} = {}; map.forEach((value, key) => obj[key] = value); expect(obj).toEqual({ a: 1, b: 2, c: 3, }); }); it('indirected-via-object function call works', () => { expect(evaluate( ` function fn(res) { return res; } const obj = {fn}; `, 'obj.fn("test")')) .toEqual('test'); }); it('template expressions work', () => { expect(evaluate('const a = 2, b = 4;', '`1${a}3${b}5`')).toEqual('12345'); }); it('enum resolution works', () => { const result = evaluate( ` enum Foo { A, B, C, } const r = Foo.B; `, 'r'); if (!(result instanceof EnumValue)) { return fail(`result is not an EnumValue`); } expect(result.enumRef.node.name.text).toBe('Foo'); expect(result.name).toBe('B'); }); it('variable declaration resolution works', () => { const value = evaluate(`import {value} from './decl';`, 'value', [ {name: 'decl.d.ts', contents: 'export declare let value: number;'}, ]); expect(value instanceof Reference).toBe(true); }); it('should resolve shorthand properties to values', () => { const {program} = makeProgram([ {name: 'entry.ts', contents: `const prop = 42; const target$ = {prop};`}, ]); const checker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(checker); const result = getDeclaration(program, 'entry.ts', 'target$', ts.isVariableDeclaration); const expr = result.initializer !as ts.ObjectLiteralExpression; const prop = expr.properties[0] as ts.ShorthandPropertyAssignment; const evaluator = new PartialEvaluator(reflectionHost, checker); const resolved = evaluator.evaluate(prop.name); expect(resolved).toBe(42); }); it('should resolve dynamic values in object literals', () => { const {program} = makeProgram([ {name: 'decl.d.ts', contents: 'export declare const fn: any;'}, { name: 'entry.ts', contents: `import {fn} from './decl'; const prop = fn.foo(); const target$ = {value: prop};` }, ]); const checker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(checker); const result = getDeclaration(program, 'entry.ts', 'target$', ts.isVariableDeclaration); const expr = result.initializer !as ts.ObjectLiteralExpression; const evaluator = new PartialEvaluator(reflectionHost, checker); const resolved = evaluator.evaluate(expr); if (!(resolved instanceof Map)) { return fail('Should have resolved to a Map'); } const value = resolved.get('value') !; if (!(value instanceof DynamicValue)) { return fail(`Should have resolved 'value' to a DynamicValue`); } const prop = expr.properties[0] as ts.PropertyAssignment; expect(value.node).toBe(prop.initializer); }); it('should resolve enums in template expressions', () => { const value = evaluate(`enum Test { VALUE = 'test', } const value = \`a.\${Test.VALUE}.b\`;`, 'value'); expect(value).toBe('a.test.b'); }); it('should not attach identifiers to FFR-resolved values', () => { const value = evaluate( ` declare function foo(arg: any): any; class Target {} const indir = foo(Target); const value = indir; `, 'value', [], firstArgFfr); if (!(value instanceof Reference)) { return fail('Expected value to be a Reference'); } const id = value.getIdentityIn(value.node.getSourceFile()); if (id === null) { return fail('Expected value to have an identity'); } expect(id.text).toEqual('Target'); }); describe('(visited file tracking)', () => { it('should track each time a source file is visited', () => { const visitedFilesSpy = jasmine.createSpy('visitedFilesCb'); const {expression, checker} = makeExpression(`class A { static foo = 42; } function bar() { return A.foo; }`, 'bar()'); const evaluator = makeEvaluator(checker); evaluator.evaluate(expression, undefined, visitedFilesSpy); expect(visitedFilesSpy) .toHaveBeenCalledTimes(3); // The initial expression, followed by two declaration visited expect(visitedFilesSpy.calls.allArgs().map(args => args[0].fileName)).toEqual([ '/entry.ts', '/entry.ts', '/entry.ts' ]); }); it('should track imported source files', () => { const visitedFilesSpy = jasmine.createSpy('visitedFilesCb'); const {expression, checker} = makeExpression(`import {Y} from './other'; const A = Y;`, 'A', [ {name: 'other.ts', contents: `export const Y = 'test';`}, {name: 'not-visited.ts', contents: `export const Z = 'nope';`} ]); const evaluator = makeEvaluator(checker); evaluator.evaluate(expression, undefined, visitedFilesSpy); expect(visitedFilesSpy).toHaveBeenCalledTimes(3); expect(visitedFilesSpy.calls.allArgs().map(args => args[0].fileName)).toEqual([ '/entry.ts', '/entry.ts', '/other.ts' ]); }); it('should track files passed through during re-exports', () => { const visitedFilesSpy = jasmine.createSpy('visitedFilesCb'); const {expression, checker} = makeExpression(`import * as mod from './direct-reexport';`, 'mod.value.property', [ {name: 'const.ts', contents: 'export const value = {property: "test"};'}, {name: 'def.ts', contents: `import {value} from './const'; export default value;`}, {name: 'indirect-reexport.ts', contents: `import value from './def'; export {value};`}, {name: 'direct-reexport.ts', contents: `export {value} from './indirect-reexport';`}, ]); const evaluator = makeEvaluator(checker); evaluator.evaluate(expression, undefined, visitedFilesSpy); expect(visitedFilesSpy).toHaveBeenCalledTimes(3); expect(visitedFilesSpy.calls.allArgs().map(args => args[0].fileName)).toEqual([ '/entry.ts', '/direct-reexport.ts', // Not '/indirect-reexport.ts' or '/def.ts'. // TS skips through them when finding the original symbol for `value` '/const.ts', ]); }); }); }); function owningModuleOf(ref: Reference): string|null { return ref.bestGuessOwningModule !== null ? ref.bestGuessOwningModule.specifier : null; } function firstArgFfr( node: Reference<ts.FunctionDeclaration|ts.MethodDeclaration|ts.FunctionExpression>, args: ReadonlyArray<ts.Expression>): ts.Expression { return args[0]; }
packages/compiler-cli/src/ngtsc/partial_evaluator/test/evaluator_spec.ts
1
https://github.com/angular/angular/commit/c3c0df9d56a68ced7664066048cf5a180fccceea
[ 0.9666000008583069, 0.023246660828590393, 0.00016405868518631905, 0.00017408626445103437, 0.1473272293806076 ]
{ "id": 0, "code_window": [ " const ret = body[0] as ts.ReturnStatement;\n", "\n", " const args = this.evaluateFunctionArguments(node, context);\n", " const newScope: Scope = new Map<ts.ParameterDeclaration, ResolvedValue>();\n", " fn.parameters.forEach((param, index) => {\n", " let arg = args[index];\n", " if (param.node.dotDotDotToken !== undefined) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const calleeContext = {...context, scope: newScope};\n" ], "file_path": "packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts", "type": "add", "edit_start_line_idx": 429 }
/** * @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 {registerLocaleData} from '@angular/common'; import {Component} from '@angular/core'; // we need to import data for the french locale import localeFr from './locale-fr'; // registering french data registerLocaleData(localeFr); // #docregion NumberPipe @Component({ selector: 'number-pipe', template: `<div> <!--output '2.718'--> <p>e (no formatting): {{e | number}}</p> <!--output '002.71828'--> <p>e (3.1-5): {{e | number:'3.1-5'}}</p> <!--output '0,002.71828'--> <p>e (4.5-5): {{e | number:'4.5-5'}}</p> <!--output '0 002,71828'--> <p>e (french): {{e | number:'4.5-5':'fr'}}</p> <!--output '3.14'--> <p>pi (no formatting): {{pi | number}}</p> <!--output '003.14'--> <p>pi (3.1-5): {{pi | number:'3.1-5'}}</p> <!--output '003.14000'--> <p>pi (3.5-5): {{pi | number:'3.5-5'}}</p> <!--output '-3' / unlike '-2' by Math.round()--> <p>-2.5 (1.0-0): {{-2.5 | number:'1.0-0'}}</p> </div>` }) export class NumberPipeComponent { pi: number = 3.14; e: number = 2.718281828459045; } // #enddocregion // #docregion DeprecatedNumberPipe @Component({ selector: 'deprecated-number-pipe', template: `<div> <p>e (no formatting): {{e}}</p> <p>e (3.1-5): {{e | number:'3.1-5'}}</p> <p>pi (no formatting): {{pi}}</p> <p>pi (3.5-5): {{pi | number:'3.5-5'}}</p> </div>` }) export class DeprecatedNumberPipeComponent { pi: number = 3.141592; e: number = 2.718281828459045; } // #enddocregion
packages/examples/common/pipes/ts/number_pipe.ts
0
https://github.com/angular/angular/commit/c3c0df9d56a68ced7664066048cf5a180fccceea
[ 0.00017767041572369635, 0.00017517575179226696, 0.00017005568952299654, 0.0001765536144375801, 0.0000026634029381966684 ]
{ "id": 0, "code_window": [ " const ret = body[0] as ts.ReturnStatement;\n", "\n", " const args = this.evaluateFunctionArguments(node, context);\n", " const newScope: Scope = new Map<ts.ParameterDeclaration, ResolvedValue>();\n", " fn.parameters.forEach((param, index) => {\n", " let arg = args[index];\n", " if (param.node.dotDotDotToken !== undefined) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const calleeContext = {...context, scope: newScope};\n" ], "file_path": "packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts", "type": "add", "edit_start_line_idx": 429 }
import { Component, OnInit } from '@angular/core'; import { Hero } from '../hero'; import { HeroService } from '../hero.service'; @Component({ selector: 'app-heroes', templateUrl: './heroes.component.html', styleUrls: ['./heroes.component.css'] }) export class HeroesComponent implements OnInit { heroes: Hero[]; constructor(private heroService: HeroService) { } ngOnInit() { this.getHeroes(); } getHeroes(): void { this.heroService.getHeroes() .subscribe(heroes => this.heroes = heroes); } // #docregion add add(name: string): void { name = name.trim(); if (!name) { return; } this.heroService.addHero({ name } as Hero) .subscribe(hero => { this.heroes.push(hero); }); } // #enddocregion add // #docregion delete delete(hero: Hero): void { this.heroes = this.heroes.filter(h => h !== hero); this.heroService.deleteHero(hero).subscribe(); } // #enddocregion delete }
aio/content/examples/toh-pt6/src/app/heroes/heroes.component.ts
0
https://github.com/angular/angular/commit/c3c0df9d56a68ced7664066048cf5a180fccceea
[ 0.0001767995854606852, 0.00017490539175923914, 0.000172819709405303, 0.00017473949992563576, 0.000001394769128637563 ]
{ "id": 0, "code_window": [ " const ret = body[0] as ts.ReturnStatement;\n", "\n", " const args = this.evaluateFunctionArguments(node, context);\n", " const newScope: Scope = new Map<ts.ParameterDeclaration, ResolvedValue>();\n", " fn.parameters.forEach((param, index) => {\n", " let arg = args[index];\n", " if (param.node.dotDotDotToken !== undefined) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const calleeContext = {...context, scope: newScope};\n" ], "file_path": "packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts", "type": "add", "edit_start_line_idx": 429 }
aio/content/examples/toh-pt2/src/app/app.component.css
0
https://github.com/angular/angular/commit/c3c0df9d56a68ced7664066048cf5a180fccceea
[ 0.00017114148067776114, 0.00017114148067776114, 0.00017114148067776114, 0.00017114148067776114, 0 ]
{ "id": 1, "code_window": [ " arg = args.slice(index);\n", " }\n", " if (arg === undefined && param.initializer !== null) {\n", " arg = this.visitExpression(param.initializer, context);\n", " }\n", " newScope.set(param.node, arg);\n", " });\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " arg = this.visitExpression(param.initializer, calleeContext);\n" ], "file_path": "packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts", "type": "replace", "edit_start_line_idx": 435 }
/** * @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 ts from 'typescript'; import {Reference} from '../../imports'; import {OwningModule} from '../../imports/src/references'; import {Declaration, ReflectionHost} from '../../reflection'; import {ArrayConcatBuiltinFn, ArraySliceBuiltinFn} from './builtin'; import {DynamicValue} from './dynamic'; import {ForeignFunctionResolver, VisitedFilesCallback} from './interface'; import {BuiltinFn, EnumValue, ResolvedValue, ResolvedValueArray, ResolvedValueMap} from './result'; /** * Tracks the scope of a function body, which includes `ResolvedValue`s for the parameters of that * body. */ type Scope = Map<ts.ParameterDeclaration, ResolvedValue>; interface BinaryOperatorDef { literal: boolean; op: (a: any, b: any) => ResolvedValue; } function literalBinaryOp(op: (a: any, b: any) => any): BinaryOperatorDef { return {op, literal: true}; } function referenceBinaryOp(op: (a: any, b: any) => any): BinaryOperatorDef { return {op, literal: false}; } const BINARY_OPERATORS = new Map<ts.SyntaxKind, BinaryOperatorDef>([ [ts.SyntaxKind.PlusToken, literalBinaryOp((a, b) => a + b)], [ts.SyntaxKind.MinusToken, literalBinaryOp((a, b) => a - b)], [ts.SyntaxKind.AsteriskToken, literalBinaryOp((a, b) => a * b)], [ts.SyntaxKind.SlashToken, literalBinaryOp((a, b) => a / b)], [ts.SyntaxKind.PercentToken, literalBinaryOp((a, b) => a % b)], [ts.SyntaxKind.AmpersandToken, literalBinaryOp((a, b) => a & b)], [ts.SyntaxKind.BarToken, literalBinaryOp((a, b) => a | b)], [ts.SyntaxKind.CaretToken, literalBinaryOp((a, b) => a ^ b)], [ts.SyntaxKind.LessThanToken, literalBinaryOp((a, b) => a < b)], [ts.SyntaxKind.LessThanEqualsToken, literalBinaryOp((a, b) => a <= b)], [ts.SyntaxKind.GreaterThanToken, literalBinaryOp((a, b) => a > b)], [ts.SyntaxKind.GreaterThanEqualsToken, literalBinaryOp((a, b) => a >= b)], [ts.SyntaxKind.LessThanLessThanToken, literalBinaryOp((a, b) => a << b)], [ts.SyntaxKind.GreaterThanGreaterThanToken, literalBinaryOp((a, b) => a >> b)], [ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken, literalBinaryOp((a, b) => a >>> b)], [ts.SyntaxKind.AsteriskAsteriskToken, literalBinaryOp((a, b) => Math.pow(a, b))], [ts.SyntaxKind.AmpersandAmpersandToken, referenceBinaryOp((a, b) => a && b)], [ts.SyntaxKind.BarBarToken, referenceBinaryOp((a, b) => a || b)] ]); const UNARY_OPERATORS = new Map<ts.SyntaxKind, (a: any) => any>([ [ts.SyntaxKind.TildeToken, a => ~a], [ts.SyntaxKind.MinusToken, a => -a], [ts.SyntaxKind.PlusToken, a => +a], [ts.SyntaxKind.ExclamationToken, a => !a] ]); interface Context { /** * The module name (if any) which was used to reach the currently resolving symbols. */ absoluteModuleName: string|null; /** * A file name representing the context in which the current `absoluteModuleName`, if any, was * resolved. */ resolutionContext: string; scope: Scope; foreignFunctionResolver?: ForeignFunctionResolver; } export class StaticInterpreter { constructor( private host: ReflectionHost, private checker: ts.TypeChecker, private visitedFilesCb?: VisitedFilesCallback) {} visit(node: ts.Expression, context: Context): ResolvedValue { return this.visitExpression(node, context); } private visitExpression(node: ts.Expression, context: Context): ResolvedValue { let result: ResolvedValue; if (node.kind === ts.SyntaxKind.TrueKeyword) { return true; } else if (node.kind === ts.SyntaxKind.FalseKeyword) { return false; } else if (ts.isStringLiteral(node)) { return node.text; } else if (ts.isNoSubstitutionTemplateLiteral(node)) { return node.text; } else if (ts.isTemplateExpression(node)) { result = this.visitTemplateExpression(node, context); } else if (ts.isNumericLiteral(node)) { return parseFloat(node.text); } else if (ts.isObjectLiteralExpression(node)) { result = this.visitObjectLiteralExpression(node, context); } else if (ts.isIdentifier(node)) { result = this.visitIdentifier(node, context); } else if (ts.isPropertyAccessExpression(node)) { result = this.visitPropertyAccessExpression(node, context); } else if (ts.isCallExpression(node)) { result = this.visitCallExpression(node, context); } else if (ts.isConditionalExpression(node)) { result = this.visitConditionalExpression(node, context); } else if (ts.isPrefixUnaryExpression(node)) { result = this.visitPrefixUnaryExpression(node, context); } else if (ts.isBinaryExpression(node)) { result = this.visitBinaryExpression(node, context); } else if (ts.isArrayLiteralExpression(node)) { result = this.visitArrayLiteralExpression(node, context); } else if (ts.isParenthesizedExpression(node)) { result = this.visitParenthesizedExpression(node, context); } else if (ts.isElementAccessExpression(node)) { result = this.visitElementAccessExpression(node, context); } else if (ts.isAsExpression(node)) { result = this.visitExpression(node.expression, context); } else if (ts.isNonNullExpression(node)) { result = this.visitExpression(node.expression, context); } else if (this.host.isClass(node)) { result = this.visitDeclaration(node, context); } else { return DynamicValue.fromUnknownExpressionType(node); } if (result instanceof DynamicValue && result.node !== node) { return DynamicValue.fromDynamicInput(node, result); } return result; } private visitArrayLiteralExpression(node: ts.ArrayLiteralExpression, context: Context): ResolvedValue { const array: ResolvedValueArray = []; for (let i = 0; i < node.elements.length; i++) { const element = node.elements[i]; if (ts.isSpreadElement(element)) { array.push(...this.visitSpreadElement(element, context)); } else { array.push(this.visitExpression(element, context)); } } return array; } private visitObjectLiteralExpression(node: ts.ObjectLiteralExpression, context: Context): ResolvedValue { const map: ResolvedValueMap = new Map<string, ResolvedValue>(); for (let i = 0; i < node.properties.length; i++) { const property = node.properties[i]; if (ts.isPropertyAssignment(property)) { const name = this.stringNameFromPropertyName(property.name, context); // Check whether the name can be determined statically. if (name === undefined) { return DynamicValue.fromDynamicInput(node, DynamicValue.fromDynamicString(property.name)); } map.set(name, this.visitExpression(property.initializer, context)); } else if (ts.isShorthandPropertyAssignment(property)) { const symbol = this.checker.getShorthandAssignmentValueSymbol(property); if (symbol === undefined || symbol.valueDeclaration === undefined) { map.set(property.name.text, DynamicValue.fromUnknown(property)); } else { map.set(property.name.text, this.visitDeclaration(symbol.valueDeclaration, context)); } } else if (ts.isSpreadAssignment(property)) { const spread = this.visitExpression(property.expression, context); if (spread instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, spread); } else if (!(spread instanceof Map)) { throw new Error(`Unexpected value in spread assignment: ${spread}`); } spread.forEach((value, key) => map.set(key, value)); } else { return DynamicValue.fromUnknown(node); } } return map; } private visitTemplateExpression(node: ts.TemplateExpression, context: Context): ResolvedValue { const pieces: string[] = [node.head.text]; for (let i = 0; i < node.templateSpans.length; i++) { const span = node.templateSpans[i]; let value = this.visit(span.expression, context); if (value instanceof EnumValue) { value = value.resolved; } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || value == null) { pieces.push(`${value}`); } else if (value instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, value); } else { return DynamicValue.fromDynamicInput(node, DynamicValue.fromDynamicString(span.expression)); } pieces.push(span.literal.text); } return pieces.join(''); } private visitIdentifier(node: ts.Identifier, context: Context): ResolvedValue { const decl = this.host.getDeclarationOfIdentifier(node); if (decl === null) { return DynamicValue.fromUnknownIdentifier(node); } const result = this.visitDeclaration(decl.node, {...context, ...joinModuleContext(context, node, decl)}); if (result instanceof Reference) { // Only record identifiers to non-synthetic references. Synthetic references may not have the // same value at runtime as they do at compile time, so it's not legal to refer to them by the // identifier here. if (!result.synthetic) { result.addIdentifier(node); } } else if (result instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, result); } return result; } private visitDeclaration(node: ts.Declaration, context: Context): ResolvedValue { if (this.visitedFilesCb) { this.visitedFilesCb(node.getSourceFile()); } if (this.host.isClass(node)) { return this.getReference(node, context); } else if (ts.isVariableDeclaration(node)) { return this.visitVariableDeclaration(node, context); } else if (ts.isParameter(node) && context.scope.has(node)) { return context.scope.get(node) !; } else if (ts.isExportAssignment(node)) { return this.visitExpression(node.expression, context); } else if (ts.isEnumDeclaration(node)) { return this.visitEnumDeclaration(node, context); } else if (ts.isSourceFile(node)) { return this.visitSourceFile(node, context); } else { return this.getReference(node, context); } } private visitVariableDeclaration(node: ts.VariableDeclaration, context: Context): ResolvedValue { const value = this.host.getVariableValue(node); if (value !== null) { return this.visitExpression(value, context); } else if (isVariableDeclarationDeclared(node)) { return this.getReference(node, context); } else { return undefined; } } private visitEnumDeclaration(node: ts.EnumDeclaration, context: Context): ResolvedValue { const enumRef = this.getReference(node, context) as Reference<ts.EnumDeclaration>; const map = new Map<string, EnumValue>(); node.members.forEach(member => { const name = this.stringNameFromPropertyName(member.name, context); if (name !== undefined) { const resolved = member.initializer && this.visit(member.initializer, context); map.set(name, new EnumValue(enumRef, name, resolved)); } }); return map; } private visitElementAccessExpression(node: ts.ElementAccessExpression, context: Context): ResolvedValue { const lhs = this.visitExpression(node.expression, context); if (node.argumentExpression === undefined) { throw new Error(`Expected argument in ElementAccessExpression`); } if (lhs instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, lhs); } const rhs = this.visitExpression(node.argumentExpression, context); if (rhs instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, rhs); } if (typeof rhs !== 'string' && typeof rhs !== 'number') { throw new Error( `ElementAccessExpression index should be string or number, got ${typeof rhs}: ${rhs}`); } return this.accessHelper(node, lhs, rhs, context); } private visitPropertyAccessExpression(node: ts.PropertyAccessExpression, context: Context): ResolvedValue { const lhs = this.visitExpression(node.expression, context); const rhs = node.name.text; // TODO: handle reference to class declaration. if (lhs instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, lhs); } return this.accessHelper(node, lhs, rhs, context); } private visitSourceFile(node: ts.SourceFile, context: Context): ResolvedValue { const declarations = this.host.getExportsOfModule(node); if (declarations === null) { return DynamicValue.fromUnknown(node); } const map = new Map<string, ResolvedValue>(); declarations.forEach((decl, name) => { const value = this.visitDeclaration( decl.node, { ...context, ...joinModuleContext(context, node, decl), }); map.set(name, value); }); return map; } private accessHelper( node: ts.Expression, lhs: ResolvedValue, rhs: string|number, context: Context): ResolvedValue { const strIndex = `${rhs}`; if (lhs instanceof Map) { if (lhs.has(strIndex)) { return lhs.get(strIndex) !; } else { throw new Error(`Invalid map access: [${Array.from(lhs.keys())}] dot ${rhs}`); } } else if (Array.isArray(lhs)) { if (rhs === 'length') { return lhs.length; } else if (rhs === 'slice') { return new ArraySliceBuiltinFn(node, lhs); } else if (rhs === 'concat') { return new ArrayConcatBuiltinFn(node, lhs); } if (typeof rhs !== 'number' || !Number.isInteger(rhs)) { return DynamicValue.fromUnknown(node); } if (rhs < 0 || rhs >= lhs.length) { throw new Error(`Index out of bounds: ${rhs} vs ${lhs.length}`); } return lhs[rhs]; } else if (lhs instanceof Reference) { const ref = lhs.node; if (this.host.isClass(ref)) { const module = owningModule(context, lhs.bestGuessOwningModule); let value: ResolvedValue = undefined; const member = this.host.getMembersOfClass(ref).find( member => member.isStatic && member.name === strIndex); if (member !== undefined) { if (member.value !== null) { value = this.visitExpression(member.value, context); } else if (member.implementation !== null) { value = new Reference(member.implementation, module); } else if (member.node) { value = new Reference(member.node, module); } } return value; } } else if (lhs instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, lhs); } else { throw new Error(`Invalid dot property access: ${lhs} dot ${rhs}`); } } private visitCallExpression(node: ts.CallExpression, context: Context): ResolvedValue { const lhs = this.visitExpression(node.expression, context); if (lhs instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, lhs); } // If the call refers to a builtin function, attempt to evaluate the function. if (lhs instanceof BuiltinFn) { return lhs.evaluate(this.evaluateFunctionArguments(node, context)); } if (!(lhs instanceof Reference)) { return DynamicValue.fromInvalidExpressionType(node.expression, lhs); } else if (!isFunctionOrMethodReference(lhs)) { return DynamicValue.fromInvalidExpressionType(node.expression, lhs); } const fn = this.host.getDefinitionOfFunction(lhs.node); // If the function is foreign (declared through a d.ts file), attempt to resolve it with the // foreignFunctionResolver, if one is specified. if (fn.body === null) { let expr: ts.Expression|null = null; if (context.foreignFunctionResolver) { expr = context.foreignFunctionResolver(lhs, node.arguments); } if (expr === null) { return DynamicValue.fromDynamicInput( node, DynamicValue.fromExternalReference(node.expression, lhs)); } // If the function is declared in a different file, resolve the foreign function expression // using the absolute module name of that file (if any). if (lhs.bestGuessOwningModule !== null) { context = { ...context, absoluteModuleName: lhs.bestGuessOwningModule.specifier, resolutionContext: node.getSourceFile().fileName, }; } const res = this.visitExpression(expr, context); if (res instanceof Reference) { // This Reference was created synthetically, via a foreign function resolver. The real // runtime value of the function expression may be different than the foreign function // resolved value, so mark the Reference as synthetic to avoid it being misinterpreted. res.synthetic = true; } return res; } const body = fn.body; if (body.length !== 1 || !ts.isReturnStatement(body[0])) { throw new Error('Function body must have a single return statement only.'); } const ret = body[0] as ts.ReturnStatement; const args = this.evaluateFunctionArguments(node, context); const newScope: Scope = new Map<ts.ParameterDeclaration, ResolvedValue>(); fn.parameters.forEach((param, index) => { let arg = args[index]; if (param.node.dotDotDotToken !== undefined) { arg = args.slice(index); } if (arg === undefined && param.initializer !== null) { arg = this.visitExpression(param.initializer, context); } newScope.set(param.node, arg); }); return ret.expression !== undefined ? this.visitExpression(ret.expression, {...context, scope: newScope}) : undefined; } private visitConditionalExpression(node: ts.ConditionalExpression, context: Context): ResolvedValue { const condition = this.visitExpression(node.condition, context); if (condition instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, condition); } if (condition) { return this.visitExpression(node.whenTrue, context); } else { return this.visitExpression(node.whenFalse, context); } } private visitPrefixUnaryExpression(node: ts.PrefixUnaryExpression, context: Context): ResolvedValue { const operatorKind = node.operator; if (!UNARY_OPERATORS.has(operatorKind)) { throw new Error(`Unsupported prefix unary operator: ${ts.SyntaxKind[operatorKind]}`); } const op = UNARY_OPERATORS.get(operatorKind) !; const value = this.visitExpression(node.operand, context); if (value instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, value); } else { return op(value); } } private visitBinaryExpression(node: ts.BinaryExpression, context: Context): ResolvedValue { const tokenKind = node.operatorToken.kind; if (!BINARY_OPERATORS.has(tokenKind)) { throw new Error(`Unsupported binary operator: ${ts.SyntaxKind[tokenKind]}`); } const opRecord = BINARY_OPERATORS.get(tokenKind) !; let lhs: ResolvedValue, rhs: ResolvedValue; if (opRecord.literal) { lhs = literal(this.visitExpression(node.left, context)); rhs = literal(this.visitExpression(node.right, context)); } else { lhs = this.visitExpression(node.left, context); rhs = this.visitExpression(node.right, context); } if (lhs instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, lhs); } else if (rhs instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, rhs); } else { return opRecord.op(lhs, rhs); } } private visitParenthesizedExpression(node: ts.ParenthesizedExpression, context: Context): ResolvedValue { return this.visitExpression(node.expression, context); } private evaluateFunctionArguments(node: ts.CallExpression, context: Context): ResolvedValueArray { const args: ResolvedValueArray = []; for (const arg of node.arguments) { if (ts.isSpreadElement(arg)) { args.push(...this.visitSpreadElement(arg, context)); } else { args.push(this.visitExpression(arg, context)); } } return args; } private visitSpreadElement(node: ts.SpreadElement, context: Context): ResolvedValueArray { const spread = this.visitExpression(node.expression, context); if (spread instanceof DynamicValue) { return [DynamicValue.fromDynamicInput(node.expression, spread)]; } else if (!Array.isArray(spread)) { throw new Error(`Unexpected value in spread expression: ${spread}`); } else { return spread; } } private stringNameFromPropertyName(node: ts.PropertyName, context: Context): string|undefined { if (ts.isIdentifier(node) || ts.isStringLiteral(node) || ts.isNumericLiteral(node)) { return node.text; } else { // ts.ComputedPropertyName const literal = this.visitExpression(node.expression, context); return typeof literal === 'string' ? literal : undefined; } } private getReference(node: ts.Declaration, context: Context): Reference { return new Reference(node, owningModule(context)); } } function isFunctionOrMethodReference(ref: Reference<ts.Node>): ref is Reference<ts.FunctionDeclaration|ts.MethodDeclaration|ts.FunctionExpression> { return ts.isFunctionDeclaration(ref.node) || ts.isMethodDeclaration(ref.node) || ts.isFunctionExpression(ref.node); } function literal(value: ResolvedValue): any { if (value instanceof DynamicValue || value === null || value === undefined || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { return value; } throw new Error(`Value ${value} is not literal and cannot be used in this context.`); } function isVariableDeclarationDeclared(node: ts.VariableDeclaration): boolean { if (node.parent === undefined || !ts.isVariableDeclarationList(node.parent)) { return false; } const declList = node.parent; if (declList.parent === undefined || !ts.isVariableStatement(declList.parent)) { return false; } const varStmt = declList.parent; return varStmt.modifiers !== undefined && varStmt.modifiers.some(mod => mod.kind === ts.SyntaxKind.DeclareKeyword); } const EMPTY = {}; function joinModuleContext(existing: Context, node: ts.Node, decl: Declaration): { absoluteModuleName?: string, resolutionContext?: string, } { if (decl.viaModule !== null && decl.viaModule !== existing.absoluteModuleName) { return { absoluteModuleName: decl.viaModule, resolutionContext: node.getSourceFile().fileName, }; } else { return EMPTY; } } function owningModule(context: Context, override: OwningModule | null = null): OwningModule|null { let specifier = context.absoluteModuleName; if (override !== null) { specifier = override.specifier; } if (specifier !== null) { return { specifier, resolutionContext: context.resolutionContext, }; } else { return null; } }
packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts
1
https://github.com/angular/angular/commit/c3c0df9d56a68ced7664066048cf5a180fccceea
[ 0.9980839490890503, 0.03398439660668373, 0.0001632013445487246, 0.0002460353134665638, 0.1781919002532959 ]
{ "id": 1, "code_window": [ " arg = args.slice(index);\n", " }\n", " if (arg === undefined && param.initializer !== null) {\n", " arg = this.visitExpression(param.initializer, context);\n", " }\n", " newScope.set(param.node, arg);\n", " });\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " arg = this.visitExpression(param.initializer, calleeContext);\n" ], "file_path": "packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts", "type": "replace", "edit_start_line_idx": 435 }
/** * @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 */ /** * @module * @description * Entry point for all public APIs of this package. */ export * from './src/browser';
packages/animations/browser/public_api.ts
0
https://github.com/angular/angular/commit/c3c0df9d56a68ced7664066048cf5a180fccceea
[ 0.00017769582336768508, 0.00017374289745930582, 0.00016978997155092657, 0.00017374289745930582, 0.000003952925908379257 ]
{ "id": 1, "code_window": [ " arg = args.slice(index);\n", " }\n", " if (arg === undefined && param.initializer !== null) {\n", " arg = this.visitExpression(param.initializer, context);\n", " }\n", " newScope.set(param.node, arg);\n", " });\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " arg = this.visitExpression(param.initializer, calleeContext);\n" ], "file_path": "packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts", "type": "replace", "edit_start_line_idx": 435 }
/** * @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 */ export const IMPORT_PREFIX = 'ɵngcc';
packages/compiler-cli/ngcc/src/constants.ts
0
https://github.com/angular/angular/commit/c3c0df9d56a68ced7664066048cf5a180fccceea
[ 0.0001778136211214587, 0.0001778136211214587, 0.0001778136211214587, 0.0001778136211214587, 0 ]
{ "id": 1, "code_window": [ " arg = args.slice(index);\n", " }\n", " if (arg === undefined && param.initializer !== null) {\n", " arg = this.visitExpression(param.initializer, context);\n", " }\n", " newScope.set(param.node, arg);\n", " });\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " arg = this.visitExpression(param.initializer, calleeContext);\n" ], "file_path": "packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts", "type": "replace", "edit_start_line_idx": 435 }
// #docregion import { Component } from '@angular/core'; @Component({ selector: 'app-hero-list', templateUrl: './hero-list.component.1.html', styleUrls: ['./hero-list.component.1.css'] }) export class HeroListComponent { }
aio/content/examples/router/src/app/hero-list/hero-list.component.1.ts
0
https://github.com/angular/angular/commit/c3c0df9d56a68ced7664066048cf5a180fccceea
[ 0.00017764179210644215, 0.00017613059026189148, 0.00017461940296925604, 0.00017613059026189148, 0.000001511194568593055 ]
{ "id": 2, "code_window": [ " newScope.set(param.node, arg);\n", " });\n", "\n", " return ret.expression !== undefined ?\n", " this.visitExpression(ret.expression, {...context, scope: newScope}) :\n", " undefined;\n", " }\n", "\n", " private visitConditionalExpression(node: ts.ConditionalExpression, context: Context):\n", " ResolvedValue {\n", " const condition = this.visitExpression(node.condition, context);\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return ret.expression !== undefined ? this.visitExpression(ret.expression, calleeContext) :\n", " undefined;\n" ], "file_path": "packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts", "type": "replace", "edit_start_line_idx": 440 }
/** * @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 ts from 'typescript'; import {Reference} from '../../imports'; import {TypeScriptReflectionHost} from '../../reflection'; import {getDeclaration, makeProgram} from '../../testing/in_memory_typescript'; import {DynamicValue} from '../src/dynamic'; import {ForeignFunctionResolver, PartialEvaluator} from '../src/interface'; import {EnumValue, ResolvedValue} from '../src/result'; function makeExpression( code: string, expr: string, supportingFiles: {name: string, contents: string}[] = []): { expression: ts.Expression, host: ts.CompilerHost, checker: ts.TypeChecker, program: ts.Program, options: ts.CompilerOptions } { const {program, options, host} = makeProgram( [{name: 'entry.ts', contents: `${code}; const target$ = ${expr};`}, ...supportingFiles]); const checker = program.getTypeChecker(); const decl = getDeclaration(program, 'entry.ts', 'target$', ts.isVariableDeclaration); return { expression: decl.initializer !, host, options, checker, program, }; } function makeEvaluator(checker: ts.TypeChecker): PartialEvaluator { const reflectionHost = new TypeScriptReflectionHost(checker); return new PartialEvaluator(reflectionHost, checker); } function evaluate<T extends ResolvedValue>( code: string, expr: string, supportingFiles: {name: string, contents: string}[] = [], foreignFunctionResolver?: ForeignFunctionResolver): T { const {expression, checker} = makeExpression(code, expr, supportingFiles); const evaluator = makeEvaluator(checker); return evaluator.evaluate(expression, foreignFunctionResolver) as T; } describe('ngtsc metadata', () => { it('reads a file correctly', () => { const value = evaluate( ` import {Y} from './other'; const A = Y; `, 'A', [ { name: 'other.ts', contents: ` export const Y = 'test'; ` }, ]); expect(value).toEqual('test'); }); it('map access works', () => { expect(evaluate('const obj = {a: "test"};', 'obj.a')).toEqual('test'); }); it('function calls work', () => { expect(evaluate(`function foo(bar) { return bar; }`, 'foo("test")')).toEqual('test'); }); it('function call spread works', () => { expect(evaluate(`function foo(a, ...b) { return [a, b]; }`, 'foo(1, ...[2, 3])')).toEqual([ 1, [2, 3] ]); }); it('conditionals work', () => { expect(evaluate(`const x = false; const y = x ? 'true' : 'false';`, 'y')).toEqual('false'); }); it('addition works', () => { expect(evaluate(`const x = 1 + 2;`, 'x')).toEqual(3); }); it('static property on class works', () => { expect(evaluate(`class Foo { static bar = 'test'; }`, 'Foo.bar')).toEqual('test'); }); it('static property call works', () => { expect(evaluate(`class Foo { static bar(test) { return test; } }`, 'Foo.bar("test")')) .toEqual('test'); }); it('indirected static property call works', () => { expect( evaluate( `class Foo { static bar(test) { return test; } }; const fn = Foo.bar;`, 'fn("test")')) .toEqual('test'); }); it('array works', () => { expect(evaluate(`const x = 'test'; const y = [1, x, 2];`, 'y')).toEqual([1, 'test', 2]); }); it('array spread works', () => { expect(evaluate(`const a = [1, 2]; const b = [4, 5]; const c = [...a, 3, ...b];`, 'c')) .toEqual([1, 2, 3, 4, 5]); }); it('&& operations work', () => { expect(evaluate(`const a = 'hello', b = 'world';`, 'a && b')).toEqual('world'); expect(evaluate(`const a = false, b = 'world';`, 'a && b')).toEqual(false); expect(evaluate(`const a = 'hello', b = 0;`, 'a && b')).toEqual(0); }); it('|| operations work', () => { expect(evaluate(`const a = 'hello', b = 'world';`, 'a || b')).toEqual('hello'); expect(evaluate(`const a = false, b = 'world';`, 'a || b')).toEqual('world'); expect(evaluate(`const a = 'hello', b = 0;`, 'a || b')).toEqual('hello'); }); it('parentheticals work', () => { expect(evaluate(`const a = 3, b = 4;`, 'a * (a + b)')).toEqual(21); }); it('array access works', () => { expect(evaluate(`const a = [1, 2, 3];`, 'a[1] + a[0]')).toEqual(3); }); it('array `length` property access works', () => { expect(evaluate(`const a = [1, 2, 3];`, 'a[\'length\'] + 1')).toEqual(4); }); it('array `slice` function works', () => { expect(evaluate(`const a = [1, 2, 3];`, 'a[\'slice\']()')).toEqual([1, 2, 3]); }); it('array `concat` function works', () => { expect(evaluate(`const a = [1, 2], b = [3, 4];`, 'a[\'concat\'](b)')).toEqual([1, 2, 3, 4]); expect(evaluate(`const a = [1, 2], b = 3;`, 'a[\'concat\'](b)')).toEqual([1, 2, 3]); expect(evaluate(`const a = [1, 2], b = 3, c = [4, 5];`, 'a[\'concat\'](b, c)')).toEqual([ 1, 2, 3, 4, 5 ]); expect(evaluate(`const a = [1, 2], b = [3, 4]`, 'a[\'concat\'](...b)')).toEqual([1, 2, 3, 4]); }); it('negation works', () => { expect(evaluate(`const x = 3;`, '!x')).toEqual(false); expect(evaluate(`const x = 3;`, '!!x')).toEqual(true); }); it('imports work', () => { const {program, options, host} = makeProgram([ {name: 'second.ts', contents: 'export function foo(bar) { return bar; }'}, { name: 'entry.ts', contents: ` import {foo} from './second'; const target$ = foo; ` }, ]); const checker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(checker); const result = getDeclaration(program, 'entry.ts', 'target$', ts.isVariableDeclaration); const expr = result.initializer !; const evaluator = new PartialEvaluator(reflectionHost, checker); const resolved = evaluator.evaluate(expr); if (!(resolved instanceof Reference)) { return fail('Expected expression to resolve to a reference'); } expect(ts.isFunctionDeclaration(resolved.node)).toBe(true); const reference = resolved.getIdentityIn(program.getSourceFile('entry.ts') !); if (reference === null) { return fail('Expected to get an identifier'); } expect(reference.getSourceFile()).toEqual(program.getSourceFile('entry.ts') !); }); it('absolute imports work', () => { const {program, options, host} = makeProgram([ {name: 'node_modules/some_library/index.d.ts', contents: 'export declare function foo(bar);'}, { name: 'entry.ts', contents: ` import {foo} from 'some_library'; const target$ = foo; ` }, ]); const checker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(checker); const result = getDeclaration(program, 'entry.ts', 'target$', ts.isVariableDeclaration); const expr = result.initializer !; const evaluator = new PartialEvaluator(reflectionHost, checker); const resolved = evaluator.evaluate(expr); if (!(resolved instanceof Reference)) { return fail('Expected expression to resolve to an absolute reference'); } expect(owningModuleOf(resolved)).toBe('some_library'); expect(ts.isFunctionDeclaration(resolved.node)).toBe(true); const reference = resolved.getIdentityIn(program.getSourceFile('entry.ts') !); expect(reference).not.toBeNull(); expect(reference !.getSourceFile()).toEqual(program.getSourceFile('entry.ts') !); }); it('reads values from default exports', () => { const value = evaluate( ` import mod from './second'; `, 'mod.property', [ {name: 'second.ts', contents: 'export default {property: "test"}'}, ]); expect(value).toEqual('test'); }); it('reads values from named exports', () => { const value = evaluate(`import * as mod from './second';`, 'mod.a.property', [ {name: 'second.ts', contents: 'export const a = {property: "test"};'}, ]); expect(value).toEqual('test'); }); it('chain of re-exports works', () => { const value = evaluate(`import * as mod from './direct-reexport';`, 'mod.value.property', [ {name: 'const.ts', contents: 'export const value = {property: "test"};'}, {name: 'def.ts', contents: `import {value} from './const'; export default value;`}, {name: 'indirect-reexport.ts', contents: `import value from './def'; export {value};`}, {name: 'direct-reexport.ts', contents: `export {value} from './indirect-reexport';`}, ]); expect(value).toEqual('test'); }); it('map spread works', () => { const map: Map<string, number> = evaluate<Map<string, number>>( `const a = {a: 1}; const b = {b: 2, c: 1}; const c = {...a, ...b, c: 3};`, 'c'); const obj: {[key: string]: number} = {}; map.forEach((value, key) => obj[key] = value); expect(obj).toEqual({ a: 1, b: 2, c: 3, }); }); it('indirected-via-object function call works', () => { expect(evaluate( ` function fn(res) { return res; } const obj = {fn}; `, 'obj.fn("test")')) .toEqual('test'); }); it('template expressions work', () => { expect(evaluate('const a = 2, b = 4;', '`1${a}3${b}5`')).toEqual('12345'); }); it('enum resolution works', () => { const result = evaluate( ` enum Foo { A, B, C, } const r = Foo.B; `, 'r'); if (!(result instanceof EnumValue)) { return fail(`result is not an EnumValue`); } expect(result.enumRef.node.name.text).toBe('Foo'); expect(result.name).toBe('B'); }); it('variable declaration resolution works', () => { const value = evaluate(`import {value} from './decl';`, 'value', [ {name: 'decl.d.ts', contents: 'export declare let value: number;'}, ]); expect(value instanceof Reference).toBe(true); }); it('should resolve shorthand properties to values', () => { const {program} = makeProgram([ {name: 'entry.ts', contents: `const prop = 42; const target$ = {prop};`}, ]); const checker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(checker); const result = getDeclaration(program, 'entry.ts', 'target$', ts.isVariableDeclaration); const expr = result.initializer !as ts.ObjectLiteralExpression; const prop = expr.properties[0] as ts.ShorthandPropertyAssignment; const evaluator = new PartialEvaluator(reflectionHost, checker); const resolved = evaluator.evaluate(prop.name); expect(resolved).toBe(42); }); it('should resolve dynamic values in object literals', () => { const {program} = makeProgram([ {name: 'decl.d.ts', contents: 'export declare const fn: any;'}, { name: 'entry.ts', contents: `import {fn} from './decl'; const prop = fn.foo(); const target$ = {value: prop};` }, ]); const checker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(checker); const result = getDeclaration(program, 'entry.ts', 'target$', ts.isVariableDeclaration); const expr = result.initializer !as ts.ObjectLiteralExpression; const evaluator = new PartialEvaluator(reflectionHost, checker); const resolved = evaluator.evaluate(expr); if (!(resolved instanceof Map)) { return fail('Should have resolved to a Map'); } const value = resolved.get('value') !; if (!(value instanceof DynamicValue)) { return fail(`Should have resolved 'value' to a DynamicValue`); } const prop = expr.properties[0] as ts.PropertyAssignment; expect(value.node).toBe(prop.initializer); }); it('should resolve enums in template expressions', () => { const value = evaluate(`enum Test { VALUE = 'test', } const value = \`a.\${Test.VALUE}.b\`;`, 'value'); expect(value).toBe('a.test.b'); }); it('should not attach identifiers to FFR-resolved values', () => { const value = evaluate( ` declare function foo(arg: any): any; class Target {} const indir = foo(Target); const value = indir; `, 'value', [], firstArgFfr); if (!(value instanceof Reference)) { return fail('Expected value to be a Reference'); } const id = value.getIdentityIn(value.node.getSourceFile()); if (id === null) { return fail('Expected value to have an identity'); } expect(id.text).toEqual('Target'); }); describe('(visited file tracking)', () => { it('should track each time a source file is visited', () => { const visitedFilesSpy = jasmine.createSpy('visitedFilesCb'); const {expression, checker} = makeExpression(`class A { static foo = 42; } function bar() { return A.foo; }`, 'bar()'); const evaluator = makeEvaluator(checker); evaluator.evaluate(expression, undefined, visitedFilesSpy); expect(visitedFilesSpy) .toHaveBeenCalledTimes(3); // The initial expression, followed by two declaration visited expect(visitedFilesSpy.calls.allArgs().map(args => args[0].fileName)).toEqual([ '/entry.ts', '/entry.ts', '/entry.ts' ]); }); it('should track imported source files', () => { const visitedFilesSpy = jasmine.createSpy('visitedFilesCb'); const {expression, checker} = makeExpression(`import {Y} from './other'; const A = Y;`, 'A', [ {name: 'other.ts', contents: `export const Y = 'test';`}, {name: 'not-visited.ts', contents: `export const Z = 'nope';`} ]); const evaluator = makeEvaluator(checker); evaluator.evaluate(expression, undefined, visitedFilesSpy); expect(visitedFilesSpy).toHaveBeenCalledTimes(3); expect(visitedFilesSpy.calls.allArgs().map(args => args[0].fileName)).toEqual([ '/entry.ts', '/entry.ts', '/other.ts' ]); }); it('should track files passed through during re-exports', () => { const visitedFilesSpy = jasmine.createSpy('visitedFilesCb'); const {expression, checker} = makeExpression(`import * as mod from './direct-reexport';`, 'mod.value.property', [ {name: 'const.ts', contents: 'export const value = {property: "test"};'}, {name: 'def.ts', contents: `import {value} from './const'; export default value;`}, {name: 'indirect-reexport.ts', contents: `import value from './def'; export {value};`}, {name: 'direct-reexport.ts', contents: `export {value} from './indirect-reexport';`}, ]); const evaluator = makeEvaluator(checker); evaluator.evaluate(expression, undefined, visitedFilesSpy); expect(visitedFilesSpy).toHaveBeenCalledTimes(3); expect(visitedFilesSpy.calls.allArgs().map(args => args[0].fileName)).toEqual([ '/entry.ts', '/direct-reexport.ts', // Not '/indirect-reexport.ts' or '/def.ts'. // TS skips through them when finding the original symbol for `value` '/const.ts', ]); }); }); }); function owningModuleOf(ref: Reference): string|null { return ref.bestGuessOwningModule !== null ? ref.bestGuessOwningModule.specifier : null; } function firstArgFfr( node: Reference<ts.FunctionDeclaration|ts.MethodDeclaration|ts.FunctionExpression>, args: ReadonlyArray<ts.Expression>): ts.Expression { return args[0]; }
packages/compiler-cli/src/ngtsc/partial_evaluator/test/evaluator_spec.ts
1
https://github.com/angular/angular/commit/c3c0df9d56a68ced7664066048cf5a180fccceea
[ 0.0005109736230224371, 0.0001865802623797208, 0.0001635839871596545, 0.00017353602743241936, 0.00005499728649738245 ]
{ "id": 2, "code_window": [ " newScope.set(param.node, arg);\n", " });\n", "\n", " return ret.expression !== undefined ?\n", " this.visitExpression(ret.expression, {...context, scope: newScope}) :\n", " undefined;\n", " }\n", "\n", " private visitConditionalExpression(node: ts.ConditionalExpression, context: Context):\n", " ResolvedValue {\n", " const condition = this.visitExpression(node.condition, context);\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return ret.expression !== undefined ? this.visitExpression(ret.expression, calleeContext) :\n", " undefined;\n" ], "file_path": "packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts", "type": "replace", "edit_start_line_idx": 440 }
load("//tools:defaults.bzl", "ng_module") load("@npm_bazel_typescript//:index.bzl", "ts_devserver") package(default_visibility = ["//modules/playground:__subpackages__"]) ng_module( name = "animations", srcs = glob(["**/*.ts"]), tsconfig = "//modules/playground:tsconfig-build.json", # TODO: FW-1004 Type checking is currently not complete. type_check = False, deps = [ "//packages/animations", "//packages/core", "//packages/platform-webworker", "//packages/platform-webworker-dynamic", ], ) ts_devserver( name = "devserver", data = [ "loader.js", "//modules/playground/src/web_workers:worker-config", "@npm//node_modules/rxjs:bundles/rxjs.umd.js", "@npm//node_modules/tslib:tslib.js", ], entry_module = "angular/modules/playground/src/web_workers/animations/index", index_html = "index.html", port = 4200, scripts = ["@npm//node_modules/tslib:tslib.js"], static_files = ["@npm//node_modules/zone.js:dist/zone.js"], deps = [":animations"], )
modules/playground/src/web_workers/animations/BUILD.bazel
0
https://github.com/angular/angular/commit/c3c0df9d56a68ced7664066048cf5a180fccceea
[ 0.00017612571537028998, 0.00017387479601893574, 0.00017255230341106653, 0.0001734105753712356, 0.0000013675136187885073 ]
{ "id": 2, "code_window": [ " newScope.set(param.node, arg);\n", " });\n", "\n", " return ret.expression !== undefined ?\n", " this.visitExpression(ret.expression, {...context, scope: newScope}) :\n", " undefined;\n", " }\n", "\n", " private visitConditionalExpression(node: ts.ConditionalExpression, context: Context):\n", " ResolvedValue {\n", " const condition = this.visitExpression(node.condition, context);\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return ret.expression !== undefined ? this.visitExpression(ret.expression, calleeContext) :\n", " undefined;\n" ], "file_path": "packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts", "type": "replace", "edit_start_line_idx": 440 }
/** * @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 */ /** * @fileoverview This files is only here so that @npm//@angular/bazel/bin:ngc-wrapped * is a valid target as it is part of `esm5_outputs_aspect` in /packages/bazel/src/esm5.bzl * TODO(gregmagolan): fix esm5_outputs_aspect so that this is not required */ throw new Error('should never be run');
tools/npm/@angular_bazel/index.js
0
https://github.com/angular/angular/commit/c3c0df9d56a68ced7664066048cf5a180fccceea
[ 0.00017342617502436042, 0.00017328416288364679, 0.00017314215074293315, 0.00017328416288364679, 1.420121407136321e-7 ]
{ "id": 2, "code_window": [ " newScope.set(param.node, arg);\n", " });\n", "\n", " return ret.expression !== undefined ?\n", " this.visitExpression(ret.expression, {...context, scope: newScope}) :\n", " undefined;\n", " }\n", "\n", " private visitConditionalExpression(node: ts.ConditionalExpression, context: Context):\n", " ResolvedValue {\n", " const condition = this.visitExpression(node.condition, context);\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return ret.expression !== undefined ? this.visitExpression(ret.expression, calleeContext) :\n", " undefined;\n" ], "file_path": "packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts", "type": "replace", "edit_start_line_idx": 440 }
/** * @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 */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; export default [ [ ['mi', 'n', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], ['midnight', 'noon', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], u ], [['midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'], u, u], [ '00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'], ['21:00', '06:00'] ] ];
packages/common/locales/extra/en-NG.ts
0
https://github.com/angular/angular/commit/c3c0df9d56a68ced7664066048cf5a180fccceea
[ 0.00017587481124792248, 0.0001729605719447136, 0.00017137468967121094, 0.0001716322440188378, 0.0000020633522126445314 ]
{ "id": 3, "code_window": [ "\n", " it('function calls work', () => {\n", " expect(evaluate(`function foo(bar) { return bar; }`, 'foo(\"test\")')).toEqual('test');\n", " });\n", "\n", " it('function call spread works', () => {\n", " expect(evaluate(`function foo(a, ...b) { return [a, b]; }`, 'foo(1, ...[2, 3])')).toEqual([\n", " 1, [2, 3]\n", " ]);\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('function call default value works', () => {\n", " expect(evaluate(`function foo(bar = 1) { return bar; }`, 'foo()')).toEqual(1);\n", " expect(evaluate(`function foo(bar = 1) { return bar; }`, 'foo(2)')).toEqual(2);\n", " expect(evaluate(`function foo(a, c = a) { return c; }; const a = 1;`, 'foo(2)')).toEqual(2);\n", " });\n", "\n" ], "file_path": "packages/compiler-cli/src/ngtsc/partial_evaluator/test/evaluator_spec.ts", "type": "add", "edit_start_line_idx": 77 }
/** * @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 ts from 'typescript'; import {Reference} from '../../imports'; import {TypeScriptReflectionHost} from '../../reflection'; import {getDeclaration, makeProgram} from '../../testing/in_memory_typescript'; import {DynamicValue} from '../src/dynamic'; import {ForeignFunctionResolver, PartialEvaluator} from '../src/interface'; import {EnumValue, ResolvedValue} from '../src/result'; function makeExpression( code: string, expr: string, supportingFiles: {name: string, contents: string}[] = []): { expression: ts.Expression, host: ts.CompilerHost, checker: ts.TypeChecker, program: ts.Program, options: ts.CompilerOptions } { const {program, options, host} = makeProgram( [{name: 'entry.ts', contents: `${code}; const target$ = ${expr};`}, ...supportingFiles]); const checker = program.getTypeChecker(); const decl = getDeclaration(program, 'entry.ts', 'target$', ts.isVariableDeclaration); return { expression: decl.initializer !, host, options, checker, program, }; } function makeEvaluator(checker: ts.TypeChecker): PartialEvaluator { const reflectionHost = new TypeScriptReflectionHost(checker); return new PartialEvaluator(reflectionHost, checker); } function evaluate<T extends ResolvedValue>( code: string, expr: string, supportingFiles: {name: string, contents: string}[] = [], foreignFunctionResolver?: ForeignFunctionResolver): T { const {expression, checker} = makeExpression(code, expr, supportingFiles); const evaluator = makeEvaluator(checker); return evaluator.evaluate(expression, foreignFunctionResolver) as T; } describe('ngtsc metadata', () => { it('reads a file correctly', () => { const value = evaluate( ` import {Y} from './other'; const A = Y; `, 'A', [ { name: 'other.ts', contents: ` export const Y = 'test'; ` }, ]); expect(value).toEqual('test'); }); it('map access works', () => { expect(evaluate('const obj = {a: "test"};', 'obj.a')).toEqual('test'); }); it('function calls work', () => { expect(evaluate(`function foo(bar) { return bar; }`, 'foo("test")')).toEqual('test'); }); it('function call spread works', () => { expect(evaluate(`function foo(a, ...b) { return [a, b]; }`, 'foo(1, ...[2, 3])')).toEqual([ 1, [2, 3] ]); }); it('conditionals work', () => { expect(evaluate(`const x = false; const y = x ? 'true' : 'false';`, 'y')).toEqual('false'); }); it('addition works', () => { expect(evaluate(`const x = 1 + 2;`, 'x')).toEqual(3); }); it('static property on class works', () => { expect(evaluate(`class Foo { static bar = 'test'; }`, 'Foo.bar')).toEqual('test'); }); it('static property call works', () => { expect(evaluate(`class Foo { static bar(test) { return test; } }`, 'Foo.bar("test")')) .toEqual('test'); }); it('indirected static property call works', () => { expect( evaluate( `class Foo { static bar(test) { return test; } }; const fn = Foo.bar;`, 'fn("test")')) .toEqual('test'); }); it('array works', () => { expect(evaluate(`const x = 'test'; const y = [1, x, 2];`, 'y')).toEqual([1, 'test', 2]); }); it('array spread works', () => { expect(evaluate(`const a = [1, 2]; const b = [4, 5]; const c = [...a, 3, ...b];`, 'c')) .toEqual([1, 2, 3, 4, 5]); }); it('&& operations work', () => { expect(evaluate(`const a = 'hello', b = 'world';`, 'a && b')).toEqual('world'); expect(evaluate(`const a = false, b = 'world';`, 'a && b')).toEqual(false); expect(evaluate(`const a = 'hello', b = 0;`, 'a && b')).toEqual(0); }); it('|| operations work', () => { expect(evaluate(`const a = 'hello', b = 'world';`, 'a || b')).toEqual('hello'); expect(evaluate(`const a = false, b = 'world';`, 'a || b')).toEqual('world'); expect(evaluate(`const a = 'hello', b = 0;`, 'a || b')).toEqual('hello'); }); it('parentheticals work', () => { expect(evaluate(`const a = 3, b = 4;`, 'a * (a + b)')).toEqual(21); }); it('array access works', () => { expect(evaluate(`const a = [1, 2, 3];`, 'a[1] + a[0]')).toEqual(3); }); it('array `length` property access works', () => { expect(evaluate(`const a = [1, 2, 3];`, 'a[\'length\'] + 1')).toEqual(4); }); it('array `slice` function works', () => { expect(evaluate(`const a = [1, 2, 3];`, 'a[\'slice\']()')).toEqual([1, 2, 3]); }); it('array `concat` function works', () => { expect(evaluate(`const a = [1, 2], b = [3, 4];`, 'a[\'concat\'](b)')).toEqual([1, 2, 3, 4]); expect(evaluate(`const a = [1, 2], b = 3;`, 'a[\'concat\'](b)')).toEqual([1, 2, 3]); expect(evaluate(`const a = [1, 2], b = 3, c = [4, 5];`, 'a[\'concat\'](b, c)')).toEqual([ 1, 2, 3, 4, 5 ]); expect(evaluate(`const a = [1, 2], b = [3, 4]`, 'a[\'concat\'](...b)')).toEqual([1, 2, 3, 4]); }); it('negation works', () => { expect(evaluate(`const x = 3;`, '!x')).toEqual(false); expect(evaluate(`const x = 3;`, '!!x')).toEqual(true); }); it('imports work', () => { const {program, options, host} = makeProgram([ {name: 'second.ts', contents: 'export function foo(bar) { return bar; }'}, { name: 'entry.ts', contents: ` import {foo} from './second'; const target$ = foo; ` }, ]); const checker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(checker); const result = getDeclaration(program, 'entry.ts', 'target$', ts.isVariableDeclaration); const expr = result.initializer !; const evaluator = new PartialEvaluator(reflectionHost, checker); const resolved = evaluator.evaluate(expr); if (!(resolved instanceof Reference)) { return fail('Expected expression to resolve to a reference'); } expect(ts.isFunctionDeclaration(resolved.node)).toBe(true); const reference = resolved.getIdentityIn(program.getSourceFile('entry.ts') !); if (reference === null) { return fail('Expected to get an identifier'); } expect(reference.getSourceFile()).toEqual(program.getSourceFile('entry.ts') !); }); it('absolute imports work', () => { const {program, options, host} = makeProgram([ {name: 'node_modules/some_library/index.d.ts', contents: 'export declare function foo(bar);'}, { name: 'entry.ts', contents: ` import {foo} from 'some_library'; const target$ = foo; ` }, ]); const checker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(checker); const result = getDeclaration(program, 'entry.ts', 'target$', ts.isVariableDeclaration); const expr = result.initializer !; const evaluator = new PartialEvaluator(reflectionHost, checker); const resolved = evaluator.evaluate(expr); if (!(resolved instanceof Reference)) { return fail('Expected expression to resolve to an absolute reference'); } expect(owningModuleOf(resolved)).toBe('some_library'); expect(ts.isFunctionDeclaration(resolved.node)).toBe(true); const reference = resolved.getIdentityIn(program.getSourceFile('entry.ts') !); expect(reference).not.toBeNull(); expect(reference !.getSourceFile()).toEqual(program.getSourceFile('entry.ts') !); }); it('reads values from default exports', () => { const value = evaluate( ` import mod from './second'; `, 'mod.property', [ {name: 'second.ts', contents: 'export default {property: "test"}'}, ]); expect(value).toEqual('test'); }); it('reads values from named exports', () => { const value = evaluate(`import * as mod from './second';`, 'mod.a.property', [ {name: 'second.ts', contents: 'export const a = {property: "test"};'}, ]); expect(value).toEqual('test'); }); it('chain of re-exports works', () => { const value = evaluate(`import * as mod from './direct-reexport';`, 'mod.value.property', [ {name: 'const.ts', contents: 'export const value = {property: "test"};'}, {name: 'def.ts', contents: `import {value} from './const'; export default value;`}, {name: 'indirect-reexport.ts', contents: `import value from './def'; export {value};`}, {name: 'direct-reexport.ts', contents: `export {value} from './indirect-reexport';`}, ]); expect(value).toEqual('test'); }); it('map spread works', () => { const map: Map<string, number> = evaluate<Map<string, number>>( `const a = {a: 1}; const b = {b: 2, c: 1}; const c = {...a, ...b, c: 3};`, 'c'); const obj: {[key: string]: number} = {}; map.forEach((value, key) => obj[key] = value); expect(obj).toEqual({ a: 1, b: 2, c: 3, }); }); it('indirected-via-object function call works', () => { expect(evaluate( ` function fn(res) { return res; } const obj = {fn}; `, 'obj.fn("test")')) .toEqual('test'); }); it('template expressions work', () => { expect(evaluate('const a = 2, b = 4;', '`1${a}3${b}5`')).toEqual('12345'); }); it('enum resolution works', () => { const result = evaluate( ` enum Foo { A, B, C, } const r = Foo.B; `, 'r'); if (!(result instanceof EnumValue)) { return fail(`result is not an EnumValue`); } expect(result.enumRef.node.name.text).toBe('Foo'); expect(result.name).toBe('B'); }); it('variable declaration resolution works', () => { const value = evaluate(`import {value} from './decl';`, 'value', [ {name: 'decl.d.ts', contents: 'export declare let value: number;'}, ]); expect(value instanceof Reference).toBe(true); }); it('should resolve shorthand properties to values', () => { const {program} = makeProgram([ {name: 'entry.ts', contents: `const prop = 42; const target$ = {prop};`}, ]); const checker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(checker); const result = getDeclaration(program, 'entry.ts', 'target$', ts.isVariableDeclaration); const expr = result.initializer !as ts.ObjectLiteralExpression; const prop = expr.properties[0] as ts.ShorthandPropertyAssignment; const evaluator = new PartialEvaluator(reflectionHost, checker); const resolved = evaluator.evaluate(prop.name); expect(resolved).toBe(42); }); it('should resolve dynamic values in object literals', () => { const {program} = makeProgram([ {name: 'decl.d.ts', contents: 'export declare const fn: any;'}, { name: 'entry.ts', contents: `import {fn} from './decl'; const prop = fn.foo(); const target$ = {value: prop};` }, ]); const checker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(checker); const result = getDeclaration(program, 'entry.ts', 'target$', ts.isVariableDeclaration); const expr = result.initializer !as ts.ObjectLiteralExpression; const evaluator = new PartialEvaluator(reflectionHost, checker); const resolved = evaluator.evaluate(expr); if (!(resolved instanceof Map)) { return fail('Should have resolved to a Map'); } const value = resolved.get('value') !; if (!(value instanceof DynamicValue)) { return fail(`Should have resolved 'value' to a DynamicValue`); } const prop = expr.properties[0] as ts.PropertyAssignment; expect(value.node).toBe(prop.initializer); }); it('should resolve enums in template expressions', () => { const value = evaluate(`enum Test { VALUE = 'test', } const value = \`a.\${Test.VALUE}.b\`;`, 'value'); expect(value).toBe('a.test.b'); }); it('should not attach identifiers to FFR-resolved values', () => { const value = evaluate( ` declare function foo(arg: any): any; class Target {} const indir = foo(Target); const value = indir; `, 'value', [], firstArgFfr); if (!(value instanceof Reference)) { return fail('Expected value to be a Reference'); } const id = value.getIdentityIn(value.node.getSourceFile()); if (id === null) { return fail('Expected value to have an identity'); } expect(id.text).toEqual('Target'); }); describe('(visited file tracking)', () => { it('should track each time a source file is visited', () => { const visitedFilesSpy = jasmine.createSpy('visitedFilesCb'); const {expression, checker} = makeExpression(`class A { static foo = 42; } function bar() { return A.foo; }`, 'bar()'); const evaluator = makeEvaluator(checker); evaluator.evaluate(expression, undefined, visitedFilesSpy); expect(visitedFilesSpy) .toHaveBeenCalledTimes(3); // The initial expression, followed by two declaration visited expect(visitedFilesSpy.calls.allArgs().map(args => args[0].fileName)).toEqual([ '/entry.ts', '/entry.ts', '/entry.ts' ]); }); it('should track imported source files', () => { const visitedFilesSpy = jasmine.createSpy('visitedFilesCb'); const {expression, checker} = makeExpression(`import {Y} from './other'; const A = Y;`, 'A', [ {name: 'other.ts', contents: `export const Y = 'test';`}, {name: 'not-visited.ts', contents: `export const Z = 'nope';`} ]); const evaluator = makeEvaluator(checker); evaluator.evaluate(expression, undefined, visitedFilesSpy); expect(visitedFilesSpy).toHaveBeenCalledTimes(3); expect(visitedFilesSpy.calls.allArgs().map(args => args[0].fileName)).toEqual([ '/entry.ts', '/entry.ts', '/other.ts' ]); }); it('should track files passed through during re-exports', () => { const visitedFilesSpy = jasmine.createSpy('visitedFilesCb'); const {expression, checker} = makeExpression(`import * as mod from './direct-reexport';`, 'mod.value.property', [ {name: 'const.ts', contents: 'export const value = {property: "test"};'}, {name: 'def.ts', contents: `import {value} from './const'; export default value;`}, {name: 'indirect-reexport.ts', contents: `import value from './def'; export {value};`}, {name: 'direct-reexport.ts', contents: `export {value} from './indirect-reexport';`}, ]); const evaluator = makeEvaluator(checker); evaluator.evaluate(expression, undefined, visitedFilesSpy); expect(visitedFilesSpy).toHaveBeenCalledTimes(3); expect(visitedFilesSpy.calls.allArgs().map(args => args[0].fileName)).toEqual([ '/entry.ts', '/direct-reexport.ts', // Not '/indirect-reexport.ts' or '/def.ts'. // TS skips through them when finding the original symbol for `value` '/const.ts', ]); }); }); }); function owningModuleOf(ref: Reference): string|null { return ref.bestGuessOwningModule !== null ? ref.bestGuessOwningModule.specifier : null; } function firstArgFfr( node: Reference<ts.FunctionDeclaration|ts.MethodDeclaration|ts.FunctionExpression>, args: ReadonlyArray<ts.Expression>): ts.Expression { return args[0]; }
packages/compiler-cli/src/ngtsc/partial_evaluator/test/evaluator_spec.ts
1
https://github.com/angular/angular/commit/c3c0df9d56a68ced7664066048cf5a180fccceea
[ 0.995233952999115, 0.0686199888586998, 0.00016654745559208095, 0.00017583687440492213, 0.2304670810699463 ]
{ "id": 3, "code_window": [ "\n", " it('function calls work', () => {\n", " expect(evaluate(`function foo(bar) { return bar; }`, 'foo(\"test\")')).toEqual('test');\n", " });\n", "\n", " it('function call spread works', () => {\n", " expect(evaluate(`function foo(a, ...b) { return [a, b]; }`, 'foo(1, ...[2, 3])')).toEqual([\n", " 1, [2, 3]\n", " ]);\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('function call default value works', () => {\n", " expect(evaluate(`function foo(bar = 1) { return bar; }`, 'foo()')).toEqual(1);\n", " expect(evaluate(`function foo(bar = 1) { return bar; }`, 'foo(2)')).toEqual(2);\n", " expect(evaluate(`function foo(a, c = a) { return c; }; const a = 1;`, 'foo(2)')).toEqual(2);\n", " });\n", "\n" ], "file_path": "packages/compiler-cli/src/ngtsc/partial_evaluator/test/evaluator_spec.ts", "type": "add", "edit_start_line_idx": 77 }
/** * @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 {StaticSymbol} from '../aot/static_symbol'; import * as o from '../output/output_ast'; import {OutputContext} from '../util'; /** * Convert an object map with `Expression` values into a `LiteralMapExpr`. */ export function mapToMapExpression(map: {[key: string]: o.Expression}): o.LiteralMapExpr { const result = Object.keys(map).map(key => ({key, value: map[key], quoted: false})); return o.literalMap(result); } /** * Convert metadata into an `Expression` in the given `OutputContext`. * * This operation will handle arrays, references to symbols, or literal `null` or `undefined`. */ export function convertMetaToOutput(meta: any, ctx: OutputContext): o.Expression { if (Array.isArray(meta)) { return o.literalArr(meta.map(entry => convertMetaToOutput(entry, ctx))); } if (meta instanceof StaticSymbol) { return ctx.importExpr(meta); } if (meta == null) { return o.literal(meta); } throw new Error(`Internal error: Unsupported or unknown metadata: ${meta}`); } export function typeWithParameters(type: o.Expression, numParams: number): o.ExpressionType { let params: o.Type[]|null = null; if (numParams > 0) { params = []; for (let i = 0; i < numParams; i++) { params.push(o.DYNAMIC_TYPE); } } return o.expressionType(type, null, params); } export interface R3Reference { value: o.Expression; type: o.Expression; } const ANIMATE_SYMBOL_PREFIX = '@'; export function prepareSyntheticPropertyName(name: string) { return `${ANIMATE_SYMBOL_PREFIX}${name}`; } export function prepareSyntheticListenerName(name: string, phase: string) { return `${ANIMATE_SYMBOL_PREFIX}${name}.${phase}`; } export function isSyntheticPropertyOrListener(name: string) { return name.charAt(0) == ANIMATE_SYMBOL_PREFIX; } export function getSyntheticPropertyName(name: string) { // this will strip out listener phase values... // @foo.start => @foo const i = name.indexOf('.'); name = i > 0 ? name.substring(0, i) : name; if (name.charAt(0) !== ANIMATE_SYMBOL_PREFIX) { name = ANIMATE_SYMBOL_PREFIX + name; } return name; } export function prepareSyntheticListenerFunctionName(name: string, phase: string) { return `animation_${name}_${phase}`; }
packages/compiler/src/render3/util.ts
0
https://github.com/angular/angular/commit/c3c0df9d56a68ced7664066048cf5a180fccceea
[ 0.00017739177565090358, 0.00017434943583793938, 0.0001710483484202996, 0.00017469785234425217, 0.000002053175876426394 ]
{ "id": 3, "code_window": [ "\n", " it('function calls work', () => {\n", " expect(evaluate(`function foo(bar) { return bar; }`, 'foo(\"test\")')).toEqual('test');\n", " });\n", "\n", " it('function call spread works', () => {\n", " expect(evaluate(`function foo(a, ...b) { return [a, b]; }`, 'foo(1, ...[2, 3])')).toEqual([\n", " 1, [2, 3]\n", " ]);\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('function call default value works', () => {\n", " expect(evaluate(`function foo(bar = 1) { return bar; }`, 'foo()')).toEqual(1);\n", " expect(evaluate(`function foo(bar = 1) { return bar; }`, 'foo(2)')).toEqual(2);\n", " expect(evaluate(`function foo(a, c = a) { return c; }; const a = 1;`, 'foo(2)')).toEqual(2);\n", " });\n", "\n" ], "file_path": "packages/compiler-cli/src/ngtsc/partial_evaluator/test/evaluator_spec.ts", "type": "add", "edit_start_line_idx": 77 }
<!--#docregion--> <!--#docregion i18n-attribute-meaning--> <h1 i18n="User welcome|An introduction header for this sample@@introductionHeader"> Hello i18n! </h1> <!--#enddocregion i18n-attribute-meaning--> <!--#docregion i18n-ng-container--> <ng-container i18n>I don't output any element</ng-container> <!--#enddocregion i18n-ng-container--> <br /> <!--#docregion i18n-title-translate--> <img [src]="logo" i18n-title title="Angular logo" /> <!--#enddocregion i18n-title-translate--> <br> <button (click)="inc(1)">+</button> <button (click)="inc(-1)">-</button> <!--#docregion i18n-plural--> <span i18n>Updated {minutes, plural, =0 {just now} =1 {one minute ago} other {{{minutes}} minutes ago}}</span> <!--#enddocregion i18n-plural--> ({{minutes}}) <br><br> <button (click)="male()">&#9794;</button> <button (click)="female()">&#9792;</button> <button (click)="other()">&#9895;</button> <!--#docregion i18n-select--> <span i18n>The author is {gender, select, male {male} female {female} other {other}}</span> <!--#enddocregion i18n-select--> <br><br> <!--#docregion i18n-nested--> <span i18n>Updated: {minutes, plural, =0 {just now} =1 {one minute ago} other {{{minutes}} minutes ago by {gender, select, male {male} female {female} other {other}}}} </span> <!--#enddocregion i18n-nested-->
aio/content/examples/i18n/src/app/app.component.html
0
https://github.com/angular/angular/commit/c3c0df9d56a68ced7664066048cf5a180fccceea
[ 0.00017518708773422986, 0.00017467702855356038, 0.000174170098034665, 0.0001746754569467157, 3.632191578617494e-7 ]
{ "id": 3, "code_window": [ "\n", " it('function calls work', () => {\n", " expect(evaluate(`function foo(bar) { return bar; }`, 'foo(\"test\")')).toEqual('test');\n", " });\n", "\n", " it('function call spread works', () => {\n", " expect(evaluate(`function foo(a, ...b) { return [a, b]; }`, 'foo(1, ...[2, 3])')).toEqual([\n", " 1, [2, 3]\n", " ]);\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('function call default value works', () => {\n", " expect(evaluate(`function foo(bar = 1) { return bar; }`, 'foo()')).toEqual(1);\n", " expect(evaluate(`function foo(bar = 1) { return bar; }`, 'foo(2)')).toEqual(2);\n", " expect(evaluate(`function foo(a, c = a) { return c; }; const a = 1;`, 'foo(2)')).toEqual(2);\n", " });\n", "\n" ], "file_path": "packages/compiler-cli/src/ngtsc/partial_evaluator/test/evaluator_spec.ts", "type": "add", "edit_start_line_idx": 77 }
/** * @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 */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; function plural(n: number): number { if (n === 0) return 0; if (n === 1) return 1; if (n === 2) return 2; if (n % 100 === Math.floor(n % 100) && n % 100 >= 3 && n % 100 <= 10) return 3; if (n % 100 === Math.floor(n % 100) && n % 100 >= 11 && n % 100 <= 99) return 4; return 5; } export default [ 'ar-LB', [['ص', 'م'], u, u], [['ص', 'م'], u, ['صباحًا', 'مساءً']], [ ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], [ 'الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت' ], u, ['أحد', 'إثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت'] ], u, [ ['ك', 'ش', 'آ', 'ن', 'أ', 'ح', 'ت', 'آ', 'أ', 'ت', 'ت', 'ك'], [ 'كانون الثاني', 'شباط', 'آذار', 'نيسان', 'أيار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول' ], u ], u, [['ق.م', 'م'], u, ['قبل الميلاد', 'ميلادي']], 1, [6, 0], ['d\u200f/M\u200f/y', 'dd\u200f/MM\u200f/y', 'd MMMM y', 'EEEE، d MMMM y'], ['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'], ['{1} {0}', u, u, u], [ ',', '.', ';', '\u200e%\u200e', '\u200e+', '\u200e-', 'E', '×', '‰', '∞', 'ليس رقمًا', ':' ], ['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'], 'ل.ل.\u200f', 'جنيه لبناني', { 'AED': ['د.إ.\u200f'], 'ARS': [u, 'AR$'], 'AUD': ['AU$'], 'BBD': [u, 'BB$'], 'BHD': ['د.ب.\u200f'], 'BMD': [u, 'BM$'], 'BND': [u, 'BN$'], 'BSD': [u, 'BS$'], 'BZD': [u, 'BZ$'], 'CAD': ['CA$'], 'CLP': [u, 'CL$'], 'CNY': ['CN¥'], 'COP': [u, 'CO$'], 'CUP': [u, 'CU$'], 'DOP': [u, 'DO$'], 'DZD': ['د.ج.\u200f'], 'EGP': ['ج.م.\u200f', 'E£'], 'FJD': [u, 'FJ$'], 'GBP': ['£', 'UK£'], 'GYD': [u, 'GY$'], 'HKD': ['HK$'], 'IQD': ['د.ع.\u200f'], 'IRR': ['ر.إ.'], 'JMD': [u, 'JM$'], 'JOD': ['د.أ.\u200f'], 'JPY': ['JP¥'], 'KWD': ['د.ك.\u200f'], 'KYD': [u, 'KY$'], 'LBP': ['ل.ل.\u200f', 'L£'], 'LYD': ['د.ل.\u200f'], 'MAD': ['د.م.\u200f'], 'MRO': ['أ.م.\u200f'], 'MXN': ['MX$'], 'NZD': ['NZ$'], 'OMR': ['ر.ع.\u200f'], 'QAR': ['ر.ق.\u200f'], 'SAR': ['ر.س.\u200f'], 'SBD': [u, 'SB$'], 'SDD': ['د.س.\u200f'], 'SRD': [u, 'SR$'], 'SYP': ['ل.س.\u200f', '£'], 'THB': ['฿'], 'TND': ['د.ت.\u200f'], 'TTD': [u, 'TT$'], 'TWD': ['NT$'], 'USD': ['US$'], 'UYU': [u, 'UY$'], 'XXX': ['***'], 'YER': ['ر.ي.\u200f'] }, plural ];
packages/common/locales/ar-LB.ts
0
https://github.com/angular/angular/commit/c3c0df9d56a68ced7664066048cf5a180fccceea
[ 0.00017707812367007136, 0.00017354747978970408, 0.0001677315594861284, 0.00017480281530879438, 0.0000031864283300819807 ]
{ "id": 0, "code_window": [ "}\n", "\n", "const cjs = [\n", " {\n", " input: \"modules/index.js\",\n", " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\" },\n", " external: isBareModuleId,\n", " plugins: [\n", " babel({ exclude: /node_modules/ }),\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\", esModule: false },\n" ], "file_path": "packages/react-router-config/rollup.config.js", "type": "replace", "edit_start_line_idx": 18 }
const babel = require("rollup-plugin-babel"); const replace = require("rollup-plugin-replace"); const commonjs = require("rollup-plugin-commonjs"); const nodeResolve = require("rollup-plugin-node-resolve"); const { sizeSnapshot } = require("rollup-plugin-size-snapshot"); const { uglify } = require("rollup-plugin-uglify"); const path = require("path"); const pkg = require("./package.json"); function isBareModuleId(id) { return ( !id.startsWith(".") && !id.includes(path.join(process.cwd(), "modules")) ); } const cjs = [ { input: "modules/index.js", output: { file: `cjs/${pkg.name}.js`, format: "cjs" }, external: isBareModuleId, plugins: [ babel({ exclude: /node_modules/ }), replace({ "process.env.NODE_ENV": JSON.stringify("development"), "process.env.BUILD_FORMAT": JSON.stringify("cjs") }) ] }, { input: "modules/index.js", output: { file: `cjs/${pkg.name}.min.js`, format: "cjs" }, external: isBareModuleId, plugins: [ babel({ exclude: /node_modules/ }), replace({ "process.env.NODE_ENV": JSON.stringify("production"), "process.env.BUILD_FORMAT": JSON.stringify("cjs") }), uglify() ] } ]; const esm = [ { input: "modules/index.js", output: { file: `esm/${pkg.name}.js`, format: "esm" }, external: isBareModuleId, plugins: [ babel({ exclude: /node_modules/, runtimeHelpers: true, plugins: [["@babel/transform-runtime", { useESModules: true }]] }), replace({ "process.env.BUILD_FORMAT": JSON.stringify("esm") }), sizeSnapshot() ] } ]; const globals = { react: "React" }; const umd = [ { input: "modules/index.js", output: { file: `umd/${pkg.name}.js`, format: "umd", name: "ReactRouter", globals }, external: Object.keys(globals), plugins: [ babel({ exclude: /node_modules/, runtimeHelpers: true, plugins: [["@babel/transform-runtime", { useESModules: true }]] }), nodeResolve(), commonjs({ include: /node_modules/, namedExports: { "node_modules/react-is/index.js": ["isValidElementType"] } }), replace({ "process.env.NODE_ENV": JSON.stringify("development"), "process.env.BUILD_FORMAT": JSON.stringify("umd") }), sizeSnapshot() ] }, { input: "modules/index.js", output: { file: `umd/${pkg.name}.min.js`, format: "umd", name: "ReactRouter", globals }, external: Object.keys(globals), plugins: [ babel({ exclude: /node_modules/, runtimeHelpers: true, plugins: [["@babel/transform-runtime", { useESModules: true }]] }), nodeResolve(), commonjs({ include: /node_modules/, namedExports: { "node_modules/react-is/index.js": ["isValidElementType"] } }), replace({ "process.env.NODE_ENV": JSON.stringify("production"), "process.env.BUILD_FORMAT": JSON.stringify("umd") }), sizeSnapshot(), uglify() ] } ]; let config; switch (process.env.BUILD_ENV) { case "cjs": config = cjs; break; case "esm": config = esm; break; case "umd": config = umd; break; default: config = cjs.concat(esm).concat(umd); } module.exports = config;
packages/react-router/rollup.config.js
1
https://github.com/remix-run/react-router/commit/caa9950c752386ab1b4db71e322b452d2f72dfca
[ 0.9983396530151367, 0.20461681485176086, 0.00016648313612677157, 0.0037198010832071304, 0.3937148153781891 ]
{ "id": 0, "code_window": [ "}\n", "\n", "const cjs = [\n", " {\n", " input: \"modules/index.js\",\n", " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\" },\n", " external: isBareModuleId,\n", " plugins: [\n", " babel({ exclude: /node_modules/ }),\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\", esModule: false },\n" ], "file_path": "packages/react-router-config/rollup.config.js", "type": "replace", "edit_start_line_idx": 18 }
# Migrating from v2/v3 to v4 React Router v4 is a complete rewrite, so there is not a simple migration path. This guide will provide you with a number of steps to help you understand how to upgrade your application. **Note:** This migration guide is for both React Router v2 and v3, but for brevity, references to previous versions will only mention v3. **For react-router-redux users:** This library [has been deprecated](/packages/react-router-redux/README.md#project-deprecated). It is recommended that you separate out Redux and React Router, as their state semantics don't match up exactly. But if you wish to attempt to keep them in sync, you can use a library such as [connected-react-router](https://github.com/supasate/connected-react-router). - [The Router](#the-router) - [Routes](#routes) - [Nesting Routes](#nesting-routes) - [on\* properties](#on-properties) - [Optional Parameters](#optional-parameters) - [Query Strings](#query-strings) - [Switch](#switch) - [Redirect](#redirect) - [PatternUtils](#patternutils) - [Link](#link) ## The Router In React Router v3, there was a single `<Router>` component. It would be provided a `history` object as a prop. Also, you would provide it your application's route configuration to the `<Router>` either using the `routes` prop or as the `children` of the `<Router>`. ```jsx // v3 import routes from './routes' <Router history={browserHistory} routes={routes} /> // or <Router history={browserHistory}> <Route path='/' component={App}> // ... </Route> </Router> ``` With React Router v4, one of the big changes is that there are a number of different router components. Each one will create a `history` object for you. The `<BrowserRouter>` creates a browser history, the `<HashRouter>` creates a hash history, and the `<MemoryRouter>` creates a memory history. In v4, there is no centralized route configuration. Anywhere that you need to render content based on a route, you will just render a `<Route>` component. ```jsx //v4 <BrowserRouter> <div> <Route path="/about" component={About} /> <Route path="/contact" component={Contact} /> </div> </BrowserRouter> ``` One thing to note is that the router component must only be given one child element. ```jsx // yes <BrowserRouter> <div> <Route path='/about' component={About} /> <Route path='/contact' component={Contact} /> </div> </BrowserRouter> // no <BrowserRouter> <Route path='/about' component={About} /> <Route path='/contact' component={Contact} /> </BrowserRouter> ``` ## Routes In v3, the `<Route>` was not really a component. Instead, all of your application's `<Route>` elements were just used to create a route configuration object. ```jsx /// in v3 the element <Route path='contact' component={Contact} /> // was equivalent to { path: 'contact', component: Contact } ``` With v4, you layout your app's components just like a regular React application. Anywhere that you want to render content based on the location (specifically, its `pathname`), you render a `<Route>`. The v4 `<Route>` component is actually a component, so wherever you render a `<Route>` component, content will be rendered. When the `<Route>`'s `path` matches the current location, it will use its rendering prop (`component`, `render`, or `children`) to render. When the `<Route>`'s `path` does not match, it will render `null`. ### Nesting Routes In v3, `<Route>`s were nested by passing them as the `children` of their parent `<Route>`. ```jsx <Route path="parent" component={Parent}> <Route path="child" component={Child} /> <Route path="other" component={Other} /> </Route> ``` When a nested `<Route>` matched, React elements would be created using both the child and parent `<Route>`'s `component` prop. The child element would be passed to the parent element as its `children` prop. ```jsx <Parent {...routeProps}> <Child {...routeProps} /> </Parent> ``` With v4, children `<Route>`s should just be rendered by the parent `<Route>`'s component. ```jsx <Route path="parent" component={Parent} />; function Parent() { return ( <div> <Route path="child" component={Child} /> <Route path="other" component={Other} /> </div> ); } ``` ### `on*` properties React Router v3 provides `onEnter`, `onUpdate`, and `onLeave` methods. These were essentially recreating React's lifecycle methods. With v4, you should use the lifecycle methods of the component rendered by a `<Route>`. Instead of `onEnter`, you would use `componentDidMount`. Where you would use `onUpdate`, you can use `componentDidUpdate`. `onLeave` can be replaced with `componentWillUnmount`. ### Optional Parameters In v3, parameters were made optional with parentheses: `path="/entity/:entityId(/:parentId)"` In v4, the syntax is changed to a trailing question mark: `path="/entity/:entityId/:parentId?"` ### Query Strings In v4, there is no parsing done on query strings. The unparsed query string is available on the `location.search` property. The [qhistory](https://github.com/pshrmn/qhistory) library can provide this functionality if it is necessary for your application. Read more regarding intentions for this change and possible solutions in [this issue](https://github.com/ReactTraining/react-router/issues/4410). ### `<Switch>` In v3, you could specify a number of child routes, and only the first one that matched would be rendered. ```jsx // v3 <Route path="/" component={App}> <IndexRoute component={Home} /> <Route path="about" component={About} /> <Route path="contact" component={Contact} /> </Route> ``` v4 provides a similar functionality with the `<Switch>` component. When a `<Switch>` is rendered, it will only render the first child `<Route>` that matches the current location. ```jsx // v4 const App = () => ( <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> <Route path="/contact" component={Contact} /> </Switch> ); ``` ### `<Redirect>` In v3, if you wanted to redirect from one path to another, for instance / to /welcome, you would use `<IndexRedirect >`. ```jsx // v3 <Route path="/" component={App}> <IndexRedirect to="/welcome" /> </Route> ``` In v4, you can achieve the same functionality using `<Redirect>`. ```jsx // v4 <Route exact path="/" render={() => <Redirect to="/welcome" component={App} />} /> <Switch> <Route exact path="/" component={App} /> <Route path="/login" component={Login} /> <Redirect path="*" to="/" /> </Switch> ``` In v3, `<Redirect>` preserved the query string: ```jsx // v3 <Redirect from="/" to="/welcome" /> // /?source=google → /welcome?source=google ``` In v4, you must re-pass these properties to the `to` prop: ```jsx // v4 <Redirect from="/" to="/welcome" /> // /?source=google → /welcome <Redirect from="/" to={{ ...location, pathname: "/welcome" }} /> // /?source=google → /welcome?source=google ``` ## PatternUtils ### matchPattern(pattern, pathname) In v3, you could use the same matching code used internally to check if a path matched a pattern. In v4 this has been replaced by [matchPath](/packages/react-router/docs/api/matchPath.md) which is powered by the [`path-to-regexp@^1.7.0`](https://github.com/pillarjs/path-to-regexp/tree/v1.7.0) library. ### formatPattern(pattern, params) In v3, you could use PatternUtils.formatPattern to generate a valid path from a path pattern (perhaps in a constant or in your central routing config) and an object containing the names parameters: ```jsx // v3 const THING_PATH = "/thing/:id"; <Link to={PatternUtils.formatPattern(THING_PATH, { id: 1 })}>A thing</Link>; ``` In v4, you can achieve the same functionality using the [`compile`](https://github.com/pillarjs/path-to-regexp/tree/v1.7.0#compile-reverse-path-to-regexp) function in [`path-to-regexp@^1.7.0`](https://github.com/pillarjs/path-to-regexp/tree/v1.7.0). ```jsx // v4 const THING_PATH = "/thing/:id"; const thingPath = pathToRegexp.compile(THING_PATH); <Link to={thingPath({ id: 1 })}>A thing</Link>; ``` ### getParamNames The `getParamNames` functionality can be achieved using the [`parse`](https://github.com/pillarjs/path-to-regexp/tree/v1.7.0#parse) function in [`path-to-regexp@^1.7.0`](https://github.com/pillarjs/path-to-regexp/tree/v1.7.0). ## Link ### `to` property is required In v3, you could omit `to` property or set it to null to create an anchor tag without `href` attribute. ```jsx // v3 <Link to={disabled ? null : `/item/${id}`} className="item"> // item content </Link> ``` In v4, you should always provide `to`. In case you are rely on empty `to` you can make a simple wrapper. ```jsx // v4 import { Link } from 'react-router-dom' const LinkWrapper = (props) => { const Component = props.to ? Link : 'a' return ( <Component {...props}> { props.children } </Component> ) } <LinkWrapper to={disabled ? null : `/item/${id}`} className="item"> // item content </LinkWrapper> ```
packages/react-router/docs/guides/migrating.md
0
https://github.com/remix-run/react-router/commit/caa9950c752386ab1b4db71e322b452d2f72dfca
[ 0.00017762264178600162, 0.00016956772014964372, 0.0001611746847629547, 0.00017016779747791588, 0.000003757527565539931 ]
{ "id": 0, "code_window": [ "}\n", "\n", "const cjs = [\n", " {\n", " input: \"modules/index.js\",\n", " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\" },\n", " external: isBareModuleId,\n", " plugins: [\n", " babel({ exclude: /node_modules/ }),\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\", esModule: false },\n" ], "file_path": "packages/react-router-config/rollup.config.js", "type": "replace", "edit_start_line_idx": 18 }
"use strict"; require("./warnAboutDeprecatedCJSRequire")("Route"); module.exports = require("./index.js").Route;
packages/react-router-dom/Route.js
0
https://github.com/remix-run/react-router/commit/caa9950c752386ab1b4db71e322b452d2f72dfca
[ 0.00016532375593669713, 0.00016532375593669713, 0.00016532375593669713, 0.00016532375593669713, 0 ]
{ "id": 0, "code_window": [ "}\n", "\n", "const cjs = [\n", " {\n", " input: \"modules/index.js\",\n", " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\" },\n", " external: isBareModuleId,\n", " plugins: [\n", " babel({ exclude: /node_modules/ }),\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\", esModule: false },\n" ], "file_path": "packages/react-router-config/rollup.config.js", "type": "replace", "edit_start_line_idx": 18 }
{ "private": true, "name": "react-router-website", "version": "5.0.0", "scripts": { "build": "cross-env NODE_ENV=production webpack -p", "start": "webpack-dev-server --inline --host 0.0.0.0" }, "dependencies": { "@codesandbox/react-embed": "0.0.14", "animated": "^0.2.1", "cheerio": "^0.22.0", "isomorphic-fetch": "^2.2.1", "prop-types": "^15.6.1", "query-string": "^5.1.0", "react": "^16.4.0", "react-css-property-operations": "^15.4.1", "react-dom": "^16.4.0", "react-icons": "^2.2.7", "react-media": "^1.6.1", "react-motion": "^0.5.2", "react-transition-group": "^2.2.1", "resolve-pathname": "^2.2.0", "slug": "^0.9.2" }, "devDependencies": { "babel-core": "^6.26.3", "babel-eslint": "^8.2.3", "babel-loader": "^7.1.2", "babel-plugin-dev-expression": "^0.2.1", "babel-plugin-transform-class-properties": "^6.24.1", "babel-plugin-transform-export-default": "^7.0.0-alpha.20", "babel-plugin-transform-object-rest-spread": "^6.26.0", "babel-polyfill": "^6.23.0", "babel-preset-env": "^1.7.0", "babel-preset-react": "^6.5.0", "bundle-loader": "^0.5.5", "cheerio": "^0.22.0", "copy-webpack-plugin": "^4.0.1", "cross-env": "^5.2.0", "css-loader": "^2.1.1", "eslint": "^4.19.1", "eslint-plugin-import": "^2.12.0", "eslint-plugin-react": "^7.9.1", "file-loader": "^1.1.5", "html-loader": "^0.5.1", "html-webpack-plugin": "^3.2.0", "isomorphic-fetch": "^2.2.1", "jsxstyle": "^2.1.1", "loader-utils": "1.1.0", "markdown-it": "^7.0.0", "postcss-loader": "^2.1.5", "prismjs": "^1.8.4", "prop-types": "^15.6.1", "query-string": "^5.1.0", "raw-loader": "^0.5.1", "react": "^16.8.4", "react-css-property-operations": "^15.4.1", "react-dom": "^16.8.4", "react-icons": "^2.2.7", "react-media": "^1.6.1", "react-motion": "^0.5.2", "react-transition-group": "^2.2.1", "resolve-pathname": "^2.2.0", "slug": "^1.0.0", "style-loader": "^0.19.0", "sw-precache": "^4.2.2", "sw-precache-webpack-plugin": "^0.11.5", "unicode": "^9.0.1", "url-loader": "^0.6.2", "webpack": "^4.29.6", "webpack-cli": "^3.2.3", "webpack-dev-server": "^3.2.1" } }
website/package.json
0
https://github.com/remix-run/react-router/commit/caa9950c752386ab1b4db71e322b452d2f72dfca
[ 0.00017466404824517667, 0.0001723844325169921, 0.00016951042925938964, 0.00017201295122504234, 0.000001548579461996269 ]
{ "id": 1, "code_window": [ "}\n", "\n", "const cjs = [\n", " {\n", " input: \"modules/index.js\",\n", " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\" },\n", " external: isBareModuleId,\n", " plugins: [\n", " babel({ exclude: /node_modules/ }),\n", " replace({ \"process.env.NODE_ENV\": JSON.stringify(\"development\") })\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\", esModule: false },\n" ], "file_path": "packages/react-router-dom/rollup.config.js", "type": "replace", "edit_start_line_idx": 18 }
const babel = require("rollup-plugin-babel"); const replace = require("rollup-plugin-replace"); const commonjs = require("rollup-plugin-commonjs"); const nodeResolve = require("rollup-plugin-node-resolve"); const { sizeSnapshot } = require("rollup-plugin-size-snapshot"); const { uglify } = require("rollup-plugin-uglify"); const path = require("path"); const pkg = require("./package.json"); function isBareModuleId(id) { return ( !id.startsWith(".") && !id.includes(path.join(process.cwd(), "modules")) ); } const cjs = [ { input: "modules/index.js", output: { file: `cjs/${pkg.name}.js`, format: "cjs" }, external: isBareModuleId, plugins: [ babel({ exclude: /node_modules/ }), replace({ "process.env.NODE_ENV": JSON.stringify("development"), "process.env.BUILD_FORMAT": JSON.stringify("cjs") }) ] }, { input: "modules/index.js", output: { file: `cjs/${pkg.name}.min.js`, format: "cjs" }, external: isBareModuleId, plugins: [ babel({ exclude: /node_modules/ }), replace({ "process.env.NODE_ENV": JSON.stringify("production"), "process.env.BUILD_FORMAT": JSON.stringify("cjs") }), uglify() ] } ]; const esm = [ { input: "modules/index.js", output: { file: `esm/${pkg.name}.js`, format: "esm" }, external: isBareModuleId, plugins: [ babel({ exclude: /node_modules/, runtimeHelpers: true, plugins: [["@babel/transform-runtime", { useESModules: true }]] }), replace({ "process.env.BUILD_FORMAT": JSON.stringify("esm") }), sizeSnapshot() ] } ]; const globals = { react: "React" }; const umd = [ { input: "modules/index.js", output: { file: `umd/${pkg.name}.js`, format: "umd", name: "ReactRouter", globals }, external: Object.keys(globals), plugins: [ babel({ exclude: /node_modules/, runtimeHelpers: true, plugins: [["@babel/transform-runtime", { useESModules: true }]] }), nodeResolve(), commonjs({ include: /node_modules/, namedExports: { "node_modules/react-is/index.js": ["isValidElementType"] } }), replace({ "process.env.NODE_ENV": JSON.stringify("development"), "process.env.BUILD_FORMAT": JSON.stringify("umd") }), sizeSnapshot() ] }, { input: "modules/index.js", output: { file: `umd/${pkg.name}.min.js`, format: "umd", name: "ReactRouter", globals }, external: Object.keys(globals), plugins: [ babel({ exclude: /node_modules/, runtimeHelpers: true, plugins: [["@babel/transform-runtime", { useESModules: true }]] }), nodeResolve(), commonjs({ include: /node_modules/, namedExports: { "node_modules/react-is/index.js": ["isValidElementType"] } }), replace({ "process.env.NODE_ENV": JSON.stringify("production"), "process.env.BUILD_FORMAT": JSON.stringify("umd") }), sizeSnapshot(), uglify() ] } ]; let config; switch (process.env.BUILD_ENV) { case "cjs": config = cjs; break; case "esm": config = esm; break; case "umd": config = umd; break; default: config = cjs.concat(esm).concat(umd); } module.exports = config;
packages/react-router/rollup.config.js
1
https://github.com/remix-run/react-router/commit/caa9950c752386ab1b4db71e322b452d2f72dfca
[ 0.9983112812042236, 0.21853826940059662, 0.00017240691522601992, 0.005003203172236681, 0.3877662122249603 ]
{ "id": 1, "code_window": [ "}\n", "\n", "const cjs = [\n", " {\n", " input: \"modules/index.js\",\n", " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\" },\n", " external: isBareModuleId,\n", " plugins: [\n", " babel({ exclude: /node_modules/ }),\n", " replace({ \"process.env.NODE_ENV\": JSON.stringify(\"development\") })\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\", esModule: false },\n" ], "file_path": "packages/react-router-dom/rollup.config.js", "type": "replace", "edit_start_line_idx": 18 }
import React from "react"; import { isValidElementType } from "react-is"; import PropTypes from "prop-types"; import invariant from "tiny-invariant"; import warning from "tiny-warning"; import RouterContext from "./RouterContext"; import matchPath from "./matchPath"; function isEmptyChildren(children) { return React.Children.count(children) === 0; } /** * The public API for matching a single path and rendering. */ class Route extends React.Component { render() { return ( <RouterContext.Consumer> {context => { invariant(context, "You should not use <Route> outside a <Router>"); const location = this.props.location || context.location; const match = this.props.computedMatch ? this.props.computedMatch // <Switch> already computed the match for us : this.props.path ? matchPath(location.pathname, this.props) : context.match; const props = { ...context, location, match }; let { children, component, render } = this.props; // Preact uses an empty array as children by // default, so use null if that's the case. if (Array.isArray(children) && children.length === 0) { children = null; } if (typeof children === "function") { children = children(props); if (children === undefined) { if (__DEV__) { const { path } = this.props; warning( false, "You returned `undefined` from the `children` function of " + `<Route${path ? ` path="${path}"` : ""}>, but you ` + "should have returned a React element or `null`" ); } children = null; } } return ( <RouterContext.Provider value={props}> {children && !isEmptyChildren(children) ? children : props.match ? component ? React.createElement(component, props) : render ? render(props) : null : null} </RouterContext.Provider> ); }} </RouterContext.Consumer> ); } } if (__DEV__) { Route.propTypes = { children: PropTypes.oneOfType([PropTypes.func, PropTypes.node]), component: (props, propName) => { if (props[propName] && !isValidElementType(props[propName])) { return new Error( `Invalid prop 'component' supplied to 'Route': the prop is not a valid React component` ); } }, exact: PropTypes.bool, location: PropTypes.object, path: PropTypes.oneOfType([ PropTypes.string, PropTypes.arrayOf(PropTypes.string) ]), render: PropTypes.func, sensitive: PropTypes.bool, strict: PropTypes.bool }; Route.prototype.componentDidMount = function() { warning( !( this.props.children && !isEmptyChildren(this.props.children) && this.props.component ), "You should not use <Route component> and <Route children> in the same route; <Route component> will be ignored" ); warning( !( this.props.children && !isEmptyChildren(this.props.children) && this.props.render ), "You should not use <Route render> and <Route children> in the same route; <Route render> will be ignored" ); warning( !(this.props.component && this.props.render), "You should not use <Route component> and <Route render> in the same route; <Route render> will be ignored" ); }; Route.prototype.componentDidUpdate = function(prevProps) { warning( !(this.props.location && !prevProps.location), '<Route> elements should not change from uncontrolled to controlled (or vice versa). You initially used no "location" prop and then provided one on a subsequent render.' ); warning( !(!this.props.location && prevProps.location), '<Route> elements should not change from controlled to uncontrolled (or vice versa). You provided a "location" prop initially but omitted it on a subsequent render.' ); }; } export default Route;
packages/react-router/modules/Route.js
0
https://github.com/remix-run/react-router/commit/caa9950c752386ab1b4db71e322b452d2f72dfca
[ 0.00017616097466088831, 0.0001727117778500542, 0.00016596310888417065, 0.0001729131181491539, 0.0000026727871045295615 ]
{ "id": 1, "code_window": [ "}\n", "\n", "const cjs = [\n", " {\n", " input: \"modules/index.js\",\n", " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\" },\n", " external: isBareModuleId,\n", " plugins: [\n", " babel({ exclude: /node_modules/ }),\n", " replace({ \"process.env.NODE_ENV\": JSON.stringify(\"development\") })\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\", esModule: false },\n" ], "file_path": "packages/react-router-dom/rollup.config.js", "type": "replace", "edit_start_line_idx": 18 }
import React from "react"; import { __RouterContext as RouterContext } from "react-router"; import { createLocation } from "history"; import PropTypes from "prop-types"; import invariant from "tiny-invariant"; function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } /** * The public API for rendering a history-aware <a>. */ class Link extends React.Component { handleClick(event, history) { try { if (this.props.onClick) this.props.onClick(event); } catch (ex) { event.preventDefault(); throw ex; } if ( !event.defaultPrevented && // onClick prevented default event.button === 0 && // ignore everything but left clicks (!this.props.target || this.props.target === "_self") && // let browser handle "target=_blank" etc. !isModifiedEvent(event) // ignore clicks with modifier keys ) { event.preventDefault(); const method = this.props.replace ? history.replace : history.push; method(this.props.to); } } render() { const { innerRef, replace, to, ...rest } = this.props; // eslint-disable-line no-unused-vars return ( <RouterContext.Consumer> {context => { invariant(context, "You should not use <Link> outside a <Router>"); const location = typeof to === "string" ? createLocation(to, null, null, context.location) : to; const href = location ? context.history.createHref(location) : ""; return ( <a {...rest} onClick={event => this.handleClick(event, context.history)} href={href} ref={innerRef} /> ); }} </RouterContext.Consumer> ); } } if (__DEV__) { const toType = PropTypes.oneOfType([PropTypes.string, PropTypes.object]); const innerRefType = PropTypes.oneOfType([ PropTypes.string, PropTypes.func, PropTypes.shape({ current: PropTypes.any }) ]); Link.propTypes = { innerRef: innerRefType, onClick: PropTypes.func, replace: PropTypes.bool, target: PropTypes.string, to: toType.isRequired }; } export default Link;
packages/react-router-dom/modules/Link.js
0
https://github.com/remix-run/react-router/commit/caa9950c752386ab1b4db71e322b452d2f72dfca
[ 0.0013921010540798306, 0.0003074918349739164, 0.0001679056731518358, 0.0001721767766866833, 0.0003834724484477192 ]
{ "id": 1, "code_window": [ "}\n", "\n", "const cjs = [\n", " {\n", " input: \"modules/index.js\",\n", " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\" },\n", " external: isBareModuleId,\n", " plugins: [\n", " babel({ exclude: /node_modules/ }),\n", " replace({ \"process.env.NODE_ENV\": JSON.stringify(\"development\") })\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\", esModule: false },\n" ], "file_path": "packages/react-router-dom/rollup.config.js", "type": "replace", "edit_start_line_idx": 18 }
import React from "react"; import { BrowserRouter as Router, Route, Link } from "react-router-dom"; function CustomLinkExample() { return ( <Router> <div> <OldSchoolMenuLink activeOnlyWhenExact={true} to="/" label="Home" /> <OldSchoolMenuLink to="/about" label="About" /> <hr /> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> </div> </Router> ); } function OldSchoolMenuLink({ label, to, activeOnlyWhenExact }) { return ( <Route path={to} exact={activeOnlyWhenExact} children={({ match }) => ( <div className={match ? "active" : ""}> {match ? "> " : ""} <Link to={to}>{label}</Link> </div> )} /> ); } function Home() { return ( <div> <h2>Home</h2> </div> ); } function About() { return ( <div> <h2>About</h2> </div> ); } export default CustomLinkExample;
website/modules/examples/CustomLink.js
0
https://github.com/remix-run/react-router/commit/caa9950c752386ab1b4db71e322b452d2f72dfca
[ 0.00017499979003332555, 0.00017225810734089464, 0.00016670140030328184, 0.0001734561228659004, 0.000002910893272201065 ]
{ "id": 2, "code_window": [ "}\n", "\n", "const cjs = [\n", " {\n", " input: \"modules/index.js\",\n", " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\" },\n", " external: isBareModuleId,\n", " plugins: [\n", " babel({ exclude: /node_modules/ }),\n", " replace({\n", " \"process.env.NODE_ENV\": JSON.stringify(\"development\"),\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\", esModule: false },\n" ], "file_path": "packages/react-router/rollup.config.js", "type": "replace", "edit_start_line_idx": 18 }
const babel = require("rollup-plugin-babel"); const replace = require("rollup-plugin-replace"); const commonjs = require("rollup-plugin-commonjs"); const nodeResolve = require("rollup-plugin-node-resolve"); const { sizeSnapshot } = require("rollup-plugin-size-snapshot"); const { uglify } = require("rollup-plugin-uglify"); const path = require("path"); const pkg = require("./package.json"); function isBareModuleId(id) { return ( !id.startsWith(".") && !id.includes(path.join(process.cwd(), "modules")) ); } const cjs = [ { input: "modules/index.js", output: { file: `cjs/${pkg.name}.js`, format: "cjs" }, external: isBareModuleId, plugins: [ babel({ exclude: /node_modules/ }), replace({ "process.env.NODE_ENV": JSON.stringify("development") }) ] }, { input: "modules/index.js", output: { file: `cjs/${pkg.name}.min.js`, format: "cjs" }, external: isBareModuleId, plugins: [ babel({ exclude: /node_modules/ }), replace({ "process.env.NODE_ENV": JSON.stringify("production") }), uglify() ] } ]; const esm = [ { input: "modules/index.js", output: { file: `esm/${pkg.name}.js`, format: "esm" }, external: isBareModuleId, plugins: [ babel({ exclude: /node_modules/, runtimeHelpers: true, plugins: [["@babel/transform-runtime", { useESModules: true }]] }), sizeSnapshot() ] } ]; const globals = { react: "React" }; const umd = [ { input: "modules/index.js", output: { file: `umd/${pkg.name}.js`, format: "umd", name: "ReactRouterDOM", globals }, external: Object.keys(globals), plugins: [ babel({ exclude: /node_modules/, runtimeHelpers: true, plugins: [["@babel/transform-runtime", { useESModules: true }]] }), nodeResolve(), commonjs({ include: /node_modules/, namedExports: { "../react-router/node_modules/react-is/index.js": [ "isValidElementType" ] } }), replace({ "process.env.NODE_ENV": JSON.stringify("development") }), sizeSnapshot() ] }, { input: "modules/index.js", output: { file: `umd/${pkg.name}.min.js`, format: "umd", name: "ReactRouterDOM", globals }, external: Object.keys(globals), plugins: [ babel({ exclude: /node_modules/, runtimeHelpers: true, plugins: [["@babel/transform-runtime", { useESModules: true }]] }), nodeResolve(), commonjs({ include: /node_modules/, namedExports: { "../react-router/node_modules/react-is/index.js": [ "isValidElementType" ] } }), replace({ "process.env.NODE_ENV": JSON.stringify("production") }), sizeSnapshot(), uglify() ] } ]; let config; switch (process.env.BUILD_ENV) { case "cjs": config = cjs; break; case "esm": config = esm; break; case "umd": config = umd; break; default: config = cjs.concat(esm).concat(umd); } module.exports = config;
packages/react-router-dom/rollup.config.js
1
https://github.com/remix-run/react-router/commit/caa9950c752386ab1b4db71e322b452d2f72dfca
[ 0.9983093738555908, 0.2522953152656555, 0.00016503002552781254, 0.004807271063327789, 0.4054485261440277 ]
{ "id": 2, "code_window": [ "}\n", "\n", "const cjs = [\n", " {\n", " input: \"modules/index.js\",\n", " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\" },\n", " external: isBareModuleId,\n", " plugins: [\n", " babel({ exclude: /node_modules/ }),\n", " replace({\n", " \"process.env.NODE_ENV\": JSON.stringify(\"development\"),\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\", esModule: false },\n" ], "file_path": "packages/react-router/rollup.config.js", "type": "replace", "edit_start_line_idx": 18 }
import React from "react"; import ReactDOM from "react-dom"; import { createMemoryHistory as createHistory } from "history"; import { Route, Router, __RouterContext as RouterContext } from "react-router"; import renderStrict from "./utils/renderStrict"; describe("A <Route>", () => { const node = document.createElement("div"); afterEach(() => { ReactDOM.unmountComponentAtNode(node); }); describe("context", () => { let context; function ContextChecker() { return ( <RouterContext.Consumer> {value => { context = value; return null; }} </RouterContext.Consumer> ); } afterEach(() => { context = undefined; }); it("has a `history` property", () => { const history = createHistory(); renderStrict( <Router history={history}> <Route component={ContextChecker} /> </Router>, node ); expect(context.history).toBe(history); }); it("has a `location` property", () => { const history = createHistory(); renderStrict( <Router history={history}> <Route component={ContextChecker} /> </Router>, node ); expect(context.location).toBe(history.location); }); it("has a `match` property", () => { const history = createHistory({ initialEntries: ["/"] }); renderStrict( <Router history={history}> <Route component={ContextChecker} /> </Router>, node ); expect(context.match).toMatchObject({ path: "/", url: "/", params: {}, isExact: true }); }); }); });
packages/react-router/modules/__tests__/Route-context-test.js
0
https://github.com/remix-run/react-router/commit/caa9950c752386ab1b4db71e322b452d2f72dfca
[ 0.00017687732179183513, 0.00017288129311054945, 0.00016773764218669385, 0.00017268903320655227, 0.000002441375954731484 ]
{ "id": 2, "code_window": [ "}\n", "\n", "const cjs = [\n", " {\n", " input: \"modules/index.js\",\n", " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\" },\n", " external: isBareModuleId,\n", " plugins: [\n", " babel({ exclude: /node_modules/ }),\n", " replace({\n", " \"process.env.NODE_ENV\": JSON.stringify(\"development\"),\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\", esModule: false },\n" ], "file_path": "packages/react-router/rollup.config.js", "type": "replace", "edit_start_line_idx": 18 }
import React from "react"; import { BrowserRouter as Router, Route, Link } from "react-router-dom"; function ParamsExample() { return ( <Router> <div> <h2>Accounts</h2> <ul> <li> <Link to="/netflix">Netflix</Link> </li> <li> <Link to="/zillow-group">Zillow Group</Link> </li> <li> <Link to="/yahoo">Yahoo</Link> </li> <li> <Link to="/modus-create">Modus Create</Link> </li> </ul> <Route path="/:id" component={Child} /> {/* It's possible to use regular expressions to control what param values should be matched. * "/order/asc" - matched * "/order/desc" - matched * "/order/foo" - not matched */} <Route path="/order/:direction(asc|desc)" component={ComponentWithRegex} /> </div> </Router> ); } function Child({ match }) { return ( <div> <h3>ID: {match.params.id}</h3> </div> ); } function ComponentWithRegex({ match }) { return ( <div> <h3>Only asc/desc are allowed: {match.params.direction}</h3> </div> ); } export default ParamsExample;
website/modules/examples/Params.js
0
https://github.com/remix-run/react-router/commit/caa9950c752386ab1b4db71e322b452d2f72dfca
[ 0.00017632331582717597, 0.00017481419490650296, 0.00017199905414599925, 0.00017523576389066875, 0.0000015043560779304244 ]
{ "id": 2, "code_window": [ "}\n", "\n", "const cjs = [\n", " {\n", " input: \"modules/index.js\",\n", " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\" },\n", " external: isBareModuleId,\n", " plugins: [\n", " babel({ exclude: /node_modules/ }),\n", " replace({\n", " \"process.env.NODE_ENV\": JSON.stringify(\"development\"),\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " output: { file: `cjs/${pkg.name}.js`, format: \"cjs\", esModule: false },\n" ], "file_path": "packages/react-router/rollup.config.js", "type": "replace", "edit_start_line_idx": 18 }
let mappedModule; switch (process.env.TEST_ENV) { case "cjs": mappedModule = "<rootDir>/cjs/react-router.js"; break; case "umd": mappedModule = "<rootDir>/umd/react-router.js"; break; default: mappedModule = "<rootDir>/modules/index.js"; } module.exports = { testRunner: "jest-circus/runner", restoreMocks: true, globals: { __DEV__: true }, moduleNameMapper: { "^react-router$": mappedModule }, modulePaths: ["<rootDir>/node_modules"], setupFiles: ["raf/polyfill"], testMatch: ["**/__tests__/**/*-test.js"], testURL: "http://localhost/" };
packages/react-router/jest.config.js
0
https://github.com/remix-run/react-router/commit/caa9950c752386ab1b4db71e322b452d2f72dfca
[ 0.00033978602732531726, 0.00022280809935182333, 0.00016373487596865743, 0.00016490340931341052, 0.00008271725528175011 ]
{ "id": 0, "code_window": [ " ctrl.isPanelVisible = function () {\n", " var position = panelContainer[0].getBoundingClientRect();\n", " return (0 < position.top) && (position.top < window.innerHeight);\n", " };\n", "\n", " const refreshOnScroll = _.debounce(function () {\n", " if (ctrl.skippedLastRefresh) {\n", " ctrl.refresh();\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const refreshOnScroll = function () {\n" ], "file_path": "public/app/features/panel/panel_directive.ts", "type": "replace", "edit_start_line_idx": 182 }
///<reference path="../../headers/common.d.ts" /> import angular from 'angular'; import $ from 'jquery'; import _ from 'lodash'; import Drop from 'tether-drop'; var module = angular.module('grafana.directives'); var panelTemplate = ` <div class="panel-container"> <div class="panel-header"> <span class="panel-info-corner"> <i class="fa"></i> <span class="panel-info-corner-inner"></span> </span> <span class="panel-loading" ng-show="ctrl.loading"> <i class="fa fa-spinner fa-spin"></i> </span> <div class="panel-title-container drag-handle" panel-menu></div> </div> <div class="panel-content"> <ng-transclude></ng-transclude> </div> <panel-resizer></panel-resizer> </div> <div class="panel-full-edit" ng-if="ctrl.editMode"> <div class="tabbed-view tabbed-view--panel-edit"> <div class="tabbed-view-header"> <h2 class="tabbed-view-title"> {{ctrl.pluginName}} </h2> <ul class="gf-tabs"> <li class="gf-tabs-item" ng-repeat="tab in ::ctrl.editorTabs"> <a class="gf-tabs-link" ng-click="ctrl.changeTab($index)" ng-class="{active: ctrl.editorTabIndex === $index}"> {{::tab.title}} </a> </li> </ul> <button class="tabbed-view-close-btn" ng-click="ctrl.exitFullscreen();"> <i class="fa fa-remove"></i> </button> </div> <div class="tabbed-view-body"> <div ng-repeat="tab in ctrl.editorTabs" ng-if="ctrl.editorTabIndex === $index"> <panel-editor-tab editor-tab="tab" ctrl="ctrl" index="$index"></panel-editor-tab> </div> </div> </div> </div> `; module.directive('grafanaPanel', function($rootScope, $document) { return { restrict: 'E', template: panelTemplate, transclude: true, scope: { ctrl: "=" }, link: function(scope, elem) { var panelContainer = elem.find('.panel-container'); var cornerInfoElem = elem.find('.panel-info-corner'); var ctrl = scope.ctrl; var infoDrop; // the reason for handling these classes this way is for performance // limit the watchers on panels etc var transparentLastState = false; var lastHasAlertRule = false; var lastAlertState; var hasAlertRule; var lastHeight = 0; function mouseEnter() { panelContainer.toggleClass('panel-hover-highlight', true); ctrl.dashboard.setPanelFocus(ctrl.panel.id); } function mouseLeave() { panelContainer.toggleClass('panel-hover-highlight', false); ctrl.dashboard.setPanelFocus(0); } // set initial height if (!ctrl.containerHeight) { ctrl.calculatePanelHeight(); panelContainer.css({minHeight: ctrl.containerHeight}); lastHeight = ctrl.containerHeight; } // set initial transparency if (ctrl.panel.transparent) { transparentLastState = true; panelContainer.addClass('panel-transparent', true); } ctrl.events.on('render', () => { if (lastHeight !== ctrl.containerHeight) { panelContainer.css({minHeight: ctrl.containerHeight}); lastHeight = ctrl.containerHeight; } if (transparentLastState !== ctrl.panel.transparent) { panelContainer.toggleClass('panel-transparent', ctrl.panel.transparent === true); transparentLastState = ctrl.panel.transparent; } hasAlertRule = ctrl.panel.alert !== undefined; if (lastHasAlertRule !== hasAlertRule) { panelContainer.toggleClass('panel-has-alert', hasAlertRule); lastHasAlertRule = hasAlertRule; } if (ctrl.alertState) { if (lastAlertState) { panelContainer.removeClass('panel-alert-state--' + lastAlertState); } if (ctrl.alertState.state === 'ok' || ctrl.alertState.state === 'alerting') { panelContainer.addClass('panel-alert-state--' + ctrl.alertState.state); } lastAlertState = ctrl.alertState.state; } else if (lastAlertState) { panelContainer.removeClass('panel-alert-state--' + lastAlertState); lastAlertState = null; } }); var lastFullscreen; $rootScope.onAppEvent('panel-change-view', function(evt, payload) { if (lastFullscreen !== ctrl.fullscreen) { elem.toggleClass('panel-fullscreen', ctrl.fullscreen ? true : false); lastFullscreen = ctrl.fullscreen; } }, scope); function updatePanelCornerInfo() { var cornerMode = ctrl.getInfoMode(); cornerInfoElem[0].className = 'panel-info-corner panel-info-corner--' + cornerMode; if (cornerMode) { if (infoDrop) { infoDrop.destroy(); } infoDrop = new Drop({ target: cornerInfoElem[0], content: function() { return ctrl.getInfoContent({mode: 'tooltip'}); }, position: 'top center', classes: ctrl.error ? 'drop-error' : 'drop-help', openOn: 'hover', hoverOpenDelay: 100, }); } } scope.$watchGroup(['ctrl.error', 'ctrl.panel.description'], updatePanelCornerInfo); scope.$watchCollection('ctrl.panel.links', updatePanelCornerInfo); cornerInfoElem.on('click', function() { infoDrop.close(); scope.$apply(ctrl.openInspector.bind(ctrl)); }); elem.on('mouseenter', mouseEnter); elem.on('mouseleave', mouseLeave); ctrl.isPanelVisible = function () { var position = panelContainer[0].getBoundingClientRect(); return (0 < position.top) && (position.top < window.innerHeight); }; const refreshOnScroll = _.debounce(function () { if (ctrl.skippedLastRefresh) { ctrl.refresh(); } }, 250); $document.on('scroll', refreshOnScroll); scope.$on('$destroy', function() { elem.off(); cornerInfoElem.off(); $document.off('scroll', refreshOnScroll); if (infoDrop) { infoDrop.destroy(); } }); } }; }); module.directive('panelResizer', function($rootScope) { return { restrict: 'E', template: '<span class="resize-panel-handle icon-gf icon-gf-grabber"></span>', link: function(scope, elem) { var resizing = false; var lastPanel; var ctrl = scope.ctrl; var handleOffset; var originalHeight; var originalWidth; var maxWidth; function dragStartHandler(e) { e.preventDefault(); resizing = true; handleOffset = $(e.target).offset(); originalHeight = parseInt(ctrl.row.height); originalWidth = ctrl.panel.span; maxWidth = $(document).width(); lastPanel = ctrl.row.panels[ctrl.row.panels.length - 1]; $('body').on('mousemove', moveHandler); $('body').on('mouseup', dragEndHandler); } function moveHandler(e) { ctrl.row.height = Math.round(originalHeight + (e.pageY - handleOffset.top)); ctrl.panel.span = originalWidth + (((e.pageX - handleOffset.left) / maxWidth) * 12); ctrl.panel.span = Math.min(Math.max(ctrl.panel.span, 1), 12); ctrl.row.updateRowSpan(); var rowSpan = ctrl.row.span; // auto adjust other panels if (Math.floor(rowSpan) < 14) { // last panel should not push row down if (lastPanel === ctrl.panel && rowSpan > 12) { lastPanel.span -= rowSpan - 12; } else if (lastPanel !== ctrl.panel) { // reduce width of last panel so total in row is 12 lastPanel.span = lastPanel.span - (rowSpan - 12); lastPanel.span = Math.min(Math.max(lastPanel.span, 1), 12); } } ctrl.row.panelSpanChanged(true); scope.$apply(function() { ctrl.render(); }); } function dragEndHandler() { ctrl.panel.span = Math.round(ctrl.panel.span); if (lastPanel) { lastPanel.span = Math.round(lastPanel.span); } // first digest to propagate panel width change // then render $rootScope.$apply(function() { ctrl.row.panelSpanChanged(); setTimeout(function() { $rootScope.$broadcast('render'); }); }); $('body').off('mousemove', moveHandler); $('body').off('mouseup', dragEndHandler); } elem.on('mousedown', dragStartHandler); var unbind = scope.$on("$destroy", function() { elem.off('mousedown', dragStartHandler); unbind(); }); } }; }); module.directive('panelHelpCorner', function($rootScope) { return { restrict: 'E', template: ` <span class="alert-error panel-error small pointer" ng-if="ctrl.error" ng-click="ctrl.openInspector()"> <span data-placement="top" bs-tooltip="ctrl.error"> <i class="fa fa-exclamation"></i><span class="panel-error-arrow"></span> </span> </span> `, link: function(scope, elem) { } }; });
public/app/features/panel/panel_directive.ts
1
https://github.com/grafana/grafana/commit/7f8a3a0a2db142b7b6a89e56af7e9600dd9d0537
[ 0.9982642531394958, 0.09929554909467697, 0.00016521125508006662, 0.0007441962952725589, 0.2941768765449524 ]
{ "id": 0, "code_window": [ " ctrl.isPanelVisible = function () {\n", " var position = panelContainer[0].getBoundingClientRect();\n", " return (0 < position.top) && (position.top < window.innerHeight);\n", " };\n", "\n", " const refreshOnScroll = _.debounce(function () {\n", " if (ctrl.skippedLastRefresh) {\n", " ctrl.refresh();\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const refreshOnScroll = function () {\n" ], "file_path": "public/app/features/panel/panel_directive.ts", "type": "replace", "edit_start_line_idx": 182 }
3.1.0
docs/VERSION
0
https://github.com/grafana/grafana/commit/7f8a3a0a2db142b7b6a89e56af7e9600dd9d0537
[ 0.0001691558863967657, 0.0001691558863967657, 0.0001691558863967657, 0.0001691558863967657, 0 ]
{ "id": 0, "code_window": [ " ctrl.isPanelVisible = function () {\n", " var position = panelContainer[0].getBoundingClientRect();\n", " return (0 < position.top) && (position.top < window.innerHeight);\n", " };\n", "\n", " const refreshOnScroll = _.debounce(function () {\n", " if (ctrl.skippedLastRefresh) {\n", " ctrl.refresh();\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const refreshOnScroll = function () {\n" ], "file_path": "public/app/features/panel/panel_directive.ts", "type": "replace", "edit_start_line_idx": 182 }
max(strings)
vendor/github.com/jmespath/go-jmespath/fuzz/corpus/expr-115
0
https://github.com/grafana/grafana/commit/7f8a3a0a2db142b7b6a89e56af7e9600dd9d0537
[ 0.0001658270921325311, 0.0001658270921325311, 0.0001658270921325311, 0.0001658270921325311, 0 ]
{ "id": 0, "code_window": [ " ctrl.isPanelVisible = function () {\n", " var position = panelContainer[0].getBoundingClientRect();\n", " return (0 < position.top) && (position.top < window.innerHeight);\n", " };\n", "\n", " const refreshOnScroll = _.debounce(function () {\n", " if (ctrl.skippedLastRefresh) {\n", " ctrl.refresh();\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const refreshOnScroll = function () {\n" ], "file_path": "public/app/features/panel/panel_directive.ts", "type": "replace", "edit_start_line_idx": 182 }
// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package atom provides integer codes (also known as atoms) for a fixed set of // frequently occurring HTML strings: tag names and attribute keys such as "p" // and "id". // // Sharing an atom's name between all elements with the same tag can result in // fewer string allocations when tokenizing and parsing HTML. Integer // comparisons are also generally faster than string comparisons. // // The value of an atom's particular code is not guaranteed to stay the same // between versions of this package. Neither is any ordering guaranteed: // whether atom.H1 < atom.H2 may also change. The codes are not guaranteed to // be dense. The only guarantees are that e.g. looking up "div" will yield // atom.Div, calling atom.Div.String will return "div", and atom.Div != 0. package atom // import "golang.org/x/net/html/atom" // Atom is an integer code for a string. The zero value maps to "". type Atom uint32 // String returns the atom's name. func (a Atom) String() string { start := uint32(a >> 8) n := uint32(a & 0xff) if start+n > uint32(len(atomText)) { return "" } return atomText[start : start+n] } func (a Atom) string() string { return atomText[a>>8 : a>>8+a&0xff] } // fnv computes the FNV hash with an arbitrary starting value h. func fnv(h uint32, s []byte) uint32 { for i := range s { h ^= uint32(s[i]) h *= 16777619 } return h } func match(s string, t []byte) bool { for i, c := range t { if s[i] != c { return false } } return true } // Lookup returns the atom whose name is s. It returns zero if there is no // such atom. The lookup is case sensitive. func Lookup(s []byte) Atom { if len(s) == 0 || len(s) > maxAtomLen { return 0 } h := fnv(hash0, s) if a := table[h&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) { return a } if a := table[(h>>16)&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) { return a } return 0 } // String returns a string whose contents are equal to s. In that sense, it is // equivalent to string(s) but may be more efficient. func String(s []byte) string { if a := Lookup(s); a != 0 { return a.String() } return string(s) }
vendor/golang.org/x/net/html/atom/atom.go
0
https://github.com/grafana/grafana/commit/7f8a3a0a2db142b7b6a89e56af7e9600dd9d0537
[ 0.0011229400988668203, 0.00029025442199781537, 0.00015732595056761056, 0.00017396784096490592, 0.0003147778334096074 ]
{ "id": 1, "code_window": [ " if (ctrl.skippedLastRefresh) {\n", " ctrl.refresh();\n", " }\n", " }, 250);\n", "\n", " $document.on('scroll', refreshOnScroll);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " };\n" ], "file_path": "public/app/features/panel/panel_directive.ts", "type": "replace", "edit_start_line_idx": 186 }
///<reference path="../../headers/common.d.ts" /> import angular from 'angular'; import $ from 'jquery'; import _ from 'lodash'; import Drop from 'tether-drop'; var module = angular.module('grafana.directives'); var panelTemplate = ` <div class="panel-container"> <div class="panel-header"> <span class="panel-info-corner"> <i class="fa"></i> <span class="panel-info-corner-inner"></span> </span> <span class="panel-loading" ng-show="ctrl.loading"> <i class="fa fa-spinner fa-spin"></i> </span> <div class="panel-title-container drag-handle" panel-menu></div> </div> <div class="panel-content"> <ng-transclude></ng-transclude> </div> <panel-resizer></panel-resizer> </div> <div class="panel-full-edit" ng-if="ctrl.editMode"> <div class="tabbed-view tabbed-view--panel-edit"> <div class="tabbed-view-header"> <h2 class="tabbed-view-title"> {{ctrl.pluginName}} </h2> <ul class="gf-tabs"> <li class="gf-tabs-item" ng-repeat="tab in ::ctrl.editorTabs"> <a class="gf-tabs-link" ng-click="ctrl.changeTab($index)" ng-class="{active: ctrl.editorTabIndex === $index}"> {{::tab.title}} </a> </li> </ul> <button class="tabbed-view-close-btn" ng-click="ctrl.exitFullscreen();"> <i class="fa fa-remove"></i> </button> </div> <div class="tabbed-view-body"> <div ng-repeat="tab in ctrl.editorTabs" ng-if="ctrl.editorTabIndex === $index"> <panel-editor-tab editor-tab="tab" ctrl="ctrl" index="$index"></panel-editor-tab> </div> </div> </div> </div> `; module.directive('grafanaPanel', function($rootScope, $document) { return { restrict: 'E', template: panelTemplate, transclude: true, scope: { ctrl: "=" }, link: function(scope, elem) { var panelContainer = elem.find('.panel-container'); var cornerInfoElem = elem.find('.panel-info-corner'); var ctrl = scope.ctrl; var infoDrop; // the reason for handling these classes this way is for performance // limit the watchers on panels etc var transparentLastState = false; var lastHasAlertRule = false; var lastAlertState; var hasAlertRule; var lastHeight = 0; function mouseEnter() { panelContainer.toggleClass('panel-hover-highlight', true); ctrl.dashboard.setPanelFocus(ctrl.panel.id); } function mouseLeave() { panelContainer.toggleClass('panel-hover-highlight', false); ctrl.dashboard.setPanelFocus(0); } // set initial height if (!ctrl.containerHeight) { ctrl.calculatePanelHeight(); panelContainer.css({minHeight: ctrl.containerHeight}); lastHeight = ctrl.containerHeight; } // set initial transparency if (ctrl.panel.transparent) { transparentLastState = true; panelContainer.addClass('panel-transparent', true); } ctrl.events.on('render', () => { if (lastHeight !== ctrl.containerHeight) { panelContainer.css({minHeight: ctrl.containerHeight}); lastHeight = ctrl.containerHeight; } if (transparentLastState !== ctrl.panel.transparent) { panelContainer.toggleClass('panel-transparent', ctrl.panel.transparent === true); transparentLastState = ctrl.panel.transparent; } hasAlertRule = ctrl.panel.alert !== undefined; if (lastHasAlertRule !== hasAlertRule) { panelContainer.toggleClass('panel-has-alert', hasAlertRule); lastHasAlertRule = hasAlertRule; } if (ctrl.alertState) { if (lastAlertState) { panelContainer.removeClass('panel-alert-state--' + lastAlertState); } if (ctrl.alertState.state === 'ok' || ctrl.alertState.state === 'alerting') { panelContainer.addClass('panel-alert-state--' + ctrl.alertState.state); } lastAlertState = ctrl.alertState.state; } else if (lastAlertState) { panelContainer.removeClass('panel-alert-state--' + lastAlertState); lastAlertState = null; } }); var lastFullscreen; $rootScope.onAppEvent('panel-change-view', function(evt, payload) { if (lastFullscreen !== ctrl.fullscreen) { elem.toggleClass('panel-fullscreen', ctrl.fullscreen ? true : false); lastFullscreen = ctrl.fullscreen; } }, scope); function updatePanelCornerInfo() { var cornerMode = ctrl.getInfoMode(); cornerInfoElem[0].className = 'panel-info-corner panel-info-corner--' + cornerMode; if (cornerMode) { if (infoDrop) { infoDrop.destroy(); } infoDrop = new Drop({ target: cornerInfoElem[0], content: function() { return ctrl.getInfoContent({mode: 'tooltip'}); }, position: 'top center', classes: ctrl.error ? 'drop-error' : 'drop-help', openOn: 'hover', hoverOpenDelay: 100, }); } } scope.$watchGroup(['ctrl.error', 'ctrl.panel.description'], updatePanelCornerInfo); scope.$watchCollection('ctrl.panel.links', updatePanelCornerInfo); cornerInfoElem.on('click', function() { infoDrop.close(); scope.$apply(ctrl.openInspector.bind(ctrl)); }); elem.on('mouseenter', mouseEnter); elem.on('mouseleave', mouseLeave); ctrl.isPanelVisible = function () { var position = panelContainer[0].getBoundingClientRect(); return (0 < position.top) && (position.top < window.innerHeight); }; const refreshOnScroll = _.debounce(function () { if (ctrl.skippedLastRefresh) { ctrl.refresh(); } }, 250); $document.on('scroll', refreshOnScroll); scope.$on('$destroy', function() { elem.off(); cornerInfoElem.off(); $document.off('scroll', refreshOnScroll); if (infoDrop) { infoDrop.destroy(); } }); } }; }); module.directive('panelResizer', function($rootScope) { return { restrict: 'E', template: '<span class="resize-panel-handle icon-gf icon-gf-grabber"></span>', link: function(scope, elem) { var resizing = false; var lastPanel; var ctrl = scope.ctrl; var handleOffset; var originalHeight; var originalWidth; var maxWidth; function dragStartHandler(e) { e.preventDefault(); resizing = true; handleOffset = $(e.target).offset(); originalHeight = parseInt(ctrl.row.height); originalWidth = ctrl.panel.span; maxWidth = $(document).width(); lastPanel = ctrl.row.panels[ctrl.row.panels.length - 1]; $('body').on('mousemove', moveHandler); $('body').on('mouseup', dragEndHandler); } function moveHandler(e) { ctrl.row.height = Math.round(originalHeight + (e.pageY - handleOffset.top)); ctrl.panel.span = originalWidth + (((e.pageX - handleOffset.left) / maxWidth) * 12); ctrl.panel.span = Math.min(Math.max(ctrl.panel.span, 1), 12); ctrl.row.updateRowSpan(); var rowSpan = ctrl.row.span; // auto adjust other panels if (Math.floor(rowSpan) < 14) { // last panel should not push row down if (lastPanel === ctrl.panel && rowSpan > 12) { lastPanel.span -= rowSpan - 12; } else if (lastPanel !== ctrl.panel) { // reduce width of last panel so total in row is 12 lastPanel.span = lastPanel.span - (rowSpan - 12); lastPanel.span = Math.min(Math.max(lastPanel.span, 1), 12); } } ctrl.row.panelSpanChanged(true); scope.$apply(function() { ctrl.render(); }); } function dragEndHandler() { ctrl.panel.span = Math.round(ctrl.panel.span); if (lastPanel) { lastPanel.span = Math.round(lastPanel.span); } // first digest to propagate panel width change // then render $rootScope.$apply(function() { ctrl.row.panelSpanChanged(); setTimeout(function() { $rootScope.$broadcast('render'); }); }); $('body').off('mousemove', moveHandler); $('body').off('mouseup', dragEndHandler); } elem.on('mousedown', dragStartHandler); var unbind = scope.$on("$destroy", function() { elem.off('mousedown', dragStartHandler); unbind(); }); } }; }); module.directive('panelHelpCorner', function($rootScope) { return { restrict: 'E', template: ` <span class="alert-error panel-error small pointer" ng-if="ctrl.error" ng-click="ctrl.openInspector()"> <span data-placement="top" bs-tooltip="ctrl.error"> <i class="fa fa-exclamation"></i><span class="panel-error-arrow"></span> </span> </span> `, link: function(scope, elem) { } }; });
public/app/features/panel/panel_directive.ts
1
https://github.com/grafana/grafana/commit/7f8a3a0a2db142b7b6a89e56af7e9600dd9d0537
[ 0.993854820728302, 0.034122973680496216, 0.00016515313473064452, 0.0008271690458059311, 0.1752522587776184 ]
{ "id": 1, "code_window": [ " if (ctrl.skippedLastRefresh) {\n", " ctrl.refresh();\n", " }\n", " }, 250);\n", "\n", " $document.on('scroll', refreshOnScroll);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " };\n" ], "file_path": "public/app/features/panel/panel_directive.ts", "type": "replace", "edit_start_line_idx": 186 }
define( [ "./core", "./data/var/dataPriv", "./deferred", "./callbacks" ], function( jQuery, dataPriv ) { "use strict"; jQuery.extend( { queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = dataPriv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // Clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // Not public - generate a queueHooks object, or return the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { empty: jQuery.Callbacks( "once memory" ).add( function() { dataPriv.remove( elem, [ type + "queue", key ] ); } ) } ); } } ); jQuery.fn.extend( { queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[ 0 ], type ); } return data === undefined ? this : this.each( function() { var queue = jQuery.queue( this, type, data ); // Ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { jQuery.dequeue( this, type ); } } ); }, dequeue: function( type ) { return this.each( function() { jQuery.dequeue( this, type ); } ); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } } ); return jQuery; } );
public/vendor/jquery/src/queue.js
0
https://github.com/grafana/grafana/commit/7f8a3a0a2db142b7b6a89e56af7e9600dd9d0537
[ 0.00017236682469956577, 0.0001697531552053988, 0.00016494446026626974, 0.00017012834723573178, 0.000002124716957041528 ]
{ "id": 1, "code_window": [ " if (ctrl.skippedLastRefresh) {\n", " ctrl.refresh();\n", " }\n", " }, 250);\n", "\n", " $document.on('scroll', refreshOnScroll);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " };\n" ], "file_path": "public/app/features/panel/panel_directive.ts", "type": "replace", "edit_start_line_idx": 186 }
///<reference path="../../../headers/common.d.ts" /> import _ from 'lodash'; import config from 'app/core/config'; import {PanelCtrl} from 'app/plugins/sdk'; import {impressions} from 'app/features/dashboard/impression_store'; class DashListCtrl extends PanelCtrl { static templateUrl = 'module.html'; groups: any[]; modes: any[]; panelDefaults = { query: '', limit: 10, tags: [], recent: false, search: false, starred: true, headings: true, }; /** @ngInject */ constructor($scope, $injector, private backendSrv) { super($scope, $injector); _.defaults(this.panel, this.panelDefaults); if (this.panel.tag) { this.panel.tags = [this.panel.tag]; delete this.panel.tag; } this.events.on('refresh', this.onRefresh.bind(this)); this.events.on('init-edit-mode', this.onInitEditMode.bind(this)); this.groups = [ {list: [], show: false, header: "Starred dashboards",}, {list: [], show: false, header: "Recently viewed dashboards"}, {list: [], show: false, header: "Search"}, ]; // update capability if (this.panel.mode) { if (this.panel.mode === 'starred') { this.panel.starred = true; this.panel.headings = false; } if (this.panel.mode === 'recently viewed') { this.panel.recent = true; this.panel.starred = false; this.panel.headings = false; } if (this.panel.mode === 'search') { this.panel.search = true; this.panel.starred = false; this.panel.headings = false; } delete this.panel.mode; } } onInitEditMode() { this.editorTabIndex = 1; this.modes = ['starred', 'search', 'recently viewed']; this.addEditorTab('Options', 'public/app/plugins/panel/dashlist/editor.html'); } onRefresh() { var promises = []; promises.push(this.getRecentDashboards()); promises.push(this.getStarred()); promises.push(this.getSearch()); return Promise.all(promises) .then(this.renderingCompleted.bind(this)); } getSearch() { this.groups[2].show = this.panel.search; if (!this.panel.search) { return Promise.resolve(); } var params = { limit: this.panel.limit, query: this.panel.query, tag: this.panel.tags, }; return this.backendSrv.search(params).then(result => { this.groups[2].list = result; }); } getStarred() { this.groups[0].show = this.panel.starred; if (!this.panel.starred) { return Promise.resolve(); } var params = {limit: this.panel.limit, starred: "true"}; return this.backendSrv.search(params).then(result => { this.groups[0].list = result; }); } getRecentDashboards() { this.groups[1].show = this.panel.recent; if (!this.panel.recent) { return Promise.resolve(); } var dashIds = _.take(impressions.getDashboardOpened(), this.panel.limit); return this.backendSrv.search({dashboardIds: dashIds, limit: this.panel.limit}).then(result => { this.groups[1].list = dashIds.map(orderId => { return _.find(result, dashboard => { return dashboard.id === orderId; }); }).filter(el => { return el !== undefined; }); }); } } export {DashListCtrl, DashListCtrl as PanelCtrl}
public/app/plugins/panel/dashlist/module.ts
0
https://github.com/grafana/grafana/commit/7f8a3a0a2db142b7b6a89e56af7e9600dd9d0537
[ 0.0009218002669513226, 0.00022648301091976464, 0.00016410484386142343, 0.00016815689741633832, 0.00020074192434549332 ]
{ "id": 1, "code_window": [ " if (ctrl.skippedLastRefresh) {\n", " ctrl.refresh();\n", " }\n", " }, 250);\n", "\n", " $document.on('scroll', refreshOnScroll);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " };\n" ], "file_path": "public/app/features/panel/panel_directive.ts", "type": "replace", "edit_start_line_idx": 186 }
package alerting import ( "strconv" "strings" "time" "github.com/grafana/grafana/pkg/log" "github.com/grafana/grafana/pkg/metrics" "github.com/grafana/grafana/pkg/models" ) type DefaultEvalHandler struct { log log.Logger alertJobTimeout time.Duration } func NewEvalHandler() *DefaultEvalHandler { return &DefaultEvalHandler{ log: log.New("alerting.evalHandler"), alertJobTimeout: time.Second * 5, } } func (e *DefaultEvalHandler) Eval(context *EvalContext) { firing := true noDataFound := true conditionEvals := "" for i := 0; i < len(context.Rule.Conditions); i++ { condition := context.Rule.Conditions[i] cr, err := condition.Eval(context) if err != nil { context.Error = err } // break if condition could not be evaluated if context.Error != nil { break } // calculating Firing based on operator if cr.Operator == "or" { firing = firing || cr.Firing noDataFound = noDataFound || cr.NoDataFound } else { firing = firing && cr.Firing noDataFound = noDataFound && cr.NoDataFound } if i > 0 { conditionEvals = "[" + conditionEvals + " " + strings.ToUpper(cr.Operator) + " " + strconv.FormatBool(cr.Firing) + "]" } else { conditionEvals = strconv.FormatBool(firing) } context.EvalMatches = append(context.EvalMatches, cr.EvalMatches...) } context.ConditionEvals = conditionEvals + " = " + strconv.FormatBool(firing) context.Firing = firing context.NoDataFound = noDataFound context.EndTime = time.Now() context.Rule.State = e.getNewState(context) elapsedTime := context.EndTime.Sub(context.StartTime) / time.Millisecond metrics.M_Alerting_Execution_Time.Update(elapsedTime) } // This should be move into evalContext once its been refactored. func (handler *DefaultEvalHandler) getNewState(evalContext *EvalContext) models.AlertStateType { if evalContext.Error != nil { handler.log.Error("Alert Rule Result Error", "ruleId", evalContext.Rule.Id, "name", evalContext.Rule.Name, "error", evalContext.Error, "changing state to", evalContext.Rule.ExecutionErrorState.ToAlertState()) if evalContext.Rule.ExecutionErrorState == models.ExecutionErrorKeepState { return evalContext.PrevAlertState } else { return evalContext.Rule.ExecutionErrorState.ToAlertState() } } else if evalContext.Firing { return models.AlertStateAlerting } else if evalContext.NoDataFound { handler.log.Info("Alert Rule returned no data", "ruleId", evalContext.Rule.Id, "name", evalContext.Rule.Name, "changing state to", evalContext.Rule.NoDataState.ToAlertState()) if evalContext.Rule.NoDataState == models.NoDataKeepState { return evalContext.PrevAlertState } else { return evalContext.Rule.NoDataState.ToAlertState() } } return models.AlertStateOK }
pkg/services/alerting/eval_handler.go
0
https://github.com/grafana/grafana/commit/7f8a3a0a2db142b7b6a89e56af7e9600dd9d0537
[ 0.0001754161057760939, 0.00017065316205844283, 0.00016422585758846253, 0.00017122294229920954, 0.0000028905833460157737 ]
{ "id": 2, "code_window": [ " }\n", "\n", " if (target.filters && target.filters.length > 0) {\n", " query.filters = angular.copy(target.filters);\n", " if(query.filters){\n", " for(var filter_key in query.filters){\n", " query.filters[filter_key].filter = templateSrv.replace(query.filters[filter_key].filter, options.scopedVars, 'pipe');\n", " }\n", " }\n", " } else {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (query.filters){\n", " for (var filter_key in query.filters) {\n" ], "file_path": "public/app/plugins/datasource/opentsdb/datasource.js", "type": "replace", "edit_start_line_idx": 413 }
///<reference path="../../headers/common.d.ts" /> import angular from 'angular'; import $ from 'jquery'; import _ from 'lodash'; import Drop from 'tether-drop'; var module = angular.module('grafana.directives'); var panelTemplate = ` <div class="panel-container"> <div class="panel-header"> <span class="panel-info-corner"> <i class="fa"></i> <span class="panel-info-corner-inner"></span> </span> <span class="panel-loading" ng-show="ctrl.loading"> <i class="fa fa-spinner fa-spin"></i> </span> <div class="panel-title-container drag-handle" panel-menu></div> </div> <div class="panel-content"> <ng-transclude></ng-transclude> </div> <panel-resizer></panel-resizer> </div> <div class="panel-full-edit" ng-if="ctrl.editMode"> <div class="tabbed-view tabbed-view--panel-edit"> <div class="tabbed-view-header"> <h2 class="tabbed-view-title"> {{ctrl.pluginName}} </h2> <ul class="gf-tabs"> <li class="gf-tabs-item" ng-repeat="tab in ::ctrl.editorTabs"> <a class="gf-tabs-link" ng-click="ctrl.changeTab($index)" ng-class="{active: ctrl.editorTabIndex === $index}"> {{::tab.title}} </a> </li> </ul> <button class="tabbed-view-close-btn" ng-click="ctrl.exitFullscreen();"> <i class="fa fa-remove"></i> </button> </div> <div class="tabbed-view-body"> <div ng-repeat="tab in ctrl.editorTabs" ng-if="ctrl.editorTabIndex === $index"> <panel-editor-tab editor-tab="tab" ctrl="ctrl" index="$index"></panel-editor-tab> </div> </div> </div> </div> `; module.directive('grafanaPanel', function($rootScope, $document) { return { restrict: 'E', template: panelTemplate, transclude: true, scope: { ctrl: "=" }, link: function(scope, elem) { var panelContainer = elem.find('.panel-container'); var cornerInfoElem = elem.find('.panel-info-corner'); var ctrl = scope.ctrl; var infoDrop; // the reason for handling these classes this way is for performance // limit the watchers on panels etc var transparentLastState = false; var lastHasAlertRule = false; var lastAlertState; var hasAlertRule; var lastHeight = 0; function mouseEnter() { panelContainer.toggleClass('panel-hover-highlight', true); ctrl.dashboard.setPanelFocus(ctrl.panel.id); } function mouseLeave() { panelContainer.toggleClass('panel-hover-highlight', false); ctrl.dashboard.setPanelFocus(0); } // set initial height if (!ctrl.containerHeight) { ctrl.calculatePanelHeight(); panelContainer.css({minHeight: ctrl.containerHeight}); lastHeight = ctrl.containerHeight; } // set initial transparency if (ctrl.panel.transparent) { transparentLastState = true; panelContainer.addClass('panel-transparent', true); } ctrl.events.on('render', () => { if (lastHeight !== ctrl.containerHeight) { panelContainer.css({minHeight: ctrl.containerHeight}); lastHeight = ctrl.containerHeight; } if (transparentLastState !== ctrl.panel.transparent) { panelContainer.toggleClass('panel-transparent', ctrl.panel.transparent === true); transparentLastState = ctrl.panel.transparent; } hasAlertRule = ctrl.panel.alert !== undefined; if (lastHasAlertRule !== hasAlertRule) { panelContainer.toggleClass('panel-has-alert', hasAlertRule); lastHasAlertRule = hasAlertRule; } if (ctrl.alertState) { if (lastAlertState) { panelContainer.removeClass('panel-alert-state--' + lastAlertState); } if (ctrl.alertState.state === 'ok' || ctrl.alertState.state === 'alerting') { panelContainer.addClass('panel-alert-state--' + ctrl.alertState.state); } lastAlertState = ctrl.alertState.state; } else if (lastAlertState) { panelContainer.removeClass('panel-alert-state--' + lastAlertState); lastAlertState = null; } }); var lastFullscreen; $rootScope.onAppEvent('panel-change-view', function(evt, payload) { if (lastFullscreen !== ctrl.fullscreen) { elem.toggleClass('panel-fullscreen', ctrl.fullscreen ? true : false); lastFullscreen = ctrl.fullscreen; } }, scope); function updatePanelCornerInfo() { var cornerMode = ctrl.getInfoMode(); cornerInfoElem[0].className = 'panel-info-corner panel-info-corner--' + cornerMode; if (cornerMode) { if (infoDrop) { infoDrop.destroy(); } infoDrop = new Drop({ target: cornerInfoElem[0], content: function() { return ctrl.getInfoContent({mode: 'tooltip'}); }, position: 'top center', classes: ctrl.error ? 'drop-error' : 'drop-help', openOn: 'hover', hoverOpenDelay: 100, }); } } scope.$watchGroup(['ctrl.error', 'ctrl.panel.description'], updatePanelCornerInfo); scope.$watchCollection('ctrl.panel.links', updatePanelCornerInfo); cornerInfoElem.on('click', function() { infoDrop.close(); scope.$apply(ctrl.openInspector.bind(ctrl)); }); elem.on('mouseenter', mouseEnter); elem.on('mouseleave', mouseLeave); ctrl.isPanelVisible = function () { var position = panelContainer[0].getBoundingClientRect(); return (0 < position.top) && (position.top < window.innerHeight); }; const refreshOnScroll = _.debounce(function () { if (ctrl.skippedLastRefresh) { ctrl.refresh(); } }, 250); $document.on('scroll', refreshOnScroll); scope.$on('$destroy', function() { elem.off(); cornerInfoElem.off(); $document.off('scroll', refreshOnScroll); if (infoDrop) { infoDrop.destroy(); } }); } }; }); module.directive('panelResizer', function($rootScope) { return { restrict: 'E', template: '<span class="resize-panel-handle icon-gf icon-gf-grabber"></span>', link: function(scope, elem) { var resizing = false; var lastPanel; var ctrl = scope.ctrl; var handleOffset; var originalHeight; var originalWidth; var maxWidth; function dragStartHandler(e) { e.preventDefault(); resizing = true; handleOffset = $(e.target).offset(); originalHeight = parseInt(ctrl.row.height); originalWidth = ctrl.panel.span; maxWidth = $(document).width(); lastPanel = ctrl.row.panels[ctrl.row.panels.length - 1]; $('body').on('mousemove', moveHandler); $('body').on('mouseup', dragEndHandler); } function moveHandler(e) { ctrl.row.height = Math.round(originalHeight + (e.pageY - handleOffset.top)); ctrl.panel.span = originalWidth + (((e.pageX - handleOffset.left) / maxWidth) * 12); ctrl.panel.span = Math.min(Math.max(ctrl.panel.span, 1), 12); ctrl.row.updateRowSpan(); var rowSpan = ctrl.row.span; // auto adjust other panels if (Math.floor(rowSpan) < 14) { // last panel should not push row down if (lastPanel === ctrl.panel && rowSpan > 12) { lastPanel.span -= rowSpan - 12; } else if (lastPanel !== ctrl.panel) { // reduce width of last panel so total in row is 12 lastPanel.span = lastPanel.span - (rowSpan - 12); lastPanel.span = Math.min(Math.max(lastPanel.span, 1), 12); } } ctrl.row.panelSpanChanged(true); scope.$apply(function() { ctrl.render(); }); } function dragEndHandler() { ctrl.panel.span = Math.round(ctrl.panel.span); if (lastPanel) { lastPanel.span = Math.round(lastPanel.span); } // first digest to propagate panel width change // then render $rootScope.$apply(function() { ctrl.row.panelSpanChanged(); setTimeout(function() { $rootScope.$broadcast('render'); }); }); $('body').off('mousemove', moveHandler); $('body').off('mouseup', dragEndHandler); } elem.on('mousedown', dragStartHandler); var unbind = scope.$on("$destroy", function() { elem.off('mousedown', dragStartHandler); unbind(); }); } }; }); module.directive('panelHelpCorner', function($rootScope) { return { restrict: 'E', template: ` <span class="alert-error panel-error small pointer" ng-if="ctrl.error" ng-click="ctrl.openInspector()"> <span data-placement="top" bs-tooltip="ctrl.error"> <i class="fa fa-exclamation"></i><span class="panel-error-arrow"></span> </span> </span> `, link: function(scope, elem) { } }; });
public/app/features/panel/panel_directive.ts
1
https://github.com/grafana/grafana/commit/7f8a3a0a2db142b7b6a89e56af7e9600dd9d0537
[ 0.0002106726315105334, 0.00017164571909233928, 0.00016278901603072882, 0.00017077552911359817, 0.000008264302778115962 ]
{ "id": 2, "code_window": [ " }\n", "\n", " if (target.filters && target.filters.length > 0) {\n", " query.filters = angular.copy(target.filters);\n", " if(query.filters){\n", " for(var filter_key in query.filters){\n", " query.filters[filter_key].filter = templateSrv.replace(query.filters[filter_key].filter, options.scopedVars, 'pipe');\n", " }\n", " }\n", " } else {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (query.filters){\n", " for (var filter_key in query.filters) {\n" ], "file_path": "public/app/plugins/datasource/opentsdb/datasource.js", "type": "replace", "edit_start_line_idx": 413 }
// Based on ssh/terminal: // Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build linux,!appengine darwin freebsd openbsd package term import ( "syscall" "unsafe" ) // IsTty returns true if the given file descriptor is a terminal. func IsTty(fd uintptr) bool { var termios Termios _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) return err == 0 }
vendor/github.com/inconshreveable/log15/term/terminal_notwindows.go
0
https://github.com/grafana/grafana/commit/7f8a3a0a2db142b7b6a89e56af7e9600dd9d0537
[ 0.0001820717443479225, 0.00017467212455812842, 0.00016589129518251866, 0.00017605333414394408, 0.000006677451892755926 ]
{ "id": 2, "code_window": [ " }\n", "\n", " if (target.filters && target.filters.length > 0) {\n", " query.filters = angular.copy(target.filters);\n", " if(query.filters){\n", " for(var filter_key in query.filters){\n", " query.filters[filter_key].filter = templateSrv.replace(query.filters[filter_key].filter, options.scopedVars, 'pipe');\n", " }\n", " }\n", " } else {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (query.filters){\n", " for (var filter_key in query.filters) {\n" ], "file_path": "public/app/plugins/datasource/opentsdb/datasource.js", "type": "replace", "edit_start_line_idx": 413 }
package plugins import ( "time" "github.com/grafana/grafana/pkg/bus" m "github.com/grafana/grafana/pkg/models" ) func init() { bus.AddEventListener(handlePluginStateChanged) } func updateAppDashboards() { time.Sleep(time.Second * 5) plog.Debug("Looking for App Dashboard Updates") query := m.GetPluginSettingsQuery{OrgId: 0} if err := bus.Dispatch(&query); err != nil { plog.Error("Failed to get all plugin settings", "error", err) return } for _, pluginSetting := range query.Result { // ignore disabled plugins if !pluginSetting.Enabled { continue } if pluginDef, exist := Plugins[pluginSetting.PluginId]; exist { if pluginDef.Info.Version != pluginSetting.PluginVersion { syncPluginDashboards(pluginDef, pluginSetting.OrgId) } } } } func autoUpdateAppDashboard(pluginDashInfo *PluginDashboardInfoDTO, orgId int64) error { if dash, err := loadPluginDashboard(pluginDashInfo.PluginId, pluginDashInfo.Path); err != nil { return err } else { plog.Info("Auto updating App dashboard", "dashboard", dash.Title, "newRev", pluginDashInfo.Revision, "oldRev", pluginDashInfo.ImportedRevision) updateCmd := ImportDashboardCommand{ OrgId: orgId, PluginId: pluginDashInfo.PluginId, Overwrite: true, Dashboard: dash.Data, UserId: 0, Path: pluginDashInfo.Path, } if err := bus.Dispatch(&updateCmd); err != nil { return err } } return nil } func syncPluginDashboards(pluginDef *PluginBase, orgId int64) { plog.Info("Syncing plugin dashboards to DB", "pluginId", pluginDef.Id) // Get plugin dashboards dashboards, err := GetPluginDashboards(orgId, pluginDef.Id) if err != nil { plog.Error("Failed to load app dashboards", "error", err) return } // Update dashboards with updated revisions for _, dash := range dashboards { // remove removed ones if dash.Removed { plog.Info("Deleting plugin dashboard", "pluginId", pluginDef.Id, "dashboard", dash.Slug) deleteCmd := m.DeleteDashboardCommand{OrgId: orgId, Slug: dash.Slug} if err := bus.Dispatch(&deleteCmd); err != nil { plog.Error("Failed to auto update app dashboard", "pluginId", pluginDef.Id, "error", err) return } continue } // update updated ones if dash.ImportedRevision != dash.Revision { if err := autoUpdateAppDashboard(dash, orgId); err != nil { plog.Error("Failed to auto update app dashboard", "pluginId", pluginDef.Id, "error", err) return } } } // update version in plugin_setting table to mark that we have processed the update query := m.GetPluginSettingByIdQuery{PluginId: pluginDef.Id, OrgId: orgId} if err := bus.Dispatch(&query); err != nil { plog.Error("Failed to read plugin setting by id", "error", err) return } appSetting := query.Result cmd := m.UpdatePluginSettingVersionCmd{ OrgId: appSetting.OrgId, PluginId: appSetting.PluginId, PluginVersion: pluginDef.Info.Version, } if err := bus.Dispatch(&cmd); err != nil { plog.Error("Failed to update plugin setting version", "error", err) } } func handlePluginStateChanged(event *m.PluginStateChangedEvent) error { plog.Info("Plugin state changed", "pluginId", event.PluginId, "enabled", event.Enabled) if event.Enabled { syncPluginDashboards(Plugins[event.PluginId], event.OrgId) } else { query := m.GetDashboardsByPluginIdQuery{PluginId: event.PluginId, OrgId: event.OrgId} if err := bus.Dispatch(&query); err != nil { return err } else { for _, dash := range query.Result { deleteCmd := m.DeleteDashboardCommand{OrgId: dash.OrgId, Slug: dash.Slug} plog.Info("Deleting plugin dashboard", "pluginId", event.PluginId, "dashboard", dash.Slug) if err := bus.Dispatch(&deleteCmd); err != nil { return err } } } } return nil }
pkg/plugins/dashboards_updater.go
0
https://github.com/grafana/grafana/commit/7f8a3a0a2db142b7b6a89e56af7e9600dd9d0537
[ 0.005826839245855808, 0.0008985631284303963, 0.0001677587570156902, 0.00017228395154234022, 0.0015459528658539057 ]
{ "id": 2, "code_window": [ " }\n", "\n", " if (target.filters && target.filters.length > 0) {\n", " query.filters = angular.copy(target.filters);\n", " if(query.filters){\n", " for(var filter_key in query.filters){\n", " query.filters[filter_key].filter = templateSrv.replace(query.filters[filter_key].filter, options.scopedVars, 'pipe');\n", " }\n", " }\n", " } else {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (query.filters){\n", " for (var filter_key in query.filters) {\n" ], "file_path": "public/app/plugins/datasource/opentsdb/datasource.js", "type": "replace", "edit_start_line_idx": 413 }
" "
vendor/github.com/jmespath/go-jmespath/fuzz/corpus/expr-204
0
https://github.com/grafana/grafana/commit/7f8a3a0a2db142b7b6a89e56af7e9600dd9d0537
[ 0.00017040206876117736, 0.00017040206876117736, 0.00017040206876117736, 0.00017040206876117736, 0 ]
{ "id": 3, "code_window": [ " }\n", " } else {\n", " query.tags = angular.copy(target.tags);\n", " if(query.tags){\n", " for(var tag_key in query.tags){\n", " query.tags[tag_key] = templateSrv.replace(query.tags[tag_key], options.scopedVars, 'pipe');\n", " }\n", " }\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (query.tags){\n", " for (var tag_key in query.tags) {\n" ], "file_path": "public/app/plugins/datasource/opentsdb/datasource.js", "type": "replace", "edit_start_line_idx": 420 }
///<reference path="../../headers/common.d.ts" /> import angular from 'angular'; import $ from 'jquery'; import _ from 'lodash'; import Drop from 'tether-drop'; var module = angular.module('grafana.directives'); var panelTemplate = ` <div class="panel-container"> <div class="panel-header"> <span class="panel-info-corner"> <i class="fa"></i> <span class="panel-info-corner-inner"></span> </span> <span class="panel-loading" ng-show="ctrl.loading"> <i class="fa fa-spinner fa-spin"></i> </span> <div class="panel-title-container drag-handle" panel-menu></div> </div> <div class="panel-content"> <ng-transclude></ng-transclude> </div> <panel-resizer></panel-resizer> </div> <div class="panel-full-edit" ng-if="ctrl.editMode"> <div class="tabbed-view tabbed-view--panel-edit"> <div class="tabbed-view-header"> <h2 class="tabbed-view-title"> {{ctrl.pluginName}} </h2> <ul class="gf-tabs"> <li class="gf-tabs-item" ng-repeat="tab in ::ctrl.editorTabs"> <a class="gf-tabs-link" ng-click="ctrl.changeTab($index)" ng-class="{active: ctrl.editorTabIndex === $index}"> {{::tab.title}} </a> </li> </ul> <button class="tabbed-view-close-btn" ng-click="ctrl.exitFullscreen();"> <i class="fa fa-remove"></i> </button> </div> <div class="tabbed-view-body"> <div ng-repeat="tab in ctrl.editorTabs" ng-if="ctrl.editorTabIndex === $index"> <panel-editor-tab editor-tab="tab" ctrl="ctrl" index="$index"></panel-editor-tab> </div> </div> </div> </div> `; module.directive('grafanaPanel', function($rootScope, $document) { return { restrict: 'E', template: panelTemplate, transclude: true, scope: { ctrl: "=" }, link: function(scope, elem) { var panelContainer = elem.find('.panel-container'); var cornerInfoElem = elem.find('.panel-info-corner'); var ctrl = scope.ctrl; var infoDrop; // the reason for handling these classes this way is for performance // limit the watchers on panels etc var transparentLastState = false; var lastHasAlertRule = false; var lastAlertState; var hasAlertRule; var lastHeight = 0; function mouseEnter() { panelContainer.toggleClass('panel-hover-highlight', true); ctrl.dashboard.setPanelFocus(ctrl.panel.id); } function mouseLeave() { panelContainer.toggleClass('panel-hover-highlight', false); ctrl.dashboard.setPanelFocus(0); } // set initial height if (!ctrl.containerHeight) { ctrl.calculatePanelHeight(); panelContainer.css({minHeight: ctrl.containerHeight}); lastHeight = ctrl.containerHeight; } // set initial transparency if (ctrl.panel.transparent) { transparentLastState = true; panelContainer.addClass('panel-transparent', true); } ctrl.events.on('render', () => { if (lastHeight !== ctrl.containerHeight) { panelContainer.css({minHeight: ctrl.containerHeight}); lastHeight = ctrl.containerHeight; } if (transparentLastState !== ctrl.panel.transparent) { panelContainer.toggleClass('panel-transparent', ctrl.panel.transparent === true); transparentLastState = ctrl.panel.transparent; } hasAlertRule = ctrl.panel.alert !== undefined; if (lastHasAlertRule !== hasAlertRule) { panelContainer.toggleClass('panel-has-alert', hasAlertRule); lastHasAlertRule = hasAlertRule; } if (ctrl.alertState) { if (lastAlertState) { panelContainer.removeClass('panel-alert-state--' + lastAlertState); } if (ctrl.alertState.state === 'ok' || ctrl.alertState.state === 'alerting') { panelContainer.addClass('panel-alert-state--' + ctrl.alertState.state); } lastAlertState = ctrl.alertState.state; } else if (lastAlertState) { panelContainer.removeClass('panel-alert-state--' + lastAlertState); lastAlertState = null; } }); var lastFullscreen; $rootScope.onAppEvent('panel-change-view', function(evt, payload) { if (lastFullscreen !== ctrl.fullscreen) { elem.toggleClass('panel-fullscreen', ctrl.fullscreen ? true : false); lastFullscreen = ctrl.fullscreen; } }, scope); function updatePanelCornerInfo() { var cornerMode = ctrl.getInfoMode(); cornerInfoElem[0].className = 'panel-info-corner panel-info-corner--' + cornerMode; if (cornerMode) { if (infoDrop) { infoDrop.destroy(); } infoDrop = new Drop({ target: cornerInfoElem[0], content: function() { return ctrl.getInfoContent({mode: 'tooltip'}); }, position: 'top center', classes: ctrl.error ? 'drop-error' : 'drop-help', openOn: 'hover', hoverOpenDelay: 100, }); } } scope.$watchGroup(['ctrl.error', 'ctrl.panel.description'], updatePanelCornerInfo); scope.$watchCollection('ctrl.panel.links', updatePanelCornerInfo); cornerInfoElem.on('click', function() { infoDrop.close(); scope.$apply(ctrl.openInspector.bind(ctrl)); }); elem.on('mouseenter', mouseEnter); elem.on('mouseleave', mouseLeave); ctrl.isPanelVisible = function () { var position = panelContainer[0].getBoundingClientRect(); return (0 < position.top) && (position.top < window.innerHeight); }; const refreshOnScroll = _.debounce(function () { if (ctrl.skippedLastRefresh) { ctrl.refresh(); } }, 250); $document.on('scroll', refreshOnScroll); scope.$on('$destroy', function() { elem.off(); cornerInfoElem.off(); $document.off('scroll', refreshOnScroll); if (infoDrop) { infoDrop.destroy(); } }); } }; }); module.directive('panelResizer', function($rootScope) { return { restrict: 'E', template: '<span class="resize-panel-handle icon-gf icon-gf-grabber"></span>', link: function(scope, elem) { var resizing = false; var lastPanel; var ctrl = scope.ctrl; var handleOffset; var originalHeight; var originalWidth; var maxWidth; function dragStartHandler(e) { e.preventDefault(); resizing = true; handleOffset = $(e.target).offset(); originalHeight = parseInt(ctrl.row.height); originalWidth = ctrl.panel.span; maxWidth = $(document).width(); lastPanel = ctrl.row.panels[ctrl.row.panels.length - 1]; $('body').on('mousemove', moveHandler); $('body').on('mouseup', dragEndHandler); } function moveHandler(e) { ctrl.row.height = Math.round(originalHeight + (e.pageY - handleOffset.top)); ctrl.panel.span = originalWidth + (((e.pageX - handleOffset.left) / maxWidth) * 12); ctrl.panel.span = Math.min(Math.max(ctrl.panel.span, 1), 12); ctrl.row.updateRowSpan(); var rowSpan = ctrl.row.span; // auto adjust other panels if (Math.floor(rowSpan) < 14) { // last panel should not push row down if (lastPanel === ctrl.panel && rowSpan > 12) { lastPanel.span -= rowSpan - 12; } else if (lastPanel !== ctrl.panel) { // reduce width of last panel so total in row is 12 lastPanel.span = lastPanel.span - (rowSpan - 12); lastPanel.span = Math.min(Math.max(lastPanel.span, 1), 12); } } ctrl.row.panelSpanChanged(true); scope.$apply(function() { ctrl.render(); }); } function dragEndHandler() { ctrl.panel.span = Math.round(ctrl.panel.span); if (lastPanel) { lastPanel.span = Math.round(lastPanel.span); } // first digest to propagate panel width change // then render $rootScope.$apply(function() { ctrl.row.panelSpanChanged(); setTimeout(function() { $rootScope.$broadcast('render'); }); }); $('body').off('mousemove', moveHandler); $('body').off('mouseup', dragEndHandler); } elem.on('mousedown', dragStartHandler); var unbind = scope.$on("$destroy", function() { elem.off('mousedown', dragStartHandler); unbind(); }); } }; }); module.directive('panelHelpCorner', function($rootScope) { return { restrict: 'E', template: ` <span class="alert-error panel-error small pointer" ng-if="ctrl.error" ng-click="ctrl.openInspector()"> <span data-placement="top" bs-tooltip="ctrl.error"> <i class="fa fa-exclamation"></i><span class="panel-error-arrow"></span> </span> </span> `, link: function(scope, elem) { } }; });
public/app/features/panel/panel_directive.ts
1
https://github.com/grafana/grafana/commit/7f8a3a0a2db142b7b6a89e56af7e9600dd9d0537
[ 0.00017460659728385508, 0.00017077659140340984, 0.00016537675401195884, 0.0001714114478090778, 0.000002280800799780991 ]
{ "id": 3, "code_window": [ " }\n", " } else {\n", " query.tags = angular.copy(target.tags);\n", " if(query.tags){\n", " for(var tag_key in query.tags){\n", " query.tags[tag_key] = templateSrv.replace(query.tags[tag_key], options.scopedVars, 'pipe');\n", " }\n", " }\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (query.tags){\n", " for (var tag_key in query.tags) {\n" ], "file_path": "public/app/plugins/datasource/opentsdb/datasource.js", "type": "replace", "edit_start_line_idx": 420 }
///<reference path="../../headers/common.d.ts" /> import _ from 'lodash'; import kbn from 'app/core/utils/kbn'; import {Variable, containsVariable, assignModelProperties, variableTypes} from './variable'; import {VariableSrv} from './variable_srv'; function getNoneOption() { return { text: 'None', value: '', isNone: true }; } export class QueryVariable implements Variable { datasource: any; query: any; regex: any; sort: any; options: any; current: any; refresh: number; hide: number; name: string; multi: boolean; includeAll: boolean; useTags: boolean; tagsQuery: string; tagValuesQuery: string; tags: any[]; defaults = { type: 'query', label: null, query: '', regex: '', sort: 0, datasource: null, refresh: 0, hide: 0, name: '', multi: false, includeAll: false, allValue: null, options: [], current: {}, tags: [], useTags: false, tagsQuery: "", tagValuesQuery: "", }; /** @ngInject **/ constructor(private model, private datasourceSrv, private templateSrv, private variableSrv, private $q) { // copy model properties to this instance assignModelProperties(this, model, this.defaults); } getSaveModel() { // copy back model properties to model assignModelProperties(this.model, this, this.defaults); // remove options if (this.refresh !== 0) { this.model.options = []; } return this.model; } setValue(option){ return this.variableSrv.setOptionAsCurrent(this, option); } setValueFromUrl(urlValue) { return this.variableSrv.setOptionFromUrl(this, urlValue); } getValueForUrl() { if (this.current.text === 'All') { return 'All'; } return this.current.value; } updateOptions() { return this.datasourceSrv.get(this.datasource) .then(this.updateOptionsFromMetricFindQuery.bind(this)) .then(this.updateTags.bind(this)) .then(this.variableSrv.validateVariableSelectionState.bind(this.variableSrv, this)); } updateTags(datasource) { if (this.useTags) { return datasource.metricFindQuery(this.tagsQuery).then(results => { this.tags = []; for (var i = 0; i < results.length; i++) { this.tags.push(results[i].text); } return datasource; }); } else { delete this.tags; } return datasource; } getValuesForTag(tagKey) { return this.datasourceSrv.get(this.datasource).then(datasource => { var query = this.tagValuesQuery.replace('$tag', tagKey); return datasource.metricFindQuery(query).then(function (results) { return _.map(results, function(value) { return value.text; }); }); }); } updateOptionsFromMetricFindQuery(datasource) { return datasource.metricFindQuery(this.query).then(results => { this.options = this.metricNamesToVariableValues(results); if (this.includeAll) { this.addAllOption(); } if (!this.options.length) { this.options.push(getNoneOption()); } return datasource; }); } addAllOption() { this.options.unshift({text: 'All', value: "$__all"}); } metricNamesToVariableValues(metricNames) { var regex, options, i, matches; options = []; if (this.regex) { regex = kbn.stringToJsRegex(this.templateSrv.replace(this.regex, {}, 'regex')); } for (i = 0; i < metricNames.length; i++) { var item = metricNames[i]; var text = item.text === undefined || item.text === null ? item.value : item.text; var value = item.value === undefined || item.value === null ? item.text : item.value; if (_.isNumber(value)) { value = value.toString(); } if (_.isNumber(text)) { text = text.toString(); } if (regex) { matches = regex.exec(value); if (!matches) { continue; } if (matches.length > 1) { value = matches[1]; text = matches[1]; } } options.push({text: text, value: value}); } options = _.uniqBy(options, 'value'); return this.sortVariableValues(options, this.sort); } sortVariableValues(options, sortOrder) { if (sortOrder === 0) { return options; } var sortType = Math.ceil(sortOrder / 2); var reverseSort = (sortOrder % 2 === 0); if (sortType === 1) { options = _.sortBy(options, 'text'); } else if (sortType === 2) { options = _.sortBy(options, (opt) => { var matches = opt.text.match(/.*?(\d+).*/); if (!matches || matches.length < 2) { return -1; } else { return parseInt(matches[1], 10); } }); } if (reverseSort) { options = options.reverse(); } return options; } dependsOn(variable) { return containsVariable(this.query, this.datasource, variable.name); } } variableTypes['query'] = { name: 'Query', ctor: QueryVariable, description: 'Variable values are fetched from a datasource query', supportsMulti: true, };
public/app/features/templating/query_variable.ts
0
https://github.com/grafana/grafana/commit/7f8a3a0a2db142b7b6a89e56af7e9600dd9d0537
[ 0.00344133866019547, 0.0008972224313765764, 0.000162124473717995, 0.00018466227629687637, 0.0010190510656684637 ]
{ "id": 3, "code_window": [ " }\n", " } else {\n", " query.tags = angular.copy(target.tags);\n", " if(query.tags){\n", " for(var tag_key in query.tags){\n", " query.tags[tag_key] = templateSrv.replace(query.tags[tag_key], options.scopedVars, 'pipe');\n", " }\n", " }\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (query.tags){\n", " for (var tag_key in query.tags) {\n" ], "file_path": "public/app/plugins/datasource/opentsdb/datasource.js", "type": "replace", "edit_start_line_idx": 420 }
" \t"
vendor/github.com/jmespath/go-jmespath/fuzz/corpus/expr-203
0
https://github.com/grafana/grafana/commit/7f8a3a0a2db142b7b6a89e56af7e9600dd9d0537
[ 0.0001723024033708498, 0.0001723024033708498, 0.0001723024033708498, 0.0001723024033708498, 0 ]
{ "id": 3, "code_window": [ " }\n", " } else {\n", " query.tags = angular.copy(target.tags);\n", " if(query.tags){\n", " for(var tag_key in query.tags){\n", " query.tags[tag_key] = templateSrv.replace(query.tags[tag_key], options.scopedVars, 'pipe');\n", " }\n", " }\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (query.tags){\n", " for (var tag_key in query.tags) {\n" ], "file_path": "public/app/plugins/datasource/opentsdb/datasource.js", "type": "replace", "edit_start_line_idx": 420 }
# Implements the TOML test suite interface This is an implementation of the interface expected by [toml-test](https://github.com/BurntSushi/toml-test) for my [toml parser written in Go](https://github.com/BurntSushi/toml). In particular, it maps TOML data on `stdin` to a JSON format on `stdout`. Compatible with TOML version [v0.2.0](https://github.com/mojombo/toml/blob/master/versions/toml-v0.2.0.md) Compatible with `toml-test` version [v0.2.0](https://github.com/BurntSushi/toml-test/tree/v0.2.0)
vendor/github.com/BurntSushi/toml/cmd/toml-test-decoder/README.md
0
https://github.com/grafana/grafana/commit/7f8a3a0a2db142b7b6a89e56af7e9600dd9d0537
[ 0.00016631004109513015, 0.00016198665252886713, 0.0001576632639626041, 0.00016198665252886713, 0.00000432338856626302 ]
{ "id": 2, "code_window": [ "\n", "@Component({selector: 'root-cmp', template: `<router-outlet></router-outlet>`})\n", "class RootCmp {\n", "}\n", "\n", "@Component({\n", " selector: 'root-cmp',\n", " template:\n", " `primary [<router-outlet></router-outlet>] right [<router-outlet name=\"right\"></router-outlet>]`\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "@Component({selector: 'root-cmp-on-init', template: `<router-outlet></router-outlet>`})\n", "class RootCmpWithOnInit {\n", " constructor(private router: Router) {}\n", "\n", " ngOnInit(): void { this.router.navigate(['one']); }\n", "}\n", "\n" ], "file_path": "modules/@angular/router/test/integration.spec.ts", "type": "add", "edit_start_line_idx": 2039 }
/** * @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 {Compiler, ComponentFactoryResolver, Injector, NgModuleFactoryLoader, ReflectiveInjector, Type} from '@angular/core'; import {BehaviorSubject} from 'rxjs/BehaviorSubject'; import {Observable} from 'rxjs/Observable'; import {Subject} from 'rxjs/Subject'; import {Subscription} from 'rxjs/Subscription'; import {from} from 'rxjs/observable/from'; import {of } from 'rxjs/observable/of'; import {concatMap} from 'rxjs/operator/concatMap'; import {every} from 'rxjs/operator/every'; import {first} from 'rxjs/operator/first'; import {map} from 'rxjs/operator/map'; import {mergeMap} from 'rxjs/operator/mergeMap'; import {reduce} from 'rxjs/operator/reduce'; import {applyRedirects} from './apply_redirects'; import {ResolveData, Routes, validateConfig} from './config'; import {createRouterState} from './create_router_state'; import {createUrlTree} from './create_url_tree'; import {RouterOutlet} from './directives/router_outlet'; import {recognize} from './recognize'; import {DetachedRouteHandle, DetachedRouteHandleInternal, RouteReuseStrategy} from './route_reuse_strategy'; import {LoadedRouterConfig, RouterConfigLoader} from './router_config_loader'; import {RouterOutletMap} from './router_outlet_map'; import {ActivatedRoute, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot, advanceActivatedRoute, createEmptyState, equalParamsAndUrlSegments, inheritedParamsDataResolve} from './router_state'; import {NavigationCancelingError, PRIMARY_OUTLET, Params} from './shared'; import {DefaultUrlHandlingStrategy, UrlHandlingStrategy} from './url_handling_strategy'; import {UrlSerializer, UrlTree, containsTree, createEmptyUrlTree} from './url_tree'; import {andObservables, forEach, merge, waitForMap, wrapIntoObservable} from './utils/collection'; import {TreeNode} from './utils/tree'; declare let Zone: any; /** * @whatItDoes Represents the extra options used during navigation. * * @stable */ export interface NavigationExtras { /** * Enables relative navigation from the current ActivatedRoute. * * Configuration: * * ``` * [{ * path: 'parent', * component: ParentComponent, * children: [{ * path: 'list', * component: ListComponent * },{ * path: 'child', * component: ChildComponent * }] * }] * ``` * * Navigate to list route from child route: * * ``` * @Component({...}) * class ChildComponent { * constructor(private router: Router, private route: ActivatedRoute) {} * * go() { * this.router.navigate(['../list'], { relativeTo: this.route }); * } * } * ``` */ relativeTo?: ActivatedRoute; /** * Sets query parameters to the URL. * * ``` * // Navigate to /results?page=1 * this.router.navigate(['/results'], { queryParams: { page: 1 } }); * ``` */ queryParams?: Params; /** * Sets the hash fragment for the URL. * * ``` * // Navigate to /results#top * this.router.navigate(['/results'], { fragment: 'top' }); * ``` */ fragment?: string; /** * Preserves the query parameters for the next navigation. * * ``` * // Preserve query params from /results?page=1 to /view?page=1 * this.router.navigate(['/view'], { preserveQueryParams: true }); * ``` */ preserveQueryParams?: boolean; /** * Preserves the fragment for the next navigation * * ``` * // Preserve fragment from /results#top to /view#top * this.router.navigate(['/view'], { preserveFragment: true }); * ``` */ preserveFragment?: boolean; /** * Navigates without pushing a new state into history. * * ``` * // Navigate silently to /view * this.router.navigate(['/view'], { skipLocationChange: true }); * ``` */ skipLocationChange?: boolean; /** * Navigates while replacing the current state in history. * * ``` * // Navigate to /view * this.router.navigate(['/view'], { replaceUrl: true }); * ``` */ replaceUrl?: boolean; } /** * @whatItDoes Represents an event triggered when a navigation starts. * * @stable */ export class NavigationStart { // TODO: vsavkin: make internal constructor( /** @docsNotRequired */ public id: number, /** @docsNotRequired */ public url: string) {} /** @docsNotRequired */ toString(): string { return `NavigationStart(id: ${this.id}, url: '${this.url}')`; } } /** * @whatItDoes Represents an event triggered when a navigation ends successfully. * * @stable */ export class NavigationEnd { // TODO: vsavkin: make internal constructor( /** @docsNotRequired */ public id: number, /** @docsNotRequired */ public url: string, /** @docsNotRequired */ public urlAfterRedirects: string) {} /** @docsNotRequired */ toString(): string { return `NavigationEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}')`; } } /** * @whatItDoes Represents an event triggered when a navigation is canceled. * * @stable */ export class NavigationCancel { // TODO: vsavkin: make internal constructor( /** @docsNotRequired */ public id: number, /** @docsNotRequired */ public url: string, /** @docsNotRequired */ public reason: string) {} /** @docsNotRequired */ toString(): string { return `NavigationCancel(id: ${this.id}, url: '${this.url}')`; } } /** * @whatItDoes Represents an event triggered when a navigation fails due to an unexpected error. * * @stable */ export class NavigationError { // TODO: vsavkin: make internal constructor( /** @docsNotRequired */ public id: number, /** @docsNotRequired */ public url: string, /** @docsNotRequired */ public error: any) {} /** @docsNotRequired */ toString(): string { return `NavigationError(id: ${this.id}, url: '${this.url}', error: ${this.error})`; } } /** * @whatItDoes Represents an event triggered when routes are recognized. * * @stable */ export class RoutesRecognized { // TODO: vsavkin: make internal constructor( /** @docsNotRequired */ public id: number, /** @docsNotRequired */ public url: string, /** @docsNotRequired */ public urlAfterRedirects: string, /** @docsNotRequired */ public state: RouterStateSnapshot) {} /** @docsNotRequired */ toString(): string { return `RoutesRecognized(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`; } } /** * @whatItDoes Represents a router event. * * Please see {@link NavigationStart}, {@link NavigationEnd}, {@link NavigationCancel}, {@link * NavigationError}, * {@link RoutesRecognized} for more information. * * @stable */ export type Event = NavigationStart | NavigationEnd | NavigationCancel | NavigationError | RoutesRecognized; /** * @whatItDoes Error handler that is invoked when a navigation errors. * * @description * If the handler returns a value, the navigation promise will be resolved with this value. * If the handler throws an exception, the navigation promise will be rejected with * the exception. * * @stable */ export type ErrorHandler = (error: any) => any; function defaultErrorHandler(error: any): any { throw error; } type NavigationSource = 'imperative' | 'popstate' | 'hashchange'; type NavigationParams = { id: number, rawUrl: UrlTree, extras: NavigationExtras, resolve: any, reject: any, promise: Promise<boolean>, source: NavigationSource, }; /** * Does not detach any subtrees. Reuses routes as long as their route config is the same. */ export class DefaultRouteReuseStrategy implements RouteReuseStrategy { shouldDetach(route: ActivatedRouteSnapshot): boolean { return false; } store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void {} shouldAttach(route: ActivatedRouteSnapshot): boolean { return false; } retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { return null; } shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { return future.routeConfig === curr.routeConfig; } } /** * @whatItDoes Provides the navigation and url manipulation capabilities. * * See {@link Routes} for more details and examples. * * @ngModule RouterModule * * @stable */ export class Router { private currentUrlTree: UrlTree; private rawUrlTree: UrlTree; private navigations = new BehaviorSubject<NavigationParams>(null); private routerEvents = new Subject<Event>(); private currentRouterState: RouterState; private locationSubscription: Subscription; private navigationId: number = 0; private configLoader: RouterConfigLoader; /** * Error handler that is invoked when a navigation errors. * * See {@link ErrorHandler} for more information. */ errorHandler: ErrorHandler = defaultErrorHandler; /** * Indicates if at least one navigation happened. */ navigated: boolean = false; /** * Extracts and merges URLs. Used for AngularJS to Angular migrations. */ urlHandlingStrategy: UrlHandlingStrategy = new DefaultUrlHandlingStrategy(); routeReuseStrategy: RouteReuseStrategy = new DefaultRouteReuseStrategy(); /** * Creates the router service. */ // TODO: vsavkin make internal after the final is out. constructor( private rootComponentType: Type<any>, private urlSerializer: UrlSerializer, private outletMap: RouterOutletMap, private location: Location, private injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler, public config: Routes) { this.resetConfig(config); this.currentUrlTree = createEmptyUrlTree(); this.rawUrlTree = this.currentUrlTree; this.configLoader = new RouterConfigLoader(loader, compiler); this.currentRouterState = createEmptyState(this.currentUrlTree, this.rootComponentType); this.processNavigations(); } /** * @internal * TODO: this should be removed once the constructor of the router made internal */ resetRootComponentType(rootComponentType: Type<any>): void { this.rootComponentType = rootComponentType; // TODO: vsavkin router 4.0 should make the root component set to null // this will simplify the lifecycle of the router. this.currentRouterState.root.component = this.rootComponentType; } /** * Sets up the location change listener and performs the initial navigation. */ initialNavigation(): void { this.setUpLocationChangeListener(); this.navigateByUrl(this.location.path(true), {replaceUrl: true}); } /** * Sets up the location change listener. */ setUpLocationChangeListener(): void { // Zone.current.wrap is needed because of the issue with RxJS scheduler, // which does not work properly with zone.js in IE and Safari if (!this.locationSubscription) { this.locationSubscription = <any>this.location.subscribe(Zone.current.wrap((change: any) => { const rawUrlTree = this.urlSerializer.parse(change['url']); const source: NavigationSource = change['type'] === 'popstate' ? 'popstate' : 'hashchange'; setTimeout(() => { this.scheduleNavigation(rawUrlTree, source, {replaceUrl: true}); }, 0); })); } } /** The current route state */ get routerState(): RouterState { return this.currentRouterState; } /** The current url */ get url(): string { return this.serializeUrl(this.currentUrlTree); } /** An observable of router events */ get events(): Observable<Event> { return this.routerEvents; } /** * Resets the configuration used for navigation and generating links. * * ### Usage * * ``` * router.resetConfig([ * { path: 'team/:id', component: TeamCmp, children: [ * { path: 'simple', component: SimpleCmp }, * { path: 'user/:name', component: UserCmp } * ]} * ]); * ``` */ resetConfig(config: Routes): void { validateConfig(config); this.config = config; } /** @docsNotRequired */ ngOnDestroy() { this.dispose(); } /** Disposes of the router */ dispose(): void { if (this.locationSubscription) { this.locationSubscription.unsubscribe(); this.locationSubscription = null; } } /** * Applies an array of commands to the current url tree and creates a new url tree. * * When given an activate route, applies the given commands starting from the route. * When not given a route, applies the given command starting from the root. * * ### Usage * * ``` * // create /team/33/user/11 * router.createUrlTree(['/team', 33, 'user', 11]); * * // create /team/33;expand=true/user/11 * router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]); * * // you can collapse static segments like this (this works only with the first passed-in value): * router.createUrlTree(['/team/33/user', userId]); * * // If the first segment can contain slashes, and you do not want the router to split it, you * // can do the following: * * router.createUrlTree([{segmentPath: '/one/two'}]); * * // create /team/33/(user/11//right:chat) * router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}]); * * // remove the right secondary node * router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: null}}]); * * // assuming the current url is `/team/33/user/11` and the route points to `user/11` * * // navigate to /team/33/user/11/details * router.createUrlTree(['details'], {relativeTo: route}); * * // navigate to /team/33/user/22 * router.createUrlTree(['../22'], {relativeTo: route}); * * // navigate to /team/44/user/22 * router.createUrlTree(['../../team/44/user/22'], {relativeTo: route}); * ``` */ createUrlTree( commands: any[], {relativeTo, queryParams, fragment, preserveQueryParams, preserveFragment}: NavigationExtras = {}): UrlTree { const a = relativeTo || this.routerState.root; const q = preserveQueryParams ? this.currentUrlTree.queryParams : queryParams; const f = preserveFragment ? this.currentUrlTree.fragment : fragment; return createUrlTree(a, this.currentUrlTree, commands, q, f); } /** * Navigate based on the provided url. This navigation is always absolute. * * Returns a promise that: * - resolves to 'true' when navigation succeeds, * - resolves to 'false' when navigation fails, * - is rejected when an error happens. * * ### Usage * * ``` * router.navigateByUrl("/team/33/user/11"); * * // Navigate without updating the URL * router.navigateByUrl("/team/33/user/11", { skipLocationChange: true }); * ``` * * In opposite to `navigate`, `navigateByUrl` takes a whole URL * and does not apply any delta to the current one. */ navigateByUrl(url: string|UrlTree, extras: NavigationExtras = {skipLocationChange: false}): Promise<boolean> { if (url instanceof UrlTree) { return this.scheduleNavigation( this.urlHandlingStrategy.merge(url, this.rawUrlTree), 'imperative', extras); } const urlTree = this.urlSerializer.parse(url); return this.scheduleNavigation( this.urlHandlingStrategy.merge(urlTree, this.rawUrlTree), 'imperative', extras); } /** * Navigate based on the provided array of commands and a starting point. * If no starting route is provided, the navigation is absolute. * * Returns a promise that: * - resolves to 'true' when navigation succeeds, * - resolves to 'false' when navigation fails, * - is rejected when an error happens. * * ### Usage * * ``` * router.navigate(['team', 33, 'user', 11], {relativeTo: route}); * * // Navigate without updating the URL * router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true}); * ``` * * In opposite to `navigateByUrl`, `navigate` always takes a delta that is applied to the current * URL. */ navigate(commands: any[], extras: NavigationExtras = {skipLocationChange: false}): Promise<boolean> { validateCommands(commands); if (typeof extras.queryParams === 'object' && extras.queryParams !== null) { extras.queryParams = this.removeEmptyProps(extras.queryParams); } return this.navigateByUrl(this.createUrlTree(commands, extras), extras); } /** Serializes a {@link UrlTree} into a string */ serializeUrl(url: UrlTree): string { return this.urlSerializer.serialize(url); } /** Parses a string into a {@link UrlTree} */ parseUrl(url: string): UrlTree { return this.urlSerializer.parse(url); } /** Returns whether the url is activated */ isActive(url: string|UrlTree, exact: boolean): boolean { if (url instanceof UrlTree) { return containsTree(this.currentUrlTree, url, exact); } else { const urlTree = this.urlSerializer.parse(url); return containsTree(this.currentUrlTree, urlTree, exact); } } private removeEmptyProps(params: Params): Params { return Object.keys(params).reduce((result: Params, key: string) => { const value: any = params[key]; if (value !== null && value !== undefined) { result[key] = value; } return result; }, {}); } private processNavigations(): void { concatMap .call( this.navigations, (nav: NavigationParams) => { if (nav) { this.executeScheduledNavigation(nav); // a failed navigation should not stop the router from processing // further navigations => the catch return nav.promise.catch(() => {}); } else { return <any>of (null); } }) .subscribe(() => {}); } private scheduleNavigation(rawUrl: UrlTree, source: NavigationSource, extras: NavigationExtras): Promise<boolean> { const lastNavigation = this.navigations.value; // If the user triggers a navigation imperatively (e.g., by using navigateByUrl), // and that navigation results in 'replaceState' that leads to the same URL, // we should skip those. if (lastNavigation && source !== 'imperative' && lastNavigation.source === 'imperative' && lastNavigation.rawUrl.toString() === rawUrl.toString()) { return null; // return value is not used } // Because of a bug in IE and Edge, the location class fires two events (popstate and // hashchange) // every single time. The second one should be ignored. Otherwise, the URL will flicker. if (lastNavigation && source == 'hashchange' && lastNavigation.source === 'popstate' && lastNavigation.rawUrl.toString() === rawUrl.toString()) { return null; // return value is not used } let resolve: any = null; let reject: any = null; const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); const id = ++this.navigationId; this.navigations.next({id, source, rawUrl, extras, resolve, reject, promise}); // Make sure that the error is propagated even though `processNavigations` catch // handler does not rethrow return promise.catch((e: any) => Promise.reject(e)); } private executeScheduledNavigation({id, rawUrl, extras, resolve, reject}: NavigationParams): void { const url = this.urlHandlingStrategy.extract(rawUrl); const urlTransition = !this.navigated || url.toString() !== this.currentUrlTree.toString(); if (urlTransition && this.urlHandlingStrategy.shouldProcessUrl(rawUrl)) { this.routerEvents.next(new NavigationStart(id, this.serializeUrl(url))); Promise.resolve() .then( (_) => this.runNavigate( url, rawUrl, extras.skipLocationChange, extras.replaceUrl, id, null)) .then(resolve, reject); // we cannot process the current URL, but we could process the previous one => // we need to do some cleanup } else if ( urlTransition && this.rawUrlTree && this.urlHandlingStrategy.shouldProcessUrl(this.rawUrlTree)) { this.routerEvents.next(new NavigationStart(id, this.serializeUrl(url))); Promise.resolve() .then( (_) => this.runNavigate( url, rawUrl, false, false, id, createEmptyState(url, this.rootComponentType).snapshot)) .then(resolve, reject); } else { this.rawUrlTree = rawUrl; resolve(null); } } private runNavigate( url: UrlTree, rawUrl: UrlTree, shouldPreventPushState: boolean, shouldReplaceUrl: boolean, id: number, precreatedState: RouterStateSnapshot): Promise<boolean> { if (id !== this.navigationId) { this.location.go(this.urlSerializer.serialize(this.currentUrlTree)); this.routerEvents.next(new NavigationCancel( id, this.serializeUrl(url), `Navigation ID ${id} is not equal to the current navigation id ${this.navigationId}`)); return Promise.resolve(false); } return new Promise((resolvePromise, rejectPromise) => { // create an observable of the url and route state snapshot // this operation do not result in any side effects let urlAndSnapshot$: Observable<{appliedUrl: UrlTree, snapshot: RouterStateSnapshot}>; if (!precreatedState) { const redirectsApplied$ = applyRedirects(this.injector, this.configLoader, this.urlSerializer, url, this.config); urlAndSnapshot$ = mergeMap.call(redirectsApplied$, (appliedUrl: UrlTree) => { return map.call( recognize( this.rootComponentType, this.config, appliedUrl, this.serializeUrl(appliedUrl)), (snapshot: any) => { this.routerEvents.next(new RoutesRecognized( id, this.serializeUrl(url), this.serializeUrl(appliedUrl), snapshot)); return {appliedUrl, snapshot}; }); }); } else { urlAndSnapshot$ = of ({appliedUrl: url, snapshot: precreatedState}); } // run preactivation: guards and data resolvers let preActivation: PreActivation; const preactivationTraverse$ = map.call(urlAndSnapshot$, ({appliedUrl, snapshot}: any) => { preActivation = new PreActivation(snapshot, this.currentRouterState.snapshot, this.injector); preActivation.traverse(this.outletMap); return {appliedUrl, snapshot}; }); const preactivationCheckGuards = mergeMap.call(preactivationTraverse$, ({appliedUrl, snapshot}: any) => { if (this.navigationId !== id) return of (false); return map.call(preActivation.checkGuards(), (shouldActivate: boolean) => { return {appliedUrl: appliedUrl, snapshot: snapshot, shouldActivate: shouldActivate}; }); }); const preactivationResolveData$ = mergeMap.call(preactivationCheckGuards, (p: any) => { if (this.navigationId !== id) return of (false); if (p.shouldActivate) { return map.call(preActivation.resolveData(), () => p); } else { return of (p); } }); // create router state // this operation has side effects => route state is being affected const routerState$ = map.call(preactivationResolveData$, ({appliedUrl, snapshot, shouldActivate}: any) => { if (shouldActivate) { const state = createRouterState(this.routeReuseStrategy, snapshot, this.currentRouterState); return {appliedUrl, state, shouldActivate}; } else { return {appliedUrl, state: null, shouldActivate}; } }); // applied the new router state // this operation has side effects let navigationIsSuccessful: boolean; const storedState = this.currentRouterState; const storedUrl = this.currentUrlTree; routerState$ .forEach(({appliedUrl, state, shouldActivate}: any) => { if (!shouldActivate || id !== this.navigationId) { navigationIsSuccessful = false; return; } this.currentUrlTree = appliedUrl; this.rawUrlTree = this.urlHandlingStrategy.merge(this.currentUrlTree, rawUrl); this.currentRouterState = state; if (!shouldPreventPushState) { const path = this.urlSerializer.serialize(this.rawUrlTree); if (this.location.isCurrentPathEqualTo(path) || shouldReplaceUrl) { this.location.replaceState(path); } else { this.location.go(path); } } new ActivateRoutes(this.routeReuseStrategy, state, storedState) .activate(this.outletMap); navigationIsSuccessful = true; }) .then( () => { if (navigationIsSuccessful) { this.navigated = true; this.routerEvents.next(new NavigationEnd( id, this.serializeUrl(url), this.serializeUrl(this.currentUrlTree))); resolvePromise(true); } else { this.resetUrlToCurrentUrlTree(); this.routerEvents.next(new NavigationCancel(id, this.serializeUrl(url), '')); resolvePromise(false); } }, (e: any) => { if (e instanceof NavigationCancelingError) { this.resetUrlToCurrentUrlTree(); this.navigated = true; this.routerEvents.next( new NavigationCancel(id, this.serializeUrl(url), e.message)); resolvePromise(false); } else { this.routerEvents.next(new NavigationError(id, this.serializeUrl(url), e)); try { resolvePromise(this.errorHandler(e)); } catch (ee) { rejectPromise(ee); } } this.currentRouterState = storedState; this.currentUrlTree = storedUrl; this.rawUrlTree = this.urlHandlingStrategy.merge(this.currentUrlTree, rawUrl); this.location.replaceState(this.serializeUrl(this.rawUrlTree)); }); }); } private resetUrlToCurrentUrlTree(): void { const path = this.urlSerializer.serialize(this.rawUrlTree); this.location.replaceState(path); } } class CanActivate { constructor(public path: ActivatedRouteSnapshot[]) {} get route(): ActivatedRouteSnapshot { return this.path[this.path.length - 1]; } } class CanDeactivate { constructor(public component: Object, public route: ActivatedRouteSnapshot) {} } export class PreActivation { private checks: Array<CanActivate|CanDeactivate> = []; constructor( private future: RouterStateSnapshot, private curr: RouterStateSnapshot, private injector: Injector) {} traverse(parentOutletMap: RouterOutletMap): void { const futureRoot = this.future._root; const currRoot = this.curr ? this.curr._root : null; this.traverseChildRoutes(futureRoot, currRoot, parentOutletMap, [futureRoot.value]); } checkGuards(): Observable<boolean> { if (this.checks.length === 0) return of (true); const checks$ = from(this.checks); const runningChecks$ = mergeMap.call(checks$, (s: any) => { if (s instanceof CanActivate) { return andObservables( from([this.runCanActivateChild(s.path), this.runCanActivate(s.route)])); } else if (s instanceof CanDeactivate) { // workaround https://github.com/Microsoft/TypeScript/issues/7271 const s2 = s as CanDeactivate; return this.runCanDeactivate(s2.component, s2.route); } else { throw new Error('Cannot be reached'); } }); return every.call(runningChecks$, (result: any) => result === true); } resolveData(): Observable<any> { if (this.checks.length === 0) return of (null); const checks$ = from(this.checks); const runningChecks$ = concatMap.call(checks$, (s: any) => { if (s instanceof CanActivate) { return this.runResolve(s.route); } else { return of (null); } }); return reduce.call(runningChecks$, (_: any, __: any) => _); } private traverseChildRoutes( futureNode: TreeNode<ActivatedRouteSnapshot>, currNode: TreeNode<ActivatedRouteSnapshot>, outletMap: RouterOutletMap, futurePath: ActivatedRouteSnapshot[]): void { const prevChildren: {[key: string]: any} = nodeChildrenAsMap(currNode); futureNode.children.forEach(c => { this.traverseRoutes(c, prevChildren[c.value.outlet], outletMap, futurePath.concat([c.value])); delete prevChildren[c.value.outlet]; }); forEach( prevChildren, (v: any, k: string) => this.deactiveRouteAndItsChildren(v, outletMap._outlets[k])); } traverseRoutes( futureNode: TreeNode<ActivatedRouteSnapshot>, currNode: TreeNode<ActivatedRouteSnapshot>, parentOutletMap: RouterOutletMap, futurePath: ActivatedRouteSnapshot[]): void { const future = futureNode.value; const curr = currNode ? currNode.value : null; const outlet = parentOutletMap ? parentOutletMap._outlets[futureNode.value.outlet] : null; // reusing the node if (curr && future._routeConfig === curr._routeConfig) { if (!equalParamsAndUrlSegments(future, curr)) { this.checks.push(new CanDeactivate(outlet.component, curr), new CanActivate(futurePath)); } else { // we need to set the data future.data = curr.data; future._resolvedData = curr._resolvedData; } // If we have a component, we need to go through an outlet. if (future.component) { this.traverseChildRoutes( futureNode, currNode, outlet ? outlet.outletMap : null, futurePath); // if we have a componentless route, we recurse but keep the same outlet map. } else { this.traverseChildRoutes(futureNode, currNode, parentOutletMap, futurePath); } } else { if (curr) { this.deactiveRouteAndItsChildren(currNode, outlet); } this.checks.push(new CanActivate(futurePath)); // If we have a component, we need to go through an outlet. if (future.component) { this.traverseChildRoutes(futureNode, null, outlet ? outlet.outletMap : null, futurePath); // if we have a componentless route, we recurse but keep the same outlet map. } else { this.traverseChildRoutes(futureNode, null, parentOutletMap, futurePath); } } } private deactiveRouteAndItsChildren( route: TreeNode<ActivatedRouteSnapshot>, outlet: RouterOutlet): void { const prevChildren: {[key: string]: any} = nodeChildrenAsMap(route); const r = route.value; forEach(prevChildren, (v: any, k: string) => { if (!r.component) { this.deactiveRouteAndItsChildren(v, outlet); } else if (!!outlet) { this.deactiveRouteAndItsChildren(v, outlet.outletMap._outlets[k]); } else { this.deactiveRouteAndItsChildren(v, null); } }); if (!r.component) { this.checks.push(new CanDeactivate(null, r)); } else if (outlet && outlet.isActivated) { this.checks.push(new CanDeactivate(outlet.component, r)); } else { this.checks.push(new CanDeactivate(null, r)); } } private runCanActivate(future: ActivatedRouteSnapshot): Observable<boolean> { const canActivate = future._routeConfig ? future._routeConfig.canActivate : null; if (!canActivate || canActivate.length === 0) return of (true); const obs = map.call(from(canActivate), (c: any) => { const guard = this.getToken(c, future); let observable: Observable<boolean>; if (guard.canActivate) { observable = wrapIntoObservable(guard.canActivate(future, this.future)); } else { observable = wrapIntoObservable(guard(future, this.future)); } return first.call(observable); }); return andObservables(obs); } private runCanActivateChild(path: ActivatedRouteSnapshot[]): Observable<boolean> { const future = path[path.length - 1]; const canActivateChildGuards = path.slice(0, path.length - 1) .reverse() .map(p => this.extractCanActivateChild(p)) .filter(_ => _ !== null); return andObservables(map.call(from(canActivateChildGuards), (d: any) => { const obs = map.call(from(d.guards), (c: any) => { const guard = this.getToken(c, c.node); let observable: Observable<boolean>; if (guard.canActivateChild) { observable = wrapIntoObservable(guard.canActivateChild(future, this.future)); } else { observable = wrapIntoObservable(guard(future, this.future)); } return first.call(observable); }); return andObservables(obs); })); } private extractCanActivateChild(p: ActivatedRouteSnapshot): {node: ActivatedRouteSnapshot, guards: any[]} { const canActivateChild = p._routeConfig ? p._routeConfig.canActivateChild : null; if (!canActivateChild || canActivateChild.length === 0) return null; return {node: p, guards: canActivateChild}; } private runCanDeactivate(component: Object, curr: ActivatedRouteSnapshot): Observable<boolean> { const canDeactivate = curr && curr._routeConfig ? curr._routeConfig.canDeactivate : null; if (!canDeactivate || canDeactivate.length === 0) return of (true); const canDeactivate$ = mergeMap.call(from(canDeactivate), (c: any) => { const guard = this.getToken(c, curr); let observable: Observable<boolean>; if (guard.canDeactivate) { observable = wrapIntoObservable(guard.canDeactivate(component, curr, this.curr, this.future)); } else { observable = wrapIntoObservable(guard(component, curr, this.curr, this.future)); } return first.call(observable); }); return every.call(canDeactivate$, (result: any) => result === true); } private runResolve(future: ActivatedRouteSnapshot): Observable<any> { const resolve = future._resolve; return map.call(this.resolveNode(resolve, future), (resolvedData: any): any => { future._resolvedData = resolvedData; future.data = merge(future.data, inheritedParamsDataResolve(future).resolve); return null; }); } private resolveNode(resolve: ResolveData, future: ActivatedRouteSnapshot): Observable<any> { return waitForMap(resolve, (k, v) => { const resolver = this.getToken(v, future); return resolver.resolve ? wrapIntoObservable(resolver.resolve(future, this.future)) : wrapIntoObservable(resolver(future, this.future)); }); } private getToken(token: any, snapshot: ActivatedRouteSnapshot): any { const config = closestLoadedConfig(snapshot); const injector = config ? config.injector : this.injector; return injector.get(token); } } class ActivateRoutes { constructor( private routeReuseStrategy: RouteReuseStrategy, private futureState: RouterState, private currState: RouterState) {} activate(parentOutletMap: RouterOutletMap): void { const futureRoot = this.futureState._root; const currRoot = this.currState ? this.currState._root : null; this.deactivateChildRoutes(futureRoot, currRoot, parentOutletMap); advanceActivatedRoute(this.futureState.root); this.activateChildRoutes(futureRoot, currRoot, parentOutletMap); } private deactivateChildRoutes( futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute>, outletMap: RouterOutletMap): void { const prevChildren: {[key: string]: any} = nodeChildrenAsMap(currNode); futureNode.children.forEach(c => { this.deactivateRoutes(c, prevChildren[c.value.outlet], outletMap); delete prevChildren[c.value.outlet]; }); forEach(prevChildren, (v: any, k: string) => this.deactiveRouteAndItsChildren(v, outletMap)); } private activateChildRoutes( futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute>, outletMap: RouterOutletMap): void { const prevChildren: {[key: string]: any} = nodeChildrenAsMap(currNode); futureNode.children.forEach( c => { this.activateRoutes(c, prevChildren[c.value.outlet], outletMap); }); } deactivateRoutes( futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute>, parentOutletMap: RouterOutletMap): void { const future = futureNode.value; const curr = currNode ? currNode.value : null; // reusing the node if (future === curr) { // If we have a normal route, we need to go through an outlet. if (future.component) { const outlet = getOutlet(parentOutletMap, future); this.deactivateChildRoutes(futureNode, currNode, outlet.outletMap); // if we have a componentless route, we recurse but keep the same outlet map. } else { this.deactivateChildRoutes(futureNode, currNode, parentOutletMap); } } else { if (curr) { this.deactiveRouteAndItsChildren(currNode, parentOutletMap); } } } activateRoutes( futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute>, parentOutletMap: RouterOutletMap): void { const future = futureNode.value; const curr = currNode ? currNode.value : null; // reusing the node if (future === curr) { // advance the route to push the parameters advanceActivatedRoute(future); // If we have a normal route, we need to go through an outlet. if (future.component) { const outlet = getOutlet(parentOutletMap, future); this.activateChildRoutes(futureNode, currNode, outlet.outletMap); // if we have a componentless route, we recurse but keep the same outlet map. } else { this.activateChildRoutes(futureNode, currNode, parentOutletMap); } } else { // if we have a normal route, we need to advance the route // and place the component into the outlet. After that recurse. if (future.component) { advanceActivatedRoute(future); const outlet = getOutlet(parentOutletMap, futureNode.value); if (this.routeReuseStrategy.shouldAttach(future.snapshot)) { const stored = (<DetachedRouteHandleInternal>this.routeReuseStrategy.retrieve(future.snapshot)); this.routeReuseStrategy.store(future.snapshot, null); outlet.attach(stored.componentRef, stored.route.value); advanceActivatedRouteNodeAndItsChildren(stored.route); } else { const outletMap = new RouterOutletMap(); this.placeComponentIntoOutlet(outletMap, future, outlet); this.activateChildRoutes(futureNode, null, outletMap); } // if we have a componentless route, we recurse but keep the same outlet map. } else { advanceActivatedRoute(future); this.activateChildRoutes(futureNode, null, parentOutletMap); } } } private placeComponentIntoOutlet( outletMap: RouterOutletMap, future: ActivatedRoute, outlet: RouterOutlet): void { const resolved = <any[]>[{provide: ActivatedRoute, useValue: future}, { provide: RouterOutletMap, useValue: outletMap }]; const config = parentLoadedConfig(future.snapshot); let resolver: ComponentFactoryResolver = null; let injector: Injector = null; if (config) { injector = config.injectorFactory(outlet.locationInjector); resolver = config.factoryResolver; resolved.push({provide: ComponentFactoryResolver, useValue: resolver}); } else { injector = outlet.locationInjector; resolver = outlet.locationFactoryResolver; } outlet.activate(future, resolver, injector, ReflectiveInjector.resolve(resolved), outletMap); } private deactiveRouteAndItsChildren( route: TreeNode<ActivatedRoute>, parentOutletMap: RouterOutletMap): void { if (this.routeReuseStrategy.shouldDetach(route.value.snapshot)) { this.detachAndStoreRouteSubtree(route, parentOutletMap); } else { this.deactiveRouteAndOutlet(route, parentOutletMap); } } private detachAndStoreRouteSubtree( route: TreeNode<ActivatedRoute>, parentOutletMap: RouterOutletMap): void { const outlet = getOutlet(parentOutletMap, route.value); const componentRef = outlet.detach(); this.routeReuseStrategy.store(route.value.snapshot, {componentRef, route}); } private deactiveRouteAndOutlet(route: TreeNode<ActivatedRoute>, parentOutletMap: RouterOutletMap): void { const prevChildren: {[key: string]: any} = nodeChildrenAsMap(route); let outlet: RouterOutlet = null; // getOutlet throws when cannot find the right outlet, // which can happen if an outlet was in an NgIf and was removed try { outlet = getOutlet(parentOutletMap, route.value); } catch (e) { return; } const childOutletMap = outlet.outletMap; forEach(prevChildren, (v: any, k: string) => { if (route.value.component) { this.deactiveRouteAndItsChildren(v, childOutletMap); } else { this.deactiveRouteAndItsChildren(v, parentOutletMap); } }); if (outlet && outlet.isActivated) { outlet.deactivate(); } } } function advanceActivatedRouteNodeAndItsChildren(node: TreeNode<ActivatedRoute>): void { advanceActivatedRoute(node.value); node.children.forEach(advanceActivatedRouteNodeAndItsChildren); } function parentLoadedConfig(snapshot: ActivatedRouteSnapshot): LoadedRouterConfig { let s = snapshot.parent; while (s) { const c: any = s._routeConfig; if (c && c._loadedConfig) return c._loadedConfig; if (c && c.component) return null; s = s.parent; } return null; } function closestLoadedConfig(snapshot: ActivatedRouteSnapshot): LoadedRouterConfig { if (!snapshot) return null; let s = snapshot.parent; while (s) { const c: any = s._routeConfig; if (c && c._loadedConfig) return c._loadedConfig; s = s.parent; } return null; } function nodeChildrenAsMap(node: TreeNode<any>) { return node ? node.children.reduce((m: any, c: TreeNode<any>) => { m[c.value.outlet] = c; return m; }, {}) : {}; } function getOutlet(outletMap: RouterOutletMap, route: ActivatedRoute): RouterOutlet { const outlet = outletMap._outlets[route.outlet]; if (!outlet) { const componentName = (<any>route.component).name; if (route.outlet === PRIMARY_OUTLET) { throw new Error(`Cannot find primary outlet to load '${componentName}'`); } else { throw new Error(`Cannot find the outlet ${route.outlet} to load '${componentName}'`); } } return outlet; } function validateCommands(commands: string[]): void { for (let i = 0; i < commands.length; i++) { const cmd = commands[i]; if (cmd == null) { throw new Error(`The requested path contains ${cmd} segment at index ${i}`); } } }
modules/@angular/router/src/router.ts
1
https://github.com/angular/angular/commit/47d41d492b650f6056926defdec08f62eb8dcd88
[ 0.0010083602974191308, 0.00020452504395507276, 0.00016348417557310313, 0.00017216596461366862, 0.00010075787577079609 ]
{ "id": 2, "code_window": [ "\n", "@Component({selector: 'root-cmp', template: `<router-outlet></router-outlet>`})\n", "class RootCmp {\n", "}\n", "\n", "@Component({\n", " selector: 'root-cmp',\n", " template:\n", " `primary [<router-outlet></router-outlet>] right [<router-outlet name=\"right\"></router-outlet>]`\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "@Component({selector: 'root-cmp-on-init', template: `<router-outlet></router-outlet>`})\n", "class RootCmpWithOnInit {\n", " constructor(private router: Router) {}\n", "\n", " ngOnInit(): void { this.router.navigate(['one']); }\n", "}\n", "\n" ], "file_path": "modules/@angular/router/test/integration.spec.ts", "type": "add", "edit_start_line_idx": 2039 }
/** * @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 {AUTO_STYLE, CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA, SchemaMetadata, SecurityContext} from '@angular/core'; import {CompilerInjectable} from '../injectable'; import {dashCaseToCamelCase} from '../util'; import {SECURITY_SCHEMA} from './dom_security_schema'; import {ElementSchemaRegistry} from './element_schema_registry'; const BOOLEAN = 'boolean'; const NUMBER = 'number'; const STRING = 'string'; const OBJECT = 'object'; /** * This array represents the DOM schema. It encodes inheritance, properties, and events. * * ## Overview * * Each line represents one kind of element. The `element_inheritance` and properties are joined * using `element_inheritance|properties` syntax. * * ## Element Inheritance * * The `element_inheritance` can be further subdivided as `element1,element2,...^parentElement`. * Here the individual elements are separated by `,` (commas). Every element in the list * has identical properties. * * An `element` may inherit additional properties from `parentElement` If no `^parentElement` is * specified then `""` (blank) element is assumed. * * NOTE: The blank element inherits from root `[Element]` element, the super element of all * elements. * * NOTE an element prefix such as `:svg:` has no special meaning to the schema. * * ## Properties * * Each element has a set of properties separated by `,` (commas). Each property can be prefixed * by a special character designating its type: * * - (no prefix): property is a string. * - `*`: property represents an event. * - `!`: property is a boolean. * - `#`: property is a number. * - `%`: property is an object. * * ## Query * * The class creates an internal squas representation which allows to easily answer the query of * if a given property exist on a given element. * * NOTE: We don't yet support querying for types or events. * NOTE: This schema is auto extracted from `schema_extractor.ts` located in the test folder, * see dom_element_schema_registry_spec.ts */ // ================================================================================================= // ================================================================================================= // =========== S T O P - S T O P - S T O P - S T O P - S T O P - S T O P =========== // ================================================================================================= // ================================================================================================= // // DO NOT EDIT THIS DOM SCHEMA WITHOUT A SECURITY REVIEW! // // Newly added properties must be security reviewed and assigned an appropriate SecurityContext in // dom_security_schema.ts. Reach out to mprobst & rjamet for details. // // ================================================================================================= const SCHEMA: string[] = [ '[Element]|textContent,%classList,className,id,innerHTML,*beforecopy,*beforecut,*beforepaste,*copy,*cut,*paste,*search,*selectstart,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerHTML,#scrollLeft,#scrollTop', '[HTMLElement]^[Element]|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*beforecopy,*beforecut,*beforepaste,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*copy,*cuechange,*cut,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*message,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*paste,*pause,*play,*playing,*progress,*ratechange,*reset,*resize,*scroll,*search,*seeked,*seeking,*select,*selectstart,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerText,!spellcheck,%style,#tabIndex,title,!translate', 'abbr,address,article,aside,b,bdi,bdo,cite,code,dd,dfn,dt,em,figcaption,figure,footer,header,i,kbd,main,mark,nav,noscript,rb,rp,rt,rtc,ruby,s,samp,section,small,strong,sub,sup,u,var,wbr^[HTMLElement]|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*beforecopy,*beforecut,*beforepaste,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*copy,*cuechange,*cut,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*message,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*paste,*pause,*play,*playing,*progress,*ratechange,*reset,*resize,*scroll,*search,*seeked,*seeking,*select,*selectstart,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerText,!spellcheck,%style,#tabIndex,title,!translate', 'media^[HTMLElement]|!autoplay,!controls,%crossOrigin,#currentTime,!defaultMuted,#defaultPlaybackRate,!disableRemotePlayback,!loop,!muted,*encrypted,#playbackRate,preload,src,%srcObject,#volume', ':svg:^[HTMLElement]|*abort,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,%style,#tabIndex', ':svg:graphics^:svg:|', ':svg:animation^:svg:|*begin,*end,*repeat', ':svg:geometry^:svg:|', ':svg:componentTransferFunction^:svg:|', ':svg:gradient^:svg:|', ':svg:textContent^:svg:graphics|', ':svg:textPositioning^:svg:textContent|', 'a^[HTMLElement]|charset,coords,download,hash,host,hostname,href,hreflang,name,password,pathname,ping,port,protocol,referrerPolicy,rel,rev,search,shape,target,text,type,username', 'area^[HTMLElement]|alt,coords,hash,host,hostname,href,!noHref,password,pathname,ping,port,protocol,referrerPolicy,search,shape,target,username', 'audio^media|', 'br^[HTMLElement]|clear', 'base^[HTMLElement]|href,target', 'body^[HTMLElement]|aLink,background,bgColor,link,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,text,vLink', 'button^[HTMLElement]|!autofocus,!disabled,formAction,formEnctype,formMethod,!formNoValidate,formTarget,name,type,value', 'canvas^[HTMLElement]|#height,#width', 'content^[HTMLElement]|select', 'dl^[HTMLElement]|!compact', 'datalist^[HTMLElement]|', 'details^[HTMLElement]|!open', 'dialog^[HTMLElement]|!open,returnValue', 'dir^[HTMLElement]|!compact', 'div^[HTMLElement]|align', 'embed^[HTMLElement]|align,height,name,src,type,width', 'fieldset^[HTMLElement]|!disabled,name', 'font^[HTMLElement]|color,face,size', 'form^[HTMLElement]|acceptCharset,action,autocomplete,encoding,enctype,method,name,!noValidate,target', 'frame^[HTMLElement]|frameBorder,longDesc,marginHeight,marginWidth,name,!noResize,scrolling,src', 'frameset^[HTMLElement]|cols,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,rows', 'hr^[HTMLElement]|align,color,!noShade,size,width', 'head^[HTMLElement]|', 'h1,h2,h3,h4,h5,h6^[HTMLElement]|align', 'html^[HTMLElement]|version', 'iframe^[HTMLElement]|align,!allowFullscreen,frameBorder,height,longDesc,marginHeight,marginWidth,name,referrerPolicy,%sandbox,scrolling,src,srcdoc,width', 'img^[HTMLElement]|align,alt,border,%crossOrigin,#height,#hspace,!isMap,longDesc,lowsrc,name,referrerPolicy,sizes,src,srcset,useMap,#vspace,#width', 'input^[HTMLElement]|accept,align,alt,autocapitalize,autocomplete,!autofocus,!checked,!defaultChecked,defaultValue,dirName,!disabled,%files,formAction,formEnctype,formMethod,!formNoValidate,formTarget,#height,!incremental,!indeterminate,max,#maxLength,min,#minLength,!multiple,name,pattern,placeholder,!readOnly,!required,selectionDirection,#selectionEnd,#selectionStart,#size,src,step,type,useMap,value,%valueAsDate,#valueAsNumber,#width', 'keygen^[HTMLElement]|!autofocus,challenge,!disabled,keytype,name', 'li^[HTMLElement]|type,#value', 'label^[HTMLElement]|htmlFor', 'legend^[HTMLElement]|align', 'link^[HTMLElement]|as,charset,%crossOrigin,!disabled,href,hreflang,integrity,media,rel,%relList,rev,%sizes,target,type', 'map^[HTMLElement]|name', 'marquee^[HTMLElement]|behavior,bgColor,direction,height,#hspace,#loop,#scrollAmount,#scrollDelay,!trueSpeed,#vspace,width', 'menu^[HTMLElement]|!compact', 'meta^[HTMLElement]|content,httpEquiv,name,scheme', 'meter^[HTMLElement]|#high,#low,#max,#min,#optimum,#value', 'ins,del^[HTMLElement]|cite,dateTime', 'ol^[HTMLElement]|!compact,!reversed,#start,type', 'object^[HTMLElement]|align,archive,border,code,codeBase,codeType,data,!declare,height,#hspace,name,standby,type,useMap,#vspace,width', 'optgroup^[HTMLElement]|!disabled,label', 'option^[HTMLElement]|!defaultSelected,!disabled,label,!selected,text,value', 'output^[HTMLElement]|defaultValue,%htmlFor,name,value', 'p^[HTMLElement]|align', 'param^[HTMLElement]|name,type,value,valueType', 'picture^[HTMLElement]|', 'pre^[HTMLElement]|#width', 'progress^[HTMLElement]|#max,#value', 'q,blockquote,cite^[HTMLElement]|', 'script^[HTMLElement]|!async,charset,%crossOrigin,!defer,event,htmlFor,integrity,src,text,type', 'select^[HTMLElement]|!autofocus,!disabled,#length,!multiple,name,!required,#selectedIndex,#size,value', 'shadow^[HTMLElement]|', 'source^[HTMLElement]|media,sizes,src,srcset,type', 'span^[HTMLElement]|', 'style^[HTMLElement]|!disabled,media,type', 'caption^[HTMLElement]|align', 'th,td^[HTMLElement]|abbr,align,axis,bgColor,ch,chOff,#colSpan,headers,height,!noWrap,#rowSpan,scope,vAlign,width', 'col,colgroup^[HTMLElement]|align,ch,chOff,#span,vAlign,width', 'table^[HTMLElement]|align,bgColor,border,%caption,cellPadding,cellSpacing,frame,rules,summary,%tFoot,%tHead,width', 'tr^[HTMLElement]|align,bgColor,ch,chOff,vAlign', 'tfoot,thead,tbody^[HTMLElement]|align,ch,chOff,vAlign', 'template^[HTMLElement]|', 'textarea^[HTMLElement]|autocapitalize,!autofocus,#cols,defaultValue,dirName,!disabled,#maxLength,#minLength,name,placeholder,!readOnly,!required,#rows,selectionDirection,#selectionEnd,#selectionStart,value,wrap', 'title^[HTMLElement]|text', 'track^[HTMLElement]|!default,kind,label,src,srclang', 'ul^[HTMLElement]|!compact,type', 'unknown^[HTMLElement]|', 'video^media|#height,poster,#width', ':svg:a^:svg:graphics|', ':svg:animate^:svg:animation|', ':svg:animateMotion^:svg:animation|', ':svg:animateTransform^:svg:animation|', ':svg:circle^:svg:geometry|', ':svg:clipPath^:svg:graphics|', ':svg:cursor^:svg:|', ':svg:defs^:svg:graphics|', ':svg:desc^:svg:|', ':svg:discard^:svg:|', ':svg:ellipse^:svg:geometry|', ':svg:feBlend^:svg:|', ':svg:feColorMatrix^:svg:|', ':svg:feComponentTransfer^:svg:|', ':svg:feComposite^:svg:|', ':svg:feConvolveMatrix^:svg:|', ':svg:feDiffuseLighting^:svg:|', ':svg:feDisplacementMap^:svg:|', ':svg:feDistantLight^:svg:|', ':svg:feDropShadow^:svg:|', ':svg:feFlood^:svg:|', ':svg:feFuncA^:svg:componentTransferFunction|', ':svg:feFuncB^:svg:componentTransferFunction|', ':svg:feFuncG^:svg:componentTransferFunction|', ':svg:feFuncR^:svg:componentTransferFunction|', ':svg:feGaussianBlur^:svg:|', ':svg:feImage^:svg:|', ':svg:feMerge^:svg:|', ':svg:feMergeNode^:svg:|', ':svg:feMorphology^:svg:|', ':svg:feOffset^:svg:|', ':svg:fePointLight^:svg:|', ':svg:feSpecularLighting^:svg:|', ':svg:feSpotLight^:svg:|', ':svg:feTile^:svg:|', ':svg:feTurbulence^:svg:|', ':svg:filter^:svg:|', ':svg:foreignObject^:svg:graphics|', ':svg:g^:svg:graphics|', ':svg:image^:svg:graphics|', ':svg:line^:svg:geometry|', ':svg:linearGradient^:svg:gradient|', ':svg:mpath^:svg:|', ':svg:marker^:svg:|', ':svg:mask^:svg:|', ':svg:metadata^:svg:|', ':svg:path^:svg:geometry|', ':svg:pattern^:svg:|', ':svg:polygon^:svg:geometry|', ':svg:polyline^:svg:geometry|', ':svg:radialGradient^:svg:gradient|', ':svg:rect^:svg:geometry|', ':svg:svg^:svg:graphics|#currentScale,#zoomAndPan', ':svg:script^:svg:|type', ':svg:set^:svg:animation|', ':svg:stop^:svg:|', ':svg:style^:svg:|!disabled,media,title,type', ':svg:switch^:svg:graphics|', ':svg:symbol^:svg:|', ':svg:tspan^:svg:textPositioning|', ':svg:text^:svg:textPositioning|', ':svg:textPath^:svg:textContent|', ':svg:title^:svg:|', ':svg:use^:svg:graphics|', ':svg:view^:svg:|#zoomAndPan', 'data^[HTMLElement]|value', 'menuitem^[HTMLElement]|type,label,icon,!disabled,!checked,radiogroup,!default', 'summary^[HTMLElement]|', 'time^[HTMLElement]|dateTime', ]; const _ATTR_TO_PROP: {[name: string]: string} = { 'class': 'className', 'for': 'htmlFor', 'formaction': 'formAction', 'innerHtml': 'innerHTML', 'readonly': 'readOnly', 'tabindex': 'tabIndex', }; @CompilerInjectable() export class DomElementSchemaRegistry extends ElementSchemaRegistry { private _schema: {[element: string]: {[property: string]: string}} = {}; constructor() { super(); SCHEMA.forEach(encodedType => { const type: {[property: string]: string} = {}; const [strType, strProperties] = encodedType.split('|'); const properties = strProperties.split(','); const [typeNames, superName] = strType.split('^'); typeNames.split(',').forEach(tag => this._schema[tag.toLowerCase()] = type); const superType = superName && this._schema[superName.toLowerCase()]; if (superType) { Object.keys(superType).forEach((prop: string) => { type[prop] = superType[prop]; }); } properties.forEach((property: string) => { if (property.length > 0) { switch (property[0]) { case '*': // We don't yet support events. // If ever allowing to bind to events, GO THROUGH A SECURITY REVIEW, allowing events // will // almost certainly introduce bad XSS vulnerabilities. // type[property.substring(1)] = EVENT; break; case '!': type[property.substring(1)] = BOOLEAN; break; case '#': type[property.substring(1)] = NUMBER; break; case '%': type[property.substring(1)] = OBJECT; break; default: type[property] = STRING; } } }); }); } hasProperty(tagName: string, propName: string, schemaMetas: SchemaMetadata[]): boolean { if (schemaMetas.some((schema) => schema.name === NO_ERRORS_SCHEMA.name)) { return true; } if (tagName.indexOf('-') > -1) { if (tagName === 'ng-container' || tagName === 'ng-content') { return false; } if (schemaMetas.some((schema) => schema.name === CUSTOM_ELEMENTS_SCHEMA.name)) { // Can't tell now as we don't know which properties a custom element will get // once it is instantiated return true; } } const elementProperties = this._schema[tagName.toLowerCase()] || this._schema['unknown']; return !!elementProperties[propName]; } hasElement(tagName: string, schemaMetas: SchemaMetadata[]): boolean { if (schemaMetas.some((schema) => schema.name === NO_ERRORS_SCHEMA.name)) { return true; } if (tagName.indexOf('-') > -1) { if (tagName === 'ng-container' || tagName === 'ng-content') { return true; } if (schemaMetas.some((schema) => schema.name === CUSTOM_ELEMENTS_SCHEMA.name)) { // Allow any custom elements return true; } } return !!this._schema[tagName.toLowerCase()]; } /** * securityContext returns the security context for the given property on the given DOM tag. * * Tag and property name are statically known and cannot change at runtime, i.e. it is not * possible to bind a value into a changing attribute or tag name. * * The filtering is white list based. All attributes in the schema above are assumed to have the * 'NONE' security context, i.e. that they are safe inert string values. Only specific well known * attack vectors are assigned their appropriate context. */ securityContext(tagName: string, propName: string, isAttribute: boolean): SecurityContext { if (isAttribute) { // NB: For security purposes, use the mapped property name, not the attribute name. propName = this.getMappedPropName(propName); } // Make sure comparisons are case insensitive, so that case differences between attribute and // property names do not have a security impact. tagName = tagName.toLowerCase(); propName = propName.toLowerCase(); let ctx = SECURITY_SCHEMA[tagName + '|' + propName]; if (ctx) { return ctx; } ctx = SECURITY_SCHEMA['*|' + propName]; return ctx ? ctx : SecurityContext.NONE; } getMappedPropName(propName: string): string { return _ATTR_TO_PROP[propName] || propName; } getDefaultComponentElementName(): string { return 'ng-component'; } validateProperty(name: string): {error: boolean, msg?: string} { if (name.toLowerCase().startsWith('on')) { const msg = `Binding to event property '${name}' is disallowed for security reasons, ` + `please use (${name.slice(2)})=...` + `\nIf '${name}' is a directive input, make sure the directive is imported by the` + ` current module.`; return {error: true, msg: msg}; } else { return {error: false}; } } validateAttribute(name: string): {error: boolean, msg?: string} { if (name.toLowerCase().startsWith('on')) { const msg = `Binding to event attribute '${name}' is disallowed for security reasons, ` + `please use (${name.slice(2)})=...`; return {error: true, msg: msg}; } else { return {error: false}; } } allKnownElementNames(): string[] { return Object.keys(this._schema); } normalizeAnimationStyleProperty(propName: string): string { return dashCaseToCamelCase(propName); } normalizeAnimationStyleValue(camelCaseProp: string, userProvidedProp: string, val: string|number): {error: string, value: string} { let unit: string = ''; const strVal = val.toString().trim(); let errorMsg: string = null; if (_isPixelDimensionStyle(camelCaseProp) && val !== 0 && val !== '0') { if (typeof val === 'number') { unit = 'px'; } else { const valAndSuffixMatch = val.match(/^[+-]?[\d\.]+([a-z]*)$/); if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) { errorMsg = `Please provide a CSS unit value for ${userProvidedProp}:${val}`; } } } return {error: errorMsg, value: strVal + unit}; } } function _isPixelDimensionStyle(prop: string): boolean { switch (prop) { case 'width': case 'height': case 'minWidth': case 'minHeight': case 'maxWidth': case 'maxHeight': case 'left': case 'top': case 'bottom': case 'right': case 'fontSize': case 'outlineWidth': case 'outlineOffset': case 'paddingTop': case 'paddingLeft': case 'paddingBottom': case 'paddingRight': case 'marginTop': case 'marginLeft': case 'marginBottom': case 'marginRight': case 'borderRadius': case 'borderWidth': case 'borderTopWidth': case 'borderLeftWidth': case 'borderRightWidth': case 'borderBottomWidth': case 'textIndent': return true; default: return false; } }
modules/@angular/compiler/src/schema/dom_element_schema_registry.ts
0
https://github.com/angular/angular/commit/47d41d492b650f6056926defdec08f62eb8dcd88
[ 0.00018043338786810637, 0.0001718220446491614, 0.00016199990932364017, 0.00017270538955926895, 0.000004395840278448304 ]
{ "id": 2, "code_window": [ "\n", "@Component({selector: 'root-cmp', template: `<router-outlet></router-outlet>`})\n", "class RootCmp {\n", "}\n", "\n", "@Component({\n", " selector: 'root-cmp',\n", " template:\n", " `primary [<router-outlet></router-outlet>] right [<router-outlet name=\"right\"></router-outlet>]`\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "@Component({selector: 'root-cmp-on-init', template: `<router-outlet></router-outlet>`})\n", "class RootCmpWithOnInit {\n", " constructor(private router: Router) {}\n", "\n", " ngOnInit(): void { this.router.navigate(['one']); }\n", "}\n", "\n" ], "file_path": "modules/@angular/router/test/integration.spec.ts", "type": "add", "edit_start_line_idx": 2039 }
/** @experimental */ export declare const platformWorkerAppDynamic: (extraProviders?: Provider[]) => PlatformRef; /** @stable */ export declare const VERSION: Version;
tools/public_api_guard/platform-webworker-dynamic/index.d.ts
0
https://github.com/angular/angular/commit/47d41d492b650f6056926defdec08f62eb8dcd88
[ 0.0001736727572279051, 0.0001736727572279051, 0.0001736727572279051, 0.0001736727572279051, 0 ]
{ "id": 2, "code_window": [ "\n", "@Component({selector: 'root-cmp', template: `<router-outlet></router-outlet>`})\n", "class RootCmp {\n", "}\n", "\n", "@Component({\n", " selector: 'root-cmp',\n", " template:\n", " `primary [<router-outlet></router-outlet>] right [<router-outlet name=\"right\"></router-outlet>]`\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "@Component({selector: 'root-cmp-on-init', template: `<router-outlet></router-outlet>`})\n", "class RootCmpWithOnInit {\n", " constructor(private router: Router) {}\n", "\n", " ngOnInit(): void { this.router.navigate(['one']); }\n", "}\n", "\n" ], "file_path": "modules/@angular/router/test/integration.spec.ts", "type": "add", "edit_start_line_idx": 2039 }
/** * @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 */ /*global jasmine, __karma__, window*/ Error.stackTraceLimit = 5; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; __karma__.loaded = function() {}; function isJsFile(path) { return path.slice(-3) == '.js'; } function isSpecFile(path) { return path.slice(-7) == 'spec.js'; } function isBuiltFile(path) { var builtPath = '/base/dist/'; return isJsFile(path) && (path.substr(0, builtPath.length) == builtPath); } var allSpecFiles = Object.keys(window.__karma__.files).filter(isSpecFile).filter(isBuiltFile); // Load our SystemJS configuration. System.config({ baseURL: '/base', }); System.config({ map: {'rxjs': 'node_modules/rxjs', '@angular': 'dist/all/@angular'}, packages: { '@angular/core/testing': {main: 'index.js', defaultExtension: 'js'}, '@angular/core': {main: 'index.js', defaultExtension: 'js'}, '@angular/compiler/testing': {main: 'index.js', defaultExtension: 'js'}, '@angular/compiler': {main: 'index.js', defaultExtension: 'js'}, '@angular/common/testing': {main: 'index.js', defaultExtension: 'js'}, '@angular/common': {main: 'index.js', defaultExtension: 'js'}, '@angular/platform-browser/testing': {main: 'index.js', defaultExtension: 'js'}, '@angular/platform-browser': {main: 'index.js', defaultExtension: 'js'}, '@angular/platform-browser-dynamic/testing': {main: 'index.js', defaultExtension: 'js'}, '@angular/platform-browser-dynamic': {main: 'index.js', defaultExtension: 'js'}, '@angular/router/testing': {main: 'index.js', defaultExtension: 'js'}, '@angular/router': {main: 'index.js', defaultExtension: 'js'}, 'rxjs': {main: 'Rx.js', defaultExtension: 'js'}, } }); Promise .all([ System.import('@angular/core/testing'), System.import('@angular/platform-browser-dynamic/testing') ]) .then(function(providers) { var testing = providers[0]; var testingBrowser = providers[1]; testing.TestBed.initTestEnvironment( testingBrowser.BrowserDynamicTestingModule, testingBrowser.platformBrowserDynamicTesting()); }) .then(function() { // Finally, load all spec files. // This will run the tests directly. return Promise.all( allSpecFiles.map(function(moduleName) { return System.import(moduleName); })); }) .then(__karma__.start, (v) => console.error(v));
modules/@angular/router/karma-test-shim.js
0
https://github.com/angular/angular/commit/47d41d492b650f6056926defdec08f62eb8dcd88
[ 0.00017629456124268472, 0.0001736811245791614, 0.00016716525715310127, 0.00017458850925322622, 0.0000027789324121840764 ]
{ "id": 0, "code_window": [ "\n", "\tconstructor() {\n", "\t\tsuper({\n", "\t\t\tid: 'workbench.action.logStorage',\n", "\t\t\ttitle: { value: nls.localize({ key: 'logStorage', comment: ['A developer only action to log the contents of the storage for the current window.'] }, \"Log Storage Database Contents\"), original: 'Developer: Log Storage Database Contents' },\n", "\t\t\tcategory: developerCategory,\n", "\t\t\tf1: true\n", "\t\t});\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\ttitle: { value: nls.localize({ key: 'logStorage', comment: ['A developer only action to log the contents of the storage for the current window.'] }, \"Log Storage Database Contents\"), original: 'Log Storage Database Contents' },\n" ], "file_path": "src/vs/workbench/browser/actions/developerActions.ts", "type": "replace", "edit_start_line_idx": 210 }
/*--------------------------------------------------------------------------------------------- * 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 { Disposable } from 'vs/base/common/lifecycle'; import { Registry } from 'vs/platform/registry/common/platform'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { MenuRegistry, MenuId, SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { ProblemMatcherRegistry } from 'vs/workbench/contrib/tasks/common/problemMatcher'; import { IProgressService, ProgressLocation } from 'vs/platform/progress/common/progress'; import * as jsonContributionRegistry from 'vs/platform/jsonschemas/common/jsonContributionRegistry'; import { IJSONSchema } from 'vs/base/common/jsonSchema'; import { StatusbarAlignment, IStatusbarService, IStatusbarEntryAccessor, IStatusbarEntry } from 'vs/workbench/services/statusbar/common/statusbar'; import { IOutputChannelRegistry, Extensions as OutputExt } from 'vs/workbench/services/output/common/output'; import { TaskEvent, TaskEventKind, TaskGroup, TASK_RUNNING_STATE } from 'vs/workbench/contrib/tasks/common/tasks'; import { ITaskService } from 'vs/workbench/contrib/tasks/common/taskService'; import { Extensions as WorkbenchExtensions, IWorkbenchContributionsRegistry, IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { IWorkbenchActionRegistry, Extensions as ActionExtensions } from 'vs/workbench/common/actions'; import { RunAutomaticTasks, ManageAutomaticTaskRunning } from 'vs/workbench/contrib/tasks/browser/runAutomaticTasks'; import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { KeyMod, KeyCode } from 'vs/base/common/keyCodes'; import schemaVersion1 from '../common/jsonSchema_v1'; import schemaVersion2, { updateProblemMatchers } from '../common/jsonSchema_v2'; import { AbstractTaskService, ConfigureTaskAction } from 'vs/workbench/contrib/tasks/browser/abstractTaskService'; import { tasksSchemaId } from 'vs/workbench/services/configuration/common/configuration'; import { Extensions as ConfigurationExtensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry'; import { WorkbenchStateContext } from 'vs/workbench/browser/contextkeys'; import { IQuickAccessRegistry, Extensions as QuickAccessExtensions } from 'vs/platform/quickinput/common/quickAccess'; import { TasksQuickAccessProvider } from 'vs/workbench/contrib/tasks/browser/tasksQuickAccess'; let tasksCategory = nls.localize('tasksCategory', "Tasks"); const workbenchRegistry = Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench); workbenchRegistry.registerWorkbenchContribution(RunAutomaticTasks, LifecyclePhase.Eventually); const actionRegistry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.from(ManageAutomaticTaskRunning), 'Tasks: Manage Automatic Tasks in Folder', tasksCategory); export class TaskStatusBarContributions extends Disposable implements IWorkbenchContribution { private runningTasksStatusItem: IStatusbarEntryAccessor | undefined; private activeTasksCount: number = 0; constructor( @ITaskService private readonly taskService: ITaskService, @IStatusbarService private readonly statusbarService: IStatusbarService, @IProgressService private readonly progressService: IProgressService ) { super(); this.registerListeners(); } private registerListeners(): void { let promise: Promise<void> | undefined = undefined; let resolver: (value?: void | Thenable<void>) => void; this.taskService.onDidStateChange(event => { if (event.kind === TaskEventKind.Changed) { this.updateRunningTasksStatus(); } if (!this.ignoreEventForUpdateRunningTasksCount(event)) { switch (event.kind) { case TaskEventKind.Active: this.activeTasksCount++; if (this.activeTasksCount === 1) { if (!promise) { promise = new Promise<void>((resolve) => { resolver = resolve; }); } } break; case TaskEventKind.Inactive: // Since the exiting of the sub process is communicated async we can't order inactive and terminate events. // So try to treat them accordingly. if (this.activeTasksCount > 0) { this.activeTasksCount--; if (this.activeTasksCount === 0) { if (promise && resolver!) { resolver!(); } } } break; case TaskEventKind.Terminated: if (this.activeTasksCount !== 0) { this.activeTasksCount = 0; if (promise && resolver!) { resolver!(); } } break; } } if (promise && (event.kind === TaskEventKind.Active) && (this.activeTasksCount === 1)) { this.progressService.withProgress({ location: ProgressLocation.Window, command: 'workbench.action.tasks.showTasks' }, progress => { progress.report({ message: nls.localize('building', 'Building...') }); return promise!; }).then(() => { promise = undefined; }); } }); } private async updateRunningTasksStatus(): Promise<void> { const tasks = await this.taskService.getActiveTasks(); if (tasks.length === 0) { if (this.runningTasksStatusItem) { this.runningTasksStatusItem.dispose(); this.runningTasksStatusItem = undefined; } } else { const itemProps: IStatusbarEntry = { text: `$(tools) ${tasks.length}`, ariaLabel: nls.localize('numberOfRunningTasks', "{0} running tasks", tasks.length), tooltip: nls.localize('runningTasks', "Show Running Tasks"), command: 'workbench.action.tasks.showTasks', }; if (!this.runningTasksStatusItem) { this.runningTasksStatusItem = this.statusbarService.addEntry(itemProps, 'status.runningTasks', nls.localize('status.runningTasks', "Running Tasks"), StatusbarAlignment.LEFT, 49 /* Medium Priority, next to Markers */); } else { this.runningTasksStatusItem.update(itemProps); } } } private ignoreEventForUpdateRunningTasksCount(event: TaskEvent): boolean { if (!this.taskService.inTerminal()) { return false; } if (event.group !== TaskGroup.Build) { return true; } if (!event.__task) { return false; } return event.__task.configurationProperties.problemMatchers === undefined || event.__task.configurationProperties.problemMatchers.length === 0; } } workbenchRegistry.registerWorkbenchContribution(TaskStatusBarContributions, LifecyclePhase.Restored); MenuRegistry.appendMenuItem(MenuId.MenubarTerminalMenu, { group: '2_run', command: { id: 'workbench.action.tasks.runTask', title: nls.localize({ key: 'miRunTask', comment: ['&& denotes a mnemonic'] }, "&&Run Task...") }, order: 1 }); MenuRegistry.appendMenuItem(MenuId.MenubarTerminalMenu, { group: '2_run', command: { id: 'workbench.action.tasks.build', title: nls.localize({ key: 'miBuildTask', comment: ['&& denotes a mnemonic'] }, "Run &&Build Task...") }, order: 2 }); // Manage Tasks MenuRegistry.appendMenuItem(MenuId.MenubarTerminalMenu, { group: '3_manage', command: { precondition: TASK_RUNNING_STATE, id: 'workbench.action.tasks.showTasks', title: nls.localize({ key: 'miRunningTask', comment: ['&& denotes a mnemonic'] }, "Show Runnin&&g Tasks...") }, order: 1 }); MenuRegistry.appendMenuItem(MenuId.MenubarTerminalMenu, { group: '3_manage', command: { precondition: TASK_RUNNING_STATE, id: 'workbench.action.tasks.restartTask', title: nls.localize({ key: 'miRestartTask', comment: ['&& denotes a mnemonic'] }, "R&&estart Running Task...") }, order: 2 }); MenuRegistry.appendMenuItem(MenuId.MenubarTerminalMenu, { group: '3_manage', command: { precondition: TASK_RUNNING_STATE, id: 'workbench.action.tasks.terminate', title: nls.localize({ key: 'miTerminateTask', comment: ['&& denotes a mnemonic'] }, "&&Terminate Task...") }, order: 3 }); // Configure Tasks MenuRegistry.appendMenuItem(MenuId.MenubarTerminalMenu, { group: '4_configure', command: { id: 'workbench.action.tasks.configureTaskRunner', title: nls.localize({ key: 'miConfigureTask', comment: ['&& denotes a mnemonic'] }, "&&Configure Tasks...") }, order: 1 }); MenuRegistry.appendMenuItem(MenuId.MenubarTerminalMenu, { group: '4_configure', command: { id: 'workbench.action.tasks.configureDefaultBuildTask', title: nls.localize({ key: 'miConfigureBuildTask', comment: ['&& denotes a mnemonic'] }, "Configure De&&fault Build Task...") }, order: 2 }); MenuRegistry.appendMenuItem(MenuId.CommandPalette, ({ command: { id: 'workbench.action.tasks.openWorkspaceFileTasks', title: nls.localize('workbench.action.tasks.openWorkspaceFileTasks', "Open Workspace Tasks"), category: tasksCategory }, when: WorkbenchStateContext.isEqualTo('workspace') })); MenuRegistry.addCommand({ id: ConfigureTaskAction.ID, title: { value: ConfigureTaskAction.TEXT, original: 'Configure Task' }, category: { value: tasksCategory, original: 'Tasks' } }); MenuRegistry.addCommand({ id: 'workbench.action.tasks.showLog', title: { value: nls.localize('ShowLogAction.label', "Show Task Log"), original: 'Show Task Log' }, category: { value: tasksCategory, original: 'Tasks' } }); MenuRegistry.addCommand({ id: 'workbench.action.tasks.runTask', title: { value: nls.localize('RunTaskAction.label', "Run Task"), original: 'Run Task' }, category: { value: tasksCategory, original: 'Tasks' } }); MenuRegistry.addCommand({ id: 'workbench.action.tasks.reRunTask', title: { value: nls.localize('ReRunTaskAction.label', "Rerun Last Task"), original: 'Rerun Last Task' }, category: { value: tasksCategory, original: 'Tasks' } }); MenuRegistry.addCommand({ id: 'workbench.action.tasks.restartTask', title: { value: nls.localize('RestartTaskAction.label', "Restart Running Task"), original: 'Restart Running Task' }, category: { value: tasksCategory, original: 'Tasks' } }); MenuRegistry.addCommand({ id: 'workbench.action.tasks.showTasks', title: { value: nls.localize('ShowTasksAction.label', "Show Running Tasks"), original: 'Show Running Tasks' }, category: { value: tasksCategory, original: 'Tasks' } }); MenuRegistry.addCommand({ id: 'workbench.action.tasks.terminate', title: { value: nls.localize('TerminateAction.label', "Terminate Task"), original: 'Terminate Task' }, category: { value: tasksCategory, original: 'Tasks' } }); MenuRegistry.addCommand({ id: 'workbench.action.tasks.build', title: { value: nls.localize('BuildAction.label', "Run Build Task"), original: 'Run Build Task' }, category: { value: tasksCategory, original: 'Tasks' } }); MenuRegistry.addCommand({ id: 'workbench.action.tasks.test', title: { value: nls.localize('TestAction.label', "Run Test Task"), original: 'Run Test Task' }, category: { value: tasksCategory, original: 'Tasks' } }); MenuRegistry.addCommand({ id: 'workbench.action.tasks.configureDefaultBuildTask', title: { value: nls.localize('ConfigureDefaultBuildTask.label', "Configure Default Build Task"), original: 'Configure Default Build Task' }, category: { value: tasksCategory, original: 'Tasks' } }); MenuRegistry.addCommand({ id: 'workbench.action.tasks.configureDefaultTestTask', title: { value: nls.localize('ConfigureDefaultTestTask.label', "Configure Default Test Task"), original: 'Configure Default Test Task' }, category: { value: tasksCategory, original: 'Tasks' } }); MenuRegistry.addCommand({ id: 'workbench.action.tasks.openUserTasks', title: { value: nls.localize('workbench.action.tasks.openUserTasks', "Open User Tasks"), original: 'Open User Tasks' }, category: { value: tasksCategory, original: 'Tasks' } }); // MenuRegistry.addCommand( { id: 'workbench.action.tasks.rebuild', title: nls.localize('RebuildAction.label', 'Run Rebuild Task'), category: tasksCategory }); // MenuRegistry.addCommand( { id: 'workbench.action.tasks.clean', title: nls.localize('CleanAction.label', 'Run Clean Task'), category: tasksCategory }); KeybindingsRegistry.registerKeybindingRule({ id: 'workbench.action.tasks.build', weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_B }); // Tasks Output channel. Register it before using it in Task Service. let outputChannelRegistry = Registry.as<IOutputChannelRegistry>(OutputExt.OutputChannels); outputChannelRegistry.registerChannel({ id: AbstractTaskService.OutputChannelId, label: AbstractTaskService.OutputChannelLabel, log: false }); // Register Quick Access const quickAccessRegistry = (Registry.as<IQuickAccessRegistry>(QuickAccessExtensions.Quickaccess)); const tasksPickerContextKey = 'inTasksPicker'; quickAccessRegistry.registerQuickAccessProvider({ ctor: TasksQuickAccessProvider, prefix: TasksQuickAccessProvider.PREFIX, contextKey: tasksPickerContextKey, placeholder: nls.localize('tasksQuickAccessPlaceholder', "Type the name of a task to run."), helpEntries: [{ description: nls.localize('tasksQuickAccessHelp', "Run Task"), needsEditor: false }] }); // tasks.json validation let schema: IJSONSchema = { id: tasksSchemaId, description: 'Task definition file', type: 'object', allowTrailingCommas: true, allowComments: true, default: { version: '2.0.0', tasks: [ { label: 'My Task', command: 'echo hello', type: 'shell', args: [], problemMatcher: ['$tsc'], presentation: { reveal: 'always' }, group: 'build' } ] } }; schema.definitions = { ...schemaVersion1.definitions, ...schemaVersion2.definitions, }; schema.oneOf = [...(schemaVersion2.oneOf || []), ...(schemaVersion1.oneOf || [])]; let jsonRegistry = <jsonContributionRegistry.IJSONContributionRegistry>Registry.as(jsonContributionRegistry.Extensions.JSONContribution); jsonRegistry.registerSchema(tasksSchemaId, schema); ProblemMatcherRegistry.onMatcherChanged(() => { updateProblemMatchers(); jsonRegistry.notifySchemaChanged(tasksSchemaId); }); const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration); configurationRegistry.registerConfiguration({ id: 'task', order: 100, title: nls.localize('tasksConfigurationTitle', "Tasks"), type: 'object', properties: { 'task.problemMatchers.neverPrompt': { markdownDescription: nls.localize('task.problemMatchers.neverPrompt', "Configures whether to show the problem matcher prompt when running a task. Set to `true` to never prompt, or use a dictionary of task types to turn off prompting only for specific task types."), 'oneOf': [ { type: 'boolean', markdownDescription: nls.localize('task.problemMatchers.neverPrompt.boolean', 'Sets problem matcher prompting behavior for all tasks.') }, { type: 'object', patternProperties: { '.*': { type: 'boolean' } }, markdownDescription: nls.localize('task.problemMatchers.neverPrompt.array', 'An object containing task type-boolean pairs to never prompt for problem matchers on.'), default: { 'shell': true } } ], default: false }, 'task.autoDetect': { markdownDescription: nls.localize('task.autoDetect', "Controls enablement of `provideTasks` for all task provider extension. If the Tasks: Run Task command is slow, disabling auto detect for task providers may help. Individual extensions may also provide settings that disable auto detection."), type: 'string', enum: ['on', 'off'], default: 'on' }, 'task.slowProviderWarning': { markdownDescription: nls.localize('task.slowProviderWarning', "Configures whether a warning is shown when a provider is slow"), 'oneOf': [ { type: 'boolean', markdownDescription: nls.localize('task.slowProviderWarning.boolean', 'Sets the slow provider warning for all tasks.') }, { type: 'array', items: { type: 'string', markdownDescription: nls.localize('task.slowProviderWarning.array', 'An array of task types to never show the slow provider warning.') } } ], default: true }, 'task.quickOpen.history': { markdownDescription: nls.localize('task.quickOpen.history', "Controls the number of recent items tracked in task quick open dialog."), type: 'number', default: 30, minimum: 0, maximum: 30 }, 'task.quickOpen.detail': { markdownDescription: nls.localize('task.quickOpen.detail', "Controls whether to show the task detail for task that have a detail in the Run Task quick pick."), type: 'boolean', default: true }, 'task.quickOpen.skip': { type: 'boolean', description: nls.localize('task.quickOpen.skip', "Controls whether the task quick pick is skipped when there is only one task to pick from."), default: false }, 'task.quickOpen.showAll': { type: 'boolean', description: nls.localize('task.quickOpen.showAll', "Causes the Tasks: Run Task command to use the slower \"show all\" behavior instead of the faster two level picker where tasks are grouped by provider."), default: false }, 'task.saveBeforeRun': { markdownDescription: nls.localize( 'task.saveBeforeRun', 'Save all dirty editors before running a task.' ), type: 'string', enum: ['always', 'never', 'prompt'], enumDescriptions: [ nls.localize('task.saveBeforeRun.always', 'Always saves all editors before running.'), nls.localize('task.saveBeforeRun.never', 'Never saves editors before running.'), nls.localize('task.SaveBeforeRun.prompt', 'Prompts whether to save editors before running.'), ], default: 'always', }, } });
src/vs/workbench/contrib/tasks/browser/task.contribution.ts
1
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00021379845566116273, 0.00017631206719670445, 0.00016415790014434606, 0.00017155928071588278, 0.000012060057997587137 ]
{ "id": 0, "code_window": [ "\n", "\tconstructor() {\n", "\t\tsuper({\n", "\t\t\tid: 'workbench.action.logStorage',\n", "\t\t\ttitle: { value: nls.localize({ key: 'logStorage', comment: ['A developer only action to log the contents of the storage for the current window.'] }, \"Log Storage Database Contents\"), original: 'Developer: Log Storage Database Contents' },\n", "\t\t\tcategory: developerCategory,\n", "\t\t\tf1: true\n", "\t\t});\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\ttitle: { value: nls.localize({ key: 'logStorage', comment: ['A developer only action to log the contents of the storage for the current window.'] }, \"Log Storage Database Contents\"), original: 'Log Storage Database Contents' },\n" ], "file_path": "src/vs/workbench/browser/actions/developerActions.ts", "type": "replace", "edit_start_line_idx": 210 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI } from 'vs/base/common/uri'; import { IDisposable } from 'vs/base/common/lifecycle'; import { Registry } from 'vs/platform/registry/common/platform'; import { IConfigurationRegistry, Extensions as ConfigurationExtensions, ConfigurationScope, getScopes } from 'vs/platform/configuration/common/configurationRegistry'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { MainThreadConfigurationShape, MainContext, ExtHostContext, IExtHostContext, IConfigurationInitData } from '../common/extHost.protocol'; import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers'; import { ConfigurationTarget, IConfigurationService, IConfigurationOverrides } from 'vs/platform/configuration/common/configuration'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; @extHostNamedCustomer(MainContext.MainThreadConfiguration) export class MainThreadConfiguration implements MainThreadConfigurationShape { private readonly _configurationListener: IDisposable; constructor( extHostContext: IExtHostContext, @IWorkspaceContextService private readonly _workspaceContextService: IWorkspaceContextService, @IConfigurationService private readonly configurationService: IConfigurationService, @IEnvironmentService private readonly _environmentService: IEnvironmentService, ) { const proxy = extHostContext.getProxy(ExtHostContext.ExtHostConfiguration); proxy.$initializeConfiguration(this._getConfigurationData()); this._configurationListener = configurationService.onDidChangeConfiguration(e => { proxy.$acceptConfigurationChanged(this._getConfigurationData(), e.change); }); } private _getConfigurationData(): IConfigurationInitData { const configurationData: IConfigurationInitData = { ...(this.configurationService.getConfigurationData()!), configurationScopes: [] }; // Send configurations scopes only in development mode. if (!this._environmentService.isBuilt || this._environmentService.isExtensionDevelopment) { configurationData.configurationScopes = getScopes(); } return configurationData; } public dispose(): void { this._configurationListener.dispose(); } $updateConfigurationOption(target: ConfigurationTarget | null, key: string, value: any, overrides: IConfigurationOverrides | undefined, scopeToLanguage: boolean | undefined): Promise<void> { overrides = { resource: overrides?.resource ? URI.revive(overrides.resource) : undefined, overrideIdentifier: overrides?.overrideIdentifier }; return this.writeConfiguration(target, key, value, overrides, scopeToLanguage); } $removeConfigurationOption(target: ConfigurationTarget | null, key: string, overrides: IConfigurationOverrides | undefined, scopeToLanguage: boolean | undefined): Promise<void> { overrides = { resource: overrides?.resource ? URI.revive(overrides.resource) : undefined, overrideIdentifier: overrides?.overrideIdentifier }; return this.writeConfiguration(target, key, undefined, overrides, scopeToLanguage); } private writeConfiguration(target: ConfigurationTarget | null, key: string, value: any, overrides: IConfigurationOverrides, scopeToLanguage: boolean | undefined): Promise<void> { target = target !== null && target !== undefined ? target : this.deriveConfigurationTarget(key, overrides); const configurationValue = this.configurationService.inspect(key, overrides); switch (target) { case ConfigurationTarget.MEMORY: return this._updateValue(key, value, target, configurationValue?.memory?.override, overrides, scopeToLanguage); case ConfigurationTarget.WORKSPACE_FOLDER: return this._updateValue(key, value, target, configurationValue?.workspaceFolder?.override, overrides, scopeToLanguage); case ConfigurationTarget.WORKSPACE: return this._updateValue(key, value, target, configurationValue?.workspace?.override, overrides, scopeToLanguage); case ConfigurationTarget.USER_REMOTE: return this._updateValue(key, value, target, configurationValue?.userRemote?.override, overrides, scopeToLanguage); default: return this._updateValue(key, value, target, configurationValue?.userLocal?.override, overrides, scopeToLanguage); } } private _updateValue(key: string, value: any, configurationTarget: ConfigurationTarget, overriddenValue: any | undefined, overrides: IConfigurationOverrides, scopeToLanguage: boolean | undefined): Promise<void> { overrides = scopeToLanguage === true ? overrides : scopeToLanguage === false ? { resource: overrides.resource } : overrides.overrideIdentifier && overriddenValue !== undefined ? overrides : { resource: overrides.resource }; return this.configurationService.updateValue(key, value, overrides, configurationTarget, true); } private deriveConfigurationTarget(key: string, overrides: IConfigurationOverrides): ConfigurationTarget { if (overrides.resource && this._workspaceContextService.getWorkbenchState() === WorkbenchState.WORKSPACE) { const configurationProperties = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).getConfigurationProperties(); if (configurationProperties[key] && (configurationProperties[key].scope === ConfigurationScope.RESOURCE || configurationProperties[key].scope === ConfigurationScope.LANGUAGE_OVERRIDABLE)) { return ConfigurationTarget.WORKSPACE_FOLDER; } } return ConfigurationTarget.WORKSPACE; } }
src/vs/workbench/api/browser/mainThreadConfiguration.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00017551412747707218, 0.00016958359628915787, 0.00016174848133232445, 0.00016963918460533023, 0.000004047931724926457 ]
{ "id": 0, "code_window": [ "\n", "\tconstructor() {\n", "\t\tsuper({\n", "\t\t\tid: 'workbench.action.logStorage',\n", "\t\t\ttitle: { value: nls.localize({ key: 'logStorage', comment: ['A developer only action to log the contents of the storage for the current window.'] }, \"Log Storage Database Contents\"), original: 'Developer: Log Storage Database Contents' },\n", "\t\t\tcategory: developerCategory,\n", "\t\t\tf1: true\n", "\t\t});\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\ttitle: { value: nls.localize({ key: 'logStorage', comment: ['A developer only action to log the contents of the storage for the current window.'] }, \"Log Storage Database Contents\"), original: 'Log Storage Database Contents' },\n" ], "file_path": "src/vs/workbench/browser/actions/developerActions.ts", "type": "replace", "edit_start_line_idx": 210 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { join } from 'vs/base/common/path'; import { Queue } from 'vs/base/common/async'; import * as fs from 'fs'; import * as os from 'os'; import * as platform from 'vs/base/common/platform'; import { Event } from 'vs/base/common/event'; import { promisify } from 'util'; import { isRootOrDriveLetter } from 'vs/base/common/extpath'; import { generateUuid } from 'vs/base/common/uuid'; import { normalizeNFC } from 'vs/base/common/normalization'; // See https://github.com/Microsoft/vscode/issues/30180 const WIN32_MAX_FILE_SIZE = 300 * 1024 * 1024; // 300 MB const GENERAL_MAX_FILE_SIZE = 16 * 1024 * 1024 * 1024; // 16 GB // See https://github.com/v8/v8/blob/5918a23a3d571b9625e5cce246bdd5b46ff7cd8b/src/heap/heap.cc#L149 const WIN32_MAX_HEAP_SIZE = 700 * 1024 * 1024; // 700 MB const GENERAL_MAX_HEAP_SIZE = 700 * 2 * 1024 * 1024; // 1400 MB export const MAX_FILE_SIZE = process.arch === 'ia32' ? WIN32_MAX_FILE_SIZE : GENERAL_MAX_FILE_SIZE; export const MAX_HEAP_SIZE = process.arch === 'ia32' ? WIN32_MAX_HEAP_SIZE : GENERAL_MAX_HEAP_SIZE; export enum RimRafMode { /** * Slow version that unlinks each file and folder. */ UNLINK, /** * Fast version that first moves the file/folder * into a temp directory and then deletes that * without waiting for it. */ MOVE } export async function rimraf(path: string, mode = RimRafMode.UNLINK): Promise<void> { if (isRootOrDriveLetter(path)) { throw new Error('rimraf - will refuse to recursively delete root'); } // delete: via unlink if (mode === RimRafMode.UNLINK) { return rimrafUnlink(path); } // delete: via move return rimrafMove(path); } async function rimrafUnlink(path: string): Promise<void> { try { const stat = await lstat(path); // Folder delete (recursive) - NOT for symbolic links though! if (stat.isDirectory() && !stat.isSymbolicLink()) { // Children const children = await readdir(path); await Promise.all(children.map(child => rimrafUnlink(join(path, child)))); // Folder await promisify(fs.rmdir)(path); } // Single file delete else { // chmod as needed to allow for unlink const mode = stat.mode; if (!(mode & 128)) { // 128 === 0200 await chmod(path, mode | 128); } return unlink(path); } } catch (error) { if (error.code !== 'ENOENT') { throw error; } } } async function rimrafMove(path: string): Promise<void> { try { const pathInTemp = join(os.tmpdir(), generateUuid()); try { await rename(path, pathInTemp); } catch (error) { return rimrafUnlink(path); // if rename fails, delete without tmp dir } // Delete but do not return as promise rimrafUnlink(pathInTemp); } catch (error) { if (error.code !== 'ENOENT') { throw error; } } } export function rimrafSync(path: string): void { if (isRootOrDriveLetter(path)) { throw new Error('rimraf - will refuse to recursively delete root'); } try { const stat = fs.lstatSync(path); // Folder delete (recursive) - NOT for symbolic links though! if (stat.isDirectory() && !stat.isSymbolicLink()) { // Children const children = readdirSync(path); children.map(child => rimrafSync(join(path, child))); // Folder fs.rmdirSync(path); } // Single file delete else { // chmod as needed to allow for unlink const mode = stat.mode; if (!(mode & 128)) { // 128 === 0200 fs.chmodSync(path, mode | 128); } return fs.unlinkSync(path); } } catch (error) { if (error.code !== 'ENOENT') { throw error; } } } export async function readdir(path: string): Promise<string[]> { return handleDirectoryChildren(await promisify(fs.readdir)(path)); } export async function readdirWithFileTypes(path: string): Promise<fs.Dirent[]> { const children = await promisify(fs.readdir)(path, { withFileTypes: true }); // Mac: uses NFD unicode form on disk, but we want NFC // See also https://github.com/nodejs/node/issues/2165 if (platform.isMacintosh) { for (const child of children) { child.name = normalizeNFC(child.name); } } return children; } export function readdirSync(path: string): string[] { return handleDirectoryChildren(fs.readdirSync(path)); } function handleDirectoryChildren(children: string[]): string[] { // Mac: uses NFD unicode form on disk, but we want NFC // See also https://github.com/nodejs/node/issues/2165 if (platform.isMacintosh) { return children.map(child => normalizeNFC(child)); } return children; } export function exists(path: string): Promise<boolean> { return promisify(fs.exists)(path); } export function chmod(path: string, mode: number): Promise<void> { return promisify(fs.chmod)(path, mode); } export function stat(path: string): Promise<fs.Stats> { return promisify(fs.stat)(path); } export interface IStatAndLink { // The stats of the file. If the file is a symbolic // link, the stats will be of that target file and // not the link itself. // If the file is a symbolic link pointing to a non // existing file, the stat will be of the link and // the `dangling` flag will indicate this. stat: fs.Stats; // Will be provided if the resource is a symbolic link // on disk. Use the `dangling` flag to find out if it // points to a resource that does not exist on disk. symbolicLink?: { dangling: boolean }; } export async function statLink(path: string): Promise<IStatAndLink> { // First stat the link let lstats: fs.Stats | undefined; try { lstats = await lstat(path); // Return early if the stat is not a symbolic link at all if (!lstats.isSymbolicLink()) { return { stat: lstats }; } } catch (error) { /* ignore - use stat() instead */ } // If the stat is a symbolic link or failed to stat, use fs.stat() // which for symbolic links will stat the target they point to try { const stats = await stat(path); return { stat: stats, symbolicLink: lstats?.isSymbolicLink() ? { dangling: false } : undefined }; } catch (error) { // If the link points to a non-existing file we still want // to return it as result while setting dangling: true flag if (error.code === 'ENOENT' && lstats) { return { stat: lstats, symbolicLink: { dangling: true } }; } throw error; } } export function lstat(path: string): Promise<fs.Stats> { return promisify(fs.lstat)(path); } export function rename(oldPath: string, newPath: string): Promise<void> { return promisify(fs.rename)(oldPath, newPath); } export function renameIgnoreError(oldPath: string, newPath: string): Promise<void> { return new Promise(resolve => fs.rename(oldPath, newPath, () => resolve())); } export function unlink(path: string): Promise<void> { return promisify(fs.unlink)(path); } export function symlink(target: string, path: string, type?: string): Promise<void> { return promisify(fs.symlink)(target, path, type); } export function truncate(path: string, len: number): Promise<void> { return promisify(fs.truncate)(path, len); } export function readFile(path: string): Promise<Buffer>; export function readFile(path: string, encoding: string): Promise<string>; export function readFile(path: string, encoding?: string): Promise<Buffer | string> { return promisify(fs.readFile)(path, encoding); } export async function mkdirp(path: string, mode?: number): Promise<void> { return promisify(fs.mkdir)(path, { mode, recursive: true }); } // According to node.js docs (https://nodejs.org/docs/v6.5.0/api/fs.html#fs_fs_writefile_file_data_options_callback) // it is not safe to call writeFile() on the same path multiple times without waiting for the callback to return. // Therefor we use a Queue on the path that is given to us to sequentialize calls to the same path properly. const writeFilePathQueues: Map<string, Queue<void>> = new Map(); export function writeFile(path: string, data: string, options?: IWriteFileOptions): Promise<void>; export function writeFile(path: string, data: Buffer, options?: IWriteFileOptions): Promise<void>; export function writeFile(path: string, data: Uint8Array, options?: IWriteFileOptions): Promise<void>; export function writeFile(path: string, data: string | Buffer | Uint8Array, options?: IWriteFileOptions): Promise<void>; export function writeFile(path: string, data: string | Buffer | Uint8Array, options?: IWriteFileOptions): Promise<void> { const queueKey = toQueueKey(path); return ensureWriteFileQueue(queueKey).queue(() => { const ensuredOptions = ensureWriteOptions(options); return new Promise((resolve, reject) => doWriteFileAndFlush(path, data, ensuredOptions, error => error ? reject(error) : resolve())); }); } function toQueueKey(path: string): string { let queueKey = path; if (platform.isWindows || platform.isMacintosh) { queueKey = queueKey.toLowerCase(); // accommodate for case insensitive file systems } return queueKey; } function ensureWriteFileQueue(queueKey: string): Queue<void> { const existingWriteFileQueue = writeFilePathQueues.get(queueKey); if (existingWriteFileQueue) { return existingWriteFileQueue; } const writeFileQueue = new Queue<void>(); writeFilePathQueues.set(queueKey, writeFileQueue); const onFinish = Event.once(writeFileQueue.onFinished); onFinish(() => { writeFilePathQueues.delete(queueKey); writeFileQueue.dispose(); }); return writeFileQueue; } export interface IWriteFileOptions { mode?: number; flag?: string; } interface IEnsuredWriteFileOptions extends IWriteFileOptions { mode: number; flag: string; } let canFlush = true; // Calls fs.writeFile() followed by a fs.sync() call to flush the changes to disk // We do this in cases where we want to make sure the data is really on disk and // not in some cache. // // See https://github.com/nodejs/node/blob/v5.10.0/lib/fs.js#L1194 function doWriteFileAndFlush(path: string, data: string | Buffer | Uint8Array, options: IEnsuredWriteFileOptions, callback: (error: Error | null) => void): void { if (!canFlush) { return fs.writeFile(path, data, { mode: options.mode, flag: options.flag }, callback); } // Open the file with same flags and mode as fs.writeFile() fs.open(path, options.flag, options.mode, (openError, fd) => { if (openError) { return callback(openError); } // It is valid to pass a fd handle to fs.writeFile() and this will keep the handle open! fs.writeFile(fd, data, writeError => { if (writeError) { return fs.close(fd, () => callback(writeError)); // still need to close the handle on error! } // Flush contents (not metadata) of the file to disk fs.fdatasync(fd, (syncError: Error | null) => { // In some exotic setups it is well possible that node fails to sync // In that case we disable flushing and warn to the console if (syncError) { console.warn('[node.js fs] fdatasync is now disabled for this session because it failed: ', syncError); canFlush = false; } return fs.close(fd, closeError => callback(closeError)); }); }); }); } export function writeFileSync(path: string, data: string | Buffer, options?: IWriteFileOptions): void { const ensuredOptions = ensureWriteOptions(options); if (!canFlush) { return fs.writeFileSync(path, data, { mode: ensuredOptions.mode, flag: ensuredOptions.flag }); } // Open the file with same flags and mode as fs.writeFile() const fd = fs.openSync(path, ensuredOptions.flag, ensuredOptions.mode); try { // It is valid to pass a fd handle to fs.writeFile() and this will keep the handle open! fs.writeFileSync(fd, data); // Flush contents (not metadata) of the file to disk try { fs.fdatasyncSync(fd); } catch (syncError) { console.warn('[node.js fs] fdatasyncSync is now disabled for this session because it failed: ', syncError); canFlush = false; } } finally { fs.closeSync(fd); } } function ensureWriteOptions(options?: IWriteFileOptions): IEnsuredWriteFileOptions { if (!options) { return { mode: 0o666, flag: 'w' }; } return { mode: typeof options.mode === 'number' ? options.mode : 0o666, flag: typeof options.flag === 'string' ? options.flag : 'w' }; } export async function readDirsInDir(dirPath: string): Promise<string[]> { const children = await readdir(dirPath); const directories: string[] = []; for (const child of children) { if (await dirExists(join(dirPath, child))) { directories.push(child); } } return directories; } export async function dirExists(path: string): Promise<boolean> { try { const fileStat = await stat(path); return fileStat.isDirectory(); } catch (error) { return false; } } export async function fileExists(path: string): Promise<boolean> { try { const fileStat = await stat(path); return fileStat.isFile(); } catch (error) { return false; } } export function whenDeleted(path: string): Promise<void> { // Complete when wait marker file is deleted return new Promise<void>(resolve => { let running = false; const interval = setInterval(() => { if (!running) { running = true; fs.exists(path, exists => { running = false; if (!exists) { clearInterval(interval); resolve(undefined); } }); } }, 1000); }); } export async function move(source: string, target: string): Promise<void> { if (source === target) { return Promise.resolve(); } async function updateMtime(path: string): Promise<void> { const stat = await lstat(path); if (stat.isDirectory() || stat.isSymbolicLink()) { return Promise.resolve(); // only for files } const fd = await promisify(fs.open)(path, 'a'); try { await promisify(fs.futimes)(fd, stat.atime, new Date()); } catch (error) { //ignore } return promisify(fs.close)(fd); } try { await rename(source, target); await updateMtime(target); } catch (error) { // In two cases we fallback to classic copy and delete: // // 1.) The EXDEV error indicates that source and target are on different devices // In this case, fallback to using a copy() operation as there is no way to // rename() between different devices. // // 2.) The user tries to rename a file/folder that ends with a dot. This is not // really possible to move then, at least on UNC devices. if (source.toLowerCase() !== target.toLowerCase() && error.code === 'EXDEV' || source.endsWith('.')) { await copy(source, target); await rimraf(source, RimRafMode.MOVE); await updateMtime(target); } else { throw error; } } } export async function copy(source: string, target: string, copiedSourcesIn?: { [path: string]: boolean }): Promise<void> { const copiedSources = copiedSourcesIn ? copiedSourcesIn : Object.create(null); const fileStat = await stat(source); if (!fileStat.isDirectory()) { return doCopyFile(source, target, fileStat.mode & 511); } if (copiedSources[source]) { return Promise.resolve(); // escape when there are cycles (can happen with symlinks) } copiedSources[source] = true; // remember as copied // Create folder await mkdirp(target, fileStat.mode & 511); // Copy each file recursively const files = await readdir(source); for (let i = 0; i < files.length; i++) { const file = files[i]; await copy(join(source, file), join(target, file), copiedSources); } } async function doCopyFile(source: string, target: string, mode: number): Promise<void> { return new Promise((resolve, reject) => { const reader = fs.createReadStream(source); const writer = fs.createWriteStream(target, { mode }); let finished = false; const finish = (error?: Error) => { if (!finished) { finished = true; // in error cases, pass to callback if (error) { return reject(error); } // we need to explicitly chmod because of https://github.com/nodejs/node/issues/1104 fs.chmod(target, mode, error => error ? reject(error) : resolve()); } }; // handle errors properly reader.once('error', error => finish(error)); writer.once('error', error => finish(error)); // we are done (underlying fd has been closed) writer.once('close', () => finish()); // start piping reader.pipe(writer); }); }
src/vs/base/node/pfs.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.0003257832140661776, 0.00017706330982036889, 0.00016004570352379233, 0.00017301617481280118, 0.000023552820493932813 ]
{ "id": 0, "code_window": [ "\n", "\tconstructor() {\n", "\t\tsuper({\n", "\t\t\tid: 'workbench.action.logStorage',\n", "\t\t\ttitle: { value: nls.localize({ key: 'logStorage', comment: ['A developer only action to log the contents of the storage for the current window.'] }, \"Log Storage Database Contents\"), original: 'Developer: Log Storage Database Contents' },\n", "\t\t\tcategory: developerCategory,\n", "\t\t\tf1: true\n", "\t\t});\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\ttitle: { value: nls.localize({ key: 'logStorage', comment: ['A developer only action to log the contents of the storage for the current window.'] }, \"Log Storage Database Contents\"), original: 'Log Storage Database Contents' },\n" ], "file_path": "src/vs/workbench/browser/actions/developerActions.ts", "type": "replace", "edit_start_line_idx": 210 }
"use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ const path_1 = require("path"); const utils_1 = require("./utils"); module.exports = new class NoNlsInStandaloneEditorRule { constructor() { this.meta = { messages: { badImport: 'Not allowed to import standalone editor modules.' }, docs: { url: 'https://github.com/microsoft/vscode/wiki/Source-Code-Organization' } }; } create(context) { if (/vs(\/|\\)editor/.test(context.getFilename())) { // the vs/editor folder is allowed to use the standalone editor return {}; } return utils_1.createImportRuleListener((node, path) => { // resolve relative paths if (path[0] === '.') { path = path_1.join(context.getFilename(), path); } if (/vs(\/|\\)editor(\/|\\)standalone(\/|\\)/.test(path) || /vs(\/|\\)editor(\/|\\)common(\/|\\)standalone(\/|\\)/.test(path) || /vs(\/|\\)editor(\/|\\)editor.api/.test(path) || /vs(\/|\\)editor(\/|\\)editor.main/.test(path) || /vs(\/|\\)editor(\/|\\)editor.worker/.test(path)) { context.report({ loc: node.loc, messageId: 'badImport' }); } }); } };
build/lib/eslint/code-no-standalone-editor.js
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00017495706561021507, 0.00017179784481413662, 0.00016676023369655013, 0.00017244424088858068, 0.0000029469485980371246 ]
{ "id": 1, "code_window": [ "\n", "replaceContributions();\n", "searchWidgetContributions();\n", "\n", "const category = nls.localize('search', \"Search\");\n", "\n", "KeybindingsRegistry.registerCommandAndKeybindingRule({\n", "\tid: 'workbench.action.search.toggleQueryDetails',\n", "\tweight: KeybindingWeight.WorkbenchContrib,\n", "\twhen: ContextKeyExpr.or(Constants.SearchViewFocusedKey, SearchEditorConstants.InSearchEditor),\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const category = { value: nls.localize('search', \"Search\"), original: 'Search' };\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 65 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Action } from 'vs/base/common/actions'; import { distinct } from 'vs/base/common/arrays'; import { onUnexpectedError } from 'vs/base/common/errors'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import * as objects from 'vs/base/common/objects'; import * as platform from 'vs/base/common/platform'; import { dirname } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { ToggleCaseSensitiveKeybinding, ToggleRegexKeybinding, ToggleWholeWordKeybinding } from 'vs/editor/contrib/find/findModel'; import * as nls from 'vs/nls'; import { ICommandAction, MenuId, MenuRegistry, SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { CommandsRegistry, ICommandHandler } from 'vs/platform/commands/common/commands'; import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry'; import { ContextKeyExpr, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IFileService } from 'vs/platform/files/common/files'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { IListService, WorkbenchListFocusContextKey, WorkbenchObjectTree } from 'vs/platform/list/browser/listService'; import { Registry } from 'vs/platform/registry/common/platform'; import { defaultQuickAccessContextKeyValue } from 'vs/workbench/browser/quickaccess'; import { Extensions as ActionExtensions, IWorkbenchActionRegistry } from 'vs/workbench/common/actions'; import { Extensions as WorkbenchExtensions, IWorkbenchContribution, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions'; import { Extensions as ViewExtensions, IViewsRegistry, IViewContainersRegistry, ViewContainerLocation, IViewDescriptorService, IViewsService } from 'vs/workbench/common/views'; import { getMultiSelectedResources } from 'vs/workbench/contrib/files/browser/files'; import { ExplorerFolderContext, ExplorerRootContext, FilesExplorerFocusCondition, IExplorerService, VIEWLET_ID as VIEWLET_ID_FILES } from 'vs/workbench/contrib/files/common/files'; import { registerContributions as replaceContributions } from 'vs/workbench/contrib/search/browser/replaceContributions'; import { clearHistoryCommand, ClearSearchResultsAction, CloseReplaceAction, CollapseDeepestExpandedLevelAction, copyAllCommand, copyMatchCommand, copyPathCommand, FocusNextInputAction, FocusNextSearchResultAction, FocusPreviousInputAction, FocusPreviousSearchResultAction, focusSearchListCommand, getSearchView, openSearchView, OpenSearchViewletAction, RefreshAction, RemoveAction, ReplaceAction, ReplaceAllAction, ReplaceAllInFolderAction, ReplaceInFilesAction, toggleCaseSensitiveCommand, toggleRegexCommand, toggleWholeWordCommand, FindInFilesCommand, ToggleSearchOnTypeAction, ExpandAllAction } from 'vs/workbench/contrib/search/browser/searchActions'; import { SearchView } from 'vs/workbench/contrib/search/browser/searchView'; import { registerContributions as searchWidgetContributions } from 'vs/workbench/contrib/search/browser/searchWidget'; import * as Constants from 'vs/workbench/contrib/search/common/constants'; import * as SearchEditorConstants from 'vs/workbench/contrib/searchEditor/browser/constants'; import { getWorkspaceSymbols } from 'vs/workbench/contrib/search/common/search'; import { ISearchHistoryService, SearchHistoryService } from 'vs/workbench/contrib/search/common/searchHistoryService'; import { FileMatchOrMatch, ISearchWorkbenchService, RenderableMatch, SearchWorkbenchService, FileMatch, Match, FolderMatch } from 'vs/workbench/contrib/search/common/searchModel'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { VIEWLET_ID, VIEW_ID, SEARCH_EXCLUDE_CONFIG, SearchSortOrder } from 'vs/workbench/services/search/common/search'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { ExplorerViewPaneContainer } from 'vs/workbench/contrib/files/browser/explorerViewlet'; import { assertType, assertIsDefined } from 'vs/base/common/types'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { SearchEditor } from 'vs/workbench/contrib/searchEditor/browser/searchEditor'; import { ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { IQuickAccessRegistry, Extensions as QuickAccessExtensions } from 'vs/platform/quickinput/common/quickAccess'; import { SymbolsQuickAccessProvider } from 'vs/workbench/contrib/search/browser/symbolsQuickAccess'; import { AnythingQuickAccessProvider } from 'vs/workbench/contrib/search/browser/anythingQuickAccess'; import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { AbstractGotoLineQuickAccessProvider } from 'vs/editor/contrib/quickAccess/gotoLineQuickAccess'; import { GotoSymbolQuickAccessProvider } from 'vs/workbench/contrib/codeEditor/browser/quickaccess/gotoSymbolQuickAccess'; import { searchViewIcon } from 'vs/workbench/contrib/search/browser/searchIcons'; registerSingleton(ISearchWorkbenchService, SearchWorkbenchService, true); registerSingleton(ISearchHistoryService, SearchHistoryService, true); replaceContributions(); searchWidgetContributions(); const category = nls.localize('search', "Search"); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'workbench.action.search.toggleQueryDetails', weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or(Constants.SearchViewFocusedKey, SearchEditorConstants.InSearchEditor), primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_J, handler: accessor => { const contextService = accessor.get(IContextKeyService).getContext(document.activeElement); if (contextService.getValue(SearchEditorConstants.InSearchEditor.serialize())) { (accessor.get(IEditorService).activeEditorPane as SearchEditor).toggleQueryDetails(); } else if (contextService.getValue(Constants.SearchViewFocusedKey.serialize())) { const searchView = getSearchView(accessor.get(IViewsService)); assertIsDefined(searchView).toggleQueryDetails(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.FocusSearchFromResults, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FirstMatchFocusKey), primary: KeyMod.CtrlCmd | KeyCode.UpArrow, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { searchView.focusPreviousInputBox(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.OpenMatchToSide, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyMod.CtrlCmd | KeyCode.Enter, mac: { primary: KeyMod.WinCtrl | KeyCode.Enter }, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); searchView.open(<FileMatchOrMatch>tree.getFocus()[0], false, true, true); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CancelActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, WorkbenchListFocusContextKey), primary: KeyCode.Escape, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { searchView.cancelSearch(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.RemoveActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyCode.Delete, mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace, }, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(RemoveAction, tree, tree.getFocus()[0]!).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.MatchFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAction, tree, tree.getFocus()[0] as Match, searchView).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceAllInFileActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.FileFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter], handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAllAction, searchView, tree.getFocus()[0] as FileMatch).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceAllInFolderActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.FolderFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter], handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAllInFolderAction, tree, tree.getFocus()[0] as FolderMatch).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CloseReplaceWidgetActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceInputBoxFocusedKey), primary: KeyCode.Escape, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(CloseReplaceAction, Constants.CloseReplaceWidgetActionId, '').run(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FocusNextInputAction.ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or( ContextKeyExpr.and(SearchEditorConstants.InSearchEditor, Constants.InputBoxFocusedKey), ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.InputBoxFocusedKey)), primary: KeyMod.CtrlCmd | KeyCode.DownArrow, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(FocusNextInputAction, FocusNextInputAction.ID, '').run(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FocusPreviousInputAction.ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or( ContextKeyExpr.and(SearchEditorConstants.InSearchEditor, Constants.InputBoxFocusedKey), ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.InputBoxFocusedKey, Constants.SearchInputBoxFocusedKey.toNegated())), primary: KeyMod.CtrlCmd | KeyCode.UpArrow, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(FocusPreviousInputAction, FocusPreviousInputAction.ID, '').run(); } }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceActionId, title: ReplaceAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.MatchFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceAllInFolderActionId, title: ReplaceAllInFolderAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.FolderFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceAllInFileActionId, title: ReplaceAllAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.FileFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.RemoveActionId, title: RemoveAction.LABEL }, when: Constants.FileMatchOrMatchFocusKey, group: 'search', order: 2 }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CopyMatchCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.FileMatchOrMatchFocusKey, primary: KeyMod.CtrlCmd | KeyCode.KEY_C, handler: copyMatchCommand }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyMatchCommandId, title: nls.localize('copyMatchLabel', "Copy") }, when: Constants.FileMatchOrMatchFocusKey, group: 'search_2', order: 1 }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CopyPathCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.FileMatchOrFolderMatchWithResourceFocusKey, primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_C, win: { primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_C }, handler: copyPathCommand }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyPathCommandId, title: nls.localize('copyPathLabel', "Copy Path") }, when: Constants.FileMatchOrFolderMatchWithResourceFocusKey, group: 'search_2', order: 2 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyAllCommandId, title: nls.localize('copyAllLabel', "Copy All") }, when: Constants.HasSearchResults, group: 'search_2', order: 3 }); CommandsRegistry.registerCommand({ id: Constants.CopyAllCommandId, handler: copyAllCommand }); CommandsRegistry.registerCommand({ id: Constants.ClearSearchHistoryCommandId, handler: clearHistoryCommand }); CommandsRegistry.registerCommand({ id: Constants.RevealInSideBarForSearchResults, handler: (accessor, args: any) => { const viewletService = accessor.get(IViewletService); const explorerService = accessor.get(IExplorerService); const contextService = accessor.get(IWorkspaceContextService); const searchView = getSearchView(accessor.get(IViewsService)); if (!searchView) { return; } let fileMatch: FileMatch; if (!(args instanceof FileMatch)) { args = searchView.getControl().getFocus()[0]; } if (args instanceof FileMatch) { fileMatch = args; } else { return; } viewletService.openViewlet(VIEWLET_ID_FILES, false).then((viewlet) => { if (!viewlet) { return; } const explorerViewContainer = viewlet.getViewPaneContainer() as ExplorerViewPaneContainer; const uri = fileMatch.resource; if (uri && contextService.isInsideWorkspace(uri)) { const explorerView = explorerViewContainer.getExplorerView(); explorerView.setExpanded(true); explorerService.select(uri, true).then(() => explorerView.focus(), onUnexpectedError); } }); } }); const RevealInSideBarForSearchResultsCommand: ICommandAction = { id: Constants.RevealInSideBarForSearchResults, title: nls.localize('revealInSideBar', "Reveal in Side Bar") }; MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: RevealInSideBarForSearchResultsCommand, when: ContextKeyExpr.and(Constants.FileFocusKey, Constants.HasSearchResults), group: 'search_3', order: 1 }); const clearSearchHistoryLabel = nls.localize('clearSearchHistoryLabel', "Clear Search History"); const ClearSearchHistoryCommand: ICommandAction = { id: Constants.ClearSearchHistoryCommandId, title: clearSearchHistoryLabel, category }; MenuRegistry.addCommand(ClearSearchHistoryCommand); CommandsRegistry.registerCommand({ id: Constants.FocusSearchListCommandID, handler: focusSearchListCommand }); const focusSearchListCommandLabel = nls.localize('focusSearchListCommandLabel', "Focus List"); const FocusSearchListCommand: ICommandAction = { id: Constants.FocusSearchListCommandID, title: focusSearchListCommandLabel, category }; MenuRegistry.addCommand(FocusSearchListCommand); const searchInFolderCommand: ICommandHandler = (accessor, resource?: URI) => { const listService = accessor.get(IListService); const fileService = accessor.get(IFileService); const viewsService = accessor.get(IViewsService); const resources = getMultiSelectedResources(resource, listService, accessor.get(IEditorService), accessor.get(IExplorerService)); return openSearchView(viewsService, true).then(searchView => { if (resources && resources.length && searchView) { return fileService.resolveAll(resources.map(resource => ({ resource }))).then(results => { const folders: URI[] = []; results.forEach(result => { if (result.success && result.stat) { folders.push(result.stat.isDirectory ? result.stat.resource : dirname(result.stat.resource)); } }); searchView.searchInFolders(distinct(folders, folder => folder.toString())); }); } return undefined; }); }; const FIND_IN_FOLDER_ID = 'filesExplorer.findInFolder'; KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FIND_IN_FOLDER_ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(FilesExplorerFocusCondition, ExplorerFolderContext), primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_F, handler: searchInFolderCommand }); CommandsRegistry.registerCommand({ id: ClearSearchResultsAction.ID, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(ClearSearchResultsAction, ClearSearchResultsAction.ID, '').run(); } }); CommandsRegistry.registerCommand({ id: RefreshAction.ID, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(RefreshAction, RefreshAction.ID, '').run(); } }); const FIND_IN_WORKSPACE_ID = 'filesExplorer.findInWorkspace'; CommandsRegistry.registerCommand({ id: FIND_IN_WORKSPACE_ID, handler: (accessor) => { return openSearchView(accessor.get(IViewsService), true).then(searchView => { if (searchView) { searchView.searchInFolders(); } }); } }); MenuRegistry.appendMenuItem(MenuId.ExplorerContext, { group: '4_search', order: 10, command: { id: FIND_IN_FOLDER_ID, title: nls.localize('findInFolder', "Find in Folder...") }, when: ContextKeyExpr.and(ExplorerFolderContext) }); MenuRegistry.appendMenuItem(MenuId.ExplorerContext, { group: '4_search', order: 10, command: { id: FIND_IN_WORKSPACE_ID, title: nls.localize('findInWorkspace', "Find in Workspace...") }, when: ContextKeyExpr.and(ExplorerRootContext, ExplorerFolderContext.toNegated()) }); class ShowAllSymbolsAction extends Action { static readonly ID = 'workbench.action.showAllSymbols'; static readonly LABEL = nls.localize('showTriggerActions', "Go to Symbol in Workspace..."); static readonly ALL_SYMBOLS_PREFIX = '#'; constructor( actionId: string, actionLabel: string, @IQuickInputService private readonly quickInputService: IQuickInputService ) { super(actionId, actionLabel); } async run(): Promise<void> { this.quickInputService.quickAccess.show(ShowAllSymbolsAction.ALL_SYMBOLS_PREFIX); } } const viewContainer = Registry.as<IViewContainersRegistry>(ViewExtensions.ViewContainersRegistry).registerViewContainer({ id: VIEWLET_ID, name: nls.localize('name', "Search"), ctorDescriptor: new SyncDescriptor(ViewPaneContainer, [VIEWLET_ID, { mergeViewWithContainerWhenSingleView: true, donotShowContainerTitleWhenMergedWithContainer: true }]), hideIfEmpty: true, icon: searchViewIcon.classNames, order: 1 }, ViewContainerLocation.Sidebar); const viewDescriptor = { id: VIEW_ID, containerIcon: 'codicon-search', name: nls.localize('search', "Search"), ctorDescriptor: new SyncDescriptor(SearchView), canToggleVisibility: false, canMoveView: true }; // Register search default location to sidebar Registry.as<IViewsRegistry>(ViewExtensions.ViewsRegistry).registerViews([viewDescriptor], viewContainer); // Migrate search location setting to new model class RegisterSearchViewContribution implements IWorkbenchContribution { constructor( @IConfigurationService configurationService: IConfigurationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService ) { const data = configurationService.inspect('search.location'); if (data.value === 'panel') { viewDescriptorService.moveViewToLocation(viewDescriptor, ViewContainerLocation.Panel); } if (data.userValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER); } if (data.userLocalValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER_LOCAL); } if (data.userRemoteValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER_REMOTE); } if (data.workspaceFolderValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.WORKSPACE_FOLDER); } if (data.workspaceValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.WORKSPACE); } } } Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(RegisterSearchViewContribution, LifecyclePhase.Starting); // Actions const registry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions); // Show Search and Find in Files are redundant, but we can't break keybindings by removing one. So it's the same action, same keybinding, registered to different IDs. // Show Search 'when' is redundant but if the two conflict with exactly the same keybinding and 'when' clause, then they can show up as "unbound" - #51780 registry.registerWorkbenchAction(SyncActionDescriptor.from(OpenSearchViewletAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_F }, Constants.SearchViewVisibleKey.toNegated()), 'View: Show Search', nls.localize('view', "View")); KeybindingsRegistry.registerCommandAndKeybindingRule({ description: { description: nls.localize('findInFiles.description', "Open the search viewlet"), args: [ { name: nls.localize('findInFiles.args', "A set of options for the search viewlet"), schema: { type: 'object', properties: { query: { 'type': 'string' }, replace: { 'type': 'string' }, triggerSearch: { 'type': 'boolean' }, filesToInclude: { 'type': 'string' }, filesToExclude: { 'type': 'string' }, isRegex: { 'type': 'boolean' }, isCaseSensitive: { 'type': 'boolean' }, matchWholeWord: { 'type': 'boolean' }, } } }, ] }, id: Constants.FindInFilesActionId, weight: KeybindingWeight.WorkbenchContrib, when: null, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_F, handler: FindInFilesCommand }); MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: Constants.FindInFilesActionId, title: { value: nls.localize('findInFiles', "Find in Files"), original: 'Find in Files' }, category } }); MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { group: '4_find_global', command: { id: Constants.FindInFilesActionId, title: nls.localize({ key: 'miFindInFiles', comment: ['&& denotes a mnemonic'] }, "Find &&in Files") }, order: 1 }); registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusNextSearchResultAction, { primary: KeyCode.F4 }), 'Focus Next Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor)); registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusPreviousSearchResultAction, { primary: KeyMod.Shift | KeyCode.F4 }), 'Focus Previous Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor)); registry.registerWorkbenchAction(SyncActionDescriptor.from(ReplaceInFilesAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_H }), 'Replace in Files', category); MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { group: '4_find_global', command: { id: ReplaceInFilesAction.ID, title: nls.localize({ key: 'miReplaceInFiles', comment: ['&& denotes a mnemonic'] }, "Replace &&in Files") }, order: 2 }); if (platform.isMacintosh) { // Register this with a more restrictive `when` on mac to avoid conflict with "copy path" KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleCaseSensitiveCommandId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewFocusedKey, Constants.FileMatchOrFolderMatchFocusKey.toNegated()), handler: toggleCaseSensitiveCommand }, ToggleCaseSensitiveKeybinding)); } else { KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleCaseSensitiveCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleCaseSensitiveCommand }, ToggleCaseSensitiveKeybinding)); } KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleWholeWordCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleWholeWordCommand }, ToggleWholeWordKeybinding)); KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleRegexCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleRegexCommand }, ToggleRegexKeybinding)); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.AddCursorsAtSearchResults, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_L, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); searchView.openEditorWithMultiCursor(<FileMatchOrMatch>tree.getFocus()[0]); } } }); registry.registerWorkbenchAction(SyncActionDescriptor.from(CollapseDeepestExpandedLevelAction), 'Search: Collapse All', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ExpandAllAction), 'Search: Expand All', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ShowAllSymbolsAction, { primary: KeyMod.CtrlCmd | KeyCode.KEY_T }), 'Go to Symbol in Workspace...'); registry.registerWorkbenchAction(SyncActionDescriptor.from(ToggleSearchOnTypeAction), 'Search: Toggle Search on Type', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(RefreshAction), 'Search: Refresh', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ClearSearchResultsAction), 'Search: Clear Search Results', category); // Register Quick Access Handler const quickAccessRegistry = Registry.as<IQuickAccessRegistry>(QuickAccessExtensions.Quickaccess); quickAccessRegistry.registerQuickAccessProvider({ ctor: AnythingQuickAccessProvider, prefix: AnythingQuickAccessProvider.PREFIX, placeholder: nls.localize('anythingQuickAccessPlaceholder', "Search files by name (append {0} to go to line or {1} to go to symbol)", AbstractGotoLineQuickAccessProvider.PREFIX, GotoSymbolQuickAccessProvider.PREFIX), contextKey: defaultQuickAccessContextKeyValue, helpEntries: [{ description: nls.localize('anythingQuickAccess', "Go to File"), needsEditor: false }] }); quickAccessRegistry.registerQuickAccessProvider({ ctor: SymbolsQuickAccessProvider, prefix: SymbolsQuickAccessProvider.PREFIX, placeholder: nls.localize('symbolsQuickAccessPlaceholder', "Type the name of a symbol to open."), contextKey: 'inWorkspaceSymbolsPicker', helpEntries: [{ description: nls.localize('symbolsQuickAccess', "Go to Symbol in Workspace"), needsEditor: false }] }); // Configuration const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration); configurationRegistry.registerConfiguration({ id: 'search', order: 13, title: nls.localize('searchConfigurationTitle', "Search"), type: 'object', properties: { [SEARCH_EXCLUDE_CONFIG]: { type: 'object', markdownDescription: nls.localize('exclude', "Configure glob patterns for excluding files and folders in fulltext searches and quick open. Inherits all glob patterns from the `#files.exclude#` setting. Read more about glob patterns [here](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options)."), default: { '**/node_modules': true, '**/bower_components': true, '**/*.code-search': true }, additionalProperties: { anyOf: [ { type: 'boolean', description: nls.localize('exclude.boolean', "The glob pattern to match file paths against. Set to true or false to enable or disable the pattern."), }, { type: 'object', properties: { when: { type: 'string', // expression ({ "**/*.js": { "when": "$(basename).js" } }) pattern: '\\w*\\$\\(basename\\)\\w*', default: '$(basename).ext', description: nls.localize('exclude.when', 'Additional check on the siblings of a matching file. Use $(basename) as variable for the matching file name.') } } } ] }, scope: ConfigurationScope.RESOURCE }, 'search.useRipgrep': { type: 'boolean', description: nls.localize('useRipgrep', "This setting is deprecated and now falls back on \"search.usePCRE2\"."), deprecationMessage: nls.localize('useRipgrepDeprecated', "Deprecated. Consider \"search.usePCRE2\" for advanced regex feature support."), default: true }, 'search.maintainFileSearchCache': { type: 'boolean', description: nls.localize('search.maintainFileSearchCache', "When enabled, the searchService process will be kept alive instead of being shut down after an hour of inactivity. This will keep the file search cache in memory."), default: false }, 'search.useIgnoreFiles': { type: 'boolean', markdownDescription: nls.localize('useIgnoreFiles', "Controls whether to use `.gitignore` and `.ignore` files when searching for files."), default: true, scope: ConfigurationScope.RESOURCE }, 'search.useGlobalIgnoreFiles': { type: 'boolean', markdownDescription: nls.localize('useGlobalIgnoreFiles', "Controls whether to use global `.gitignore` and `.ignore` files when searching for files."), default: false, scope: ConfigurationScope.RESOURCE }, 'search.quickOpen.includeSymbols': { type: 'boolean', description: nls.localize('search.quickOpen.includeSymbols', "Whether to include results from a global symbol search in the file results for Quick Open."), default: false }, 'search.quickOpen.includeHistory': { type: 'boolean', description: nls.localize('search.quickOpen.includeHistory', "Whether to include results from recently opened files in the file results for Quick Open."), default: true }, 'search.quickOpen.history.filterSortOrder': { 'type': 'string', 'enum': ['default', 'recency'], 'default': 'default', 'enumDescriptions': [ nls.localize('filterSortOrder.default', 'History entries are sorted by relevance based on the filter value used. More relevant entries appear first.'), nls.localize('filterSortOrder.recency', 'History entries are sorted by recency. More recently opened entries appear first.') ], 'description': nls.localize('filterSortOrder', "Controls sorting order of editor history in quick open when filtering.") }, 'search.followSymlinks': { type: 'boolean', description: nls.localize('search.followSymlinks', "Controls whether to follow symlinks while searching."), default: true }, 'search.smartCase': { type: 'boolean', description: nls.localize('search.smartCase', "Search case-insensitively if the pattern is all lowercase, otherwise, search case-sensitively."), default: false }, 'search.globalFindClipboard': { type: 'boolean', default: false, description: nls.localize('search.globalFindClipboard', "Controls whether the search view should read or modify the shared find clipboard on macOS."), included: platform.isMacintosh }, 'search.location': { type: 'string', enum: ['sidebar', 'panel'], default: 'sidebar', description: nls.localize('search.location', "Controls whether the search will be shown as a view in the sidebar or as a panel in the panel area for more horizontal space."), deprecationMessage: nls.localize('search.location.deprecationMessage', "This setting is deprecated. Please use drag and drop instead by dragging the search icon.") }, 'search.collapseResults': { type: 'string', enum: ['auto', 'alwaysCollapse', 'alwaysExpand'], enumDescriptions: [ nls.localize('search.collapseResults.auto', "Files with less than 10 results are expanded. Others are collapsed."), '', '' ], default: 'alwaysExpand', description: nls.localize('search.collapseAllResults', "Controls whether the search results will be collapsed or expanded."), }, 'search.useReplacePreview': { type: 'boolean', default: true, description: nls.localize('search.useReplacePreview', "Controls whether to open Replace Preview when selecting or replacing a match."), }, 'search.showLineNumbers': { type: 'boolean', default: false, description: nls.localize('search.showLineNumbers', "Controls whether to show line numbers for search results."), }, 'search.usePCRE2': { type: 'boolean', default: false, description: nls.localize('search.usePCRE2', "Whether to use the PCRE2 regex engine in text search. This enables using some advanced regex features like lookahead and backreferences. However, not all PCRE2 features are supported - only features that are also supported by JavaScript."), deprecationMessage: nls.localize('usePCRE2Deprecated', "Deprecated. PCRE2 will be used automatically when using regex features that are only supported by PCRE2."), }, 'search.actionsPosition': { type: 'string', enum: ['auto', 'right'], enumDescriptions: [ nls.localize('search.actionsPositionAuto', "Position the actionbar to the right when the search view is narrow, and immediately after the content when the search view is wide."), nls.localize('search.actionsPositionRight', "Always position the actionbar to the right."), ], default: 'auto', description: nls.localize('search.actionsPosition', "Controls the positioning of the actionbar on rows in the search view.") }, 'search.searchOnType': { type: 'boolean', default: true, description: nls.localize('search.searchOnType', "Search all files as you type.") }, 'search.seedWithNearestWord': { type: 'boolean', default: false, description: nls.localize('search.seedWithNearestWord', "Enable seeding search from the word nearest the cursor when the active editor has no selection.") }, 'search.seedOnFocus': { type: 'boolean', default: false, description: nls.localize('search.seedOnFocus', "Update workspace search query to the editor's selected text when focusing the search view. This happens either on click or when triggering the `workbench.views.search.focus` command.") }, 'search.searchOnTypeDebouncePeriod': { type: 'number', default: 300, markdownDescription: nls.localize('search.searchOnTypeDebouncePeriod', "When `#search.searchOnType#` is enabled, controls the timeout in milliseconds between a character being typed and the search starting. Has no effect when `search.searchOnType` is disabled.") }, 'search.searchEditor.doubleClickBehaviour': { type: 'string', enum: ['selectWord', 'goToLocation', 'openLocationToSide'], default: 'goToLocation', enumDescriptions: [ nls.localize('search.searchEditor.doubleClickBehaviour.selectWord', "Double clicking selects the word under the cursor."), nls.localize('search.searchEditor.doubleClickBehaviour.goToLocation', "Double clicking opens the result in the active editor group."), nls.localize('search.searchEditor.doubleClickBehaviour.openLocationToSide', "Double clicking opens the result in the editor group to the side, creating one if it does not yet exist."), ], markdownDescription: nls.localize('search.searchEditor.doubleClickBehaviour', "Configure effect of double clicking a result in a search editor.") }, 'search.searchEditor.reusePriorSearchConfiguration': { type: 'boolean', default: false, markdownDescription: nls.localize({ key: 'search.searchEditor.reusePriorSearchConfiguration', comment: ['"Search Editor" is a type that editor that can display search results. "includes, excludes, and flags" just refers to settings that affect search. For example, the "search.exclude" setting.'] }, "When enabled, new Search Editors will reuse the includes, excludes, and flags of the previously opened Search Editor") }, 'search.searchEditor.defaultNumberOfContextLines': { type: ['number', 'null'], default: 1, markdownDescription: nls.localize('search.searchEditor.defaultNumberOfContextLines', "The default number of surrounding context lines to use when creating new Search Editors. If using `#search.searchEditor.reusePriorSearchConfiguration#`, this can be set to `null` (empty) to use the prior Search Editor's configuration.") }, 'search.sortOrder': { 'type': 'string', 'enum': [SearchSortOrder.Default, SearchSortOrder.FileNames, SearchSortOrder.Type, SearchSortOrder.Modified, SearchSortOrder.CountDescending, SearchSortOrder.CountAscending], 'default': SearchSortOrder.Default, 'enumDescriptions': [ nls.localize('searchSortOrder.default', "Results are sorted by folder and file names, in alphabetical order."), nls.localize('searchSortOrder.filesOnly', "Results are sorted by file names ignoring folder order, in alphabetical order."), nls.localize('searchSortOrder.type', "Results are sorted by file extensions, in alphabetical order."), nls.localize('searchSortOrder.modified', "Results are sorted by file last modified date, in descending order."), nls.localize('searchSortOrder.countDescending', "Results are sorted by count per file, in descending order."), nls.localize('searchSortOrder.countAscending', "Results are sorted by count per file, in ascending order.") ], 'description': nls.localize('search.sortOrder', "Controls sorting order of search results.") }, } }); CommandsRegistry.registerCommand('_executeWorkspaceSymbolProvider', function (accessor, ...args) { const [query] = args; assertType(typeof query === 'string'); return getWorkspaceSymbols(query); }); // View menu MenuRegistry.appendMenuItem(MenuId.MenubarViewMenu, { group: '3_views', command: { id: VIEWLET_ID, title: nls.localize({ key: 'miViewSearch', comment: ['&& denotes a mnemonic'] }, "&&Search") }, order: 2 }); // Go to menu MenuRegistry.appendMenuItem(MenuId.MenubarGoMenu, { group: '3_global_nav', command: { id: 'workbench.action.showAllSymbols', title: nls.localize({ key: 'miGotoSymbolInWorkspace', comment: ['&& denotes a mnemonic'] }, "Go to Symbol in &&Workspace...") }, order: 2 });
src/vs/workbench/contrib/search/browser/search.contribution.ts
1
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.9978744983673096, 0.06410731375217438, 0.00016351394879166037, 0.00017441016098018736, 0.23768672347068787 ]
{ "id": 1, "code_window": [ "\n", "replaceContributions();\n", "searchWidgetContributions();\n", "\n", "const category = nls.localize('search', \"Search\");\n", "\n", "KeybindingsRegistry.registerCommandAndKeybindingRule({\n", "\tid: 'workbench.action.search.toggleQueryDetails',\n", "\tweight: KeybindingWeight.WorkbenchContrib,\n", "\twhen: ContextKeyExpr.or(Constants.SearchViewFocusedKey, SearchEditorConstants.InSearchEditor),\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const category = { value: nls.localize('search', \"Search\"), original: 'Search' };\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 65 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { createHash } from 'crypto'; import { stat } from 'vs/base/node/pfs'; import { Schemas } from 'vs/base/common/network'; import { URI } from 'vs/base/common/uri'; import { isLinux, isMacintosh, isWindows } from 'vs/base/common/platform'; import { IResourceIdentityService } from 'vs/platform/resource/common/resourceIdentityService'; import { Disposable } from 'vs/base/common/lifecycle'; import { ResourceMap } from 'vs/base/common/map'; export class NativeResourceIdentityService extends Disposable implements IResourceIdentityService { declare readonly _serviceBrand: undefined; private readonly cache: ResourceMap<Promise<string>> = new ResourceMap<Promise<string>>(); resolveResourceIdentity(resource: URI): Promise<string> { let promise = this.cache.get(resource); if (!promise) { promise = this.createIdentity(resource); this.cache.set(resource, promise); } return promise; } private async createIdentity(resource: URI): Promise<string> { // Return early the folder is not local if (resource.scheme !== Schemas.file) { return createHash('md5').update(resource.toString()).digest('hex'); } const fileStat = await stat(resource.fsPath); let ctime: number | undefined; if (isLinux) { ctime = fileStat.ino; // Linux: birthtime is ctime, so we cannot use it! We use the ino instead! } else if (isMacintosh) { ctime = fileStat.birthtime.getTime(); // macOS: birthtime is fine to use as is } else if (isWindows) { if (typeof fileStat.birthtimeMs === 'number') { ctime = Math.floor(fileStat.birthtimeMs); // Windows: fix precision issue in node.js 8.x to get 7.x results (see https://github.com/nodejs/node/issues/19897) } else { ctime = fileStat.birthtime.getTime(); } } // we use the ctime as extra salt to the ID so that we catch the case of a folder getting // deleted and recreated. in that case we do not want to carry over previous state return createHash('md5').update(resource.fsPath).update(ctime ? String(ctime) : '').digest('hex'); } }
src/vs/platform/resource/node/resourceIdentityServiceImpl.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00017740429029799998, 0.00017563794972375035, 0.00017144742014352232, 0.0001761389139574021, 0.00000197173153537733 ]
{ "id": 1, "code_window": [ "\n", "replaceContributions();\n", "searchWidgetContributions();\n", "\n", "const category = nls.localize('search', \"Search\");\n", "\n", "KeybindingsRegistry.registerCommandAndKeybindingRule({\n", "\tid: 'workbench.action.search.toggleQueryDetails',\n", "\tweight: KeybindingWeight.WorkbenchContrib,\n", "\twhen: ContextKeyExpr.or(Constants.SearchViewFocusedKey, SearchEditorConstants.InSearchEditor),\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const category = { value: nls.localize('search', \"Search\"), original: 'Search' };\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 65 }
/*--------------------------------------------------------------------------------------------- * 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!./standalone-tokens'; import { IDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { OpenerService } from 'vs/editor/browser/services/openerService'; import { DiffNavigator, IDiffNavigator } from 'vs/editor/browser/widget/diffNavigator'; import { EditorOptions, ConfigurationChangedEvent } from 'vs/editor/common/config/editorOptions'; import { BareFontInfo, FontInfo } from 'vs/editor/common/config/fontInfo'; import { Token } from 'vs/editor/common/core/token'; import { IEditor, EditorType } from 'vs/editor/common/editorCommon'; import { FindMatch, ITextModel, TextModelResolvedOptions } from 'vs/editor/common/model'; import * as modes from 'vs/editor/common/modes'; import { NULL_STATE, nullTokenize } from 'vs/editor/common/modes/nullMode'; import { IEditorWorkerService } from 'vs/editor/common/services/editorWorkerService'; import { ILanguageSelection } from 'vs/editor/common/services/modeService'; import { ITextModelService } from 'vs/editor/common/services/resolverService'; import { IWebWorkerOptions, MonacoWebWorker, createWebWorker as actualCreateWebWorker } from 'vs/editor/common/services/webWorker'; import * as standaloneEnums from 'vs/editor/common/standalone/standaloneEnums'; import { Colorizer, IColorizerElementOptions, IColorizerOptions } from 'vs/editor/standalone/browser/colorizer'; import { SimpleEditorModelResolverService } from 'vs/editor/standalone/browser/simpleServices'; import { IDiffEditorConstructionOptions, IStandaloneEditorConstructionOptions, IStandaloneCodeEditor, IStandaloneDiffEditor, StandaloneDiffEditor, StandaloneEditor } from 'vs/editor/standalone/browser/standaloneCodeEditor'; import { DynamicStandaloneServices, IEditorOverrideServices, StaticServices } from 'vs/editor/standalone/browser/standaloneServices'; import { IStandaloneThemeData, IStandaloneThemeService } from 'vs/editor/standalone/common/standaloneThemeService'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IContextViewService, IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IMarker, IMarkerData } from 'vs/platform/markers/common/markers'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { IAccessibilityService } from 'vs/platform/accessibility/common/accessibility'; import { clearAllFontInfos } from 'vs/editor/browser/config/configuration'; import { IEditorProgressService } from 'vs/platform/progress/common/progress'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { StandaloneThemeServiceImpl } from 'vs/editor/standalone/browser/standaloneThemeServiceImpl'; type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>; function withAllStandaloneServices<T extends IEditor>(domElement: HTMLElement, override: IEditorOverrideServices, callback: (services: DynamicStandaloneServices) => T): T { let services = new DynamicStandaloneServices(domElement, override); let simpleEditorModelResolverService: SimpleEditorModelResolverService | null = null; if (!services.has(ITextModelService)) { simpleEditorModelResolverService = new SimpleEditorModelResolverService(StaticServices.modelService.get()); services.set(ITextModelService, simpleEditorModelResolverService); } if (!services.has(IOpenerService)) { services.set(IOpenerService, new OpenerService(services.get(ICodeEditorService), services.get(ICommandService))); } let result = callback(services); if (simpleEditorModelResolverService) { simpleEditorModelResolverService.setEditor(result); } return result; } /** * Create a new editor under `domElement`. * `domElement` should be empty (not contain other dom nodes). * The editor will read the size of `domElement`. */ export function create(domElement: HTMLElement, options?: IStandaloneEditorConstructionOptions, override?: IEditorOverrideServices): IStandaloneCodeEditor { return withAllStandaloneServices(domElement, override || {}, (services) => { return new StandaloneEditor( domElement, options, services, services.get(IInstantiationService), services.get(ICodeEditorService), services.get(ICommandService), services.get(IContextKeyService), services.get(IKeybindingService), services.get(IContextViewService), services.get(IStandaloneThemeService), services.get(INotificationService), services.get(IConfigurationService), services.get(IAccessibilityService) ); }); } /** * Emitted when an editor is created. * Creating a diff editor might cause this listener to be invoked with the two editors. * @event */ export function onDidCreateEditor(listener: (codeEditor: ICodeEditor) => void): IDisposable { return StaticServices.codeEditorService.get().onCodeEditorAdd((editor) => { listener(<ICodeEditor>editor); }); } /** * Create a new diff editor under `domElement`. * `domElement` should be empty (not contain other dom nodes). * The editor will read the size of `domElement`. */ export function createDiffEditor(domElement: HTMLElement, options?: IDiffEditorConstructionOptions, override?: IEditorOverrideServices): IStandaloneDiffEditor { return withAllStandaloneServices(domElement, override || {}, (services) => { return new StandaloneDiffEditor( domElement, options, services, services.get(IInstantiationService), services.get(IContextKeyService), services.get(IKeybindingService), services.get(IContextViewService), services.get(IEditorWorkerService), services.get(ICodeEditorService), services.get(IStandaloneThemeService), services.get(INotificationService), services.get(IConfigurationService), services.get(IContextMenuService), services.get(IEditorProgressService), services.get(IClipboardService) ); }); } export interface IDiffNavigatorOptions { readonly followsCaret?: boolean; readonly ignoreCharChanges?: boolean; readonly alwaysRevealFirst?: boolean; } export function createDiffNavigator(diffEditor: IStandaloneDiffEditor, opts?: IDiffNavigatorOptions): IDiffNavigator { return new DiffNavigator(diffEditor, opts); } function doCreateModel(value: string, languageSelection: ILanguageSelection, uri?: URI): ITextModel { return StaticServices.modelService.get().createModel(value, languageSelection, uri); } /** * Create a new editor model. * You can specify the language that should be set for this model or let the language be inferred from the `uri`. */ export function createModel(value: string, language?: string, uri?: URI): ITextModel { value = value || ''; if (!language) { let firstLF = value.indexOf('\n'); let firstLine = value; if (firstLF !== -1) { firstLine = value.substring(0, firstLF); } return doCreateModel(value, StaticServices.modeService.get().createByFilepathOrFirstLine(uri || null, firstLine), uri); } return doCreateModel(value, StaticServices.modeService.get().create(language), uri); } /** * Change the language for a model. */ export function setModelLanguage(model: ITextModel, languageId: string): void { StaticServices.modelService.get().setMode(model, StaticServices.modeService.get().create(languageId)); } /** * Set the markers for a model. */ export function setModelMarkers(model: ITextModel, owner: string, markers: IMarkerData[]): void { if (model) { StaticServices.markerService.get().changeOne(owner, model.uri, markers); } } /** * Get markers for owner and/or resource * * @returns list of markers */ export function getModelMarkers(filter: { owner?: string, resource?: URI, take?: number }): IMarker[] { return StaticServices.markerService.get().read(filter); } /** * Get the model that has `uri` if it exists. */ export function getModel(uri: URI): ITextModel | null { return StaticServices.modelService.get().getModel(uri); } /** * Get all the created models. */ export function getModels(): ITextModel[] { return StaticServices.modelService.get().getModels(); } /** * Emitted when a model is created. * @event */ export function onDidCreateModel(listener: (model: ITextModel) => void): IDisposable { return StaticServices.modelService.get().onModelAdded(listener); } /** * Emitted right before a model is disposed. * @event */ export function onWillDisposeModel(listener: (model: ITextModel) => void): IDisposable { return StaticServices.modelService.get().onModelRemoved(listener); } /** * Emitted when a different language is set to a model. * @event */ export function onDidChangeModelLanguage(listener: (e: { readonly model: ITextModel; readonly oldLanguage: string; }) => void): IDisposable { return StaticServices.modelService.get().onModelModeChanged((e) => { listener({ model: e.model, oldLanguage: e.oldModeId }); }); } /** * Create a new web worker that has model syncing capabilities built in. * Specify an AMD module to load that will `create` an object that will be proxied. */ export function createWebWorker<T>(opts: IWebWorkerOptions): MonacoWebWorker<T> { return actualCreateWebWorker<T>(StaticServices.modelService.get(), opts); } /** * Colorize the contents of `domNode` using attribute `data-lang`. */ export function colorizeElement(domNode: HTMLElement, options: IColorizerElementOptions): Promise<void> { const themeService = <StandaloneThemeServiceImpl>StaticServices.standaloneThemeService.get(); themeService.registerEditorContainer(domNode); return Colorizer.colorizeElement(themeService, StaticServices.modeService.get(), domNode, options); } /** * Colorize `text` using language `languageId`. */ export function colorize(text: string, languageId: string, options: IColorizerOptions): Promise<string> { const themeService = <StandaloneThemeServiceImpl>StaticServices.standaloneThemeService.get(); themeService.registerEditorContainer(document.body); return Colorizer.colorize(StaticServices.modeService.get(), text, languageId, options); } /** * Colorize a line in a model. */ export function colorizeModelLine(model: ITextModel, lineNumber: number, tabSize: number = 4): string { const themeService = <StandaloneThemeServiceImpl>StaticServices.standaloneThemeService.get(); themeService.registerEditorContainer(document.body); return Colorizer.colorizeModelLine(model, lineNumber, tabSize); } /** * @internal */ function getSafeTokenizationSupport(language: string): Omit<modes.ITokenizationSupport, 'tokenize2'> { let tokenizationSupport = modes.TokenizationRegistry.get(language); if (tokenizationSupport) { return tokenizationSupport; } return { getInitialState: () => NULL_STATE, tokenize: (line: string, state: modes.IState, deltaOffset: number) => nullTokenize(language, line, state, deltaOffset) }; } /** * Tokenize `text` using language `languageId` */ export function tokenize(text: string, languageId: string): Token[][] { let modeService = StaticServices.modeService.get(); // Needed in order to get the mode registered for subsequent look-ups modeService.triggerMode(languageId); let tokenizationSupport = getSafeTokenizationSupport(languageId); let lines = text.split(/\r\n|\r|\n/); let result: Token[][] = []; let state = tokenizationSupport.getInitialState(); for (let i = 0, len = lines.length; i < len; i++) { let line = lines[i]; let tokenizationResult = tokenizationSupport.tokenize(line, state, 0); result[i] = tokenizationResult.tokens; state = tokenizationResult.endState; } return result; } /** * Define a new theme or update an existing theme. */ export function defineTheme(themeName: string, themeData: IStandaloneThemeData): void { StaticServices.standaloneThemeService.get().defineTheme(themeName, themeData); } /** * Switches to a theme. */ export function setTheme(themeName: string): void { StaticServices.standaloneThemeService.get().setTheme(themeName); } /** * Clears all cached font measurements and triggers re-measurement. */ export function remeasureFonts(): void { clearAllFontInfos(); } /** * @internal */ export function createMonacoEditorAPI(): typeof monaco.editor { return { // methods create: <any>create, onDidCreateEditor: <any>onDidCreateEditor, createDiffEditor: <any>createDiffEditor, createDiffNavigator: <any>createDiffNavigator, createModel: <any>createModel, setModelLanguage: <any>setModelLanguage, setModelMarkers: <any>setModelMarkers, getModelMarkers: <any>getModelMarkers, getModels: <any>getModels, getModel: <any>getModel, onDidCreateModel: <any>onDidCreateModel, onWillDisposeModel: <any>onWillDisposeModel, onDidChangeModelLanguage: <any>onDidChangeModelLanguage, createWebWorker: <any>createWebWorker, colorizeElement: <any>colorizeElement, colorize: <any>colorize, colorizeModelLine: <any>colorizeModelLine, tokenize: <any>tokenize, defineTheme: <any>defineTheme, setTheme: <any>setTheme, remeasureFonts: remeasureFonts, // enums AccessibilitySupport: standaloneEnums.AccessibilitySupport, ContentWidgetPositionPreference: standaloneEnums.ContentWidgetPositionPreference, CursorChangeReason: standaloneEnums.CursorChangeReason, DefaultEndOfLine: standaloneEnums.DefaultEndOfLine, EditorAutoIndentStrategy: standaloneEnums.EditorAutoIndentStrategy, EditorOption: standaloneEnums.EditorOption, EndOfLinePreference: standaloneEnums.EndOfLinePreference, EndOfLineSequence: standaloneEnums.EndOfLineSequence, MinimapPosition: standaloneEnums.MinimapPosition, MouseTargetType: standaloneEnums.MouseTargetType, OverlayWidgetPositionPreference: standaloneEnums.OverlayWidgetPositionPreference, OverviewRulerLane: standaloneEnums.OverviewRulerLane, RenderLineNumbersType: standaloneEnums.RenderLineNumbersType, RenderMinimap: standaloneEnums.RenderMinimap, ScrollbarVisibility: standaloneEnums.ScrollbarVisibility, ScrollType: standaloneEnums.ScrollType, TextEditorCursorBlinkingStyle: standaloneEnums.TextEditorCursorBlinkingStyle, TextEditorCursorStyle: standaloneEnums.TextEditorCursorStyle, TrackedRangeStickiness: standaloneEnums.TrackedRangeStickiness, WrappingIndent: standaloneEnums.WrappingIndent, // classes ConfigurationChangedEvent: <any>ConfigurationChangedEvent, BareFontInfo: <any>BareFontInfo, FontInfo: <any>FontInfo, TextModelResolvedOptions: <any>TextModelResolvedOptions, FindMatch: <any>FindMatch, // vars EditorType: EditorType, EditorOptions: <any>EditorOptions }; }
src/vs/editor/standalone/browser/standaloneEditor.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00017748583923093975, 0.00017311055853497237, 0.0001629632752155885, 0.00017356465104967356, 0.000004030988293379778 ]
{ "id": 1, "code_window": [ "\n", "replaceContributions();\n", "searchWidgetContributions();\n", "\n", "const category = nls.localize('search', \"Search\");\n", "\n", "KeybindingsRegistry.registerCommandAndKeybindingRule({\n", "\tid: 'workbench.action.search.toggleQueryDetails',\n", "\tweight: KeybindingWeight.WorkbenchContrib,\n", "\twhen: ContextKeyExpr.or(Constants.SearchViewFocusedKey, SearchEditorConstants.InSearchEditor),\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const category = { value: nls.localize('search', \"Search\"), original: 'Search' };\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 65 }
{ "extends": "../shared.tsconfig.json", "compilerOptions": { "outDir": "./out" }, "include": [ "src/**/*" ] }
extensions/python/tsconfig.json
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00017662839672993869, 0.00017662839672993869, 0.00017662839672993869, 0.00017662839672993869, 0 ]
{ "id": 2, "code_window": [ "\tgroup: 'search_3',\n", "\torder: 1\n", "});\n", "\n", "const clearSearchHistoryLabel = nls.localize('clearSearchHistoryLabel', \"Clear Search History\");\n", "const ClearSearchHistoryCommand: ICommandAction = {\n", "\tid: Constants.ClearSearchHistoryCommandId,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 370 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Action } from 'vs/base/common/actions'; import { distinct } from 'vs/base/common/arrays'; import { onUnexpectedError } from 'vs/base/common/errors'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import * as objects from 'vs/base/common/objects'; import * as platform from 'vs/base/common/platform'; import { dirname } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { ToggleCaseSensitiveKeybinding, ToggleRegexKeybinding, ToggleWholeWordKeybinding } from 'vs/editor/contrib/find/findModel'; import * as nls from 'vs/nls'; import { ICommandAction, MenuId, MenuRegistry, SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { CommandsRegistry, ICommandHandler } from 'vs/platform/commands/common/commands'; import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry'; import { ContextKeyExpr, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IFileService } from 'vs/platform/files/common/files'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { IListService, WorkbenchListFocusContextKey, WorkbenchObjectTree } from 'vs/platform/list/browser/listService'; import { Registry } from 'vs/platform/registry/common/platform'; import { defaultQuickAccessContextKeyValue } from 'vs/workbench/browser/quickaccess'; import { Extensions as ActionExtensions, IWorkbenchActionRegistry } from 'vs/workbench/common/actions'; import { Extensions as WorkbenchExtensions, IWorkbenchContribution, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions'; import { Extensions as ViewExtensions, IViewsRegistry, IViewContainersRegistry, ViewContainerLocation, IViewDescriptorService, IViewsService } from 'vs/workbench/common/views'; import { getMultiSelectedResources } from 'vs/workbench/contrib/files/browser/files'; import { ExplorerFolderContext, ExplorerRootContext, FilesExplorerFocusCondition, IExplorerService, VIEWLET_ID as VIEWLET_ID_FILES } from 'vs/workbench/contrib/files/common/files'; import { registerContributions as replaceContributions } from 'vs/workbench/contrib/search/browser/replaceContributions'; import { clearHistoryCommand, ClearSearchResultsAction, CloseReplaceAction, CollapseDeepestExpandedLevelAction, copyAllCommand, copyMatchCommand, copyPathCommand, FocusNextInputAction, FocusNextSearchResultAction, FocusPreviousInputAction, FocusPreviousSearchResultAction, focusSearchListCommand, getSearchView, openSearchView, OpenSearchViewletAction, RefreshAction, RemoveAction, ReplaceAction, ReplaceAllAction, ReplaceAllInFolderAction, ReplaceInFilesAction, toggleCaseSensitiveCommand, toggleRegexCommand, toggleWholeWordCommand, FindInFilesCommand, ToggleSearchOnTypeAction, ExpandAllAction } from 'vs/workbench/contrib/search/browser/searchActions'; import { SearchView } from 'vs/workbench/contrib/search/browser/searchView'; import { registerContributions as searchWidgetContributions } from 'vs/workbench/contrib/search/browser/searchWidget'; import * as Constants from 'vs/workbench/contrib/search/common/constants'; import * as SearchEditorConstants from 'vs/workbench/contrib/searchEditor/browser/constants'; import { getWorkspaceSymbols } from 'vs/workbench/contrib/search/common/search'; import { ISearchHistoryService, SearchHistoryService } from 'vs/workbench/contrib/search/common/searchHistoryService'; import { FileMatchOrMatch, ISearchWorkbenchService, RenderableMatch, SearchWorkbenchService, FileMatch, Match, FolderMatch } from 'vs/workbench/contrib/search/common/searchModel'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { VIEWLET_ID, VIEW_ID, SEARCH_EXCLUDE_CONFIG, SearchSortOrder } from 'vs/workbench/services/search/common/search'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { ExplorerViewPaneContainer } from 'vs/workbench/contrib/files/browser/explorerViewlet'; import { assertType, assertIsDefined } from 'vs/base/common/types'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { SearchEditor } from 'vs/workbench/contrib/searchEditor/browser/searchEditor'; import { ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { IQuickAccessRegistry, Extensions as QuickAccessExtensions } from 'vs/platform/quickinput/common/quickAccess'; import { SymbolsQuickAccessProvider } from 'vs/workbench/contrib/search/browser/symbolsQuickAccess'; import { AnythingQuickAccessProvider } from 'vs/workbench/contrib/search/browser/anythingQuickAccess'; import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { AbstractGotoLineQuickAccessProvider } from 'vs/editor/contrib/quickAccess/gotoLineQuickAccess'; import { GotoSymbolQuickAccessProvider } from 'vs/workbench/contrib/codeEditor/browser/quickaccess/gotoSymbolQuickAccess'; import { searchViewIcon } from 'vs/workbench/contrib/search/browser/searchIcons'; registerSingleton(ISearchWorkbenchService, SearchWorkbenchService, true); registerSingleton(ISearchHistoryService, SearchHistoryService, true); replaceContributions(); searchWidgetContributions(); const category = nls.localize('search', "Search"); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'workbench.action.search.toggleQueryDetails', weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or(Constants.SearchViewFocusedKey, SearchEditorConstants.InSearchEditor), primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_J, handler: accessor => { const contextService = accessor.get(IContextKeyService).getContext(document.activeElement); if (contextService.getValue(SearchEditorConstants.InSearchEditor.serialize())) { (accessor.get(IEditorService).activeEditorPane as SearchEditor).toggleQueryDetails(); } else if (contextService.getValue(Constants.SearchViewFocusedKey.serialize())) { const searchView = getSearchView(accessor.get(IViewsService)); assertIsDefined(searchView).toggleQueryDetails(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.FocusSearchFromResults, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FirstMatchFocusKey), primary: KeyMod.CtrlCmd | KeyCode.UpArrow, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { searchView.focusPreviousInputBox(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.OpenMatchToSide, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyMod.CtrlCmd | KeyCode.Enter, mac: { primary: KeyMod.WinCtrl | KeyCode.Enter }, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); searchView.open(<FileMatchOrMatch>tree.getFocus()[0], false, true, true); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CancelActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, WorkbenchListFocusContextKey), primary: KeyCode.Escape, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { searchView.cancelSearch(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.RemoveActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyCode.Delete, mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace, }, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(RemoveAction, tree, tree.getFocus()[0]!).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.MatchFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAction, tree, tree.getFocus()[0] as Match, searchView).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceAllInFileActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.FileFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter], handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAllAction, searchView, tree.getFocus()[0] as FileMatch).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceAllInFolderActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.FolderFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter], handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAllInFolderAction, tree, tree.getFocus()[0] as FolderMatch).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CloseReplaceWidgetActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceInputBoxFocusedKey), primary: KeyCode.Escape, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(CloseReplaceAction, Constants.CloseReplaceWidgetActionId, '').run(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FocusNextInputAction.ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or( ContextKeyExpr.and(SearchEditorConstants.InSearchEditor, Constants.InputBoxFocusedKey), ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.InputBoxFocusedKey)), primary: KeyMod.CtrlCmd | KeyCode.DownArrow, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(FocusNextInputAction, FocusNextInputAction.ID, '').run(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FocusPreviousInputAction.ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or( ContextKeyExpr.and(SearchEditorConstants.InSearchEditor, Constants.InputBoxFocusedKey), ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.InputBoxFocusedKey, Constants.SearchInputBoxFocusedKey.toNegated())), primary: KeyMod.CtrlCmd | KeyCode.UpArrow, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(FocusPreviousInputAction, FocusPreviousInputAction.ID, '').run(); } }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceActionId, title: ReplaceAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.MatchFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceAllInFolderActionId, title: ReplaceAllInFolderAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.FolderFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceAllInFileActionId, title: ReplaceAllAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.FileFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.RemoveActionId, title: RemoveAction.LABEL }, when: Constants.FileMatchOrMatchFocusKey, group: 'search', order: 2 }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CopyMatchCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.FileMatchOrMatchFocusKey, primary: KeyMod.CtrlCmd | KeyCode.KEY_C, handler: copyMatchCommand }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyMatchCommandId, title: nls.localize('copyMatchLabel', "Copy") }, when: Constants.FileMatchOrMatchFocusKey, group: 'search_2', order: 1 }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CopyPathCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.FileMatchOrFolderMatchWithResourceFocusKey, primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_C, win: { primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_C }, handler: copyPathCommand }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyPathCommandId, title: nls.localize('copyPathLabel', "Copy Path") }, when: Constants.FileMatchOrFolderMatchWithResourceFocusKey, group: 'search_2', order: 2 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyAllCommandId, title: nls.localize('copyAllLabel', "Copy All") }, when: Constants.HasSearchResults, group: 'search_2', order: 3 }); CommandsRegistry.registerCommand({ id: Constants.CopyAllCommandId, handler: copyAllCommand }); CommandsRegistry.registerCommand({ id: Constants.ClearSearchHistoryCommandId, handler: clearHistoryCommand }); CommandsRegistry.registerCommand({ id: Constants.RevealInSideBarForSearchResults, handler: (accessor, args: any) => { const viewletService = accessor.get(IViewletService); const explorerService = accessor.get(IExplorerService); const contextService = accessor.get(IWorkspaceContextService); const searchView = getSearchView(accessor.get(IViewsService)); if (!searchView) { return; } let fileMatch: FileMatch; if (!(args instanceof FileMatch)) { args = searchView.getControl().getFocus()[0]; } if (args instanceof FileMatch) { fileMatch = args; } else { return; } viewletService.openViewlet(VIEWLET_ID_FILES, false).then((viewlet) => { if (!viewlet) { return; } const explorerViewContainer = viewlet.getViewPaneContainer() as ExplorerViewPaneContainer; const uri = fileMatch.resource; if (uri && contextService.isInsideWorkspace(uri)) { const explorerView = explorerViewContainer.getExplorerView(); explorerView.setExpanded(true); explorerService.select(uri, true).then(() => explorerView.focus(), onUnexpectedError); } }); } }); const RevealInSideBarForSearchResultsCommand: ICommandAction = { id: Constants.RevealInSideBarForSearchResults, title: nls.localize('revealInSideBar', "Reveal in Side Bar") }; MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: RevealInSideBarForSearchResultsCommand, when: ContextKeyExpr.and(Constants.FileFocusKey, Constants.HasSearchResults), group: 'search_3', order: 1 }); const clearSearchHistoryLabel = nls.localize('clearSearchHistoryLabel', "Clear Search History"); const ClearSearchHistoryCommand: ICommandAction = { id: Constants.ClearSearchHistoryCommandId, title: clearSearchHistoryLabel, category }; MenuRegistry.addCommand(ClearSearchHistoryCommand); CommandsRegistry.registerCommand({ id: Constants.FocusSearchListCommandID, handler: focusSearchListCommand }); const focusSearchListCommandLabel = nls.localize('focusSearchListCommandLabel', "Focus List"); const FocusSearchListCommand: ICommandAction = { id: Constants.FocusSearchListCommandID, title: focusSearchListCommandLabel, category }; MenuRegistry.addCommand(FocusSearchListCommand); const searchInFolderCommand: ICommandHandler = (accessor, resource?: URI) => { const listService = accessor.get(IListService); const fileService = accessor.get(IFileService); const viewsService = accessor.get(IViewsService); const resources = getMultiSelectedResources(resource, listService, accessor.get(IEditorService), accessor.get(IExplorerService)); return openSearchView(viewsService, true).then(searchView => { if (resources && resources.length && searchView) { return fileService.resolveAll(resources.map(resource => ({ resource }))).then(results => { const folders: URI[] = []; results.forEach(result => { if (result.success && result.stat) { folders.push(result.stat.isDirectory ? result.stat.resource : dirname(result.stat.resource)); } }); searchView.searchInFolders(distinct(folders, folder => folder.toString())); }); } return undefined; }); }; const FIND_IN_FOLDER_ID = 'filesExplorer.findInFolder'; KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FIND_IN_FOLDER_ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(FilesExplorerFocusCondition, ExplorerFolderContext), primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_F, handler: searchInFolderCommand }); CommandsRegistry.registerCommand({ id: ClearSearchResultsAction.ID, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(ClearSearchResultsAction, ClearSearchResultsAction.ID, '').run(); } }); CommandsRegistry.registerCommand({ id: RefreshAction.ID, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(RefreshAction, RefreshAction.ID, '').run(); } }); const FIND_IN_WORKSPACE_ID = 'filesExplorer.findInWorkspace'; CommandsRegistry.registerCommand({ id: FIND_IN_WORKSPACE_ID, handler: (accessor) => { return openSearchView(accessor.get(IViewsService), true).then(searchView => { if (searchView) { searchView.searchInFolders(); } }); } }); MenuRegistry.appendMenuItem(MenuId.ExplorerContext, { group: '4_search', order: 10, command: { id: FIND_IN_FOLDER_ID, title: nls.localize('findInFolder', "Find in Folder...") }, when: ContextKeyExpr.and(ExplorerFolderContext) }); MenuRegistry.appendMenuItem(MenuId.ExplorerContext, { group: '4_search', order: 10, command: { id: FIND_IN_WORKSPACE_ID, title: nls.localize('findInWorkspace', "Find in Workspace...") }, when: ContextKeyExpr.and(ExplorerRootContext, ExplorerFolderContext.toNegated()) }); class ShowAllSymbolsAction extends Action { static readonly ID = 'workbench.action.showAllSymbols'; static readonly LABEL = nls.localize('showTriggerActions', "Go to Symbol in Workspace..."); static readonly ALL_SYMBOLS_PREFIX = '#'; constructor( actionId: string, actionLabel: string, @IQuickInputService private readonly quickInputService: IQuickInputService ) { super(actionId, actionLabel); } async run(): Promise<void> { this.quickInputService.quickAccess.show(ShowAllSymbolsAction.ALL_SYMBOLS_PREFIX); } } const viewContainer = Registry.as<IViewContainersRegistry>(ViewExtensions.ViewContainersRegistry).registerViewContainer({ id: VIEWLET_ID, name: nls.localize('name', "Search"), ctorDescriptor: new SyncDescriptor(ViewPaneContainer, [VIEWLET_ID, { mergeViewWithContainerWhenSingleView: true, donotShowContainerTitleWhenMergedWithContainer: true }]), hideIfEmpty: true, icon: searchViewIcon.classNames, order: 1 }, ViewContainerLocation.Sidebar); const viewDescriptor = { id: VIEW_ID, containerIcon: 'codicon-search', name: nls.localize('search', "Search"), ctorDescriptor: new SyncDescriptor(SearchView), canToggleVisibility: false, canMoveView: true }; // Register search default location to sidebar Registry.as<IViewsRegistry>(ViewExtensions.ViewsRegistry).registerViews([viewDescriptor], viewContainer); // Migrate search location setting to new model class RegisterSearchViewContribution implements IWorkbenchContribution { constructor( @IConfigurationService configurationService: IConfigurationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService ) { const data = configurationService.inspect('search.location'); if (data.value === 'panel') { viewDescriptorService.moveViewToLocation(viewDescriptor, ViewContainerLocation.Panel); } if (data.userValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER); } if (data.userLocalValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER_LOCAL); } if (data.userRemoteValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER_REMOTE); } if (data.workspaceFolderValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.WORKSPACE_FOLDER); } if (data.workspaceValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.WORKSPACE); } } } Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(RegisterSearchViewContribution, LifecyclePhase.Starting); // Actions const registry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions); // Show Search and Find in Files are redundant, but we can't break keybindings by removing one. So it's the same action, same keybinding, registered to different IDs. // Show Search 'when' is redundant but if the two conflict with exactly the same keybinding and 'when' clause, then they can show up as "unbound" - #51780 registry.registerWorkbenchAction(SyncActionDescriptor.from(OpenSearchViewletAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_F }, Constants.SearchViewVisibleKey.toNegated()), 'View: Show Search', nls.localize('view', "View")); KeybindingsRegistry.registerCommandAndKeybindingRule({ description: { description: nls.localize('findInFiles.description', "Open the search viewlet"), args: [ { name: nls.localize('findInFiles.args', "A set of options for the search viewlet"), schema: { type: 'object', properties: { query: { 'type': 'string' }, replace: { 'type': 'string' }, triggerSearch: { 'type': 'boolean' }, filesToInclude: { 'type': 'string' }, filesToExclude: { 'type': 'string' }, isRegex: { 'type': 'boolean' }, isCaseSensitive: { 'type': 'boolean' }, matchWholeWord: { 'type': 'boolean' }, } } }, ] }, id: Constants.FindInFilesActionId, weight: KeybindingWeight.WorkbenchContrib, when: null, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_F, handler: FindInFilesCommand }); MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: Constants.FindInFilesActionId, title: { value: nls.localize('findInFiles', "Find in Files"), original: 'Find in Files' }, category } }); MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { group: '4_find_global', command: { id: Constants.FindInFilesActionId, title: nls.localize({ key: 'miFindInFiles', comment: ['&& denotes a mnemonic'] }, "Find &&in Files") }, order: 1 }); registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusNextSearchResultAction, { primary: KeyCode.F4 }), 'Focus Next Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor)); registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusPreviousSearchResultAction, { primary: KeyMod.Shift | KeyCode.F4 }), 'Focus Previous Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor)); registry.registerWorkbenchAction(SyncActionDescriptor.from(ReplaceInFilesAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_H }), 'Replace in Files', category); MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { group: '4_find_global', command: { id: ReplaceInFilesAction.ID, title: nls.localize({ key: 'miReplaceInFiles', comment: ['&& denotes a mnemonic'] }, "Replace &&in Files") }, order: 2 }); if (platform.isMacintosh) { // Register this with a more restrictive `when` on mac to avoid conflict with "copy path" KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleCaseSensitiveCommandId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewFocusedKey, Constants.FileMatchOrFolderMatchFocusKey.toNegated()), handler: toggleCaseSensitiveCommand }, ToggleCaseSensitiveKeybinding)); } else { KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleCaseSensitiveCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleCaseSensitiveCommand }, ToggleCaseSensitiveKeybinding)); } KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleWholeWordCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleWholeWordCommand }, ToggleWholeWordKeybinding)); KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleRegexCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleRegexCommand }, ToggleRegexKeybinding)); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.AddCursorsAtSearchResults, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_L, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); searchView.openEditorWithMultiCursor(<FileMatchOrMatch>tree.getFocus()[0]); } } }); registry.registerWorkbenchAction(SyncActionDescriptor.from(CollapseDeepestExpandedLevelAction), 'Search: Collapse All', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ExpandAllAction), 'Search: Expand All', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ShowAllSymbolsAction, { primary: KeyMod.CtrlCmd | KeyCode.KEY_T }), 'Go to Symbol in Workspace...'); registry.registerWorkbenchAction(SyncActionDescriptor.from(ToggleSearchOnTypeAction), 'Search: Toggle Search on Type', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(RefreshAction), 'Search: Refresh', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ClearSearchResultsAction), 'Search: Clear Search Results', category); // Register Quick Access Handler const quickAccessRegistry = Registry.as<IQuickAccessRegistry>(QuickAccessExtensions.Quickaccess); quickAccessRegistry.registerQuickAccessProvider({ ctor: AnythingQuickAccessProvider, prefix: AnythingQuickAccessProvider.PREFIX, placeholder: nls.localize('anythingQuickAccessPlaceholder', "Search files by name (append {0} to go to line or {1} to go to symbol)", AbstractGotoLineQuickAccessProvider.PREFIX, GotoSymbolQuickAccessProvider.PREFIX), contextKey: defaultQuickAccessContextKeyValue, helpEntries: [{ description: nls.localize('anythingQuickAccess', "Go to File"), needsEditor: false }] }); quickAccessRegistry.registerQuickAccessProvider({ ctor: SymbolsQuickAccessProvider, prefix: SymbolsQuickAccessProvider.PREFIX, placeholder: nls.localize('symbolsQuickAccessPlaceholder', "Type the name of a symbol to open."), contextKey: 'inWorkspaceSymbolsPicker', helpEntries: [{ description: nls.localize('symbolsQuickAccess', "Go to Symbol in Workspace"), needsEditor: false }] }); // Configuration const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration); configurationRegistry.registerConfiguration({ id: 'search', order: 13, title: nls.localize('searchConfigurationTitle', "Search"), type: 'object', properties: { [SEARCH_EXCLUDE_CONFIG]: { type: 'object', markdownDescription: nls.localize('exclude', "Configure glob patterns for excluding files and folders in fulltext searches and quick open. Inherits all glob patterns from the `#files.exclude#` setting. Read more about glob patterns [here](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options)."), default: { '**/node_modules': true, '**/bower_components': true, '**/*.code-search': true }, additionalProperties: { anyOf: [ { type: 'boolean', description: nls.localize('exclude.boolean', "The glob pattern to match file paths against. Set to true or false to enable or disable the pattern."), }, { type: 'object', properties: { when: { type: 'string', // expression ({ "**/*.js": { "when": "$(basename).js" } }) pattern: '\\w*\\$\\(basename\\)\\w*', default: '$(basename).ext', description: nls.localize('exclude.when', 'Additional check on the siblings of a matching file. Use $(basename) as variable for the matching file name.') } } } ] }, scope: ConfigurationScope.RESOURCE }, 'search.useRipgrep': { type: 'boolean', description: nls.localize('useRipgrep', "This setting is deprecated and now falls back on \"search.usePCRE2\"."), deprecationMessage: nls.localize('useRipgrepDeprecated', "Deprecated. Consider \"search.usePCRE2\" for advanced regex feature support."), default: true }, 'search.maintainFileSearchCache': { type: 'boolean', description: nls.localize('search.maintainFileSearchCache', "When enabled, the searchService process will be kept alive instead of being shut down after an hour of inactivity. This will keep the file search cache in memory."), default: false }, 'search.useIgnoreFiles': { type: 'boolean', markdownDescription: nls.localize('useIgnoreFiles', "Controls whether to use `.gitignore` and `.ignore` files when searching for files."), default: true, scope: ConfigurationScope.RESOURCE }, 'search.useGlobalIgnoreFiles': { type: 'boolean', markdownDescription: nls.localize('useGlobalIgnoreFiles', "Controls whether to use global `.gitignore` and `.ignore` files when searching for files."), default: false, scope: ConfigurationScope.RESOURCE }, 'search.quickOpen.includeSymbols': { type: 'boolean', description: nls.localize('search.quickOpen.includeSymbols', "Whether to include results from a global symbol search in the file results for Quick Open."), default: false }, 'search.quickOpen.includeHistory': { type: 'boolean', description: nls.localize('search.quickOpen.includeHistory', "Whether to include results from recently opened files in the file results for Quick Open."), default: true }, 'search.quickOpen.history.filterSortOrder': { 'type': 'string', 'enum': ['default', 'recency'], 'default': 'default', 'enumDescriptions': [ nls.localize('filterSortOrder.default', 'History entries are sorted by relevance based on the filter value used. More relevant entries appear first.'), nls.localize('filterSortOrder.recency', 'History entries are sorted by recency. More recently opened entries appear first.') ], 'description': nls.localize('filterSortOrder', "Controls sorting order of editor history in quick open when filtering.") }, 'search.followSymlinks': { type: 'boolean', description: nls.localize('search.followSymlinks', "Controls whether to follow symlinks while searching."), default: true }, 'search.smartCase': { type: 'boolean', description: nls.localize('search.smartCase', "Search case-insensitively if the pattern is all lowercase, otherwise, search case-sensitively."), default: false }, 'search.globalFindClipboard': { type: 'boolean', default: false, description: nls.localize('search.globalFindClipboard', "Controls whether the search view should read or modify the shared find clipboard on macOS."), included: platform.isMacintosh }, 'search.location': { type: 'string', enum: ['sidebar', 'panel'], default: 'sidebar', description: nls.localize('search.location', "Controls whether the search will be shown as a view in the sidebar or as a panel in the panel area for more horizontal space."), deprecationMessage: nls.localize('search.location.deprecationMessage', "This setting is deprecated. Please use drag and drop instead by dragging the search icon.") }, 'search.collapseResults': { type: 'string', enum: ['auto', 'alwaysCollapse', 'alwaysExpand'], enumDescriptions: [ nls.localize('search.collapseResults.auto', "Files with less than 10 results are expanded. Others are collapsed."), '', '' ], default: 'alwaysExpand', description: nls.localize('search.collapseAllResults', "Controls whether the search results will be collapsed or expanded."), }, 'search.useReplacePreview': { type: 'boolean', default: true, description: nls.localize('search.useReplacePreview', "Controls whether to open Replace Preview when selecting or replacing a match."), }, 'search.showLineNumbers': { type: 'boolean', default: false, description: nls.localize('search.showLineNumbers', "Controls whether to show line numbers for search results."), }, 'search.usePCRE2': { type: 'boolean', default: false, description: nls.localize('search.usePCRE2', "Whether to use the PCRE2 regex engine in text search. This enables using some advanced regex features like lookahead and backreferences. However, not all PCRE2 features are supported - only features that are also supported by JavaScript."), deprecationMessage: nls.localize('usePCRE2Deprecated', "Deprecated. PCRE2 will be used automatically when using regex features that are only supported by PCRE2."), }, 'search.actionsPosition': { type: 'string', enum: ['auto', 'right'], enumDescriptions: [ nls.localize('search.actionsPositionAuto', "Position the actionbar to the right when the search view is narrow, and immediately after the content when the search view is wide."), nls.localize('search.actionsPositionRight', "Always position the actionbar to the right."), ], default: 'auto', description: nls.localize('search.actionsPosition', "Controls the positioning of the actionbar on rows in the search view.") }, 'search.searchOnType': { type: 'boolean', default: true, description: nls.localize('search.searchOnType', "Search all files as you type.") }, 'search.seedWithNearestWord': { type: 'boolean', default: false, description: nls.localize('search.seedWithNearestWord', "Enable seeding search from the word nearest the cursor when the active editor has no selection.") }, 'search.seedOnFocus': { type: 'boolean', default: false, description: nls.localize('search.seedOnFocus', "Update workspace search query to the editor's selected text when focusing the search view. This happens either on click or when triggering the `workbench.views.search.focus` command.") }, 'search.searchOnTypeDebouncePeriod': { type: 'number', default: 300, markdownDescription: nls.localize('search.searchOnTypeDebouncePeriod', "When `#search.searchOnType#` is enabled, controls the timeout in milliseconds between a character being typed and the search starting. Has no effect when `search.searchOnType` is disabled.") }, 'search.searchEditor.doubleClickBehaviour': { type: 'string', enum: ['selectWord', 'goToLocation', 'openLocationToSide'], default: 'goToLocation', enumDescriptions: [ nls.localize('search.searchEditor.doubleClickBehaviour.selectWord', "Double clicking selects the word under the cursor."), nls.localize('search.searchEditor.doubleClickBehaviour.goToLocation', "Double clicking opens the result in the active editor group."), nls.localize('search.searchEditor.doubleClickBehaviour.openLocationToSide', "Double clicking opens the result in the editor group to the side, creating one if it does not yet exist."), ], markdownDescription: nls.localize('search.searchEditor.doubleClickBehaviour', "Configure effect of double clicking a result in a search editor.") }, 'search.searchEditor.reusePriorSearchConfiguration': { type: 'boolean', default: false, markdownDescription: nls.localize({ key: 'search.searchEditor.reusePriorSearchConfiguration', comment: ['"Search Editor" is a type that editor that can display search results. "includes, excludes, and flags" just refers to settings that affect search. For example, the "search.exclude" setting.'] }, "When enabled, new Search Editors will reuse the includes, excludes, and flags of the previously opened Search Editor") }, 'search.searchEditor.defaultNumberOfContextLines': { type: ['number', 'null'], default: 1, markdownDescription: nls.localize('search.searchEditor.defaultNumberOfContextLines', "The default number of surrounding context lines to use when creating new Search Editors. If using `#search.searchEditor.reusePriorSearchConfiguration#`, this can be set to `null` (empty) to use the prior Search Editor's configuration.") }, 'search.sortOrder': { 'type': 'string', 'enum': [SearchSortOrder.Default, SearchSortOrder.FileNames, SearchSortOrder.Type, SearchSortOrder.Modified, SearchSortOrder.CountDescending, SearchSortOrder.CountAscending], 'default': SearchSortOrder.Default, 'enumDescriptions': [ nls.localize('searchSortOrder.default', "Results are sorted by folder and file names, in alphabetical order."), nls.localize('searchSortOrder.filesOnly', "Results are sorted by file names ignoring folder order, in alphabetical order."), nls.localize('searchSortOrder.type', "Results are sorted by file extensions, in alphabetical order."), nls.localize('searchSortOrder.modified', "Results are sorted by file last modified date, in descending order."), nls.localize('searchSortOrder.countDescending', "Results are sorted by count per file, in descending order."), nls.localize('searchSortOrder.countAscending', "Results are sorted by count per file, in ascending order.") ], 'description': nls.localize('search.sortOrder', "Controls sorting order of search results.") }, } }); CommandsRegistry.registerCommand('_executeWorkspaceSymbolProvider', function (accessor, ...args) { const [query] = args; assertType(typeof query === 'string'); return getWorkspaceSymbols(query); }); // View menu MenuRegistry.appendMenuItem(MenuId.MenubarViewMenu, { group: '3_views', command: { id: VIEWLET_ID, title: nls.localize({ key: 'miViewSearch', comment: ['&& denotes a mnemonic'] }, "&&Search") }, order: 2 }); // Go to menu MenuRegistry.appendMenuItem(MenuId.MenubarGoMenu, { group: '3_global_nav', command: { id: 'workbench.action.showAllSymbols', title: nls.localize({ key: 'miGotoSymbolInWorkspace', comment: ['&& denotes a mnemonic'] }, "Go to Symbol in &&Workspace...") }, order: 2 });
src/vs/workbench/contrib/search/browser/search.contribution.ts
1
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.9985947012901306, 0.044980283826589584, 0.00016341607260983437, 0.00016970935394056141, 0.2056157886981964 ]
{ "id": 2, "code_window": [ "\tgroup: 'search_3',\n", "\torder: 1\n", "});\n", "\n", "const clearSearchHistoryLabel = nls.localize('clearSearchHistoryLabel', \"Clear Search History\");\n", "const ClearSearchHistoryCommand: ICommandAction = {\n", "\tid: Constants.ClearSearchHistoryCommandId,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 370 }
/*---------------------------------------------------------- The base color for this template is #5c87b2. If you'd like to use a different color start by replacing all instances of #5c87b2 with your new color. ----------------------------------------------------------*/ body { background-color: #5c87b2; font-size: .75em; font-family: Segoe UI, Verdana, Helvetica, Sans-Serif; margin: 8px; padding: 0; color: #696969; } h1, h2, h3, h4, h5, h6 { color: #000; font-size: 40px; margin: 0px; } textarea { font-family: Consolas } #results { margin-top: 2em; margin-left: 2em; color: black; font-size: medium; }
src/vs/workbench/services/search/test/node/fixtures/site.css
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00017455498164054006, 0.00017303982167504728, 0.00017188429774250835, 0.00017286001821048558, 0.0000010049495813291287 ]
{ "id": 2, "code_window": [ "\tgroup: 'search_3',\n", "\torder: 1\n", "});\n", "\n", "const clearSearchHistoryLabel = nls.localize('clearSearchHistoryLabel', \"Clear Search History\");\n", "const ClearSearchHistoryCommand: ICommandAction = {\n", "\tid: Constants.ClearSearchHistoryCommandId,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 370 }
{ "registrations": [ { "component": { "type": "git", "git": { "name": "davidrios/pug-tmbundle", "repositoryUrl": "https://github.com/davidrios/pug-tmbundle", "commitHash": "e67e895f6fb64932aa122e471000fa55d826bff6" } }, "license": "MIT", "description": "The file syntaxes/pug.tmLanguage.json was derived from Syntaxes/Pug.JSON-tmLanguage in https://github.com/davidrios/pug-tmbundle.", "version": "0.0.0" } ], "version": 1 }
extensions/pug/cgmanifest.json
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00017312004638370126, 0.00017304974608123302, 0.00017297946033068, 0.00017304974608123302, 7.029302651062608e-8 ]
{ "id": 2, "code_window": [ "\tgroup: 'search_3',\n", "\torder: 1\n", "});\n", "\n", "const clearSearchHistoryLabel = nls.localize('clearSearchHistoryLabel', \"Clear Search History\");\n", "const ClearSearchHistoryCommand: ICommandAction = {\n", "\tid: Constants.ClearSearchHistoryCommandId,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 370 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // eslint-disable-next-line code-import-patterns import 'vs/css!vs/workbench/contrib/notebook/browser/media/notebook'; import { getZoomLevel } from 'vs/base/browser/browser'; import * as DOM from 'vs/base/browser/dom'; import { domEvent } from 'vs/base/browser/event'; import { IListRenderer, IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar'; import { IAction } from 'vs/base/common/actions'; import { Delayer } from 'vs/base/common/async'; import { renderCodicons } from 'vs/base/common/codicons'; import { Color } from 'vs/base/common/color'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable, DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { deepClone } from 'vs/base/common/objects'; import * as platform from 'vs/base/common/platform'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget'; import { EditorOption, EDITOR_FONT_DEFAULTS, IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { BareFontInfo } from 'vs/editor/common/config/fontInfo'; import { Range } from 'vs/editor/common/core/range'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { ITextModel } from 'vs/editor/common/model'; import * as modes from 'vs/editor/common/modes'; import { tokenizeLineToHTML } from 'vs/editor/common/modes/textToHtmlTokenizer'; import { IModeService } from 'vs/editor/common/services/modeService'; import { ContextAwareMenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IMenu, MenuItemAction } from 'vs/platform/actions/common/actions'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { BOTTOM_CELL_TOOLBAR_HEIGHT, EDITOR_BOTTOM_PADDING, EDITOR_TOOLBAR_HEIGHT, EDITOR_TOP_MARGIN, EDITOR_TOP_PADDING, CELL_BOTTOM_MARGIN } from 'vs/workbench/contrib/notebook/browser/constants'; import { CancelCellAction, ChangeCellLanguageAction, ExecuteCellAction, INotebookCellActionContext, CELL_TITLE_GROUP_ID } from 'vs/workbench/contrib/notebook/browser/contrib/coreActions'; import { BaseCellRenderTemplate, CellEditState, CodeCellRenderTemplate, ICellViewModel, INotebookCellList, INotebookEditor, MarkdownCellRenderTemplate, isCodeCellRenderTemplate } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { CellMenus } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellMenus'; import { CodeCell } from 'vs/workbench/contrib/notebook/browser/view/renderers/codeCell'; import { StatefullMarkdownCell } from 'vs/workbench/contrib/notebook/browser/view/renderers/markdownCell'; import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel'; import { MarkdownCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/markdownCellViewModel'; import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModel'; import { CellKind, NotebookCellRunState, NotebookCellMetadata } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { CellContextKeyManager } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellContextKeys'; const $ = DOM.$; export class NotebookCellListDelegate implements IListVirtualDelegate<CellViewModel> { private readonly lineHeight: number; constructor( @IConfigurationService private readonly configurationService: IConfigurationService ) { const editorOptions = this.configurationService.getValue<IEditorOptions>('editor'); this.lineHeight = BareFontInfo.createFromRawSettings(editorOptions, getZoomLevel()).lineHeight; } getHeight(element: CellViewModel): number { return element.getHeight(this.lineHeight); } hasDynamicHeight(element: CellViewModel): boolean { return element.hasDynamicHeight(); } getTemplateId(element: CellViewModel): string { if (element.cellKind === CellKind.Markdown) { return MarkdownCellRenderer.TEMPLATE_ID; } else { return CodeCellRenderer.TEMPLATE_ID; } } } export class CodiconActionViewItem extends ContextAwareMenuEntryActionViewItem { constructor( readonly _action: MenuItemAction, keybindingService: IKeybindingService, notificationService: INotificationService, contextMenuService: IContextMenuService ) { super(_action, keybindingService, notificationService, contextMenuService); } updateLabel(): void { if (this.options.label && this.label) { this.label.innerHTML = renderCodicons(this._commandAction.label ?? ''); } } } export class CellEditorOptions { private static fixedEditorOptions: IEditorOptions = { padding: { top: EDITOR_TOP_PADDING, bottom: EDITOR_BOTTOM_PADDING }, scrollBeyondLastLine: false, scrollbar: { verticalScrollbarSize: 14, horizontal: 'auto', useShadows: true, verticalHasArrows: false, horizontalHasArrows: false, alwaysConsumeMouseWheel: false }, renderLineHighlightOnlyWhenFocus: true, overviewRulerLanes: 0, selectOnLineNumbers: false, lineNumbers: 'off', lineDecorationsWidth: 0, glyphMargin: false, fixedOverflowWidgets: true, minimap: { enabled: false }, renderValidationDecorations: 'on' }; private _value: IEditorOptions; private disposable: IDisposable; private readonly _onDidChange = new Emitter<IEditorOptions>(); readonly onDidChange: Event<IEditorOptions> = this._onDidChange.event; constructor(configurationService: IConfigurationService, language: string) { this.disposable = configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('editor')) { this._value = computeEditorOptions(); this._onDidChange.fire(this.value); } }); const computeEditorOptions = () => { const editorOptions = deepClone(configurationService.getValue<IEditorOptions>('editor', { overrideIdentifier: language })); const computed = { ...editorOptions, ...CellEditorOptions.fixedEditorOptions }; if (!computed.folding) { computed.lineDecorationsWidth = 16; } return computed; }; this._value = computeEditorOptions(); } dispose(): void { this._onDidChange.dispose(); this.disposable.dispose(); } get value(): IEditorOptions { return this._value; } setGlyphMargin(gm: boolean): void { if (gm !== this._value.glyphMargin) { this._value.glyphMargin = gm; this._onDidChange.fire(this.value); } } } abstract class AbstractCellRenderer { protected editorOptions: CellEditorOptions; constructor( protected readonly instantiationService: IInstantiationService, protected readonly notebookEditor: INotebookEditor, protected readonly contextMenuService: IContextMenuService, configurationService: IConfigurationService, private readonly keybindingService: IKeybindingService, private readonly notificationService: INotificationService, protected readonly contextKeyServiceProvider: (container?: HTMLElement) => IContextKeyService, language: string, protected readonly dndController: CellDragAndDropController ) { this.editorOptions = new CellEditorOptions(configurationService, language); } dispose() { this.editorOptions.dispose(); } protected createBetweenCellToolbar(container: HTMLElement, disposables: DisposableStore, contextKeyService: IContextKeyService): ToolBar { const toolbar = new ToolBar(container, this.contextMenuService, { actionViewItemProvider: action => { if (action instanceof MenuItemAction) { const item = new CodiconActionViewItem(action, this.keybindingService, this.notificationService, this.contextMenuService); return item; } return undefined; } }); toolbar.getContainer().style.height = `${BOTTOM_CELL_TOOLBAR_HEIGHT}px`; container.style.height = `${BOTTOM_CELL_TOOLBAR_HEIGHT}px`; const cellMenu = this.instantiationService.createInstance(CellMenus); const menu = disposables.add(cellMenu.getCellInsertionMenu(contextKeyService)); const actions = this.getCellToolbarActions(menu); toolbar.setActions(actions.primary, actions.secondary); return toolbar; } protected setBetweenCellToolbarContext(templateData: BaseCellRenderTemplate, element: CodeCellViewModel | MarkdownCellViewModel, context: INotebookCellActionContext): void { templateData.betweenCellToolbar.context = context; const container = templateData.bottomCellContainer; if (element instanceof CodeCellViewModel) { const bottomToolbarOffset = element.layoutInfo.bottomToolbarOffset; container.style.top = `${bottomToolbarOffset}px`; templateData.elementDisposables.add(element.onDidChangeLayout(() => { const bottomToolbarOffset = element.layoutInfo.bottomToolbarOffset; container.style.top = `${bottomToolbarOffset}px`; })); } } protected createToolbar(container: HTMLElement): ToolBar { const toolbar = new ToolBar(container, this.contextMenuService, { actionViewItemProvider: action => { if (action instanceof MenuItemAction) { const item = new ContextAwareMenuEntryActionViewItem(action, this.keybindingService, this.notificationService, this.contextMenuService); return item; } return undefined; } }); return toolbar; } private getCellToolbarActions(menu: IMenu): { primary: IAction[], secondary: IAction[] } { const primary: IAction[] = []; const secondary: IAction[] = []; const actions = menu.getActions({ shouldForwardArgs: true }); for (let [id, menuActions] of actions) { if (id === CELL_TITLE_GROUP_ID) { primary.push(...menuActions); } else { secondary.push(...menuActions); } } return { primary, secondary }; } protected setupCellToolbarActions(scopedContextKeyService: IContextKeyService, templateData: BaseCellRenderTemplate, disposables: DisposableStore): void { const cellMenu = this.instantiationService.createInstance(CellMenus); const menu = disposables.add(cellMenu.getCellTitleMenu(scopedContextKeyService)); const updateActions = () => { const actions = this.getCellToolbarActions(menu); const hadFocus = DOM.isAncestor(document.activeElement, templateData.toolbar.getContainer()); templateData.toolbar.setActions(actions.primary, actions.secondary); if (hadFocus) { this.notebookEditor.focus(); } if (actions.primary.length || actions.secondary.length) { templateData.container.classList.add('cell-has-toolbar-actions'); if (isCodeCellRenderTemplate(templateData)) { templateData.focusIndicator.style.top = `${EDITOR_TOOLBAR_HEIGHT + EDITOR_TOP_MARGIN}px`; templateData.focusIndicatorRight.style.top = `${EDITOR_TOOLBAR_HEIGHT + EDITOR_TOP_MARGIN}px`; } } else { templateData.container.classList.remove('cell-has-toolbar-actions'); if (isCodeCellRenderTemplate(templateData)) { templateData.focusIndicator.style.top = `${EDITOR_TOP_MARGIN}px`; templateData.focusIndicatorRight.style.top = `${EDITOR_TOP_MARGIN}px`; } } }; updateActions(); disposables.add(menu.onDidChange(() => { if (this.notebookEditor.isDisposed) { return; } updateActions(); })); } protected commonRenderTemplate(templateData: BaseCellRenderTemplate): void { templateData.disposables.add(DOM.addDisposableListener(templateData.container, DOM.EventType.FOCUS, () => { if (templateData.currentRenderedCell) { this.notebookEditor.selectElement(templateData.currentRenderedCell); } }, true)); } protected commonRenderElement(element: ICellViewModel, index: number, templateData: BaseCellRenderTemplate): void { if (element.dragging) { templateData.container.classList.add(DRAGGING_CLASS); } else { templateData.container.classList.remove(DRAGGING_CLASS); } } } export class MarkdownCellRenderer extends AbstractCellRenderer implements IListRenderer<MarkdownCellViewModel, MarkdownCellRenderTemplate> { static readonly TEMPLATE_ID = 'markdown_cell'; constructor( notebookEditor: INotebookEditor, dndController: CellDragAndDropController, private renderedEditors: Map<ICellViewModel, ICodeEditor | undefined>, contextKeyServiceProvider: (container?: HTMLElement) => IContextKeyService, @IInstantiationService instantiationService: IInstantiationService, @IConfigurationService configurationService: IConfigurationService, @IContextMenuService contextMenuService: IContextMenuService, @IKeybindingService keybindingService: IKeybindingService, @INotificationService notificationService: INotificationService, ) { super(instantiationService, notebookEditor, contextMenuService, configurationService, keybindingService, notificationService, contextKeyServiceProvider, 'markdown', dndController); } get templateId() { return MarkdownCellRenderer.TEMPLATE_ID; } renderTemplate(container: HTMLElement): MarkdownCellRenderTemplate { container.classList.add('markdown-cell-row'); const disposables = new DisposableStore(); const contextKeyService = disposables.add(this.contextKeyServiceProvider(container)); const toolbar = disposables.add(this.createToolbar(container)); const focusIndicator = DOM.append(container, DOM.$('.cell-focus-indicator.cell-focus-indicator-side.cell-focus-indicator-left')); focusIndicator.setAttribute('draggable', 'true'); const codeInnerContent = DOM.append(container, $('.cell.code')); const editorPart = DOM.append(codeInnerContent, $('.cell-editor-part')); const editorContainer = DOM.append(editorPart, $('.cell-editor-container')); editorPart.style.display = 'none'; const innerContent = DOM.append(container, $('.cell.markdown')); const foldingIndicator = DOM.append(focusIndicator, DOM.$('.notebook-folding-indicator')); const bottomCellContainer = DOM.append(container, $('.cell-bottom-toolbar-container')); DOM.append(bottomCellContainer, $('.separator')); const betweenCellToolbar = disposables.add(this.createBetweenCellToolbar(bottomCellContainer, disposables, contextKeyService)); DOM.append(bottomCellContainer, $('.separator')); const statusBar = this.instantiationService.createInstance(CellEditorStatusBar, editorPart); const templateData: MarkdownCellRenderTemplate = { contextKeyService, container, cellContainer: innerContent, editorPart, editorContainer, focusIndicator, foldingIndicator, disposables, elementDisposables: new DisposableStore(), toolbar, betweenCellToolbar, bottomCellContainer, statusBarContainer: statusBar.statusBarContainer, languageStatusBarItem: statusBar.languageStatusBarItem, toJSON: () => { return {}; } }; this.dndController.registerDragHandle(templateData, () => this.getDragImage(templateData)); this.commonRenderTemplate(templateData); return templateData; } private getDragImage(templateData: MarkdownCellRenderTemplate): HTMLElement { if (templateData.currentRenderedCell!.editState === CellEditState.Editing) { return this.getEditDragImage(templateData); } else { return this.getMarkdownDragImage(templateData); } } private getMarkdownDragImage(templateData: MarkdownCellRenderTemplate): HTMLElement { const dragImageContainer = DOM.$('.cell-drag-image.monaco-list-row.focused.markdown-cell-row'); dragImageContainer.innerHTML = templateData.container.innerHTML; // Remove all rendered content nodes after the const markdownContent = dragImageContainer.querySelector('.cell.markdown')!; const contentNodes = markdownContent.children[0].children; for (let i = contentNodes.length - 1; i >= 1; i--) { contentNodes.item(i)!.remove(); } return dragImageContainer; } private getEditDragImage(templateData: MarkdownCellRenderTemplate): HTMLElement { return new CodeCellDragImageRenderer().getDragImage(templateData, templateData.currentEditor!, 'markdown'); } renderElement(element: MarkdownCellViewModel, index: number, templateData: MarkdownCellRenderTemplate, height: number | undefined): void { this.commonRenderElement(element, index, templateData); templateData.currentRenderedCell = element; templateData.currentEditor = undefined; templateData.editorPart!.style.display = 'none'; templateData.cellContainer.innerHTML = ''; let renderedHTML = element.getHTML(); if (renderedHTML) { templateData.cellContainer.appendChild(renderedHTML); } if (height === undefined) { return; } const elementDisposables = templateData.elementDisposables; elementDisposables.add(new CellContextKeyManager(templateData.contextKeyService, this.notebookEditor.viewModel?.notebookDocument!, element)); // render toolbar first this.setupCellToolbarActions(templateData.contextKeyService, templateData, elementDisposables); const toolbarContext = <INotebookCellActionContext>{ cell: element, notebookEditor: this.notebookEditor, $mid: 12 }; templateData.toolbar.context = toolbarContext; this.setBetweenCellToolbarContext(templateData, element, toolbarContext); const markdownCell = this.instantiationService.createInstance(StatefullMarkdownCell, this.notebookEditor, element, templateData, this.editorOptions.value, this.renderedEditors); elementDisposables.add(this.editorOptions.onDidChange(newValue => markdownCell.updateEditorOptions(newValue))); elementDisposables.add(markdownCell); templateData.languageStatusBarItem.update(element, this.notebookEditor); } disposeTemplate(templateData: MarkdownCellRenderTemplate): void { templateData.disposables.clear(); } disposeElement(element: ICellViewModel, index: number, templateData: MarkdownCellRenderTemplate, height: number | undefined): void { if (height) { templateData.elementDisposables.clear(); element.getCellDecorations().forEach(e => { if (e.className) { templateData.container.classList.remove(e.className); } }); } } } const DRAGGING_CLASS = 'cell-dragging'; const GLOBAL_DRAG_CLASS = 'global-drag-active'; type DragImageProvider = () => HTMLElement; interface CellDragEvent { browserEvent: DragEvent; draggedOverCell: ICellViewModel; cellTop: number; cellHeight: number; dragPosRatio: number; } export class CellDragAndDropController extends Disposable { // TODO@roblourens - should probably use dataTransfer here, but any dataTransfer set makes the editor think I am dropping a file, need // to figure out how to prevent that private currentDraggedCell: ICellViewModel | undefined; private listInsertionIndicator: HTMLElement; private list!: INotebookCellList; private isScrolling = false; private scrollingDelayer: Delayer<void>; constructor( private readonly notebookEditor: INotebookEditor, insertionIndicatorContainer: HTMLElement ) { super(); this.listInsertionIndicator = DOM.append(insertionIndicatorContainer, $('.cell-list-insertion-indicator')); this._register(domEvent(document.body, DOM.EventType.DRAG_START, true)(this.onGlobalDragStart.bind(this))); this._register(domEvent(document.body, DOM.EventType.DRAG_END, true)(this.onGlobalDragEnd.bind(this))); const addCellDragListener = (eventType: string, handler: (e: CellDragEvent) => void) => { this._register(DOM.addDisposableListener( notebookEditor.getDomNode(), eventType, e => { const cellDragEvent = this.toCellDragEvent(e); if (cellDragEvent) { handler(cellDragEvent); } })); }; addCellDragListener(DOM.EventType.DRAG_OVER, event => { event.browserEvent.preventDefault(); this.onCellDragover(event); }); addCellDragListener(DOM.EventType.DROP, event => { event.browserEvent.preventDefault(); this.onCellDrop(event); }); addCellDragListener(DOM.EventType.DRAG_LEAVE, event => { event.browserEvent.preventDefault(); this.onCellDragLeave(event); }); this.scrollingDelayer = new Delayer(200); } setList(value: INotebookCellList) { this.list = value; this.list.onWillScroll(e => { if (!e.scrollTopChanged) { return; } this.setInsertIndicatorVisibility(false); this.isScrolling = true; this.scrollingDelayer.trigger(() => { this.isScrolling = false; }); }); } private setInsertIndicatorVisibility(visible: boolean) { this.listInsertionIndicator.style.opacity = visible ? '1' : '0'; } private toCellDragEvent(event: DragEvent): CellDragEvent | undefined { const targetTop = this.notebookEditor.getDomNode().getBoundingClientRect().top; const dragOffset = this.list.scrollTop + event.clientY - targetTop; const draggedOverCell = this.list.elementAt(dragOffset); if (!draggedOverCell) { return undefined; } const cellTop = this.list.getAbsoluteTopOfElement(draggedOverCell); const cellHeight = this.list.elementHeight(draggedOverCell); const dragPosInElement = dragOffset - cellTop; const dragPosRatio = dragPosInElement / cellHeight; return <CellDragEvent>{ browserEvent: event, draggedOverCell, cellTop, cellHeight, dragPosRatio }; } clearGlobalDragState() { this.notebookEditor.getDomNode().classList.remove(GLOBAL_DRAG_CLASS); } private onGlobalDragStart() { this.notebookEditor.getDomNode().classList.add(GLOBAL_DRAG_CLASS); } private onGlobalDragEnd() { this.notebookEditor.getDomNode().classList.remove(GLOBAL_DRAG_CLASS); } private onCellDragover(event: CellDragEvent): void { if (!event.browserEvent.dataTransfer) { return; } if (!this.currentDraggedCell) { event.browserEvent.dataTransfer.dropEffect = 'none'; return; } if (this.isScrolling || this.currentDraggedCell === event.draggedOverCell) { this.setInsertIndicatorVisibility(false); return; } const dropDirection = this.getDropInsertDirection(event); const insertionIndicatorAbsolutePos = dropDirection === 'above' ? event.cellTop : event.cellTop + event.cellHeight; const insertionIndicatorTop = insertionIndicatorAbsolutePos - this.list.scrollTop; if (insertionIndicatorTop >= 0) { this.listInsertionIndicator.style.top = `${insertionIndicatorAbsolutePos - this.list.scrollTop}px`; this.setInsertIndicatorVisibility(true); } else { this.setInsertIndicatorVisibility(false); } } private getDropInsertDirection(event: CellDragEvent): 'above' | 'below' { return event.dragPosRatio < 0.5 ? 'above' : 'below'; } private onCellDrop(event: CellDragEvent): void { const draggedCell = this.currentDraggedCell!; this.dragCleanup(); const isCopy = (event.browserEvent.ctrlKey && !platform.isMacintosh) || (event.browserEvent.altKey && platform.isMacintosh); const dropDirection = this.getDropInsertDirection(event); const insertionIndicatorAbsolutePos = dropDirection === 'above' ? event.cellTop : event.cellTop + event.cellHeight; const insertionIndicatorTop = insertionIndicatorAbsolutePos - this.list.scrollTop; const editorHeight = this.notebookEditor.getDomNode().getBoundingClientRect().height; if (insertionIndicatorTop < 0 || insertionIndicatorTop > editorHeight) { // Ignore drop, insertion point is off-screen return; } if (isCopy) { this.copyCell(draggedCell, event.draggedOverCell, dropDirection); } else { this.moveCell(draggedCell, event.draggedOverCell, dropDirection); } } private onCellDragLeave(event: CellDragEvent): void { if (!event.browserEvent.relatedTarget || !DOM.isAncestor(event.browserEvent.relatedTarget as HTMLElement, this.notebookEditor.getDomNode())) { this.setInsertIndicatorVisibility(false); } } private dragCleanup(): void { if (this.currentDraggedCell) { this.currentDraggedCell.dragging = false; this.currentDraggedCell = undefined; } this.setInsertIndicatorVisibility(false); } registerDragHandle(templateData: BaseCellRenderTemplate, dragImageProvider: DragImageProvider): void { const container = templateData.container; const dragHandle = templateData.focusIndicator; templateData.disposables.add(domEvent(dragHandle, DOM.EventType.DRAG_END)(() => { // Note, templateData may have a different element rendered into it by now container.classList.remove(DRAGGING_CLASS); this.dragCleanup(); })); templateData.disposables.add(domEvent(dragHandle, DOM.EventType.DRAG_START)(event => { if (!event.dataTransfer) { return; } this.currentDraggedCell = templateData.currentRenderedCell!; this.currentDraggedCell.dragging = true; const dragImage = dragImageProvider(); container.parentElement!.appendChild(dragImage); event.dataTransfer.setDragImage(dragImage, 0, 0); setTimeout(() => container.parentElement!.removeChild(dragImage!), 0); // Comment this out to debug drag image layout container.classList.add(DRAGGING_CLASS); })); } private async moveCell(draggedCell: ICellViewModel, ontoCell: ICellViewModel, direction: 'above' | 'below') { await this.notebookEditor.moveCell(draggedCell, ontoCell, direction); } private copyCell(draggedCell: ICellViewModel, ontoCell: ICellViewModel, direction: 'above' | 'below') { const editState = draggedCell.editState; const newCell = this.notebookEditor.insertNotebookCell(ontoCell, draggedCell.cellKind, direction, draggedCell.getText()); if (newCell) { this.notebookEditor.focusNotebookCell(newCell, editState === CellEditState.Editing ? 'editor' : 'container'); } } } export class CellLanguageStatusBarItem extends Disposable { private readonly labelElement: HTMLElement; private cell: ICellViewModel | undefined; private editor: INotebookEditor | undefined; private cellDisposables: DisposableStore; constructor( readonly container: HTMLElement, @IModeService private readonly modeService: IModeService, @IInstantiationService private readonly instantiationService: IInstantiationService ) { super(); this.labelElement = DOM.append(container, $('.cell-language-picker')); this.labelElement.tabIndex = 0; this._register(DOM.addDisposableListener(this.labelElement, DOM.EventType.CLICK, () => { this.instantiationService.invokeFunction(accessor => { new ChangeCellLanguageAction().run(accessor, { notebookEditor: this.editor!, cell: this.cell! }); }); })); this._register(this.cellDisposables = new DisposableStore()); } update(cell: ICellViewModel, editor: INotebookEditor): void { this.cellDisposables.clear(); this.cell = cell; this.editor = editor; this.render(); this.cellDisposables.add(this.cell.model.onDidChangeLanguage(() => this.render())); } private render(): void { const modeId = this.modeService.getModeIdForLanguageName(this.cell!.language) || this.cell!.language; this.labelElement.textContent = this.modeService.getLanguageName(modeId) || this.modeService.getLanguageName('plaintext'); } } class EditorTextRenderer { getRichText(editor: ICodeEditor, modelRange: Range): string | null { const model = editor.getModel(); if (!model) { return null; } const colorMap = this.getDefaultColorMap(); const fontInfo = editor.getOptions().get(EditorOption.fontInfo); const fontFamily = fontInfo.fontFamily === EDITOR_FONT_DEFAULTS.fontFamily ? fontInfo.fontFamily : `'${fontInfo.fontFamily}', ${EDITOR_FONT_DEFAULTS.fontFamily}`; return `<div style="` + `color: ${colorMap[modes.ColorId.DefaultForeground]};` + `background-color: ${colorMap[modes.ColorId.DefaultBackground]};` + `font-family: ${fontFamily};` + `font-weight: ${fontInfo.fontWeight};` + `font-size: ${fontInfo.fontSize}px;` + `line-height: ${fontInfo.lineHeight}px;` + `white-space: pre;` + `">` + this.getRichTextLines(model, modelRange, colorMap) + '</div>'; } private getRichTextLines(model: ITextModel, modelRange: Range, colorMap: string[]): string { const startLineNumber = modelRange.startLineNumber; const startColumn = modelRange.startColumn; const endLineNumber = modelRange.endLineNumber; const endColumn = modelRange.endColumn; const tabSize = model.getOptions().tabSize; let result = ''; for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { const lineTokens = model.getLineTokens(lineNumber); const lineContent = lineTokens.getLineContent(); const startOffset = (lineNumber === startLineNumber ? startColumn - 1 : 0); const endOffset = (lineNumber === endLineNumber ? endColumn - 1 : lineContent.length); if (lineContent === '') { result += '<br>'; } else { result += tokenizeLineToHTML(lineContent, lineTokens.inflate(), colorMap, startOffset, endOffset, tabSize, platform.isWindows); } } return result; } private getDefaultColorMap(): string[] { let colorMap = modes.TokenizationRegistry.getColorMap(); let result: string[] = ['#000000']; if (colorMap) { for (let i = 1, len = colorMap.length; i < len; i++) { result[i] = Color.Format.CSS.formatHex(colorMap[i]); } } return result; } } class CodeCellDragImageRenderer { getDragImage(templateData: BaseCellRenderTemplate, editor: ICodeEditor, type: 'code' | 'markdown'): HTMLElement { let dragImage = this.getDragImageImpl(templateData, editor, type); if (!dragImage) { // TODO@roblourens I don't think this can happen dragImage = document.createElement('div'); dragImage.textContent = '1 cell'; } return dragImage; } private getDragImageImpl(templateData: BaseCellRenderTemplate, editor: ICodeEditor, type: 'code' | 'markdown'): HTMLElement | null { const dragImageContainer = DOM.$(`.cell-drag-image.monaco-list-row.focused.${type}-cell-row`); dragImageContainer.innerHTML = templateData.container.innerHTML; const editorContainer = dragImageContainer.querySelector('.cell-editor-container'); if (!editorContainer) { return null; } const richEditorText = new EditorTextRenderer().getRichText(editor, new Range(1, 1, 1, 1000)); if (!richEditorText) { return null; } editorContainer.innerHTML = richEditorText; return dragImageContainer; } } class CellEditorStatusBar { readonly cellStatusMessageContainer: HTMLElement; readonly cellRunStatusContainer: HTMLElement; readonly statusBarContainer: HTMLElement; readonly languageStatusBarItem: CellLanguageStatusBarItem; readonly durationContainer: HTMLElement; constructor( container: HTMLElement, @IInstantiationService instantiationService: IInstantiationService ) { this.statusBarContainer = DOM.append(container, $('.cell-statusbar-container')); const leftStatusBarItems = DOM.append(this.statusBarContainer, $('.cell-status-left')); const rightStatusBarItems = DOM.append(this.statusBarContainer, $('.cell-status-right')); this.cellRunStatusContainer = DOM.append(leftStatusBarItems, $('.cell-run-status')); this.durationContainer = DOM.append(leftStatusBarItems, $('.cell-run-duration')); this.cellStatusMessageContainer = DOM.append(leftStatusBarItems, $('.cell-status-message')); this.languageStatusBarItem = instantiationService.createInstance(CellLanguageStatusBarItem, rightStatusBarItems); } } export class CodeCellRenderer extends AbstractCellRenderer implements IListRenderer<CodeCellViewModel, CodeCellRenderTemplate> { static readonly TEMPLATE_ID = 'code_cell'; constructor( protected notebookEditor: INotebookEditor, private renderedEditors: Map<ICellViewModel, ICodeEditor | undefined>, dndController: CellDragAndDropController, contextKeyServiceProvider: (container?: HTMLElement) => IContextKeyService, @IContextMenuService contextMenuService: IContextMenuService, @IConfigurationService configurationService: IConfigurationService, @IInstantiationService instantiationService: IInstantiationService, @IKeybindingService keybindingService: IKeybindingService, @INotificationService notificationService: INotificationService, ) { super(instantiationService, notebookEditor, contextMenuService, configurationService, keybindingService, notificationService, contextKeyServiceProvider, 'python', dndController); } get templateId() { return CodeCellRenderer.TEMPLATE_ID; } renderTemplate(container: HTMLElement): CodeCellRenderTemplate { container.classList.add('code-cell-row'); const disposables = new DisposableStore(); const contextKeyService = disposables.add(this.contextKeyServiceProvider(container)); DOM.append(container, $('.cell-focus-indicator.cell-focus-indicator-top')); const toolbar = disposables.add(this.createToolbar(container)); const focusIndicator = DOM.append(container, DOM.$('.cell-focus-indicator.cell-focus-indicator-side.cell-focus-indicator-left')); focusIndicator.setAttribute('draggable', 'true'); const cellContainer = DOM.append(container, $('.cell.code')); const runButtonContainer = DOM.append(cellContainer, $('.run-button-container')); const runToolbar = this.createToolbar(runButtonContainer); disposables.add(runToolbar); const executionOrderLabel = DOM.append(runButtonContainer, $('div.execution-count-label')); // create a special context key service that set the inCompositeEditor-contextkey const editorContextKeyService = disposables.add(this.contextKeyServiceProvider(container)); const editorInstaService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, editorContextKeyService])); EditorContextKeys.inCompositeEditor.bindTo(editorContextKeyService).set(true); const editorPart = DOM.append(cellContainer, $('.cell-editor-part')); const editorContainer = DOM.append(editorPart, $('.cell-editor-container')); const editor = editorInstaService.createInstance(CodeEditorWidget, editorContainer, { ...this.editorOptions.value, dimension: { width: 0, height: 0 } }, {}); disposables.add(this.editorOptions.onDidChange(newValue => editor.updateOptions(newValue))); const progressBar = new ProgressBar(editorPart); progressBar.hide(); disposables.add(progressBar); const statusBar = this.instantiationService.createInstance(CellEditorStatusBar, editorPart); const timer = new TimerRenderer(statusBar.durationContainer); const outputContainer = DOM.append(container, $('.output')); const focusIndicatorRight = DOM.append(container, DOM.$('.cell-focus-indicator.cell-focus-indicator-side.cell-focus-indicator-right')); focusIndicatorRight.setAttribute('draggable', 'true'); const focusSinkElement = DOM.append(container, $('.cell-editor-focus-sink')); focusSinkElement.setAttribute('tabindex', '0'); const bottomCellContainer = DOM.append(container, $('.cell-bottom-toolbar-container')); DOM.append(bottomCellContainer, $('.separator')); const betweenCellToolbar = this.createBetweenCellToolbar(bottomCellContainer, disposables, contextKeyService); DOM.append(bottomCellContainer, $('.separator')); const focusIndicatorBottom = DOM.append(container, $('.cell-focus-indicator.cell-focus-indicator-bottom')); const templateData: CodeCellRenderTemplate = { contextKeyService, container, cellContainer, statusBarContainer: statusBar.statusBarContainer, cellRunStatusContainer: statusBar.cellRunStatusContainer, cellStatusMessageContainer: statusBar.cellStatusMessageContainer, languageStatusBarItem: statusBar.languageStatusBarItem, progressBar, focusIndicator, focusIndicatorRight, focusIndicatorBottom, toolbar, betweenCellToolbar, focusSinkElement, runToolbar, runButtonContainer, executionOrderLabel, outputContainer, editor, disposables, elementDisposables: new DisposableStore(), bottomCellContainer, timer, toJSON: () => { return {}; } }; this.dndController.registerDragHandle(templateData, () => new CodeCellDragImageRenderer().getDragImage(templateData, templateData.editor, 'code')); disposables.add(DOM.addDisposableListener(focusSinkElement, DOM.EventType.FOCUS, () => { if (templateData.currentRenderedCell && (templateData.currentRenderedCell as CodeCellViewModel).outputs.length) { this.notebookEditor.focusNotebookCell(templateData.currentRenderedCell, 'output'); } })); this.commonRenderTemplate(templateData); return templateData; } private updateForRunState(runState: NotebookCellRunState | undefined, templateData: CodeCellRenderTemplate): void { if (typeof runState === 'undefined') { runState = NotebookCellRunState.Idle; } if (runState === NotebookCellRunState.Running) { templateData.progressBar.infinite().show(500); templateData.runToolbar.setActions([ this.instantiationService.createInstance(CancelCellAction) ]); } else { templateData.progressBar.hide(); templateData.runToolbar.setActions([ this.instantiationService.createInstance(ExecuteCellAction) ]); } } private updateForOutputs(element: CodeCellViewModel, templateData: CodeCellRenderTemplate): void { if (element.outputs.length) { DOM.show(templateData.focusSinkElement); } else { DOM.hide(templateData.focusSinkElement); } } private updateForMetadata(element: CodeCellViewModel, templateData: CodeCellRenderTemplate): void { const metadata = element.getEvaluatedMetadata(this.notebookEditor.viewModel!.notebookDocument.metadata); DOM.toggleClass(templateData.cellContainer, 'runnable', !!metadata.runnable); this.updateExecutionOrder(metadata, templateData); templateData.cellStatusMessageContainer.textContent = metadata?.statusMessage || ''; if (metadata.runState === NotebookCellRunState.Success) { templateData.cellRunStatusContainer.innerHTML = renderCodicons('$(check)'); } else if (metadata.runState === NotebookCellRunState.Error) { templateData.cellRunStatusContainer.innerHTML = renderCodicons('$(error)'); } else if (metadata.runState === NotebookCellRunState.Running) { templateData.cellRunStatusContainer.innerHTML = renderCodicons('$(sync~spin)'); } else { templateData.cellRunStatusContainer.innerHTML = ''; } if (metadata.runState === NotebookCellRunState.Running) { if (metadata.runStartTime) { templateData.elementDisposables.add(templateData.timer.start(metadata.runStartTime)); } else { templateData.timer.clear(); } } else if (typeof metadata.lastRunDuration === 'number') { templateData.timer.show(metadata.lastRunDuration); } else { templateData.timer.clear(); } if (typeof metadata.breakpointMargin === 'boolean') { this.editorOptions.setGlyphMargin(metadata.breakpointMargin); } this.updateForRunState(metadata.runState, templateData); } private updateExecutionOrder(metadata: NotebookCellMetadata, templateData: CodeCellRenderTemplate): void { if (metadata.hasExecutionOrder) { const executionOrderLabel = typeof metadata.executionOrder === 'number' ? `[${metadata.executionOrder}]` : '[ ]'; templateData.executionOrderLabel.innerText = executionOrderLabel; } else { templateData.executionOrderLabel.innerText = ''; } } private updateForHover(element: CodeCellViewModel, templateData: CodeCellRenderTemplate): void { DOM.toggleClass(templateData.container, 'cell-output-hover', element.outputIsHovered); } private updateForLayout(element: CodeCellViewModel, templateData: CodeCellRenderTemplate): void { templateData.focusIndicator.style.height = `${element.layoutInfo.indicatorHeight}px`; templateData.focusIndicatorRight.style.height = `${element.layoutInfo.indicatorHeight}px`; templateData.focusIndicatorBottom.style.top = `${element.layoutInfo.totalHeight - BOTTOM_CELL_TOOLBAR_HEIGHT - CELL_BOTTOM_MARGIN}px`; templateData.outputContainer.style.top = `${element.layoutInfo.outputContainerOffset}px`; } renderElement(element: CodeCellViewModel, index: number, templateData: CodeCellRenderTemplate, height: number | undefined): void { const removedClassNames: string[] = []; templateData.container.classList.forEach(className => { if (/^nb\-.*$/.test(className)) { removedClassNames.push(className); } }); removedClassNames.forEach(className => { templateData.container.classList.remove(className); }); this.commonRenderElement(element, index, templateData); templateData.currentRenderedCell = element; if (height === undefined) { return; } templateData.outputContainer.innerHTML = ''; const elementDisposables = templateData.elementDisposables; elementDisposables.add(this.instantiationService.createInstance(CodeCell, this.notebookEditor, element, templateData)); this.renderedEditors.set(element, templateData.editor); elementDisposables.add(new CellContextKeyManager(templateData.contextKeyService, this.notebookEditor.viewModel?.notebookDocument!, element)); this.updateForLayout(element, templateData); elementDisposables.add(element.onDidChangeLayout(() => { this.updateForLayout(element, templateData); })); this.updateForMetadata(element, templateData); this.updateForHover(element, templateData); elementDisposables.add(element.onDidChangeState((e) => { if (e.metadataChanged) { this.updateForMetadata(element, templateData); } if (e.outputIsHoveredChanged) { this.updateForHover(element, templateData); } })); this.updateForOutputs(element, templateData); elementDisposables.add(element.onDidChangeOutputs(_e => this.updateForOutputs(element, templateData))); this.setupCellToolbarActions(templateData.contextKeyService, templateData, elementDisposables); const toolbarContext = <INotebookCellActionContext>{ cell: element, cellTemplate: templateData, notebookEditor: this.notebookEditor, $mid: 12 }; templateData.toolbar.context = toolbarContext; templateData.runToolbar.context = toolbarContext; this.setBetweenCellToolbarContext(templateData, element, toolbarContext); templateData.languageStatusBarItem.update(element, this.notebookEditor); } disposeTemplate(templateData: CodeCellRenderTemplate): void { templateData.disposables.clear(); } disposeElement(element: ICellViewModel, index: number, templateData: CodeCellRenderTemplate, height: number | undefined): void { templateData.elementDisposables.clear(); this.renderedEditors.delete(element); } } export class TimerRenderer { constructor(private readonly container: HTMLElement) { DOM.hide(container); } private intervalTimer: number | undefined; start(startTime: number): IDisposable { this.stop(); DOM.show(this.container); const intervalTimer = setInterval(() => { const duration = Date.now() - startTime; this.container.textContent = this.formatDuration(duration); }, 100); this.intervalTimer = intervalTimer as unknown as number | undefined; return toDisposable(() => { clearInterval(intervalTimer); }); } stop() { if (this.intervalTimer) { clearInterval(this.intervalTimer); } } show(duration: number) { this.stop(); DOM.show(this.container); this.container.textContent = this.formatDuration(duration); } clear() { DOM.hide(this.container); this.stop(); this.container.textContent = ''; } private formatDuration(duration: number) { const seconds = Math.floor(duration / 1000); const tenths = String(duration - seconds * 1000).charAt(0); return `${seconds}.${tenths}s`; } }
src/vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.0013153720647096634, 0.00018307396385353059, 0.0001645575393922627, 0.00017162840231321752, 0.00010542297241045162 ]
{ "id": 3, "code_window": [ "const ClearSearchHistoryCommand: ICommandAction = {\n", "\tid: Constants.ClearSearchHistoryCommandId,\n", "\ttitle: clearSearchHistoryLabel,\n", "\tcategory\n", "};\n", "MenuRegistry.addCommand(ClearSearchHistoryCommand);\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\ttitle: { value: nls.localize('clearSearchHistoryLabel', \"Clear Search History\"), original: 'Clear Search History' },\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 373 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Action } from 'vs/base/common/actions'; import { distinct } from 'vs/base/common/arrays'; import { onUnexpectedError } from 'vs/base/common/errors'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import * as objects from 'vs/base/common/objects'; import * as platform from 'vs/base/common/platform'; import { dirname } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { ToggleCaseSensitiveKeybinding, ToggleRegexKeybinding, ToggleWholeWordKeybinding } from 'vs/editor/contrib/find/findModel'; import * as nls from 'vs/nls'; import { ICommandAction, MenuId, MenuRegistry, SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { CommandsRegistry, ICommandHandler } from 'vs/platform/commands/common/commands'; import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry'; import { ContextKeyExpr, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IFileService } from 'vs/platform/files/common/files'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { IListService, WorkbenchListFocusContextKey, WorkbenchObjectTree } from 'vs/platform/list/browser/listService'; import { Registry } from 'vs/platform/registry/common/platform'; import { defaultQuickAccessContextKeyValue } from 'vs/workbench/browser/quickaccess'; import { Extensions as ActionExtensions, IWorkbenchActionRegistry } from 'vs/workbench/common/actions'; import { Extensions as WorkbenchExtensions, IWorkbenchContribution, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions'; import { Extensions as ViewExtensions, IViewsRegistry, IViewContainersRegistry, ViewContainerLocation, IViewDescriptorService, IViewsService } from 'vs/workbench/common/views'; import { getMultiSelectedResources } from 'vs/workbench/contrib/files/browser/files'; import { ExplorerFolderContext, ExplorerRootContext, FilesExplorerFocusCondition, IExplorerService, VIEWLET_ID as VIEWLET_ID_FILES } from 'vs/workbench/contrib/files/common/files'; import { registerContributions as replaceContributions } from 'vs/workbench/contrib/search/browser/replaceContributions'; import { clearHistoryCommand, ClearSearchResultsAction, CloseReplaceAction, CollapseDeepestExpandedLevelAction, copyAllCommand, copyMatchCommand, copyPathCommand, FocusNextInputAction, FocusNextSearchResultAction, FocusPreviousInputAction, FocusPreviousSearchResultAction, focusSearchListCommand, getSearchView, openSearchView, OpenSearchViewletAction, RefreshAction, RemoveAction, ReplaceAction, ReplaceAllAction, ReplaceAllInFolderAction, ReplaceInFilesAction, toggleCaseSensitiveCommand, toggleRegexCommand, toggleWholeWordCommand, FindInFilesCommand, ToggleSearchOnTypeAction, ExpandAllAction } from 'vs/workbench/contrib/search/browser/searchActions'; import { SearchView } from 'vs/workbench/contrib/search/browser/searchView'; import { registerContributions as searchWidgetContributions } from 'vs/workbench/contrib/search/browser/searchWidget'; import * as Constants from 'vs/workbench/contrib/search/common/constants'; import * as SearchEditorConstants from 'vs/workbench/contrib/searchEditor/browser/constants'; import { getWorkspaceSymbols } from 'vs/workbench/contrib/search/common/search'; import { ISearchHistoryService, SearchHistoryService } from 'vs/workbench/contrib/search/common/searchHistoryService'; import { FileMatchOrMatch, ISearchWorkbenchService, RenderableMatch, SearchWorkbenchService, FileMatch, Match, FolderMatch } from 'vs/workbench/contrib/search/common/searchModel'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { VIEWLET_ID, VIEW_ID, SEARCH_EXCLUDE_CONFIG, SearchSortOrder } from 'vs/workbench/services/search/common/search'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { ExplorerViewPaneContainer } from 'vs/workbench/contrib/files/browser/explorerViewlet'; import { assertType, assertIsDefined } from 'vs/base/common/types'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { SearchEditor } from 'vs/workbench/contrib/searchEditor/browser/searchEditor'; import { ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { IQuickAccessRegistry, Extensions as QuickAccessExtensions } from 'vs/platform/quickinput/common/quickAccess'; import { SymbolsQuickAccessProvider } from 'vs/workbench/contrib/search/browser/symbolsQuickAccess'; import { AnythingQuickAccessProvider } from 'vs/workbench/contrib/search/browser/anythingQuickAccess'; import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { AbstractGotoLineQuickAccessProvider } from 'vs/editor/contrib/quickAccess/gotoLineQuickAccess'; import { GotoSymbolQuickAccessProvider } from 'vs/workbench/contrib/codeEditor/browser/quickaccess/gotoSymbolQuickAccess'; import { searchViewIcon } from 'vs/workbench/contrib/search/browser/searchIcons'; registerSingleton(ISearchWorkbenchService, SearchWorkbenchService, true); registerSingleton(ISearchHistoryService, SearchHistoryService, true); replaceContributions(); searchWidgetContributions(); const category = nls.localize('search', "Search"); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'workbench.action.search.toggleQueryDetails', weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or(Constants.SearchViewFocusedKey, SearchEditorConstants.InSearchEditor), primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_J, handler: accessor => { const contextService = accessor.get(IContextKeyService).getContext(document.activeElement); if (contextService.getValue(SearchEditorConstants.InSearchEditor.serialize())) { (accessor.get(IEditorService).activeEditorPane as SearchEditor).toggleQueryDetails(); } else if (contextService.getValue(Constants.SearchViewFocusedKey.serialize())) { const searchView = getSearchView(accessor.get(IViewsService)); assertIsDefined(searchView).toggleQueryDetails(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.FocusSearchFromResults, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FirstMatchFocusKey), primary: KeyMod.CtrlCmd | KeyCode.UpArrow, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { searchView.focusPreviousInputBox(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.OpenMatchToSide, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyMod.CtrlCmd | KeyCode.Enter, mac: { primary: KeyMod.WinCtrl | KeyCode.Enter }, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); searchView.open(<FileMatchOrMatch>tree.getFocus()[0], false, true, true); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CancelActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, WorkbenchListFocusContextKey), primary: KeyCode.Escape, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { searchView.cancelSearch(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.RemoveActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyCode.Delete, mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace, }, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(RemoveAction, tree, tree.getFocus()[0]!).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.MatchFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAction, tree, tree.getFocus()[0] as Match, searchView).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceAllInFileActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.FileFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter], handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAllAction, searchView, tree.getFocus()[0] as FileMatch).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceAllInFolderActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.FolderFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter], handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAllInFolderAction, tree, tree.getFocus()[0] as FolderMatch).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CloseReplaceWidgetActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceInputBoxFocusedKey), primary: KeyCode.Escape, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(CloseReplaceAction, Constants.CloseReplaceWidgetActionId, '').run(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FocusNextInputAction.ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or( ContextKeyExpr.and(SearchEditorConstants.InSearchEditor, Constants.InputBoxFocusedKey), ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.InputBoxFocusedKey)), primary: KeyMod.CtrlCmd | KeyCode.DownArrow, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(FocusNextInputAction, FocusNextInputAction.ID, '').run(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FocusPreviousInputAction.ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or( ContextKeyExpr.and(SearchEditorConstants.InSearchEditor, Constants.InputBoxFocusedKey), ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.InputBoxFocusedKey, Constants.SearchInputBoxFocusedKey.toNegated())), primary: KeyMod.CtrlCmd | KeyCode.UpArrow, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(FocusPreviousInputAction, FocusPreviousInputAction.ID, '').run(); } }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceActionId, title: ReplaceAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.MatchFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceAllInFolderActionId, title: ReplaceAllInFolderAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.FolderFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceAllInFileActionId, title: ReplaceAllAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.FileFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.RemoveActionId, title: RemoveAction.LABEL }, when: Constants.FileMatchOrMatchFocusKey, group: 'search', order: 2 }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CopyMatchCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.FileMatchOrMatchFocusKey, primary: KeyMod.CtrlCmd | KeyCode.KEY_C, handler: copyMatchCommand }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyMatchCommandId, title: nls.localize('copyMatchLabel', "Copy") }, when: Constants.FileMatchOrMatchFocusKey, group: 'search_2', order: 1 }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CopyPathCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.FileMatchOrFolderMatchWithResourceFocusKey, primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_C, win: { primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_C }, handler: copyPathCommand }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyPathCommandId, title: nls.localize('copyPathLabel', "Copy Path") }, when: Constants.FileMatchOrFolderMatchWithResourceFocusKey, group: 'search_2', order: 2 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyAllCommandId, title: nls.localize('copyAllLabel', "Copy All") }, when: Constants.HasSearchResults, group: 'search_2', order: 3 }); CommandsRegistry.registerCommand({ id: Constants.CopyAllCommandId, handler: copyAllCommand }); CommandsRegistry.registerCommand({ id: Constants.ClearSearchHistoryCommandId, handler: clearHistoryCommand }); CommandsRegistry.registerCommand({ id: Constants.RevealInSideBarForSearchResults, handler: (accessor, args: any) => { const viewletService = accessor.get(IViewletService); const explorerService = accessor.get(IExplorerService); const contextService = accessor.get(IWorkspaceContextService); const searchView = getSearchView(accessor.get(IViewsService)); if (!searchView) { return; } let fileMatch: FileMatch; if (!(args instanceof FileMatch)) { args = searchView.getControl().getFocus()[0]; } if (args instanceof FileMatch) { fileMatch = args; } else { return; } viewletService.openViewlet(VIEWLET_ID_FILES, false).then((viewlet) => { if (!viewlet) { return; } const explorerViewContainer = viewlet.getViewPaneContainer() as ExplorerViewPaneContainer; const uri = fileMatch.resource; if (uri && contextService.isInsideWorkspace(uri)) { const explorerView = explorerViewContainer.getExplorerView(); explorerView.setExpanded(true); explorerService.select(uri, true).then(() => explorerView.focus(), onUnexpectedError); } }); } }); const RevealInSideBarForSearchResultsCommand: ICommandAction = { id: Constants.RevealInSideBarForSearchResults, title: nls.localize('revealInSideBar', "Reveal in Side Bar") }; MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: RevealInSideBarForSearchResultsCommand, when: ContextKeyExpr.and(Constants.FileFocusKey, Constants.HasSearchResults), group: 'search_3', order: 1 }); const clearSearchHistoryLabel = nls.localize('clearSearchHistoryLabel', "Clear Search History"); const ClearSearchHistoryCommand: ICommandAction = { id: Constants.ClearSearchHistoryCommandId, title: clearSearchHistoryLabel, category }; MenuRegistry.addCommand(ClearSearchHistoryCommand); CommandsRegistry.registerCommand({ id: Constants.FocusSearchListCommandID, handler: focusSearchListCommand }); const focusSearchListCommandLabel = nls.localize('focusSearchListCommandLabel', "Focus List"); const FocusSearchListCommand: ICommandAction = { id: Constants.FocusSearchListCommandID, title: focusSearchListCommandLabel, category }; MenuRegistry.addCommand(FocusSearchListCommand); const searchInFolderCommand: ICommandHandler = (accessor, resource?: URI) => { const listService = accessor.get(IListService); const fileService = accessor.get(IFileService); const viewsService = accessor.get(IViewsService); const resources = getMultiSelectedResources(resource, listService, accessor.get(IEditorService), accessor.get(IExplorerService)); return openSearchView(viewsService, true).then(searchView => { if (resources && resources.length && searchView) { return fileService.resolveAll(resources.map(resource => ({ resource }))).then(results => { const folders: URI[] = []; results.forEach(result => { if (result.success && result.stat) { folders.push(result.stat.isDirectory ? result.stat.resource : dirname(result.stat.resource)); } }); searchView.searchInFolders(distinct(folders, folder => folder.toString())); }); } return undefined; }); }; const FIND_IN_FOLDER_ID = 'filesExplorer.findInFolder'; KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FIND_IN_FOLDER_ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(FilesExplorerFocusCondition, ExplorerFolderContext), primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_F, handler: searchInFolderCommand }); CommandsRegistry.registerCommand({ id: ClearSearchResultsAction.ID, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(ClearSearchResultsAction, ClearSearchResultsAction.ID, '').run(); } }); CommandsRegistry.registerCommand({ id: RefreshAction.ID, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(RefreshAction, RefreshAction.ID, '').run(); } }); const FIND_IN_WORKSPACE_ID = 'filesExplorer.findInWorkspace'; CommandsRegistry.registerCommand({ id: FIND_IN_WORKSPACE_ID, handler: (accessor) => { return openSearchView(accessor.get(IViewsService), true).then(searchView => { if (searchView) { searchView.searchInFolders(); } }); } }); MenuRegistry.appendMenuItem(MenuId.ExplorerContext, { group: '4_search', order: 10, command: { id: FIND_IN_FOLDER_ID, title: nls.localize('findInFolder', "Find in Folder...") }, when: ContextKeyExpr.and(ExplorerFolderContext) }); MenuRegistry.appendMenuItem(MenuId.ExplorerContext, { group: '4_search', order: 10, command: { id: FIND_IN_WORKSPACE_ID, title: nls.localize('findInWorkspace', "Find in Workspace...") }, when: ContextKeyExpr.and(ExplorerRootContext, ExplorerFolderContext.toNegated()) }); class ShowAllSymbolsAction extends Action { static readonly ID = 'workbench.action.showAllSymbols'; static readonly LABEL = nls.localize('showTriggerActions', "Go to Symbol in Workspace..."); static readonly ALL_SYMBOLS_PREFIX = '#'; constructor( actionId: string, actionLabel: string, @IQuickInputService private readonly quickInputService: IQuickInputService ) { super(actionId, actionLabel); } async run(): Promise<void> { this.quickInputService.quickAccess.show(ShowAllSymbolsAction.ALL_SYMBOLS_PREFIX); } } const viewContainer = Registry.as<IViewContainersRegistry>(ViewExtensions.ViewContainersRegistry).registerViewContainer({ id: VIEWLET_ID, name: nls.localize('name', "Search"), ctorDescriptor: new SyncDescriptor(ViewPaneContainer, [VIEWLET_ID, { mergeViewWithContainerWhenSingleView: true, donotShowContainerTitleWhenMergedWithContainer: true }]), hideIfEmpty: true, icon: searchViewIcon.classNames, order: 1 }, ViewContainerLocation.Sidebar); const viewDescriptor = { id: VIEW_ID, containerIcon: 'codicon-search', name: nls.localize('search', "Search"), ctorDescriptor: new SyncDescriptor(SearchView), canToggleVisibility: false, canMoveView: true }; // Register search default location to sidebar Registry.as<IViewsRegistry>(ViewExtensions.ViewsRegistry).registerViews([viewDescriptor], viewContainer); // Migrate search location setting to new model class RegisterSearchViewContribution implements IWorkbenchContribution { constructor( @IConfigurationService configurationService: IConfigurationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService ) { const data = configurationService.inspect('search.location'); if (data.value === 'panel') { viewDescriptorService.moveViewToLocation(viewDescriptor, ViewContainerLocation.Panel); } if (data.userValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER); } if (data.userLocalValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER_LOCAL); } if (data.userRemoteValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER_REMOTE); } if (data.workspaceFolderValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.WORKSPACE_FOLDER); } if (data.workspaceValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.WORKSPACE); } } } Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(RegisterSearchViewContribution, LifecyclePhase.Starting); // Actions const registry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions); // Show Search and Find in Files are redundant, but we can't break keybindings by removing one. So it's the same action, same keybinding, registered to different IDs. // Show Search 'when' is redundant but if the two conflict with exactly the same keybinding and 'when' clause, then they can show up as "unbound" - #51780 registry.registerWorkbenchAction(SyncActionDescriptor.from(OpenSearchViewletAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_F }, Constants.SearchViewVisibleKey.toNegated()), 'View: Show Search', nls.localize('view', "View")); KeybindingsRegistry.registerCommandAndKeybindingRule({ description: { description: nls.localize('findInFiles.description', "Open the search viewlet"), args: [ { name: nls.localize('findInFiles.args', "A set of options for the search viewlet"), schema: { type: 'object', properties: { query: { 'type': 'string' }, replace: { 'type': 'string' }, triggerSearch: { 'type': 'boolean' }, filesToInclude: { 'type': 'string' }, filesToExclude: { 'type': 'string' }, isRegex: { 'type': 'boolean' }, isCaseSensitive: { 'type': 'boolean' }, matchWholeWord: { 'type': 'boolean' }, } } }, ] }, id: Constants.FindInFilesActionId, weight: KeybindingWeight.WorkbenchContrib, when: null, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_F, handler: FindInFilesCommand }); MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: Constants.FindInFilesActionId, title: { value: nls.localize('findInFiles', "Find in Files"), original: 'Find in Files' }, category } }); MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { group: '4_find_global', command: { id: Constants.FindInFilesActionId, title: nls.localize({ key: 'miFindInFiles', comment: ['&& denotes a mnemonic'] }, "Find &&in Files") }, order: 1 }); registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusNextSearchResultAction, { primary: KeyCode.F4 }), 'Focus Next Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor)); registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusPreviousSearchResultAction, { primary: KeyMod.Shift | KeyCode.F4 }), 'Focus Previous Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor)); registry.registerWorkbenchAction(SyncActionDescriptor.from(ReplaceInFilesAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_H }), 'Replace in Files', category); MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { group: '4_find_global', command: { id: ReplaceInFilesAction.ID, title: nls.localize({ key: 'miReplaceInFiles', comment: ['&& denotes a mnemonic'] }, "Replace &&in Files") }, order: 2 }); if (platform.isMacintosh) { // Register this with a more restrictive `when` on mac to avoid conflict with "copy path" KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleCaseSensitiveCommandId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewFocusedKey, Constants.FileMatchOrFolderMatchFocusKey.toNegated()), handler: toggleCaseSensitiveCommand }, ToggleCaseSensitiveKeybinding)); } else { KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleCaseSensitiveCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleCaseSensitiveCommand }, ToggleCaseSensitiveKeybinding)); } KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleWholeWordCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleWholeWordCommand }, ToggleWholeWordKeybinding)); KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleRegexCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleRegexCommand }, ToggleRegexKeybinding)); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.AddCursorsAtSearchResults, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_L, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); searchView.openEditorWithMultiCursor(<FileMatchOrMatch>tree.getFocus()[0]); } } }); registry.registerWorkbenchAction(SyncActionDescriptor.from(CollapseDeepestExpandedLevelAction), 'Search: Collapse All', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ExpandAllAction), 'Search: Expand All', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ShowAllSymbolsAction, { primary: KeyMod.CtrlCmd | KeyCode.KEY_T }), 'Go to Symbol in Workspace...'); registry.registerWorkbenchAction(SyncActionDescriptor.from(ToggleSearchOnTypeAction), 'Search: Toggle Search on Type', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(RefreshAction), 'Search: Refresh', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ClearSearchResultsAction), 'Search: Clear Search Results', category); // Register Quick Access Handler const quickAccessRegistry = Registry.as<IQuickAccessRegistry>(QuickAccessExtensions.Quickaccess); quickAccessRegistry.registerQuickAccessProvider({ ctor: AnythingQuickAccessProvider, prefix: AnythingQuickAccessProvider.PREFIX, placeholder: nls.localize('anythingQuickAccessPlaceholder', "Search files by name (append {0} to go to line or {1} to go to symbol)", AbstractGotoLineQuickAccessProvider.PREFIX, GotoSymbolQuickAccessProvider.PREFIX), contextKey: defaultQuickAccessContextKeyValue, helpEntries: [{ description: nls.localize('anythingQuickAccess', "Go to File"), needsEditor: false }] }); quickAccessRegistry.registerQuickAccessProvider({ ctor: SymbolsQuickAccessProvider, prefix: SymbolsQuickAccessProvider.PREFIX, placeholder: nls.localize('symbolsQuickAccessPlaceholder', "Type the name of a symbol to open."), contextKey: 'inWorkspaceSymbolsPicker', helpEntries: [{ description: nls.localize('symbolsQuickAccess', "Go to Symbol in Workspace"), needsEditor: false }] }); // Configuration const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration); configurationRegistry.registerConfiguration({ id: 'search', order: 13, title: nls.localize('searchConfigurationTitle', "Search"), type: 'object', properties: { [SEARCH_EXCLUDE_CONFIG]: { type: 'object', markdownDescription: nls.localize('exclude', "Configure glob patterns for excluding files and folders in fulltext searches and quick open. Inherits all glob patterns from the `#files.exclude#` setting. Read more about glob patterns [here](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options)."), default: { '**/node_modules': true, '**/bower_components': true, '**/*.code-search': true }, additionalProperties: { anyOf: [ { type: 'boolean', description: nls.localize('exclude.boolean', "The glob pattern to match file paths against. Set to true or false to enable or disable the pattern."), }, { type: 'object', properties: { when: { type: 'string', // expression ({ "**/*.js": { "when": "$(basename).js" } }) pattern: '\\w*\\$\\(basename\\)\\w*', default: '$(basename).ext', description: nls.localize('exclude.when', 'Additional check on the siblings of a matching file. Use $(basename) as variable for the matching file name.') } } } ] }, scope: ConfigurationScope.RESOURCE }, 'search.useRipgrep': { type: 'boolean', description: nls.localize('useRipgrep', "This setting is deprecated and now falls back on \"search.usePCRE2\"."), deprecationMessage: nls.localize('useRipgrepDeprecated', "Deprecated. Consider \"search.usePCRE2\" for advanced regex feature support."), default: true }, 'search.maintainFileSearchCache': { type: 'boolean', description: nls.localize('search.maintainFileSearchCache', "When enabled, the searchService process will be kept alive instead of being shut down after an hour of inactivity. This will keep the file search cache in memory."), default: false }, 'search.useIgnoreFiles': { type: 'boolean', markdownDescription: nls.localize('useIgnoreFiles', "Controls whether to use `.gitignore` and `.ignore` files when searching for files."), default: true, scope: ConfigurationScope.RESOURCE }, 'search.useGlobalIgnoreFiles': { type: 'boolean', markdownDescription: nls.localize('useGlobalIgnoreFiles', "Controls whether to use global `.gitignore` and `.ignore` files when searching for files."), default: false, scope: ConfigurationScope.RESOURCE }, 'search.quickOpen.includeSymbols': { type: 'boolean', description: nls.localize('search.quickOpen.includeSymbols', "Whether to include results from a global symbol search in the file results for Quick Open."), default: false }, 'search.quickOpen.includeHistory': { type: 'boolean', description: nls.localize('search.quickOpen.includeHistory', "Whether to include results from recently opened files in the file results for Quick Open."), default: true }, 'search.quickOpen.history.filterSortOrder': { 'type': 'string', 'enum': ['default', 'recency'], 'default': 'default', 'enumDescriptions': [ nls.localize('filterSortOrder.default', 'History entries are sorted by relevance based on the filter value used. More relevant entries appear first.'), nls.localize('filterSortOrder.recency', 'History entries are sorted by recency. More recently opened entries appear first.') ], 'description': nls.localize('filterSortOrder', "Controls sorting order of editor history in quick open when filtering.") }, 'search.followSymlinks': { type: 'boolean', description: nls.localize('search.followSymlinks', "Controls whether to follow symlinks while searching."), default: true }, 'search.smartCase': { type: 'boolean', description: nls.localize('search.smartCase', "Search case-insensitively if the pattern is all lowercase, otherwise, search case-sensitively."), default: false }, 'search.globalFindClipboard': { type: 'boolean', default: false, description: nls.localize('search.globalFindClipboard', "Controls whether the search view should read or modify the shared find clipboard on macOS."), included: platform.isMacintosh }, 'search.location': { type: 'string', enum: ['sidebar', 'panel'], default: 'sidebar', description: nls.localize('search.location', "Controls whether the search will be shown as a view in the sidebar or as a panel in the panel area for more horizontal space."), deprecationMessage: nls.localize('search.location.deprecationMessage', "This setting is deprecated. Please use drag and drop instead by dragging the search icon.") }, 'search.collapseResults': { type: 'string', enum: ['auto', 'alwaysCollapse', 'alwaysExpand'], enumDescriptions: [ nls.localize('search.collapseResults.auto', "Files with less than 10 results are expanded. Others are collapsed."), '', '' ], default: 'alwaysExpand', description: nls.localize('search.collapseAllResults', "Controls whether the search results will be collapsed or expanded."), }, 'search.useReplacePreview': { type: 'boolean', default: true, description: nls.localize('search.useReplacePreview', "Controls whether to open Replace Preview when selecting or replacing a match."), }, 'search.showLineNumbers': { type: 'boolean', default: false, description: nls.localize('search.showLineNumbers', "Controls whether to show line numbers for search results."), }, 'search.usePCRE2': { type: 'boolean', default: false, description: nls.localize('search.usePCRE2', "Whether to use the PCRE2 regex engine in text search. This enables using some advanced regex features like lookahead and backreferences. However, not all PCRE2 features are supported - only features that are also supported by JavaScript."), deprecationMessage: nls.localize('usePCRE2Deprecated', "Deprecated. PCRE2 will be used automatically when using regex features that are only supported by PCRE2."), }, 'search.actionsPosition': { type: 'string', enum: ['auto', 'right'], enumDescriptions: [ nls.localize('search.actionsPositionAuto', "Position the actionbar to the right when the search view is narrow, and immediately after the content when the search view is wide."), nls.localize('search.actionsPositionRight', "Always position the actionbar to the right."), ], default: 'auto', description: nls.localize('search.actionsPosition', "Controls the positioning of the actionbar on rows in the search view.") }, 'search.searchOnType': { type: 'boolean', default: true, description: nls.localize('search.searchOnType', "Search all files as you type.") }, 'search.seedWithNearestWord': { type: 'boolean', default: false, description: nls.localize('search.seedWithNearestWord', "Enable seeding search from the word nearest the cursor when the active editor has no selection.") }, 'search.seedOnFocus': { type: 'boolean', default: false, description: nls.localize('search.seedOnFocus', "Update workspace search query to the editor's selected text when focusing the search view. This happens either on click or when triggering the `workbench.views.search.focus` command.") }, 'search.searchOnTypeDebouncePeriod': { type: 'number', default: 300, markdownDescription: nls.localize('search.searchOnTypeDebouncePeriod', "When `#search.searchOnType#` is enabled, controls the timeout in milliseconds between a character being typed and the search starting. Has no effect when `search.searchOnType` is disabled.") }, 'search.searchEditor.doubleClickBehaviour': { type: 'string', enum: ['selectWord', 'goToLocation', 'openLocationToSide'], default: 'goToLocation', enumDescriptions: [ nls.localize('search.searchEditor.doubleClickBehaviour.selectWord', "Double clicking selects the word under the cursor."), nls.localize('search.searchEditor.doubleClickBehaviour.goToLocation', "Double clicking opens the result in the active editor group."), nls.localize('search.searchEditor.doubleClickBehaviour.openLocationToSide', "Double clicking opens the result in the editor group to the side, creating one if it does not yet exist."), ], markdownDescription: nls.localize('search.searchEditor.doubleClickBehaviour', "Configure effect of double clicking a result in a search editor.") }, 'search.searchEditor.reusePriorSearchConfiguration': { type: 'boolean', default: false, markdownDescription: nls.localize({ key: 'search.searchEditor.reusePriorSearchConfiguration', comment: ['"Search Editor" is a type that editor that can display search results. "includes, excludes, and flags" just refers to settings that affect search. For example, the "search.exclude" setting.'] }, "When enabled, new Search Editors will reuse the includes, excludes, and flags of the previously opened Search Editor") }, 'search.searchEditor.defaultNumberOfContextLines': { type: ['number', 'null'], default: 1, markdownDescription: nls.localize('search.searchEditor.defaultNumberOfContextLines', "The default number of surrounding context lines to use when creating new Search Editors. If using `#search.searchEditor.reusePriorSearchConfiguration#`, this can be set to `null` (empty) to use the prior Search Editor's configuration.") }, 'search.sortOrder': { 'type': 'string', 'enum': [SearchSortOrder.Default, SearchSortOrder.FileNames, SearchSortOrder.Type, SearchSortOrder.Modified, SearchSortOrder.CountDescending, SearchSortOrder.CountAscending], 'default': SearchSortOrder.Default, 'enumDescriptions': [ nls.localize('searchSortOrder.default', "Results are sorted by folder and file names, in alphabetical order."), nls.localize('searchSortOrder.filesOnly', "Results are sorted by file names ignoring folder order, in alphabetical order."), nls.localize('searchSortOrder.type', "Results are sorted by file extensions, in alphabetical order."), nls.localize('searchSortOrder.modified', "Results are sorted by file last modified date, in descending order."), nls.localize('searchSortOrder.countDescending', "Results are sorted by count per file, in descending order."), nls.localize('searchSortOrder.countAscending', "Results are sorted by count per file, in ascending order.") ], 'description': nls.localize('search.sortOrder', "Controls sorting order of search results.") }, } }); CommandsRegistry.registerCommand('_executeWorkspaceSymbolProvider', function (accessor, ...args) { const [query] = args; assertType(typeof query === 'string'); return getWorkspaceSymbols(query); }); // View menu MenuRegistry.appendMenuItem(MenuId.MenubarViewMenu, { group: '3_views', command: { id: VIEWLET_ID, title: nls.localize({ key: 'miViewSearch', comment: ['&& denotes a mnemonic'] }, "&&Search") }, order: 2 }); // Go to menu MenuRegistry.appendMenuItem(MenuId.MenubarGoMenu, { group: '3_global_nav', command: { id: 'workbench.action.showAllSymbols', title: nls.localize({ key: 'miGotoSymbolInWorkspace', comment: ['&& denotes a mnemonic'] }, "Go to Symbol in &&Workspace...") }, order: 2 });
src/vs/workbench/contrib/search/browser/search.contribution.ts
1
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.9976279139518738, 0.044351834803819656, 0.0001651597413001582, 0.00017128532635979354, 0.2019350230693817 ]
{ "id": 3, "code_window": [ "const ClearSearchHistoryCommand: ICommandAction = {\n", "\tid: Constants.ClearSearchHistoryCommandId,\n", "\ttitle: clearSearchHistoryLabel,\n", "\tcategory\n", "};\n", "MenuRegistry.addCommand(ClearSearchHistoryCommand);\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\ttitle: { value: nls.localize('clearSearchHistoryLabel', \"Clear Search History\"), original: 'Clear Search History' },\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 373 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CharCode } from 'vs/base/common/charCode'; import * as strings from 'vs/base/common/strings'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { Selection } from 'vs/editor/common/core/selection'; import { ICommand, IEditOperationBuilder, ICursorStateComputerData } from 'vs/editor/common/editorCommon'; import { IIdentifiedSingleEditOperation, ITextModel } from 'vs/editor/common/model'; import { LanguageConfigurationRegistry } from 'vs/editor/common/modes/languageConfigurationRegistry'; import { BlockCommentCommand } from 'vs/editor/contrib/comment/blockCommentCommand'; import { Constants } from 'vs/base/common/uint'; export interface IInsertionPoint { ignore: boolean; commentStrOffset: number; } export interface ILinePreflightData { ignore: boolean; commentStr: string; commentStrOffset: number; commentStrLength: number; } export interface IPreflightDataSupported { supported: true; shouldRemoveComments: boolean; lines: ILinePreflightData[]; } export interface IPreflightDataUnsupported { supported: false; } export type IPreflightData = IPreflightDataSupported | IPreflightDataUnsupported; export interface ISimpleModel { getLineContent(lineNumber: number): string; } export const enum Type { Toggle = 0, ForceAdd = 1, ForceRemove = 2 } export class LineCommentCommand implements ICommand { private readonly _selection: Selection; private readonly _tabSize: number; private readonly _type: Type; private readonly _insertSpace: boolean; private readonly _ignoreEmptyLines: boolean; private _selectionId: string | null; private _deltaColumn: number; private _moveEndPositionDown: boolean; constructor( selection: Selection, tabSize: number, type: Type, insertSpace: boolean, ignoreEmptyLines: boolean ) { this._selection = selection; this._tabSize = tabSize; this._type = type; this._insertSpace = insertSpace; this._selectionId = null; this._deltaColumn = 0; this._moveEndPositionDown = false; this._ignoreEmptyLines = ignoreEmptyLines; } /** * Do an initial pass over the lines and gather info about the line comment string. * Returns null if any of the lines doesn't support a line comment string. */ public static _gatherPreflightCommentStrings(model: ITextModel, startLineNumber: number, endLineNumber: number): ILinePreflightData[] | null { model.tokenizeIfCheap(startLineNumber); const languageId = model.getLanguageIdAtPosition(startLineNumber, 1); const config = LanguageConfigurationRegistry.getComments(languageId); const commentStr = (config ? config.lineCommentToken : null); if (!commentStr) { // Mode does not support line comments return null; } let lines: ILinePreflightData[] = []; for (let i = 0, lineCount = endLineNumber - startLineNumber + 1; i < lineCount; i++) { lines[i] = { ignore: false, commentStr: commentStr, commentStrOffset: 0, commentStrLength: commentStr.length }; } return lines; } /** * Analyze lines and decide which lines are relevant and what the toggle should do. * Also, build up several offsets and lengths useful in the generation of editor operations. */ public static _analyzeLines(type: Type, insertSpace: boolean, model: ISimpleModel, lines: ILinePreflightData[], startLineNumber: number, ignoreEmptyLines: boolean): IPreflightData { let onlyWhitespaceLines = true; let shouldRemoveComments: boolean; if (type === Type.Toggle) { shouldRemoveComments = true; } else if (type === Type.ForceAdd) { shouldRemoveComments = false; } else { shouldRemoveComments = true; } for (let i = 0, lineCount = lines.length; i < lineCount; i++) { const lineData = lines[i]; const lineNumber = startLineNumber + i; const lineContent = model.getLineContent(lineNumber); const lineContentStartOffset = strings.firstNonWhitespaceIndex(lineContent); if (lineContentStartOffset === -1) { // Empty or whitespace only line lineData.ignore = ignoreEmptyLines; lineData.commentStrOffset = lineContent.length; continue; } onlyWhitespaceLines = false; lineData.ignore = false; lineData.commentStrOffset = lineContentStartOffset; if (shouldRemoveComments && !BlockCommentCommand._haystackHasNeedleAtOffset(lineContent, lineData.commentStr, lineContentStartOffset)) { if (type === Type.Toggle) { // Every line so far has been a line comment, but this one is not shouldRemoveComments = false; } else if (type === Type.ForceAdd) { // Will not happen } else { lineData.ignore = true; } } if (shouldRemoveComments && insertSpace) { // Remove a following space if present const commentStrEndOffset = lineContentStartOffset + lineData.commentStrLength; if (commentStrEndOffset < lineContent.length && lineContent.charCodeAt(commentStrEndOffset) === CharCode.Space) { lineData.commentStrLength += 1; } } } if (type === Type.Toggle && onlyWhitespaceLines) { // For only whitespace lines, we insert comments shouldRemoveComments = false; // Also, no longer ignore them for (let i = 0, lineCount = lines.length; i < lineCount; i++) { lines[i].ignore = false; } } return { supported: true, shouldRemoveComments: shouldRemoveComments, lines: lines }; } /** * Analyze all lines and decide exactly what to do => not supported | insert line comments | remove line comments */ public static _gatherPreflightData(type: Type, insertSpace: boolean, model: ITextModel, startLineNumber: number, endLineNumber: number, ignoreEmptyLines: boolean): IPreflightData { const lines = LineCommentCommand._gatherPreflightCommentStrings(model, startLineNumber, endLineNumber); if (lines === null) { return { supported: false }; } return LineCommentCommand._analyzeLines(type, insertSpace, model, lines, startLineNumber, ignoreEmptyLines); } /** * Given a successful analysis, execute either insert line comments, either remove line comments */ private _executeLineComments(model: ISimpleModel, builder: IEditOperationBuilder, data: IPreflightDataSupported, s: Selection): void { let ops: IIdentifiedSingleEditOperation[]; if (data.shouldRemoveComments) { ops = LineCommentCommand._createRemoveLineCommentsOperations(data.lines, s.startLineNumber); } else { LineCommentCommand._normalizeInsertionPoint(model, data.lines, s.startLineNumber, this._tabSize); ops = this._createAddLineCommentsOperations(data.lines, s.startLineNumber); } const cursorPosition = new Position(s.positionLineNumber, s.positionColumn); for (let i = 0, len = ops.length; i < len; i++) { builder.addEditOperation(ops[i].range, ops[i].text); if (Range.isEmpty(ops[i].range) && Range.getStartPosition(ops[i].range).equals(cursorPosition)) { const lineContent = model.getLineContent(cursorPosition.lineNumber); if (lineContent.length + 1 === cursorPosition.column) { this._deltaColumn = (ops[i].text || '').length; } } } this._selectionId = builder.trackSelection(s); } private _attemptRemoveBlockComment(model: ITextModel, s: Selection, startToken: string, endToken: string): IIdentifiedSingleEditOperation[] | null { let startLineNumber = s.startLineNumber; let endLineNumber = s.endLineNumber; let startTokenAllowedBeforeColumn = endToken.length + Math.max( model.getLineFirstNonWhitespaceColumn(s.startLineNumber), s.startColumn ); let startTokenIndex = model.getLineContent(startLineNumber).lastIndexOf(startToken, startTokenAllowedBeforeColumn - 1); let endTokenIndex = model.getLineContent(endLineNumber).indexOf(endToken, s.endColumn - 1 - startToken.length); if (startTokenIndex !== -1 && endTokenIndex === -1) { endTokenIndex = model.getLineContent(startLineNumber).indexOf(endToken, startTokenIndex + startToken.length); endLineNumber = startLineNumber; } if (startTokenIndex === -1 && endTokenIndex !== -1) { startTokenIndex = model.getLineContent(endLineNumber).lastIndexOf(startToken, endTokenIndex); startLineNumber = endLineNumber; } if (s.isEmpty() && (startTokenIndex === -1 || endTokenIndex === -1)) { startTokenIndex = model.getLineContent(startLineNumber).indexOf(startToken); if (startTokenIndex !== -1) { endTokenIndex = model.getLineContent(startLineNumber).indexOf(endToken, startTokenIndex + startToken.length); } } // We have to adjust to possible inner white space. // For Space after startToken, add Space to startToken - range math will work out. if (startTokenIndex !== -1 && model.getLineContent(startLineNumber).charCodeAt(startTokenIndex + startToken.length) === CharCode.Space) { startToken += ' '; } // For Space before endToken, add Space before endToken and shift index one left. if (endTokenIndex !== -1 && model.getLineContent(endLineNumber).charCodeAt(endTokenIndex - 1) === CharCode.Space) { endToken = ' ' + endToken; endTokenIndex -= 1; } if (startTokenIndex !== -1 && endTokenIndex !== -1) { return BlockCommentCommand._createRemoveBlockCommentOperations( new Range(startLineNumber, startTokenIndex + startToken.length + 1, endLineNumber, endTokenIndex + 1), startToken, endToken ); } return null; } /** * Given an unsuccessful analysis, delegate to the block comment command */ private _executeBlockComment(model: ITextModel, builder: IEditOperationBuilder, s: Selection): void { model.tokenizeIfCheap(s.startLineNumber); let languageId = model.getLanguageIdAtPosition(s.startLineNumber, 1); let config = LanguageConfigurationRegistry.getComments(languageId); if (!config || !config.blockCommentStartToken || !config.blockCommentEndToken) { // Mode does not support block comments return; } const startToken = config.blockCommentStartToken; const endToken = config.blockCommentEndToken; let ops = this._attemptRemoveBlockComment(model, s, startToken, endToken); if (!ops) { if (s.isEmpty()) { const lineContent = model.getLineContent(s.startLineNumber); let firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent); if (firstNonWhitespaceIndex === -1) { // Line is empty or contains only whitespace firstNonWhitespaceIndex = lineContent.length; } ops = BlockCommentCommand._createAddBlockCommentOperations( new Range(s.startLineNumber, firstNonWhitespaceIndex + 1, s.startLineNumber, lineContent.length + 1), startToken, endToken, this._insertSpace ); } else { ops = BlockCommentCommand._createAddBlockCommentOperations( new Range(s.startLineNumber, model.getLineFirstNonWhitespaceColumn(s.startLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), startToken, endToken, this._insertSpace ); } if (ops.length === 1) { // Leave cursor after token and Space this._deltaColumn = startToken.length + 1; } } this._selectionId = builder.trackSelection(s); for (const op of ops) { builder.addEditOperation(op.range, op.text); } } public getEditOperations(model: ITextModel, builder: IEditOperationBuilder): void { let s = this._selection; this._moveEndPositionDown = false; if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) { this._moveEndPositionDown = true; s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1)); } const data = LineCommentCommand._gatherPreflightData( this._type, this._insertSpace, model, s.startLineNumber, s.endLineNumber, this._ignoreEmptyLines ); if (data.supported) { return this._executeLineComments(model, builder, data, s); } return this._executeBlockComment(model, builder, s); } public computeCursorState(model: ITextModel, helper: ICursorStateComputerData): Selection { let result = helper.getTrackedSelection(this._selectionId!); if (this._moveEndPositionDown) { result = result.setEndPosition(result.endLineNumber + 1, 1); } return new Selection( result.selectionStartLineNumber, result.selectionStartColumn + this._deltaColumn, result.positionLineNumber, result.positionColumn + this._deltaColumn ); } /** * Generate edit operations in the remove line comment case */ public static _createRemoveLineCommentsOperations(lines: ILinePreflightData[], startLineNumber: number): IIdentifiedSingleEditOperation[] { let res: IIdentifiedSingleEditOperation[] = []; for (let i = 0, len = lines.length; i < len; i++) { const lineData = lines[i]; if (lineData.ignore) { continue; } res.push(EditOperation.delete(new Range( startLineNumber + i, lineData.commentStrOffset + 1, startLineNumber + i, lineData.commentStrOffset + lineData.commentStrLength + 1 ))); } return res; } /** * Generate edit operations in the add line comment case */ private _createAddLineCommentsOperations(lines: ILinePreflightData[], startLineNumber: number): IIdentifiedSingleEditOperation[] { let res: IIdentifiedSingleEditOperation[] = []; const afterCommentStr = this._insertSpace ? ' ' : ''; for (let i = 0, len = lines.length; i < len; i++) { const lineData = lines[i]; if (lineData.ignore) { continue; } res.push(EditOperation.insert(new Position(startLineNumber + i, lineData.commentStrOffset + 1), lineData.commentStr + afterCommentStr)); } return res; } private static nextVisibleColumn(currentVisibleColumn: number, tabSize: number, isTab: boolean, columnSize: number): number { if (isTab) { return currentVisibleColumn + (tabSize - (currentVisibleColumn % tabSize)); } return currentVisibleColumn + columnSize; } /** * Adjust insertion points to have them vertically aligned in the add line comment case */ public static _normalizeInsertionPoint(model: ISimpleModel, lines: IInsertionPoint[], startLineNumber: number, tabSize: number): void { let minVisibleColumn = Constants.MAX_SAFE_SMALL_INTEGER; let j: number; let lenJ: number; for (let i = 0, len = lines.length; i < len; i++) { if (lines[i].ignore) { continue; } const lineContent = model.getLineContent(startLineNumber + i); let currentVisibleColumn = 0; for (let j = 0, lenJ = lines[i].commentStrOffset; currentVisibleColumn < minVisibleColumn && j < lenJ; j++) { currentVisibleColumn = LineCommentCommand.nextVisibleColumn(currentVisibleColumn, tabSize, lineContent.charCodeAt(j) === CharCode.Tab, 1); } if (currentVisibleColumn < minVisibleColumn) { minVisibleColumn = currentVisibleColumn; } } minVisibleColumn = Math.floor(minVisibleColumn / tabSize) * tabSize; for (let i = 0, len = lines.length; i < len; i++) { if (lines[i].ignore) { continue; } const lineContent = model.getLineContent(startLineNumber + i); let currentVisibleColumn = 0; for (j = 0, lenJ = lines[i].commentStrOffset; currentVisibleColumn < minVisibleColumn && j < lenJ; j++) { currentVisibleColumn = LineCommentCommand.nextVisibleColumn(currentVisibleColumn, tabSize, lineContent.charCodeAt(j) === CharCode.Tab, 1); } if (currentVisibleColumn > minVisibleColumn) { lines[i].commentStrOffset = j - 1; } else { lines[i].commentStrOffset = j; } } } }
src/vs/editor/contrib/comment/lineCommentCommand.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00022795962286181748, 0.00017282180488109589, 0.00016569194849580526, 0.0001709657663013786, 0.000009193290679831989 ]
{ "id": 3, "code_window": [ "const ClearSearchHistoryCommand: ICommandAction = {\n", "\tid: Constants.ClearSearchHistoryCommandId,\n", "\ttitle: clearSearchHistoryLabel,\n", "\tcategory\n", "};\n", "MenuRegistry.addCommand(ClearSearchHistoryCommand);\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\ttitle: { value: nls.localize('clearSearchHistoryLabel', \"Clear Search History\"), original: 'Clear Search History' },\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 373 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /// <reference path='../../../../src/vs/vscode.d.ts'/> /// <reference path='../../../../src/vs/vscode.proposed.d.ts'/>
extensions/microsoft-authentication/src/typings/refs.d.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.0001773844996932894, 0.0001773844996932894, 0.0001773844996932894, 0.0001773844996932894, 0 ]
{ "id": 3, "code_window": [ "const ClearSearchHistoryCommand: ICommandAction = {\n", "\tid: Constants.ClearSearchHistoryCommandId,\n", "\ttitle: clearSearchHistoryLabel,\n", "\tcategory\n", "};\n", "MenuRegistry.addCommand(ClearSearchHistoryCommand);\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\ttitle: { value: nls.localize('clearSearchHistoryLabel', \"Clear Search History\"), original: 'Clear Search History' },\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 373 }
FROM ubuntu MAINTAINER Kimbro Staken RUN apt-get install -y software-properties-common python RUN add-apt-repository ppa:chris-lea/node.js RUN echo "deb http://us.archive.ubuntu.com/ubuntu/ precise universe" >> /etc/apt/sources.list RUN apt-get update RUN apt-get install -y nodejs #RUN apt-get install -y nodejs=0.6.12~dfsg1-1ubuntu1 RUN mkdir /var/www ADD app.js /var/www/app.js CMD ["/usr/bin/node", "/var/www/app.js"]
extensions/docker/test/colorize-fixtures/Dockerfile
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.0001719501888146624, 0.00016913923900574446, 0.00016632828919682652, 0.00016913923900574446, 0.0000028109498089179397 ]
{ "id": 4, "code_window": [ "\tid: Constants.FocusSearchListCommandID,\n", "\thandler: focusSearchListCommand\n", "});\n", "\n", "const focusSearchListCommandLabel = nls.localize('focusSearchListCommandLabel', \"Focus List\");\n", "const FocusSearchListCommand: ICommandAction = {\n", "\tid: Constants.FocusSearchListCommandID,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 383 }
/*--------------------------------------------------------------------------------------------- * 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!./media/actions'; import * as nls from 'vs/nls'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { domEvent } from 'vs/base/browser/event'; import { Event } from 'vs/base/common/event'; import { IDisposable, toDisposable, dispose, Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { getDomNodePagePosition, createStyleSheet, createCSSRule, append, $ } from 'vs/base/browser/dom'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { Context } from 'vs/platform/contextkey/browser/contextKeyService'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { timeout } from 'vs/base/common/async'; import { ILayoutService } from 'vs/platform/layout/browser/layoutService'; import { Registry } from 'vs/platform/registry/common/platform'; import { registerAction2, Action2 } from 'vs/platform/actions/common/actions'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { clamp } from 'vs/base/common/numbers'; import { KeyCode } from 'vs/base/common/keyCodes'; import { IConfigurationRegistry, Extensions as ConfigurationExtensions } from 'vs/platform/configuration/common/configurationRegistry'; import { ILogService } from 'vs/platform/log/common/log'; import { IWorkingCopyService } from 'vs/workbench/services/workingCopy/common/workingCopyService'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; const developerCategory = { value: nls.localize({ key: 'developer', comment: ['A developer on Code itself or someone diagnosing issues in Code'] }, "Developer"), original: 'Developer' }; class InspectContextKeysAction extends Action2 { constructor() { super({ id: 'workbench.action.inspectContextKeys', title: { value: nls.localize('inspect context keys', "Inspect Context Keys"), original: 'Inspect Context Keys' }, category: developerCategory, f1: true }); } run(accessor: ServicesAccessor): void { const contextKeyService = accessor.get(IContextKeyService); const disposables = new DisposableStore(); const stylesheet = createStyleSheet(); disposables.add(toDisposable(() => { if (stylesheet.parentNode) { stylesheet.parentNode.removeChild(stylesheet); } })); createCSSRule('*', 'cursor: crosshair !important;', stylesheet); const hoverFeedback = document.createElement('div'); document.body.appendChild(hoverFeedback); disposables.add(toDisposable(() => document.body.removeChild(hoverFeedback))); hoverFeedback.style.position = 'absolute'; hoverFeedback.style.pointerEvents = 'none'; hoverFeedback.style.backgroundColor = 'rgba(255, 0, 0, 0.5)'; hoverFeedback.style.zIndex = '1000'; const onMouseMove = domEvent(document.body, 'mousemove', true); disposables.add(onMouseMove(e => { const target = e.target as HTMLElement; const position = getDomNodePagePosition(target); hoverFeedback.style.top = `${position.top}px`; hoverFeedback.style.left = `${position.left}px`; hoverFeedback.style.width = `${position.width}px`; hoverFeedback.style.height = `${position.height}px`; })); const onMouseDown = Event.once(domEvent(document.body, 'mousedown', true)); onMouseDown(e => { e.preventDefault(); e.stopPropagation(); }, null, disposables); const onMouseUp = Event.once(domEvent(document.body, 'mouseup', true)); onMouseUp(e => { e.preventDefault(); e.stopPropagation(); const context = contextKeyService.getContext(e.target as HTMLElement) as Context; console.log(context.collectAllValues()); dispose(disposables); }, null, disposables); } } class ToggleScreencastModeAction extends Action2 { static disposable: IDisposable | undefined; constructor() { super({ id: 'workbench.action.toggleScreencastMode', title: { value: nls.localize('toggle screencast mode', "Toggle Screencast Mode"), original: 'Toggle Screencast Mode' }, category: developerCategory, f1: true }); } run(accessor: ServicesAccessor): void { if (ToggleScreencastModeAction.disposable) { ToggleScreencastModeAction.disposable.dispose(); ToggleScreencastModeAction.disposable = undefined; return; } const layoutService = accessor.get(ILayoutService); const configurationService = accessor.get(IConfigurationService); const keybindingService = accessor.get(IKeybindingService); const disposables = new DisposableStore(); const container = layoutService.container; const mouseMarker = append(container, $('.screencast-mouse')); disposables.add(toDisposable(() => mouseMarker.remove())); const onMouseDown = domEvent(container, 'mousedown', true); const onMouseUp = domEvent(container, 'mouseup', true); const onMouseMove = domEvent(container, 'mousemove', true); disposables.add(onMouseDown(e => { mouseMarker.style.top = `${e.clientY - 10}px`; mouseMarker.style.left = `${e.clientX - 10}px`; mouseMarker.style.display = 'block'; const mouseMoveListener = onMouseMove(e => { mouseMarker.style.top = `${e.clientY - 10}px`; mouseMarker.style.left = `${e.clientX - 10}px`; }); Event.once(onMouseUp)(() => { mouseMarker.style.display = 'none'; mouseMoveListener.dispose(); }); })); const keyboardMarker = append(container, $('.screencast-keyboard')); disposables.add(toDisposable(() => keyboardMarker.remove())); const updateKeyboardFontSize = () => { keyboardMarker.style.fontSize = `${clamp(configurationService.getValue<number>('screencastMode.fontSize') || 56, 20, 100)}px`; }; const updateKeyboardMarker = () => { keyboardMarker.style.bottom = `${clamp(configurationService.getValue<number>('screencastMode.verticalOffset') || 0, 0, 90)}%`; }; updateKeyboardFontSize(); updateKeyboardMarker(); disposables.add(configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('screencastMode.verticalOffset')) { updateKeyboardMarker(); } if (e.affectsConfiguration('screencastMode.fontSize')) { updateKeyboardFontSize(); } })); const onKeyDown = domEvent(window, 'keydown', true); let keyboardTimeout: IDisposable = Disposable.None; let length = 0; disposables.add(onKeyDown(e => { keyboardTimeout.dispose(); const event = new StandardKeyboardEvent(e); const shortcut = keybindingService.softDispatch(event, event.target); if (shortcut || !configurationService.getValue<boolean>('screencastMode.onlyKeyboardShortcuts')) { if ( event.ctrlKey || event.altKey || event.metaKey || event.shiftKey || length > 20 || event.keyCode === KeyCode.Backspace || event.keyCode === KeyCode.Escape ) { keyboardMarker.innerHTML = ''; length = 0; } const keybinding = keybindingService.resolveKeyboardEvent(event); const label = keybinding.getLabel(); const key = $('span.key', {}, label || ''); length++; append(keyboardMarker, key); } const promise = timeout(800); keyboardTimeout = toDisposable(() => promise.cancel()); promise.then(() => { keyboardMarker.textContent = ''; length = 0; }); })); ToggleScreencastModeAction.disposable = disposables; } } class LogStorageAction extends Action2 { constructor() { super({ id: 'workbench.action.logStorage', title: { value: nls.localize({ key: 'logStorage', comment: ['A developer only action to log the contents of the storage for the current window.'] }, "Log Storage Database Contents"), original: 'Developer: Log Storage Database Contents' }, category: developerCategory, f1: true }); } run(accessor: ServicesAccessor): void { accessor.get(IStorageService).logStorage(); } } class LogWorkingCopiesAction extends Action2 { constructor() { super({ id: 'workbench.action.logWorkingCopies', title: { value: nls.localize({ key: 'logWorkingCopies', comment: ['A developer only action to log the working copies that exist.'] }, "Log Working Copies"), original: 'Log Working Copies' }, category: developerCategory, f1: true }); } run(accessor: ServicesAccessor): void { const workingCopyService = accessor.get(IWorkingCopyService); const logService = accessor.get(ILogService); const msg = [ `Dirty Working Copies:`, ...workingCopyService.dirtyWorkingCopies.map(workingCopy => workingCopy.resource.toString(true)), ``, `All Working Copies:`, ...workingCopyService.workingCopies.map(workingCopy => workingCopy.resource.toString(true)), ]; logService.info(msg.join('\n')); } } // --- Actions Registration registerAction2(InspectContextKeysAction); registerAction2(ToggleScreencastModeAction); registerAction2(LogStorageAction); registerAction2(LogWorkingCopiesAction); // Screencast Mode const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration); configurationRegistry.registerConfiguration({ id: 'screencastMode', order: 9, title: nls.localize('screencastModeConfigurationTitle', "Screencast Mode"), type: 'object', properties: { 'screencastMode.verticalOffset': { type: 'number', default: 20, minimum: 0, maximum: 90, description: nls.localize('screencastMode.location.verticalPosition', "Controls the vertical offset of the screencast mode overlay from the bottom as a percentage of the workbench height.") }, 'screencastMode.fontSize': { type: 'number', default: 56, minimum: 20, maximum: 100, description: nls.localize('screencastMode.fontSize', "Controls the font size (in pixels) of the screencast mode keyboard.") }, 'screencastMode.onlyKeyboardShortcuts': { type: 'boolean', description: nls.localize('screencastMode.onlyKeyboardShortcuts', "Only show keyboard shortcuts in Screencast Mode."), default: false } } });
src/vs/workbench/browser/actions/developerActions.ts
1
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.0005325373494997621, 0.00020072034385520965, 0.0001636601227801293, 0.00017354082956444472, 0.00008357888145837933 ]
{ "id": 4, "code_window": [ "\tid: Constants.FocusSearchListCommandID,\n", "\thandler: focusSearchListCommand\n", "});\n", "\n", "const focusSearchListCommandLabel = nls.localize('focusSearchListCommandLabel', \"Focus List\");\n", "const FocusSearchListCommand: ICommandAction = {\n", "\tid: Constants.FocusSearchListCommandID,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 383 }
/*--------------------------------------------------------------------------------------------- * 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 { IViewLineTokens, LineTokens } from 'vs/editor/common/core/lineTokens'; import { MetadataConsts } from 'vs/editor/common/modes'; suite('LineTokens', () => { interface ILineToken { startIndex: number; foreground: number; } function createLineTokens(text: string, tokens: ILineToken[]): LineTokens { let binTokens = new Uint32Array(tokens.length << 1); for (let i = 0, len = tokens.length; i < len; i++) { binTokens[(i << 1)] = (i + 1 < len ? tokens[i + 1].startIndex : text.length); binTokens[(i << 1) + 1] = ( tokens[i].foreground << MetadataConsts.FOREGROUND_OFFSET ) >>> 0; } return new LineTokens(binTokens, text); } function createTestLineTokens(): LineTokens { return createLineTokens( 'Hello world, this is a lovely day', [ { startIndex: 0, foreground: 1 }, // Hello_ { startIndex: 6, foreground: 2 }, // world,_ { startIndex: 13, foreground: 3 }, // this_ { startIndex: 18, foreground: 4 }, // is_ { startIndex: 21, foreground: 5 }, // a_ { startIndex: 23, foreground: 6 }, // lovely_ { startIndex: 30, foreground: 7 }, // day ] ); } test('basics', () => { const lineTokens = createTestLineTokens(); assert.equal(lineTokens.getLineContent(), 'Hello world, this is a lovely day'); assert.equal(lineTokens.getLineContent().length, 33); assert.equal(lineTokens.getCount(), 7); assert.equal(lineTokens.getStartOffset(0), 0); assert.equal(lineTokens.getEndOffset(0), 6); assert.equal(lineTokens.getStartOffset(1), 6); assert.equal(lineTokens.getEndOffset(1), 13); assert.equal(lineTokens.getStartOffset(2), 13); assert.equal(lineTokens.getEndOffset(2), 18); assert.equal(lineTokens.getStartOffset(3), 18); assert.equal(lineTokens.getEndOffset(3), 21); assert.equal(lineTokens.getStartOffset(4), 21); assert.equal(lineTokens.getEndOffset(4), 23); assert.equal(lineTokens.getStartOffset(5), 23); assert.equal(lineTokens.getEndOffset(5), 30); assert.equal(lineTokens.getStartOffset(6), 30); assert.equal(lineTokens.getEndOffset(6), 33); }); test('findToken', () => { const lineTokens = createTestLineTokens(); assert.equal(lineTokens.findTokenIndexAtOffset(0), 0); assert.equal(lineTokens.findTokenIndexAtOffset(1), 0); assert.equal(lineTokens.findTokenIndexAtOffset(2), 0); assert.equal(lineTokens.findTokenIndexAtOffset(3), 0); assert.equal(lineTokens.findTokenIndexAtOffset(4), 0); assert.equal(lineTokens.findTokenIndexAtOffset(5), 0); assert.equal(lineTokens.findTokenIndexAtOffset(6), 1); assert.equal(lineTokens.findTokenIndexAtOffset(7), 1); assert.equal(lineTokens.findTokenIndexAtOffset(8), 1); assert.equal(lineTokens.findTokenIndexAtOffset(9), 1); assert.equal(lineTokens.findTokenIndexAtOffset(10), 1); assert.equal(lineTokens.findTokenIndexAtOffset(11), 1); assert.equal(lineTokens.findTokenIndexAtOffset(12), 1); assert.equal(lineTokens.findTokenIndexAtOffset(13), 2); assert.equal(lineTokens.findTokenIndexAtOffset(14), 2); assert.equal(lineTokens.findTokenIndexAtOffset(15), 2); assert.equal(lineTokens.findTokenIndexAtOffset(16), 2); assert.equal(lineTokens.findTokenIndexAtOffset(17), 2); assert.equal(lineTokens.findTokenIndexAtOffset(18), 3); assert.equal(lineTokens.findTokenIndexAtOffset(19), 3); assert.equal(lineTokens.findTokenIndexAtOffset(20), 3); assert.equal(lineTokens.findTokenIndexAtOffset(21), 4); assert.equal(lineTokens.findTokenIndexAtOffset(22), 4); assert.equal(lineTokens.findTokenIndexAtOffset(23), 5); assert.equal(lineTokens.findTokenIndexAtOffset(24), 5); assert.equal(lineTokens.findTokenIndexAtOffset(25), 5); assert.equal(lineTokens.findTokenIndexAtOffset(26), 5); assert.equal(lineTokens.findTokenIndexAtOffset(27), 5); assert.equal(lineTokens.findTokenIndexAtOffset(28), 5); assert.equal(lineTokens.findTokenIndexAtOffset(29), 5); assert.equal(lineTokens.findTokenIndexAtOffset(30), 6); assert.equal(lineTokens.findTokenIndexAtOffset(31), 6); assert.equal(lineTokens.findTokenIndexAtOffset(32), 6); assert.equal(lineTokens.findTokenIndexAtOffset(33), 6); assert.equal(lineTokens.findTokenIndexAtOffset(34), 6); }); interface ITestViewLineToken { endIndex: number; foreground: number; } function assertViewLineTokens(_actual: IViewLineTokens, expected: ITestViewLineToken[]): void { let actual: ITestViewLineToken[] = []; for (let i = 0, len = _actual.getCount(); i < len; i++) { actual[i] = { endIndex: _actual.getEndOffset(i), foreground: _actual.getForeground(i) }; } assert.deepEqual(actual, expected); } test('inflate', () => { const lineTokens = createTestLineTokens(); assertViewLineTokens(lineTokens.inflate(), [ { endIndex: 6, foreground: 1 }, { endIndex: 13, foreground: 2 }, { endIndex: 18, foreground: 3 }, { endIndex: 21, foreground: 4 }, { endIndex: 23, foreground: 5 }, { endIndex: 30, foreground: 6 }, { endIndex: 33, foreground: 7 }, ]); }); test('sliceAndInflate', () => { const lineTokens = createTestLineTokens(); assertViewLineTokens(lineTokens.sliceAndInflate(0, 33, 0), [ { endIndex: 6, foreground: 1 }, { endIndex: 13, foreground: 2 }, { endIndex: 18, foreground: 3 }, { endIndex: 21, foreground: 4 }, { endIndex: 23, foreground: 5 }, { endIndex: 30, foreground: 6 }, { endIndex: 33, foreground: 7 }, ]); assertViewLineTokens(lineTokens.sliceAndInflate(0, 32, 0), [ { endIndex: 6, foreground: 1 }, { endIndex: 13, foreground: 2 }, { endIndex: 18, foreground: 3 }, { endIndex: 21, foreground: 4 }, { endIndex: 23, foreground: 5 }, { endIndex: 30, foreground: 6 }, { endIndex: 32, foreground: 7 }, ]); assertViewLineTokens(lineTokens.sliceAndInflate(0, 30, 0), [ { endIndex: 6, foreground: 1 }, { endIndex: 13, foreground: 2 }, { endIndex: 18, foreground: 3 }, { endIndex: 21, foreground: 4 }, { endIndex: 23, foreground: 5 }, { endIndex: 30, foreground: 6 } ]); assertViewLineTokens(lineTokens.sliceAndInflate(0, 30, 1), [ { endIndex: 7, foreground: 1 }, { endIndex: 14, foreground: 2 }, { endIndex: 19, foreground: 3 }, { endIndex: 22, foreground: 4 }, { endIndex: 24, foreground: 5 }, { endIndex: 31, foreground: 6 } ]); assertViewLineTokens(lineTokens.sliceAndInflate(6, 18, 0), [ { endIndex: 7, foreground: 2 }, { endIndex: 12, foreground: 3 } ]); assertViewLineTokens(lineTokens.sliceAndInflate(7, 18, 0), [ { endIndex: 6, foreground: 2 }, { endIndex: 11, foreground: 3 } ]); assertViewLineTokens(lineTokens.sliceAndInflate(6, 17, 0), [ { endIndex: 7, foreground: 2 }, { endIndex: 11, foreground: 3 } ]); assertViewLineTokens(lineTokens.sliceAndInflate(6, 19, 0), [ { endIndex: 7, foreground: 2 }, { endIndex: 12, foreground: 3 }, { endIndex: 13, foreground: 4 }, ]); }); });
src/vs/editor/test/common/core/lineTokens.test.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00018003022705670446, 0.0001755700068315491, 0.00016827670333441347, 0.00017531721096020192, 0.0000025222645945177646 ]
{ "id": 4, "code_window": [ "\tid: Constants.FocusSearchListCommandID,\n", "\thandler: focusSearchListCommand\n", "});\n", "\n", "const focusSearchListCommandLabel = nls.localize('focusSearchListCommandLabel', \"Focus List\");\n", "const FocusSearchListCommand: ICommandAction = {\n", "\tid: Constants.FocusSearchListCommandID,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 383 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { URI } from 'vs/base/common/uri'; import { isMacintosh } from 'vs/base/common/platform'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IElectronService } from 'vs/platform/electron/electron-sandbox/electron'; import { VSBuffer } from 'vs/base/common/buffer'; export class NativeClipboardService implements IClipboardService { private static readonly FILE_FORMAT = 'code/file-list'; // Clipboard format for files declare readonly _serviceBrand: undefined; constructor( @IElectronService private readonly electronService: IElectronService ) { } async writeText(text: string, type?: 'selection' | 'clipboard'): Promise<void> { return this.electronService.writeClipboardText(text, type); } async readText(type?: 'selection' | 'clipboard'): Promise<string> { return this.electronService.readClipboardText(type); } async readFindText(): Promise<string> { if (isMacintosh) { return this.electronService.readClipboardFindText(); } return ''; } async writeFindText(text: string): Promise<void> { if (isMacintosh) { return this.electronService.writeClipboardFindText(text); } } async writeResources(resources: URI[]): Promise<void> { if (resources.length) { return this.electronService.writeClipboardBuffer(NativeClipboardService.FILE_FORMAT, this.resourcesToBuffer(resources)); } } async readResources(): Promise<URI[]> { return this.bufferToResources(await this.electronService.readClipboardBuffer(NativeClipboardService.FILE_FORMAT)); } async hasResources(): Promise<boolean> { return this.electronService.hasClipboard(NativeClipboardService.FILE_FORMAT); } private resourcesToBuffer(resources: URI[]): Uint8Array { return VSBuffer.fromString(resources.map(r => r.toString()).join('\n')).buffer; } private bufferToResources(buffer: Uint8Array): URI[] { if (!buffer) { return []; } const bufferValue = buffer.toString(); if (!bufferValue) { return []; } try { return bufferValue.split('\n').map(f => URI.parse(f)); } catch (error) { return []; // do not trust clipboard data } } } registerSingleton(IClipboardService, NativeClipboardService, true);
src/vs/workbench/services/clipboard/electron-sandbox/clipboardService.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00017508790188003331, 0.00017308181850239635, 0.0001709955104161054, 0.00017313193529844284, 0.0000013755357031186577 ]
{ "id": 4, "code_window": [ "\tid: Constants.FocusSearchListCommandID,\n", "\thandler: focusSearchListCommand\n", "});\n", "\n", "const focusSearchListCommandLabel = nls.localize('focusSearchListCommandLabel', \"Focus List\");\n", "const FocusSearchListCommand: ICommandAction = {\n", "\tid: Constants.FocusSearchListCommandID,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 383 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode'; import { Configuration } from 'vs/editor/browser/config/configuration'; import { DynamicViewOverlay } from 'vs/editor/browser/view/dynamicViewOverlay'; import { IVisibleLine, IVisibleLinesHost, VisibleLinesCollection } from 'vs/editor/browser/view/viewLayer'; import { ViewPart } from 'vs/editor/browser/view/viewPart'; import { IStringBuilder } from 'vs/editor/common/core/stringBuilder'; import { IConfiguration } from 'vs/editor/common/editorCommon'; import { RenderingContext, RestrictedRenderingContext } from 'vs/editor/common/view/renderingContext'; import { ViewContext } from 'vs/editor/common/view/viewContext'; import * as viewEvents from 'vs/editor/common/view/viewEvents'; import { ViewportData } from 'vs/editor/common/viewLayout/viewLinesViewportData'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; export class ViewOverlays extends ViewPart implements IVisibleLinesHost<ViewOverlayLine> { private readonly _visibleLines: VisibleLinesCollection<ViewOverlayLine>; protected readonly domNode: FastDomNode<HTMLElement>; private _dynamicOverlays: DynamicViewOverlay[]; private _isFocused: boolean; constructor(context: ViewContext) { super(context); this._visibleLines = new VisibleLinesCollection<ViewOverlayLine>(this); this.domNode = this._visibleLines.domNode; this._dynamicOverlays = []; this._isFocused = false; this.domNode.setClassName('view-overlays'); } public shouldRender(): boolean { if (super.shouldRender()) { return true; } for (let i = 0, len = this._dynamicOverlays.length; i < len; i++) { const dynamicOverlay = this._dynamicOverlays[i]; if (dynamicOverlay.shouldRender()) { return true; } } return false; } public dispose(): void { super.dispose(); for (let i = 0, len = this._dynamicOverlays.length; i < len; i++) { const dynamicOverlay = this._dynamicOverlays[i]; dynamicOverlay.dispose(); } this._dynamicOverlays = []; } public getDomNode(): FastDomNode<HTMLElement> { return this.domNode; } // ---- begin IVisibleLinesHost public createVisibleLine(): ViewOverlayLine { return new ViewOverlayLine(this._context.configuration, this._dynamicOverlays); } // ---- end IVisibleLinesHost public addDynamicOverlay(overlay: DynamicViewOverlay): void { this._dynamicOverlays.push(overlay); } // ----- event handlers public onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean { this._visibleLines.onConfigurationChanged(e); const startLineNumber = this._visibleLines.getStartLineNumber(); const endLineNumber = this._visibleLines.getEndLineNumber(); for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { const line = this._visibleLines.getVisibleLine(lineNumber); line.onConfigurationChanged(e); } return true; } public onFlushed(e: viewEvents.ViewFlushedEvent): boolean { return this._visibleLines.onFlushed(e); } public onFocusChanged(e: viewEvents.ViewFocusChangedEvent): boolean { this._isFocused = e.isFocused; return true; } public onLinesChanged(e: viewEvents.ViewLinesChangedEvent): boolean { return this._visibleLines.onLinesChanged(e); } public onLinesDeleted(e: viewEvents.ViewLinesDeletedEvent): boolean { return this._visibleLines.onLinesDeleted(e); } public onLinesInserted(e: viewEvents.ViewLinesInsertedEvent): boolean { return this._visibleLines.onLinesInserted(e); } public onScrollChanged(e: viewEvents.ViewScrollChangedEvent): boolean { return this._visibleLines.onScrollChanged(e) || true; } public onTokensChanged(e: viewEvents.ViewTokensChangedEvent): boolean { return this._visibleLines.onTokensChanged(e); } public onZonesChanged(e: viewEvents.ViewZonesChangedEvent): boolean { return this._visibleLines.onZonesChanged(e); } // ----- end event handlers public prepareRender(ctx: RenderingContext): void { const toRender = this._dynamicOverlays.filter(overlay => overlay.shouldRender()); for (let i = 0, len = toRender.length; i < len; i++) { const dynamicOverlay = toRender[i]; dynamicOverlay.prepareRender(ctx); dynamicOverlay.onDidRender(); } } public render(ctx: RestrictedRenderingContext): void { // Overwriting to bypass `shouldRender` flag this._viewOverlaysRender(ctx); this.domNode.toggleClassName('focused', this._isFocused); } _viewOverlaysRender(ctx: RestrictedRenderingContext): void { this._visibleLines.renderLines(ctx.viewportData); } } export class ViewOverlayLine implements IVisibleLine { private readonly _configuration: IConfiguration; private readonly _dynamicOverlays: DynamicViewOverlay[]; private _domNode: FastDomNode<HTMLElement> | null; private _renderedContent: string | null; private _lineHeight: number; constructor(configuration: IConfiguration, dynamicOverlays: DynamicViewOverlay[]) { this._configuration = configuration; this._lineHeight = this._configuration.options.get(EditorOption.lineHeight); this._dynamicOverlays = dynamicOverlays; this._domNode = null; this._renderedContent = null; } public getDomNode(): HTMLElement | null { if (!this._domNode) { return null; } return this._domNode.domNode; } public setDomNode(domNode: HTMLElement): void { this._domNode = createFastDomNode(domNode); } public onContentChanged(): void { // Nothing } public onTokensChanged(): void { // Nothing } public onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): void { this._lineHeight = this._configuration.options.get(EditorOption.lineHeight); } public renderLine(lineNumber: number, deltaTop: number, viewportData: ViewportData, sb: IStringBuilder): boolean { let result = ''; for (let i = 0, len = this._dynamicOverlays.length; i < len; i++) { const dynamicOverlay = this._dynamicOverlays[i]; result += dynamicOverlay.render(viewportData.startLineNumber, lineNumber); } if (this._renderedContent === result) { // No rendering needed return false; } this._renderedContent = result; sb.appendASCIIString('<div style="position:absolute;top:'); sb.appendASCIIString(String(deltaTop)); sb.appendASCIIString('px;width:100%;height:'); sb.appendASCIIString(String(this._lineHeight)); sb.appendASCIIString('px;">'); sb.appendASCIIString(result); sb.appendASCIIString('</div>'); return true; } public layoutLine(lineNumber: number, deltaTop: number): void { if (this._domNode) { this._domNode.setTop(deltaTop); this._domNode.setHeight(this._lineHeight); } } } export class ContentViewOverlays extends ViewOverlays { private _contentWidth: number; constructor(context: ViewContext) { super(context); const options = this._context.configuration.options; const layoutInfo = options.get(EditorOption.layoutInfo); this._contentWidth = layoutInfo.contentWidth; this.domNode.setHeight(0); } // --- begin event handlers public onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean { const options = this._context.configuration.options; const layoutInfo = options.get(EditorOption.layoutInfo); this._contentWidth = layoutInfo.contentWidth; return super.onConfigurationChanged(e) || true; } public onScrollChanged(e: viewEvents.ViewScrollChangedEvent): boolean { return super.onScrollChanged(e) || e.scrollWidthChanged; } // --- end event handlers _viewOverlaysRender(ctx: RestrictedRenderingContext): void { super._viewOverlaysRender(ctx); this.domNode.setWidth(Math.max(ctx.scrollWidth, this._contentWidth)); } } export class MarginViewOverlays extends ViewOverlays { private _contentLeft: number; constructor(context: ViewContext) { super(context); const options = this._context.configuration.options; const layoutInfo = options.get(EditorOption.layoutInfo); this._contentLeft = layoutInfo.contentLeft; this.domNode.setClassName('margin-view-overlays'); this.domNode.setWidth(1); Configuration.applyFontInfo(this.domNode, options.get(EditorOption.fontInfo)); } public onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean { const options = this._context.configuration.options; Configuration.applyFontInfo(this.domNode, options.get(EditorOption.fontInfo)); const layoutInfo = options.get(EditorOption.layoutInfo); this._contentLeft = layoutInfo.contentLeft; return super.onConfigurationChanged(e) || true; } public onScrollChanged(e: viewEvents.ViewScrollChangedEvent): boolean { return super.onScrollChanged(e) || e.scrollHeightChanged; } _viewOverlaysRender(ctx: RestrictedRenderingContext): void { super._viewOverlaysRender(ctx); const height = Math.min(ctx.scrollHeight, 1000000); this.domNode.setHeight(height); this.domNode.setWidth(this._contentLeft); } }
src/vs/editor/browser/view/viewOverlays.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00017839371867012233, 0.00017282507906202227, 0.00016823546320665628, 0.00017290294636040926, 0.0000024236196622950956 ]
{ "id": 5, "code_window": [ "const FocusSearchListCommand: ICommandAction = {\n", "\tid: Constants.FocusSearchListCommandID,\n", "\ttitle: focusSearchListCommandLabel,\n", "\tcategory\n", "};\n", "MenuRegistry.addCommand(FocusSearchListCommand);\n", "\n", "const searchInFolderCommand: ICommandHandler = (accessor, resource?: URI) => {\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\ttitle: { value: nls.localize('focusSearchListCommandLabel', \"Focus List\"), original: 'Focus List' },\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 386 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Action } from 'vs/base/common/actions'; import { distinct } from 'vs/base/common/arrays'; import { onUnexpectedError } from 'vs/base/common/errors'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import * as objects from 'vs/base/common/objects'; import * as platform from 'vs/base/common/platform'; import { dirname } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { ToggleCaseSensitiveKeybinding, ToggleRegexKeybinding, ToggleWholeWordKeybinding } from 'vs/editor/contrib/find/findModel'; import * as nls from 'vs/nls'; import { ICommandAction, MenuId, MenuRegistry, SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { CommandsRegistry, ICommandHandler } from 'vs/platform/commands/common/commands'; import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry'; import { ContextKeyExpr, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IFileService } from 'vs/platform/files/common/files'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { IListService, WorkbenchListFocusContextKey, WorkbenchObjectTree } from 'vs/platform/list/browser/listService'; import { Registry } from 'vs/platform/registry/common/platform'; import { defaultQuickAccessContextKeyValue } from 'vs/workbench/browser/quickaccess'; import { Extensions as ActionExtensions, IWorkbenchActionRegistry } from 'vs/workbench/common/actions'; import { Extensions as WorkbenchExtensions, IWorkbenchContribution, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions'; import { Extensions as ViewExtensions, IViewsRegistry, IViewContainersRegistry, ViewContainerLocation, IViewDescriptorService, IViewsService } from 'vs/workbench/common/views'; import { getMultiSelectedResources } from 'vs/workbench/contrib/files/browser/files'; import { ExplorerFolderContext, ExplorerRootContext, FilesExplorerFocusCondition, IExplorerService, VIEWLET_ID as VIEWLET_ID_FILES } from 'vs/workbench/contrib/files/common/files'; import { registerContributions as replaceContributions } from 'vs/workbench/contrib/search/browser/replaceContributions'; import { clearHistoryCommand, ClearSearchResultsAction, CloseReplaceAction, CollapseDeepestExpandedLevelAction, copyAllCommand, copyMatchCommand, copyPathCommand, FocusNextInputAction, FocusNextSearchResultAction, FocusPreviousInputAction, FocusPreviousSearchResultAction, focusSearchListCommand, getSearchView, openSearchView, OpenSearchViewletAction, RefreshAction, RemoveAction, ReplaceAction, ReplaceAllAction, ReplaceAllInFolderAction, ReplaceInFilesAction, toggleCaseSensitiveCommand, toggleRegexCommand, toggleWholeWordCommand, FindInFilesCommand, ToggleSearchOnTypeAction, ExpandAllAction } from 'vs/workbench/contrib/search/browser/searchActions'; import { SearchView } from 'vs/workbench/contrib/search/browser/searchView'; import { registerContributions as searchWidgetContributions } from 'vs/workbench/contrib/search/browser/searchWidget'; import * as Constants from 'vs/workbench/contrib/search/common/constants'; import * as SearchEditorConstants from 'vs/workbench/contrib/searchEditor/browser/constants'; import { getWorkspaceSymbols } from 'vs/workbench/contrib/search/common/search'; import { ISearchHistoryService, SearchHistoryService } from 'vs/workbench/contrib/search/common/searchHistoryService'; import { FileMatchOrMatch, ISearchWorkbenchService, RenderableMatch, SearchWorkbenchService, FileMatch, Match, FolderMatch } from 'vs/workbench/contrib/search/common/searchModel'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { VIEWLET_ID, VIEW_ID, SEARCH_EXCLUDE_CONFIG, SearchSortOrder } from 'vs/workbench/services/search/common/search'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { ExplorerViewPaneContainer } from 'vs/workbench/contrib/files/browser/explorerViewlet'; import { assertType, assertIsDefined } from 'vs/base/common/types'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { SearchEditor } from 'vs/workbench/contrib/searchEditor/browser/searchEditor'; import { ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { IQuickAccessRegistry, Extensions as QuickAccessExtensions } from 'vs/platform/quickinput/common/quickAccess'; import { SymbolsQuickAccessProvider } from 'vs/workbench/contrib/search/browser/symbolsQuickAccess'; import { AnythingQuickAccessProvider } from 'vs/workbench/contrib/search/browser/anythingQuickAccess'; import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { AbstractGotoLineQuickAccessProvider } from 'vs/editor/contrib/quickAccess/gotoLineQuickAccess'; import { GotoSymbolQuickAccessProvider } from 'vs/workbench/contrib/codeEditor/browser/quickaccess/gotoSymbolQuickAccess'; import { searchViewIcon } from 'vs/workbench/contrib/search/browser/searchIcons'; registerSingleton(ISearchWorkbenchService, SearchWorkbenchService, true); registerSingleton(ISearchHistoryService, SearchHistoryService, true); replaceContributions(); searchWidgetContributions(); const category = nls.localize('search', "Search"); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'workbench.action.search.toggleQueryDetails', weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or(Constants.SearchViewFocusedKey, SearchEditorConstants.InSearchEditor), primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_J, handler: accessor => { const contextService = accessor.get(IContextKeyService).getContext(document.activeElement); if (contextService.getValue(SearchEditorConstants.InSearchEditor.serialize())) { (accessor.get(IEditorService).activeEditorPane as SearchEditor).toggleQueryDetails(); } else if (contextService.getValue(Constants.SearchViewFocusedKey.serialize())) { const searchView = getSearchView(accessor.get(IViewsService)); assertIsDefined(searchView).toggleQueryDetails(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.FocusSearchFromResults, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FirstMatchFocusKey), primary: KeyMod.CtrlCmd | KeyCode.UpArrow, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { searchView.focusPreviousInputBox(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.OpenMatchToSide, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyMod.CtrlCmd | KeyCode.Enter, mac: { primary: KeyMod.WinCtrl | KeyCode.Enter }, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); searchView.open(<FileMatchOrMatch>tree.getFocus()[0], false, true, true); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CancelActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, WorkbenchListFocusContextKey), primary: KeyCode.Escape, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { searchView.cancelSearch(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.RemoveActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyCode.Delete, mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace, }, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(RemoveAction, tree, tree.getFocus()[0]!).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.MatchFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAction, tree, tree.getFocus()[0] as Match, searchView).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceAllInFileActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.FileFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter], handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAllAction, searchView, tree.getFocus()[0] as FileMatch).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceAllInFolderActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.FolderFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter], handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAllInFolderAction, tree, tree.getFocus()[0] as FolderMatch).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CloseReplaceWidgetActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceInputBoxFocusedKey), primary: KeyCode.Escape, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(CloseReplaceAction, Constants.CloseReplaceWidgetActionId, '').run(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FocusNextInputAction.ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or( ContextKeyExpr.and(SearchEditorConstants.InSearchEditor, Constants.InputBoxFocusedKey), ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.InputBoxFocusedKey)), primary: KeyMod.CtrlCmd | KeyCode.DownArrow, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(FocusNextInputAction, FocusNextInputAction.ID, '').run(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FocusPreviousInputAction.ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or( ContextKeyExpr.and(SearchEditorConstants.InSearchEditor, Constants.InputBoxFocusedKey), ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.InputBoxFocusedKey, Constants.SearchInputBoxFocusedKey.toNegated())), primary: KeyMod.CtrlCmd | KeyCode.UpArrow, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(FocusPreviousInputAction, FocusPreviousInputAction.ID, '').run(); } }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceActionId, title: ReplaceAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.MatchFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceAllInFolderActionId, title: ReplaceAllInFolderAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.FolderFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceAllInFileActionId, title: ReplaceAllAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.FileFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.RemoveActionId, title: RemoveAction.LABEL }, when: Constants.FileMatchOrMatchFocusKey, group: 'search', order: 2 }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CopyMatchCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.FileMatchOrMatchFocusKey, primary: KeyMod.CtrlCmd | KeyCode.KEY_C, handler: copyMatchCommand }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyMatchCommandId, title: nls.localize('copyMatchLabel', "Copy") }, when: Constants.FileMatchOrMatchFocusKey, group: 'search_2', order: 1 }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CopyPathCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.FileMatchOrFolderMatchWithResourceFocusKey, primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_C, win: { primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_C }, handler: copyPathCommand }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyPathCommandId, title: nls.localize('copyPathLabel', "Copy Path") }, when: Constants.FileMatchOrFolderMatchWithResourceFocusKey, group: 'search_2', order: 2 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyAllCommandId, title: nls.localize('copyAllLabel', "Copy All") }, when: Constants.HasSearchResults, group: 'search_2', order: 3 }); CommandsRegistry.registerCommand({ id: Constants.CopyAllCommandId, handler: copyAllCommand }); CommandsRegistry.registerCommand({ id: Constants.ClearSearchHistoryCommandId, handler: clearHistoryCommand }); CommandsRegistry.registerCommand({ id: Constants.RevealInSideBarForSearchResults, handler: (accessor, args: any) => { const viewletService = accessor.get(IViewletService); const explorerService = accessor.get(IExplorerService); const contextService = accessor.get(IWorkspaceContextService); const searchView = getSearchView(accessor.get(IViewsService)); if (!searchView) { return; } let fileMatch: FileMatch; if (!(args instanceof FileMatch)) { args = searchView.getControl().getFocus()[0]; } if (args instanceof FileMatch) { fileMatch = args; } else { return; } viewletService.openViewlet(VIEWLET_ID_FILES, false).then((viewlet) => { if (!viewlet) { return; } const explorerViewContainer = viewlet.getViewPaneContainer() as ExplorerViewPaneContainer; const uri = fileMatch.resource; if (uri && contextService.isInsideWorkspace(uri)) { const explorerView = explorerViewContainer.getExplorerView(); explorerView.setExpanded(true); explorerService.select(uri, true).then(() => explorerView.focus(), onUnexpectedError); } }); } }); const RevealInSideBarForSearchResultsCommand: ICommandAction = { id: Constants.RevealInSideBarForSearchResults, title: nls.localize('revealInSideBar', "Reveal in Side Bar") }; MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: RevealInSideBarForSearchResultsCommand, when: ContextKeyExpr.and(Constants.FileFocusKey, Constants.HasSearchResults), group: 'search_3', order: 1 }); const clearSearchHistoryLabel = nls.localize('clearSearchHistoryLabel', "Clear Search History"); const ClearSearchHistoryCommand: ICommandAction = { id: Constants.ClearSearchHistoryCommandId, title: clearSearchHistoryLabel, category }; MenuRegistry.addCommand(ClearSearchHistoryCommand); CommandsRegistry.registerCommand({ id: Constants.FocusSearchListCommandID, handler: focusSearchListCommand }); const focusSearchListCommandLabel = nls.localize('focusSearchListCommandLabel', "Focus List"); const FocusSearchListCommand: ICommandAction = { id: Constants.FocusSearchListCommandID, title: focusSearchListCommandLabel, category }; MenuRegistry.addCommand(FocusSearchListCommand); const searchInFolderCommand: ICommandHandler = (accessor, resource?: URI) => { const listService = accessor.get(IListService); const fileService = accessor.get(IFileService); const viewsService = accessor.get(IViewsService); const resources = getMultiSelectedResources(resource, listService, accessor.get(IEditorService), accessor.get(IExplorerService)); return openSearchView(viewsService, true).then(searchView => { if (resources && resources.length && searchView) { return fileService.resolveAll(resources.map(resource => ({ resource }))).then(results => { const folders: URI[] = []; results.forEach(result => { if (result.success && result.stat) { folders.push(result.stat.isDirectory ? result.stat.resource : dirname(result.stat.resource)); } }); searchView.searchInFolders(distinct(folders, folder => folder.toString())); }); } return undefined; }); }; const FIND_IN_FOLDER_ID = 'filesExplorer.findInFolder'; KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FIND_IN_FOLDER_ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(FilesExplorerFocusCondition, ExplorerFolderContext), primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_F, handler: searchInFolderCommand }); CommandsRegistry.registerCommand({ id: ClearSearchResultsAction.ID, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(ClearSearchResultsAction, ClearSearchResultsAction.ID, '').run(); } }); CommandsRegistry.registerCommand({ id: RefreshAction.ID, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(RefreshAction, RefreshAction.ID, '').run(); } }); const FIND_IN_WORKSPACE_ID = 'filesExplorer.findInWorkspace'; CommandsRegistry.registerCommand({ id: FIND_IN_WORKSPACE_ID, handler: (accessor) => { return openSearchView(accessor.get(IViewsService), true).then(searchView => { if (searchView) { searchView.searchInFolders(); } }); } }); MenuRegistry.appendMenuItem(MenuId.ExplorerContext, { group: '4_search', order: 10, command: { id: FIND_IN_FOLDER_ID, title: nls.localize('findInFolder', "Find in Folder...") }, when: ContextKeyExpr.and(ExplorerFolderContext) }); MenuRegistry.appendMenuItem(MenuId.ExplorerContext, { group: '4_search', order: 10, command: { id: FIND_IN_WORKSPACE_ID, title: nls.localize('findInWorkspace', "Find in Workspace...") }, when: ContextKeyExpr.and(ExplorerRootContext, ExplorerFolderContext.toNegated()) }); class ShowAllSymbolsAction extends Action { static readonly ID = 'workbench.action.showAllSymbols'; static readonly LABEL = nls.localize('showTriggerActions', "Go to Symbol in Workspace..."); static readonly ALL_SYMBOLS_PREFIX = '#'; constructor( actionId: string, actionLabel: string, @IQuickInputService private readonly quickInputService: IQuickInputService ) { super(actionId, actionLabel); } async run(): Promise<void> { this.quickInputService.quickAccess.show(ShowAllSymbolsAction.ALL_SYMBOLS_PREFIX); } } const viewContainer = Registry.as<IViewContainersRegistry>(ViewExtensions.ViewContainersRegistry).registerViewContainer({ id: VIEWLET_ID, name: nls.localize('name', "Search"), ctorDescriptor: new SyncDescriptor(ViewPaneContainer, [VIEWLET_ID, { mergeViewWithContainerWhenSingleView: true, donotShowContainerTitleWhenMergedWithContainer: true }]), hideIfEmpty: true, icon: searchViewIcon.classNames, order: 1 }, ViewContainerLocation.Sidebar); const viewDescriptor = { id: VIEW_ID, containerIcon: 'codicon-search', name: nls.localize('search', "Search"), ctorDescriptor: new SyncDescriptor(SearchView), canToggleVisibility: false, canMoveView: true }; // Register search default location to sidebar Registry.as<IViewsRegistry>(ViewExtensions.ViewsRegistry).registerViews([viewDescriptor], viewContainer); // Migrate search location setting to new model class RegisterSearchViewContribution implements IWorkbenchContribution { constructor( @IConfigurationService configurationService: IConfigurationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService ) { const data = configurationService.inspect('search.location'); if (data.value === 'panel') { viewDescriptorService.moveViewToLocation(viewDescriptor, ViewContainerLocation.Panel); } if (data.userValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER); } if (data.userLocalValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER_LOCAL); } if (data.userRemoteValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER_REMOTE); } if (data.workspaceFolderValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.WORKSPACE_FOLDER); } if (data.workspaceValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.WORKSPACE); } } } Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(RegisterSearchViewContribution, LifecyclePhase.Starting); // Actions const registry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions); // Show Search and Find in Files are redundant, but we can't break keybindings by removing one. So it's the same action, same keybinding, registered to different IDs. // Show Search 'when' is redundant but if the two conflict with exactly the same keybinding and 'when' clause, then they can show up as "unbound" - #51780 registry.registerWorkbenchAction(SyncActionDescriptor.from(OpenSearchViewletAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_F }, Constants.SearchViewVisibleKey.toNegated()), 'View: Show Search', nls.localize('view', "View")); KeybindingsRegistry.registerCommandAndKeybindingRule({ description: { description: nls.localize('findInFiles.description', "Open the search viewlet"), args: [ { name: nls.localize('findInFiles.args', "A set of options for the search viewlet"), schema: { type: 'object', properties: { query: { 'type': 'string' }, replace: { 'type': 'string' }, triggerSearch: { 'type': 'boolean' }, filesToInclude: { 'type': 'string' }, filesToExclude: { 'type': 'string' }, isRegex: { 'type': 'boolean' }, isCaseSensitive: { 'type': 'boolean' }, matchWholeWord: { 'type': 'boolean' }, } } }, ] }, id: Constants.FindInFilesActionId, weight: KeybindingWeight.WorkbenchContrib, when: null, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_F, handler: FindInFilesCommand }); MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: Constants.FindInFilesActionId, title: { value: nls.localize('findInFiles', "Find in Files"), original: 'Find in Files' }, category } }); MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { group: '4_find_global', command: { id: Constants.FindInFilesActionId, title: nls.localize({ key: 'miFindInFiles', comment: ['&& denotes a mnemonic'] }, "Find &&in Files") }, order: 1 }); registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusNextSearchResultAction, { primary: KeyCode.F4 }), 'Focus Next Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor)); registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusPreviousSearchResultAction, { primary: KeyMod.Shift | KeyCode.F4 }), 'Focus Previous Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor)); registry.registerWorkbenchAction(SyncActionDescriptor.from(ReplaceInFilesAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_H }), 'Replace in Files', category); MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { group: '4_find_global', command: { id: ReplaceInFilesAction.ID, title: nls.localize({ key: 'miReplaceInFiles', comment: ['&& denotes a mnemonic'] }, "Replace &&in Files") }, order: 2 }); if (platform.isMacintosh) { // Register this with a more restrictive `when` on mac to avoid conflict with "copy path" KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleCaseSensitiveCommandId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewFocusedKey, Constants.FileMatchOrFolderMatchFocusKey.toNegated()), handler: toggleCaseSensitiveCommand }, ToggleCaseSensitiveKeybinding)); } else { KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleCaseSensitiveCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleCaseSensitiveCommand }, ToggleCaseSensitiveKeybinding)); } KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleWholeWordCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleWholeWordCommand }, ToggleWholeWordKeybinding)); KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleRegexCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleRegexCommand }, ToggleRegexKeybinding)); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.AddCursorsAtSearchResults, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_L, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); searchView.openEditorWithMultiCursor(<FileMatchOrMatch>tree.getFocus()[0]); } } }); registry.registerWorkbenchAction(SyncActionDescriptor.from(CollapseDeepestExpandedLevelAction), 'Search: Collapse All', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ExpandAllAction), 'Search: Expand All', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ShowAllSymbolsAction, { primary: KeyMod.CtrlCmd | KeyCode.KEY_T }), 'Go to Symbol in Workspace...'); registry.registerWorkbenchAction(SyncActionDescriptor.from(ToggleSearchOnTypeAction), 'Search: Toggle Search on Type', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(RefreshAction), 'Search: Refresh', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ClearSearchResultsAction), 'Search: Clear Search Results', category); // Register Quick Access Handler const quickAccessRegistry = Registry.as<IQuickAccessRegistry>(QuickAccessExtensions.Quickaccess); quickAccessRegistry.registerQuickAccessProvider({ ctor: AnythingQuickAccessProvider, prefix: AnythingQuickAccessProvider.PREFIX, placeholder: nls.localize('anythingQuickAccessPlaceholder', "Search files by name (append {0} to go to line or {1} to go to symbol)", AbstractGotoLineQuickAccessProvider.PREFIX, GotoSymbolQuickAccessProvider.PREFIX), contextKey: defaultQuickAccessContextKeyValue, helpEntries: [{ description: nls.localize('anythingQuickAccess', "Go to File"), needsEditor: false }] }); quickAccessRegistry.registerQuickAccessProvider({ ctor: SymbolsQuickAccessProvider, prefix: SymbolsQuickAccessProvider.PREFIX, placeholder: nls.localize('symbolsQuickAccessPlaceholder', "Type the name of a symbol to open."), contextKey: 'inWorkspaceSymbolsPicker', helpEntries: [{ description: nls.localize('symbolsQuickAccess', "Go to Symbol in Workspace"), needsEditor: false }] }); // Configuration const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration); configurationRegistry.registerConfiguration({ id: 'search', order: 13, title: nls.localize('searchConfigurationTitle', "Search"), type: 'object', properties: { [SEARCH_EXCLUDE_CONFIG]: { type: 'object', markdownDescription: nls.localize('exclude', "Configure glob patterns for excluding files and folders in fulltext searches and quick open. Inherits all glob patterns from the `#files.exclude#` setting. Read more about glob patterns [here](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options)."), default: { '**/node_modules': true, '**/bower_components': true, '**/*.code-search': true }, additionalProperties: { anyOf: [ { type: 'boolean', description: nls.localize('exclude.boolean', "The glob pattern to match file paths against. Set to true or false to enable or disable the pattern."), }, { type: 'object', properties: { when: { type: 'string', // expression ({ "**/*.js": { "when": "$(basename).js" } }) pattern: '\\w*\\$\\(basename\\)\\w*', default: '$(basename).ext', description: nls.localize('exclude.when', 'Additional check on the siblings of a matching file. Use $(basename) as variable for the matching file name.') } } } ] }, scope: ConfigurationScope.RESOURCE }, 'search.useRipgrep': { type: 'boolean', description: nls.localize('useRipgrep', "This setting is deprecated and now falls back on \"search.usePCRE2\"."), deprecationMessage: nls.localize('useRipgrepDeprecated', "Deprecated. Consider \"search.usePCRE2\" for advanced regex feature support."), default: true }, 'search.maintainFileSearchCache': { type: 'boolean', description: nls.localize('search.maintainFileSearchCache', "When enabled, the searchService process will be kept alive instead of being shut down after an hour of inactivity. This will keep the file search cache in memory."), default: false }, 'search.useIgnoreFiles': { type: 'boolean', markdownDescription: nls.localize('useIgnoreFiles', "Controls whether to use `.gitignore` and `.ignore` files when searching for files."), default: true, scope: ConfigurationScope.RESOURCE }, 'search.useGlobalIgnoreFiles': { type: 'boolean', markdownDescription: nls.localize('useGlobalIgnoreFiles', "Controls whether to use global `.gitignore` and `.ignore` files when searching for files."), default: false, scope: ConfigurationScope.RESOURCE }, 'search.quickOpen.includeSymbols': { type: 'boolean', description: nls.localize('search.quickOpen.includeSymbols', "Whether to include results from a global symbol search in the file results for Quick Open."), default: false }, 'search.quickOpen.includeHistory': { type: 'boolean', description: nls.localize('search.quickOpen.includeHistory', "Whether to include results from recently opened files in the file results for Quick Open."), default: true }, 'search.quickOpen.history.filterSortOrder': { 'type': 'string', 'enum': ['default', 'recency'], 'default': 'default', 'enumDescriptions': [ nls.localize('filterSortOrder.default', 'History entries are sorted by relevance based on the filter value used. More relevant entries appear first.'), nls.localize('filterSortOrder.recency', 'History entries are sorted by recency. More recently opened entries appear first.') ], 'description': nls.localize('filterSortOrder', "Controls sorting order of editor history in quick open when filtering.") }, 'search.followSymlinks': { type: 'boolean', description: nls.localize('search.followSymlinks', "Controls whether to follow symlinks while searching."), default: true }, 'search.smartCase': { type: 'boolean', description: nls.localize('search.smartCase', "Search case-insensitively if the pattern is all lowercase, otherwise, search case-sensitively."), default: false }, 'search.globalFindClipboard': { type: 'boolean', default: false, description: nls.localize('search.globalFindClipboard', "Controls whether the search view should read or modify the shared find clipboard on macOS."), included: platform.isMacintosh }, 'search.location': { type: 'string', enum: ['sidebar', 'panel'], default: 'sidebar', description: nls.localize('search.location', "Controls whether the search will be shown as a view in the sidebar or as a panel in the panel area for more horizontal space."), deprecationMessage: nls.localize('search.location.deprecationMessage', "This setting is deprecated. Please use drag and drop instead by dragging the search icon.") }, 'search.collapseResults': { type: 'string', enum: ['auto', 'alwaysCollapse', 'alwaysExpand'], enumDescriptions: [ nls.localize('search.collapseResults.auto', "Files with less than 10 results are expanded. Others are collapsed."), '', '' ], default: 'alwaysExpand', description: nls.localize('search.collapseAllResults', "Controls whether the search results will be collapsed or expanded."), }, 'search.useReplacePreview': { type: 'boolean', default: true, description: nls.localize('search.useReplacePreview', "Controls whether to open Replace Preview when selecting or replacing a match."), }, 'search.showLineNumbers': { type: 'boolean', default: false, description: nls.localize('search.showLineNumbers', "Controls whether to show line numbers for search results."), }, 'search.usePCRE2': { type: 'boolean', default: false, description: nls.localize('search.usePCRE2', "Whether to use the PCRE2 regex engine in text search. This enables using some advanced regex features like lookahead and backreferences. However, not all PCRE2 features are supported - only features that are also supported by JavaScript."), deprecationMessage: nls.localize('usePCRE2Deprecated', "Deprecated. PCRE2 will be used automatically when using regex features that are only supported by PCRE2."), }, 'search.actionsPosition': { type: 'string', enum: ['auto', 'right'], enumDescriptions: [ nls.localize('search.actionsPositionAuto', "Position the actionbar to the right when the search view is narrow, and immediately after the content when the search view is wide."), nls.localize('search.actionsPositionRight', "Always position the actionbar to the right."), ], default: 'auto', description: nls.localize('search.actionsPosition', "Controls the positioning of the actionbar on rows in the search view.") }, 'search.searchOnType': { type: 'boolean', default: true, description: nls.localize('search.searchOnType', "Search all files as you type.") }, 'search.seedWithNearestWord': { type: 'boolean', default: false, description: nls.localize('search.seedWithNearestWord', "Enable seeding search from the word nearest the cursor when the active editor has no selection.") }, 'search.seedOnFocus': { type: 'boolean', default: false, description: nls.localize('search.seedOnFocus', "Update workspace search query to the editor's selected text when focusing the search view. This happens either on click or when triggering the `workbench.views.search.focus` command.") }, 'search.searchOnTypeDebouncePeriod': { type: 'number', default: 300, markdownDescription: nls.localize('search.searchOnTypeDebouncePeriod', "When `#search.searchOnType#` is enabled, controls the timeout in milliseconds between a character being typed and the search starting. Has no effect when `search.searchOnType` is disabled.") }, 'search.searchEditor.doubleClickBehaviour': { type: 'string', enum: ['selectWord', 'goToLocation', 'openLocationToSide'], default: 'goToLocation', enumDescriptions: [ nls.localize('search.searchEditor.doubleClickBehaviour.selectWord', "Double clicking selects the word under the cursor."), nls.localize('search.searchEditor.doubleClickBehaviour.goToLocation', "Double clicking opens the result in the active editor group."), nls.localize('search.searchEditor.doubleClickBehaviour.openLocationToSide', "Double clicking opens the result in the editor group to the side, creating one if it does not yet exist."), ], markdownDescription: nls.localize('search.searchEditor.doubleClickBehaviour', "Configure effect of double clicking a result in a search editor.") }, 'search.searchEditor.reusePriorSearchConfiguration': { type: 'boolean', default: false, markdownDescription: nls.localize({ key: 'search.searchEditor.reusePriorSearchConfiguration', comment: ['"Search Editor" is a type that editor that can display search results. "includes, excludes, and flags" just refers to settings that affect search. For example, the "search.exclude" setting.'] }, "When enabled, new Search Editors will reuse the includes, excludes, and flags of the previously opened Search Editor") }, 'search.searchEditor.defaultNumberOfContextLines': { type: ['number', 'null'], default: 1, markdownDescription: nls.localize('search.searchEditor.defaultNumberOfContextLines', "The default number of surrounding context lines to use when creating new Search Editors. If using `#search.searchEditor.reusePriorSearchConfiguration#`, this can be set to `null` (empty) to use the prior Search Editor's configuration.") }, 'search.sortOrder': { 'type': 'string', 'enum': [SearchSortOrder.Default, SearchSortOrder.FileNames, SearchSortOrder.Type, SearchSortOrder.Modified, SearchSortOrder.CountDescending, SearchSortOrder.CountAscending], 'default': SearchSortOrder.Default, 'enumDescriptions': [ nls.localize('searchSortOrder.default', "Results are sorted by folder and file names, in alphabetical order."), nls.localize('searchSortOrder.filesOnly', "Results are sorted by file names ignoring folder order, in alphabetical order."), nls.localize('searchSortOrder.type', "Results are sorted by file extensions, in alphabetical order."), nls.localize('searchSortOrder.modified', "Results are sorted by file last modified date, in descending order."), nls.localize('searchSortOrder.countDescending', "Results are sorted by count per file, in descending order."), nls.localize('searchSortOrder.countAscending', "Results are sorted by count per file, in ascending order.") ], 'description': nls.localize('search.sortOrder', "Controls sorting order of search results.") }, } }); CommandsRegistry.registerCommand('_executeWorkspaceSymbolProvider', function (accessor, ...args) { const [query] = args; assertType(typeof query === 'string'); return getWorkspaceSymbols(query); }); // View menu MenuRegistry.appendMenuItem(MenuId.MenubarViewMenu, { group: '3_views', command: { id: VIEWLET_ID, title: nls.localize({ key: 'miViewSearch', comment: ['&& denotes a mnemonic'] }, "&&Search") }, order: 2 }); // Go to menu MenuRegistry.appendMenuItem(MenuId.MenubarGoMenu, { group: '3_global_nav', command: { id: 'workbench.action.showAllSymbols', title: nls.localize({ key: 'miGotoSymbolInWorkspace', comment: ['&& denotes a mnemonic'] }, "Go to Symbol in &&Workspace...") }, order: 2 });
src/vs/workbench/contrib/search/browser/search.contribution.ts
1
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.9989577531814575, 0.05567331984639168, 0.0001637801615288481, 0.00017362491053063422, 0.22787563502788544 ]
{ "id": 5, "code_window": [ "const FocusSearchListCommand: ICommandAction = {\n", "\tid: Constants.FocusSearchListCommandID,\n", "\ttitle: focusSearchListCommandLabel,\n", "\tcategory\n", "};\n", "MenuRegistry.addCommand(FocusSearchListCommand);\n", "\n", "const searchInFolderCommand: ICommandHandler = (accessor, resource?: URI) => {\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\ttitle: { value: nls.localize('focusSearchListCommandLabel', \"Focus List\"), original: 'Focus List' },\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 386 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as strings from 'vs/base/common/strings'; import * as streams from 'vs/base/common/stream'; declare const Buffer: any; const hasBuffer = (typeof Buffer !== 'undefined'); const hasTextEncoder = (typeof TextEncoder !== 'undefined'); const hasTextDecoder = (typeof TextDecoder !== 'undefined'); let textEncoder: TextEncoder | null; let textDecoder: TextDecoder | null; export class VSBuffer { static alloc(byteLength: number): VSBuffer { if (hasBuffer) { return new VSBuffer(Buffer.allocUnsafe(byteLength)); } else { return new VSBuffer(new Uint8Array(byteLength)); } } static wrap(actual: Uint8Array): VSBuffer { if (hasBuffer && !(Buffer.isBuffer(actual))) { // https://nodejs.org/dist/latest-v10.x/docs/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length // Create a zero-copy Buffer wrapper around the ArrayBuffer pointed to by the Uint8Array actual = Buffer.from(actual.buffer, actual.byteOffset, actual.byteLength); } return new VSBuffer(actual); } static fromString(source: string): VSBuffer { if (hasBuffer) { return new VSBuffer(Buffer.from(source)); } else if (hasTextEncoder) { if (!textEncoder) { textEncoder = new TextEncoder(); } return new VSBuffer(textEncoder.encode(source)); } else { return new VSBuffer(strings.encodeUTF8(source)); } } static concat(buffers: VSBuffer[], totalLength?: number): VSBuffer { if (typeof totalLength === 'undefined') { totalLength = 0; for (let i = 0, len = buffers.length; i < len; i++) { totalLength += buffers[i].byteLength; } } const ret = VSBuffer.alloc(totalLength); let offset = 0; for (let i = 0, len = buffers.length; i < len; i++) { const element = buffers[i]; ret.set(element, offset); offset += element.byteLength; } return ret; } readonly buffer: Uint8Array; readonly byteLength: number; private constructor(buffer: Uint8Array) { this.buffer = buffer; this.byteLength = this.buffer.byteLength; } toString(): string { if (hasBuffer) { return this.buffer.toString(); } else if (hasTextDecoder) { if (!textDecoder) { textDecoder = new TextDecoder(); } return textDecoder.decode(this.buffer); } else { return strings.decodeUTF8(this.buffer); } } slice(start?: number, end?: number): VSBuffer { // IMPORTANT: use subarray instead of slice because TypedArray#slice // creates shallow copy and NodeBuffer#slice doesn't. The use of subarray // ensures the same, performant, behaviour. return new VSBuffer(this.buffer.subarray(start!/*bad lib.d.ts*/, end)); } set(array: VSBuffer, offset?: number): void; set(array: Uint8Array, offset?: number): void; set(array: VSBuffer | Uint8Array, offset?: number): void { if (array instanceof VSBuffer) { this.buffer.set(array.buffer, offset); } else { this.buffer.set(array, offset); } } readUInt32BE(offset: number): number { return readUInt32BE(this.buffer, offset); } writeUInt32BE(value: number, offset: number): void { writeUInt32BE(this.buffer, value, offset); } readUInt32LE(offset: number): number { return readUInt32LE(this.buffer, offset); } writeUInt32LE(value: number, offset: number): void { writeUInt32LE(this.buffer, value, offset); } readUInt8(offset: number): number { return readUInt8(this.buffer, offset); } writeUInt8(value: number, offset: number): void { writeUInt8(this.buffer, value, offset); } } export function readUInt16LE(source: Uint8Array, offset: number): number { return ( ((source[offset + 0] << 0) >>> 0) | ((source[offset + 1] << 8) >>> 0) ); } export function writeUInt16LE(destination: Uint8Array, value: number, offset: number): void { destination[offset + 0] = (value & 0b11111111); value = value >>> 8; destination[offset + 1] = (value & 0b11111111); } export function readUInt32BE(source: Uint8Array, offset: number): number { return ( source[offset] * 2 ** 24 + source[offset + 1] * 2 ** 16 + source[offset + 2] * 2 ** 8 + source[offset + 3] ); } export function writeUInt32BE(destination: Uint8Array, value: number, offset: number): void { destination[offset + 3] = value; value = value >>> 8; destination[offset + 2] = value; value = value >>> 8; destination[offset + 1] = value; value = value >>> 8; destination[offset] = value; } export function readUInt32LE(source: Uint8Array, offset: number): number { return ( ((source[offset + 0] << 0) >>> 0) | ((source[offset + 1] << 8) >>> 0) | ((source[offset + 2] << 16) >>> 0) | ((source[offset + 3] << 24) >>> 0) ); } export function writeUInt32LE(destination: Uint8Array, value: number, offset: number): void { destination[offset + 0] = (value & 0b11111111); value = value >>> 8; destination[offset + 1] = (value & 0b11111111); value = value >>> 8; destination[offset + 2] = (value & 0b11111111); value = value >>> 8; destination[offset + 3] = (value & 0b11111111); } export function readUInt8(source: Uint8Array, offset: number): number { return source[offset]; } export function writeUInt8(destination: Uint8Array, value: number, offset: number): void { destination[offset] = value; } export interface VSBufferReadable extends streams.Readable<VSBuffer> { } export interface VSBufferReadableStream extends streams.ReadableStream<VSBuffer> { } export interface VSBufferWriteableStream extends streams.WriteableStream<VSBuffer> { } export interface VSBufferReadableBufferedStream extends streams.ReadableBufferedStream<VSBuffer> { } export function readableToBuffer(readable: VSBufferReadable): VSBuffer { return streams.consumeReadable<VSBuffer>(readable, chunks => VSBuffer.concat(chunks)); } export function bufferToReadable(buffer: VSBuffer): VSBufferReadable { return streams.toReadable<VSBuffer>(buffer); } export function streamToBuffer(stream: streams.ReadableStream<VSBuffer>): Promise<VSBuffer> { return streams.consumeStream<VSBuffer>(stream, chunks => VSBuffer.concat(chunks)); } export async function bufferedStreamToBuffer(bufferedStream: streams.ReadableBufferedStream<VSBuffer>): Promise<VSBuffer> { if (bufferedStream.ended) { return VSBuffer.concat(bufferedStream.buffer); } return VSBuffer.concat([ // Include already read chunks... ...bufferedStream.buffer, // ...and all additional chunks await streamToBuffer(bufferedStream.stream) ]); } export function bufferToStream(buffer: VSBuffer): streams.ReadableStream<VSBuffer> { return streams.toStream<VSBuffer>(buffer, chunks => VSBuffer.concat(chunks)); } export function streamToBufferReadableStream(stream: streams.ReadableStreamEvents<Uint8Array | string>): streams.ReadableStream<VSBuffer> { return streams.transform<Uint8Array | string, VSBuffer>(stream, { data: data => typeof data === 'string' ? VSBuffer.fromString(data) : VSBuffer.wrap(data) }, chunks => VSBuffer.concat(chunks)); } export function newWriteableBufferStream(options?: streams.WriteableStreamOptions): streams.WriteableStream<VSBuffer> { return streams.newWriteableStream<VSBuffer>(chunks => VSBuffer.concat(chunks), options); }
src/vs/base/common/buffer.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00017875520279631019, 0.00017485213174950331, 0.0001673682709224522, 0.0001755920675350353, 0.0000027756507279264042 ]
{ "id": 5, "code_window": [ "const FocusSearchListCommand: ICommandAction = {\n", "\tid: Constants.FocusSearchListCommandID,\n", "\ttitle: focusSearchListCommandLabel,\n", "\tcategory\n", "};\n", "MenuRegistry.addCommand(FocusSearchListCommand);\n", "\n", "const searchInFolderCommand: ICommandHandler = (accessor, resource?: URI) => {\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\ttitle: { value: nls.localize('focusSearchListCommandLabel', \"Focus List\"), original: 'Focus List' },\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 386 }
"use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); exports.prepareIslFiles = exports.prepareI18nPackFiles = exports.pullI18nPackFiles = exports.prepareI18nFiles = exports.pullSetupXlfFiles = exports.pullCoreAndExtensionsXlfFiles = exports.findObsoleteResources = exports.pushXlfFiles = exports.createXlfFilesForIsl = exports.createXlfFilesForExtensions = exports.createXlfFilesForCoreBundle = exports.getResource = exports.processNlsFiles = exports.Limiter = exports.XLF = exports.Line = exports.externalExtensionsWithTranslations = exports.extraLanguages = exports.defaultLanguages = void 0; const path = require("path"); const fs = require("fs"); const event_stream_1 = require("event-stream"); const File = require("vinyl"); const Is = require("is"); const xml2js = require("xml2js"); const glob = require("glob"); const https = require("https"); const gulp = require("gulp"); const fancyLog = require("fancy-log"); const ansiColors = require("ansi-colors"); const iconv = require("iconv-lite-umd"); const NUMBER_OF_CONCURRENT_DOWNLOADS = 4; function log(message, ...rest) { fancyLog(ansiColors.green('[i18n]'), message, ...rest); } exports.defaultLanguages = [ { id: 'zh-tw', folderName: 'cht', translationId: 'zh-hant' }, { id: 'zh-cn', folderName: 'chs', translationId: 'zh-hans' }, { id: 'ja', folderName: 'jpn' }, { id: 'ko', folderName: 'kor' }, { id: 'de', folderName: 'deu' }, { id: 'fr', folderName: 'fra' }, { id: 'es', folderName: 'esn' }, { id: 'ru', folderName: 'rus' }, { id: 'it', folderName: 'ita' } ]; // languages requested by the community to non-stable builds exports.extraLanguages = [ { id: 'pt-br', folderName: 'ptb' }, { id: 'hu', folderName: 'hun' }, { id: 'tr', folderName: 'trk' } ]; // non built-in extensions also that are transifex and need to be part of the language packs exports.externalExtensionsWithTranslations = { 'vscode-chrome-debug': 'msjsdiag.debugger-for-chrome', 'vscode-node-debug': 'ms-vscode.node-debug', 'vscode-node-debug2': 'ms-vscode.node-debug2' }; var LocalizeInfo; (function (LocalizeInfo) { function is(value) { let candidate = value; return Is.defined(candidate) && Is.string(candidate.key) && (Is.undef(candidate.comment) || (Is.array(candidate.comment) && candidate.comment.every(element => Is.string(element)))); } LocalizeInfo.is = is; })(LocalizeInfo || (LocalizeInfo = {})); var BundledFormat; (function (BundledFormat) { function is(value) { if (Is.undef(value)) { return false; } let candidate = value; let length = Object.keys(value).length; return length === 3 && Is.defined(candidate.keys) && Is.defined(candidate.messages) && Is.defined(candidate.bundles); } BundledFormat.is = is; })(BundledFormat || (BundledFormat = {})); var PackageJsonFormat; (function (PackageJsonFormat) { function is(value) { if (Is.undef(value) || !Is.object(value)) { return false; } return Object.keys(value).every(key => { let element = value[key]; return Is.string(element) || (Is.object(element) && Is.defined(element.message) && Is.defined(element.comment)); }); } PackageJsonFormat.is = is; })(PackageJsonFormat || (PackageJsonFormat = {})); class Line { constructor(indent = 0) { this.buffer = []; if (indent > 0) { this.buffer.push(new Array(indent + 1).join(' ')); } } append(value) { this.buffer.push(value); return this; } toString() { return this.buffer.join(''); } } exports.Line = Line; class TextModel { constructor(contents) { this._lines = contents.split(/\r\n|\r|\n/); } get lines() { return this._lines; } } class XLF { constructor(project) { this.project = project; this.buffer = []; this.files = Object.create(null); this.numberOfMessages = 0; } toString() { this.appendHeader(); for (let file in this.files) { this.appendNewLine(`<file original="${file}" source-language="en" datatype="plaintext"><body>`, 2); for (let item of this.files[file]) { this.addStringItem(file, item); } this.appendNewLine('</body></file>', 2); } this.appendFooter(); return this.buffer.join('\r\n'); } addFile(original, keys, messages) { if (keys.length === 0) { console.log('No keys in ' + original); return; } if (keys.length !== messages.length) { throw new Error(`Unmatching keys(${keys.length}) and messages(${messages.length}).`); } this.numberOfMessages += keys.length; this.files[original] = []; let existingKeys = new Set(); for (let i = 0; i < keys.length; i++) { let key = keys[i]; let realKey; let comment; if (Is.string(key)) { realKey = key; comment = undefined; } else if (LocalizeInfo.is(key)) { realKey = key.key; if (key.comment && key.comment.length > 0) { comment = key.comment.map(comment => encodeEntities(comment)).join('\r\n'); } } if (!realKey || existingKeys.has(realKey)) { continue; } existingKeys.add(realKey); let message = encodeEntities(messages[i]); this.files[original].push({ id: realKey, message: message, comment: comment }); } } addStringItem(file, item) { if (!item.id || item.message === undefined || item.message === null) { throw new Error(`No item ID or value specified: ${JSON.stringify(item)}. File: ${file}`); } if (item.message.length === 0) { log(`Item with id ${item.id} in file ${file} has an empty message.`); } this.appendNewLine(`<trans-unit id="${item.id}">`, 4); this.appendNewLine(`<source xml:lang="en">${item.message}</source>`, 6); if (item.comment) { this.appendNewLine(`<note>${item.comment}</note>`, 6); } this.appendNewLine('</trans-unit>', 4); } appendHeader() { this.appendNewLine('<?xml version="1.0" encoding="utf-8"?>', 0); this.appendNewLine('<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">', 0); } appendFooter() { this.appendNewLine('</xliff>', 0); } appendNewLine(content, indent) { let line = new Line(indent); line.append(content); this.buffer.push(line.toString()); } } exports.XLF = XLF; XLF.parsePseudo = function (xlfString) { return new Promise((resolve) => { let parser = new xml2js.Parser(); let files = []; parser.parseString(xlfString, function (_err, result) { const fileNodes = result['xliff']['file']; fileNodes.forEach(file => { const originalFilePath = file.$.original; const messages = {}; const transUnits = file.body[0]['trans-unit']; if (transUnits) { transUnits.forEach((unit) => { const key = unit.$.id; const val = pseudify(unit.source[0]['_'].toString()); if (key && val) { messages[key] = decodeEntities(val); } }); files.push({ messages: messages, originalFilePath: originalFilePath, language: 'ps' }); } }); resolve(files); }); }); }; XLF.parse = function (xlfString) { return new Promise((resolve, reject) => { let parser = new xml2js.Parser(); let files = []; parser.parseString(xlfString, function (err, result) { if (err) { reject(new Error(`XLF parsing error: Failed to parse XLIFF string. ${err}`)); } const fileNodes = result['xliff']['file']; if (!fileNodes) { reject(new Error(`XLF parsing error: XLIFF file does not contain "xliff" or "file" node(s) required for parsing.`)); } fileNodes.forEach((file) => { const originalFilePath = file.$.original; if (!originalFilePath) { reject(new Error(`XLF parsing error: XLIFF file node does not contain original attribute to determine the original location of the resource file.`)); } let language = file.$['target-language']; if (!language) { reject(new Error(`XLF parsing error: XLIFF file node does not contain target-language attribute to determine translated language.`)); } const messages = {}; const transUnits = file.body[0]['trans-unit']; if (transUnits) { transUnits.forEach((unit) => { const key = unit.$.id; if (!unit.target) { return; // No translation available } let val = unit.target[0]; if (typeof val !== 'string') { val = val._; } if (key && val) { messages[key] = decodeEntities(val); } else { reject(new Error(`XLF parsing error: XLIFF file ${originalFilePath} does not contain full localization data. ID or target translation for one of the trans-unit nodes is not present.`)); } }); files.push({ messages: messages, originalFilePath: originalFilePath, language: language.toLowerCase() }); } }); resolve(files); }); }); }; class Limiter { constructor(maxDegreeOfParalellism) { this.maxDegreeOfParalellism = maxDegreeOfParalellism; this.outstandingPromises = []; this.runningPromises = 0; } queue(factory) { return new Promise((c, e) => { this.outstandingPromises.push({ factory, c, e }); this.consume(); }); } consume() { while (this.outstandingPromises.length && this.runningPromises < this.maxDegreeOfParalellism) { const iLimitedTask = this.outstandingPromises.shift(); this.runningPromises++; const promise = iLimitedTask.factory(); promise.then(iLimitedTask.c).catch(iLimitedTask.e); promise.then(() => this.consumed()).catch(() => this.consumed()); } } consumed() { this.runningPromises--; this.consume(); } } exports.Limiter = Limiter; function sortLanguages(languages) { return languages.sort((a, b) => { return a.id < b.id ? -1 : (a.id > b.id ? 1 : 0); }); } function stripComments(content) { /** * First capturing group matches double quoted string * Second matches single quotes string * Third matches block comments * Fourth matches line comments */ const regexp = /("(?:[^\\\"]*(?:\\.)?)*")|('(?:[^\\\']*(?:\\.)?)*')|(\/\*(?:\r?\n|.)*?\*\/)|(\/{2,}.*?(?:(?:\r?\n)|$))/g; let result = content.replace(regexp, (match, _m1, _m2, m3, m4) => { // Only one of m1, m2, m3, m4 matches if (m3) { // A block comment. Replace with nothing return ''; } else if (m4) { // A line comment. If it ends in \r?\n then keep it. let length = m4.length; if (length > 2 && m4[length - 1] === '\n') { return m4[length - 2] === '\r' ? '\r\n' : '\n'; } else { return ''; } } else { // We match a string return match; } }); return result; } function escapeCharacters(value) { const result = []; for (let i = 0; i < value.length; i++) { const ch = value.charAt(i); switch (ch) { case '\'': result.push('\\\''); break; case '"': result.push('\\"'); break; case '\\': result.push('\\\\'); break; case '\n': result.push('\\n'); break; case '\r': result.push('\\r'); break; case '\t': result.push('\\t'); break; case '\b': result.push('\\b'); break; case '\f': result.push('\\f'); break; default: result.push(ch); } } return result.join(''); } function processCoreBundleFormat(fileHeader, languages, json, emitter) { let keysSection = json.keys; let messageSection = json.messages; let bundleSection = json.bundles; let statistics = Object.create(null); let defaultMessages = Object.create(null); let modules = Object.keys(keysSection); modules.forEach((module) => { let keys = keysSection[module]; let messages = messageSection[module]; if (!messages || keys.length !== messages.length) { emitter.emit('error', `Message for module ${module} corrupted. Mismatch in number of keys and messages.`); return; } let messageMap = Object.create(null); defaultMessages[module] = messageMap; keys.map((key, i) => { if (typeof key === 'string') { messageMap[key] = messages[i]; } else { messageMap[key.key] = messages[i]; } }); }); let languageDirectory = path.join(__dirname, '..', '..', '..', 'vscode-loc', 'i18n'); if (!fs.existsSync(languageDirectory)) { log(`No VS Code localization repository found. Looking at ${languageDirectory}`); log(`To bundle translations please check out the vscode-loc repository as a sibling of the vscode repository.`); } let sortedLanguages = sortLanguages(languages); sortedLanguages.forEach((language) => { if (process.env['VSCODE_BUILD_VERBOSE']) { log(`Generating nls bundles for: ${language.id}`); } statistics[language.id] = 0; let localizedModules = Object.create(null); let languageFolderName = language.translationId || language.id; let i18nFile = path.join(languageDirectory, `vscode-language-pack-${languageFolderName}`, 'translations', 'main.i18n.json'); let allMessages; if (fs.existsSync(i18nFile)) { let content = stripComments(fs.readFileSync(i18nFile, 'utf8')); allMessages = JSON.parse(content); } modules.forEach((module) => { let order = keysSection[module]; let moduleMessage; if (allMessages) { moduleMessage = allMessages.contents[module]; } if (!moduleMessage) { if (process.env['VSCODE_BUILD_VERBOSE']) { log(`No localized messages found for module ${module}. Using default messages.`); } moduleMessage = defaultMessages[module]; statistics[language.id] = statistics[language.id] + Object.keys(moduleMessage).length; } let localizedMessages = []; order.forEach((keyInfo) => { let key = null; if (typeof keyInfo === 'string') { key = keyInfo; } else { key = keyInfo.key; } let message = moduleMessage[key]; if (!message) { if (process.env['VSCODE_BUILD_VERBOSE']) { log(`No localized message found for key ${key} in module ${module}. Using default message.`); } message = defaultMessages[module][key]; statistics[language.id] = statistics[language.id] + 1; } localizedMessages.push(message); }); localizedModules[module] = localizedMessages; }); Object.keys(bundleSection).forEach((bundle) => { let modules = bundleSection[bundle]; let contents = [ fileHeader, `define("${bundle}.nls.${language.id}", {` ]; modules.forEach((module, index) => { contents.push(`\t"${module}": [`); let messages = localizedModules[module]; if (!messages) { emitter.emit('error', `Didn't find messages for module ${module}.`); return; } messages.forEach((message, index) => { contents.push(`\t\t"${escapeCharacters(message)}${index < messages.length ? '",' : '"'}`); }); contents.push(index < modules.length - 1 ? '\t],' : '\t]'); }); contents.push('});'); emitter.queue(new File({ path: bundle + '.nls.' + language.id + '.js', contents: Buffer.from(contents.join('\n'), 'utf-8') })); }); }); Object.keys(statistics).forEach(key => { let value = statistics[key]; log(`${key} has ${value} untranslated strings.`); }); sortedLanguages.forEach(language => { let stats = statistics[language.id]; if (Is.undef(stats)) { log(`\tNo translations found for language ${language.id}. Using default language instead.`); } }); } function processNlsFiles(opts) { return event_stream_1.through(function (file) { let fileName = path.basename(file.path); if (fileName === 'nls.metadata.json') { let json = null; if (file.isBuffer()) { json = JSON.parse(file.contents.toString('utf8')); } else { this.emit('error', `Failed to read component file: ${file.relative}`); return; } if (BundledFormat.is(json)) { processCoreBundleFormat(opts.fileHeader, opts.languages, json, this); } } this.queue(file); }); } exports.processNlsFiles = processNlsFiles; const editorProject = 'vscode-editor', workbenchProject = 'vscode-workbench', extensionsProject = 'vscode-extensions', setupProject = 'vscode-setup'; function getResource(sourceFile) { let resource; if (/^vs\/platform/.test(sourceFile)) { return { name: 'vs/platform', project: editorProject }; } else if (/^vs\/editor\/contrib/.test(sourceFile)) { return { name: 'vs/editor/contrib', project: editorProject }; } else if (/^vs\/editor/.test(sourceFile)) { return { name: 'vs/editor', project: editorProject }; } else if (/^vs\/base/.test(sourceFile)) { return { name: 'vs/base', project: editorProject }; } else if (/^vs\/code/.test(sourceFile)) { return { name: 'vs/code', project: workbenchProject }; } else if (/^vs\/workbench\/contrib/.test(sourceFile)) { resource = sourceFile.split('/', 4).join('/'); return { name: resource, project: workbenchProject }; } else if (/^vs\/workbench\/services/.test(sourceFile)) { resource = sourceFile.split('/', 4).join('/'); return { name: resource, project: workbenchProject }; } else if (/^vs\/workbench/.test(sourceFile)) { return { name: 'vs/workbench', project: workbenchProject }; } throw new Error(`Could not identify the XLF bundle for ${sourceFile}`); } exports.getResource = getResource; function createXlfFilesForCoreBundle() { return event_stream_1.through(function (file) { const basename = path.basename(file.path); if (basename === 'nls.metadata.json') { if (file.isBuffer()) { const xlfs = Object.create(null); const json = JSON.parse(file.contents.toString('utf8')); for (let coreModule in json.keys) { const projectResource = getResource(coreModule); const resource = projectResource.name; const project = projectResource.project; const keys = json.keys[coreModule]; const messages = json.messages[coreModule]; if (keys.length !== messages.length) { this.emit('error', `There is a mismatch between keys and messages in ${file.relative} for module ${coreModule}`); return; } else { let xlf = xlfs[resource]; if (!xlf) { xlf = new XLF(project); xlfs[resource] = xlf; } xlf.addFile(`src/${coreModule}`, keys, messages); } } for (let resource in xlfs) { const xlf = xlfs[resource]; const filePath = `${xlf.project}/${resource.replace(/\//g, '_')}.xlf`; const xlfFile = new File({ path: filePath, contents: Buffer.from(xlf.toString(), 'utf8') }); this.queue(xlfFile); } } else { this.emit('error', new Error(`File ${file.relative} is not using a buffer content`)); return; } } else { this.emit('error', new Error(`File ${file.relative} is not a core meta data file.`)); return; } }); } exports.createXlfFilesForCoreBundle = createXlfFilesForCoreBundle; function createXlfFilesForExtensions() { let counter = 0; let folderStreamEnded = false; let folderStreamEndEmitted = false; return event_stream_1.through(function (extensionFolder) { const folderStream = this; const stat = fs.statSync(extensionFolder.path); if (!stat.isDirectory()) { return; } let extensionName = path.basename(extensionFolder.path); if (extensionName === 'node_modules') { return; } counter++; let _xlf; function getXlf() { if (!_xlf) { _xlf = new XLF(extensionsProject); } return _xlf; } gulp.src([`.build/extensions/${extensionName}/package.nls.json`, `.build/extensions/${extensionName}/**/nls.metadata.json`], { allowEmpty: true }).pipe(event_stream_1.through(function (file) { if (file.isBuffer()) { const buffer = file.contents; const basename = path.basename(file.path); if (basename === 'package.nls.json') { const json = JSON.parse(buffer.toString('utf8')); const keys = Object.keys(json); const messages = keys.map((key) => { const value = json[key]; if (Is.string(value)) { return value; } else if (value) { return value.message; } else { return `Unknown message for key: ${key}`; } }); getXlf().addFile(`extensions/${extensionName}/package`, keys, messages); } else if (basename === 'nls.metadata.json') { const json = JSON.parse(buffer.toString('utf8')); const relPath = path.relative(`.build/extensions/${extensionName}`, path.dirname(file.path)); for (let file in json) { const fileContent = json[file]; getXlf().addFile(`extensions/${extensionName}/${relPath}/${file}`, fileContent.keys, fileContent.messages); } } else { this.emit('error', new Error(`${file.path} is not a valid extension nls file`)); return; } } }, function () { if (_xlf) { let xlfFile = new File({ path: path.join(extensionsProject, extensionName + '.xlf'), contents: Buffer.from(_xlf.toString(), 'utf8') }); folderStream.queue(xlfFile); } this.queue(null); counter--; if (counter === 0 && folderStreamEnded && !folderStreamEndEmitted) { folderStreamEndEmitted = true; folderStream.queue(null); } })); }, function () { folderStreamEnded = true; if (counter === 0) { folderStreamEndEmitted = true; this.queue(null); } }); } exports.createXlfFilesForExtensions = createXlfFilesForExtensions; function createXlfFilesForIsl() { return event_stream_1.through(function (file) { let projectName, resourceFile; if (path.basename(file.path) === 'Default.isl') { projectName = setupProject; resourceFile = 'setup_default.xlf'; } else { projectName = workbenchProject; resourceFile = 'setup_messages.xlf'; } let xlf = new XLF(projectName), keys = [], messages = []; let model = new TextModel(file.contents.toString()); let inMessageSection = false; model.lines.forEach(line => { if (line.length === 0) { return; } let firstChar = line.charAt(0); switch (firstChar) { case ';': // Comment line; return; case '[': inMessageSection = '[Messages]' === line || '[CustomMessages]' === line; return; } if (!inMessageSection) { return; } let sections = line.split('='); if (sections.length !== 2) { throw new Error(`Badly formatted message found: ${line}`); } else { let key = sections[0]; let value = sections[1]; if (key.length > 0 && value.length > 0) { keys.push(key); messages.push(value); } } }); const originalPath = file.path.substring(file.cwd.length + 1, file.path.split('.')[0].length).replace(/\\/g, '/'); xlf.addFile(originalPath, keys, messages); // Emit only upon all ISL files combined into single XLF instance const newFilePath = path.join(projectName, resourceFile); const xlfFile = new File({ path: newFilePath, contents: Buffer.from(xlf.toString(), 'utf-8') }); this.queue(xlfFile); }); } exports.createXlfFilesForIsl = createXlfFilesForIsl; function pushXlfFiles(apiHostname, username, password) { let tryGetPromises = []; let updateCreatePromises = []; return event_stream_1.through(function (file) { const project = path.dirname(file.relative); const fileName = path.basename(file.path); const slug = fileName.substr(0, fileName.length - '.xlf'.length); const credentials = `${username}:${password}`; // Check if resource already exists, if not, then create it. let promise = tryGetResource(project, slug, apiHostname, credentials); tryGetPromises.push(promise); promise.then(exists => { if (exists) { promise = updateResource(project, slug, file, apiHostname, credentials); } else { promise = createResource(project, slug, file, apiHostname, credentials); } updateCreatePromises.push(promise); }); }, function () { // End the pipe only after all the communication with Transifex API happened Promise.all(tryGetPromises).then(() => { Promise.all(updateCreatePromises).then(() => { this.queue(null); }).catch((reason) => { throw new Error(reason); }); }).catch((reason) => { throw new Error(reason); }); }); } exports.pushXlfFiles = pushXlfFiles; function getAllResources(project, apiHostname, username, password) { return new Promise((resolve, reject) => { const credentials = `${username}:${password}`; const options = { hostname: apiHostname, path: `/api/2/project/${project}/resources`, auth: credentials, method: 'GET' }; const request = https.request(options, (res) => { let buffer = []; res.on('data', (chunk) => buffer.push(chunk)); res.on('end', () => { if (res.statusCode === 200) { let json = JSON.parse(Buffer.concat(buffer).toString()); if (Array.isArray(json)) { resolve(json.map(o => o.slug)); return; } reject(`Unexpected data format. Response code: ${res.statusCode}.`); } else { reject(`No resources in ${project} returned no data. Response code: ${res.statusCode}.`); } }); }); request.on('error', (err) => { reject(`Failed to query resources in ${project} with the following error: ${err}. ${options.path}`); }); request.end(); }); } function findObsoleteResources(apiHostname, username, password) { let resourcesByProject = Object.create(null); resourcesByProject[extensionsProject] = [].concat(exports.externalExtensionsWithTranslations); // clone return event_stream_1.through(function (file) { const project = path.dirname(file.relative); const fileName = path.basename(file.path); const slug = fileName.substr(0, fileName.length - '.xlf'.length); let slugs = resourcesByProject[project]; if (!slugs) { resourcesByProject[project] = slugs = []; } slugs.push(slug); this.push(file); }, function () { const json = JSON.parse(fs.readFileSync('./build/lib/i18n.resources.json', 'utf8')); let i18Resources = [...json.editor, ...json.workbench].map((r) => r.project + '/' + r.name.replace(/\//g, '_')); let extractedResources = []; for (let project of [workbenchProject, editorProject]) { for (let resource of resourcesByProject[project]) { if (resource !== 'setup_messages') { extractedResources.push(project + '/' + resource); } } } if (i18Resources.length !== extractedResources.length) { console.log(`[i18n] Obsolete resources in file 'build/lib/i18n.resources.json': JSON.stringify(${i18Resources.filter(p => extractedResources.indexOf(p) === -1)})`); console.log(`[i18n] Missing resources in file 'build/lib/i18n.resources.json': JSON.stringify(${extractedResources.filter(p => i18Resources.indexOf(p) === -1)})`); } let promises = []; for (let project in resourcesByProject) { promises.push(getAllResources(project, apiHostname, username, password).then(resources => { let expectedResources = resourcesByProject[project]; let unusedResources = resources.filter(resource => resource && expectedResources.indexOf(resource) === -1); if (unusedResources.length) { console.log(`[transifex] Obsolete resources in project '${project}': ${unusedResources.join(', ')}`); } })); } return Promise.all(promises).then(_ => { this.push(null); }).catch((reason) => { throw new Error(reason); }); }); } exports.findObsoleteResources = findObsoleteResources; function tryGetResource(project, slug, apiHostname, credentials) { return new Promise((resolve, reject) => { const options = { hostname: apiHostname, path: `/api/2/project/${project}/resource/${slug}/?details`, auth: credentials, method: 'GET' }; const request = https.request(options, (response) => { if (response.statusCode === 404) { resolve(false); } else if (response.statusCode === 200) { resolve(true); } else { reject(`Failed to query resource ${project}/${slug}. Response: ${response.statusCode} ${response.statusMessage}`); } }); request.on('error', (err) => { reject(`Failed to get ${project}/${slug} on Transifex: ${err}`); }); request.end(); }); } function createResource(project, slug, xlfFile, apiHostname, credentials) { return new Promise((_resolve, reject) => { const data = JSON.stringify({ 'content': xlfFile.contents.toString(), 'name': slug, 'slug': slug, 'i18n_type': 'XLIFF' }); const options = { hostname: apiHostname, path: `/api/2/project/${project}/resources`, headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) }, auth: credentials, method: 'POST' }; let request = https.request(options, (res) => { if (res.statusCode === 201) { log(`Resource ${project}/${slug} successfully created on Transifex.`); } else { reject(`Something went wrong in the request creating ${slug} in ${project}. ${res.statusCode}`); } }); request.on('error', (err) => { reject(`Failed to create ${project}/${slug} on Transifex: ${err}`); }); request.write(data); request.end(); }); } /** * The following link provides information about how Transifex handles updates of a resource file: * https://dev.befoolish.co/tx-docs/public/projects/updating-content#what-happens-when-you-update-files */ function updateResource(project, slug, xlfFile, apiHostname, credentials) { return new Promise((resolve, reject) => { const data = JSON.stringify({ content: xlfFile.contents.toString() }); const options = { hostname: apiHostname, path: `/api/2/project/${project}/resource/${slug}/content`, headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) }, auth: credentials, method: 'PUT' }; let request = https.request(options, (res) => { if (res.statusCode === 200) { res.setEncoding('utf8'); let responseBuffer = ''; res.on('data', function (chunk) { responseBuffer += chunk; }); res.on('end', () => { const response = JSON.parse(responseBuffer); log(`Resource ${project}/${slug} successfully updated on Transifex. Strings added: ${response.strings_added}, updated: ${response.strings_added}, deleted: ${response.strings_added}`); resolve(); }); } else { reject(`Something went wrong in the request updating ${slug} in ${project}. ${res.statusCode}`); } }); request.on('error', (err) => { reject(`Failed to update ${project}/${slug} on Transifex: ${err}`); }); request.write(data); request.end(); }); } // cache resources let _coreAndExtensionResources; function pullCoreAndExtensionsXlfFiles(apiHostname, username, password, language, externalExtensions) { if (!_coreAndExtensionResources) { _coreAndExtensionResources = []; // editor and workbench const json = JSON.parse(fs.readFileSync('./build/lib/i18n.resources.json', 'utf8')); _coreAndExtensionResources.push(...json.editor); _coreAndExtensionResources.push(...json.workbench); // extensions let extensionsToLocalize = Object.create(null); glob.sync('.build/extensions/**/*.nls.json').forEach(extension => extensionsToLocalize[extension.split('/')[2]] = true); glob.sync('.build/extensions/*/node_modules/vscode-nls').forEach(extension => extensionsToLocalize[extension.split('/')[2]] = true); Object.keys(extensionsToLocalize).forEach(extension => { _coreAndExtensionResources.push({ name: extension, project: extensionsProject }); }); if (externalExtensions) { for (let resourceName in externalExtensions) { _coreAndExtensionResources.push({ name: resourceName, project: extensionsProject }); } } } return pullXlfFiles(apiHostname, username, password, language, _coreAndExtensionResources); } exports.pullCoreAndExtensionsXlfFiles = pullCoreAndExtensionsXlfFiles; function pullSetupXlfFiles(apiHostname, username, password, language, includeDefault) { let setupResources = [{ name: 'setup_messages', project: workbenchProject }]; if (includeDefault) { setupResources.push({ name: 'setup_default', project: setupProject }); } return pullXlfFiles(apiHostname, username, password, language, setupResources); } exports.pullSetupXlfFiles = pullSetupXlfFiles; function pullXlfFiles(apiHostname, username, password, language, resources) { const credentials = `${username}:${password}`; let expectedTranslationsCount = resources.length; let translationsRetrieved = 0, called = false; return event_stream_1.readable(function (_count, callback) { // Mark end of stream when all resources were retrieved if (translationsRetrieved === expectedTranslationsCount) { return this.emit('end'); } if (!called) { called = true; const stream = this; resources.map(function (resource) { retrieveResource(language, resource, apiHostname, credentials).then((file) => { if (file) { stream.emit('data', file); } translationsRetrieved++; }).catch(error => { throw new Error(error); }); }); } callback(); }); } const limiter = new Limiter(NUMBER_OF_CONCURRENT_DOWNLOADS); function retrieveResource(language, resource, apiHostname, credentials) { return limiter.queue(() => new Promise((resolve, reject) => { const slug = resource.name.replace(/\//g, '_'); const project = resource.project; let transifexLanguageId = language.id === 'ps' ? 'en' : language.translationId || language.id; const options = { hostname: apiHostname, path: `/api/2/project/${project}/resource/${slug}/translation/${transifexLanguageId}?file&mode=onlyreviewed`, auth: credentials, port: 443, method: 'GET' }; console.log('[transifex] Fetching ' + options.path); let request = https.request(options, (res) => { let xlfBuffer = []; res.on('data', (chunk) => xlfBuffer.push(chunk)); res.on('end', () => { if (res.statusCode === 200) { resolve(new File({ contents: Buffer.concat(xlfBuffer), path: `${project}/${slug}.xlf` })); } else if (res.statusCode === 404) { console.log(`[transifex] ${slug} in ${project} returned no data.`); resolve(null); } else { reject(`${slug} in ${project} returned no data. Response code: ${res.statusCode}.`); } }); }); request.on('error', (err) => { reject(`Failed to query resource ${slug} with the following error: ${err}. ${options.path}`); }); request.end(); })); } function prepareI18nFiles() { let parsePromises = []; return event_stream_1.through(function (xlf) { let stream = this; let parsePromise = XLF.parse(xlf.contents.toString()); parsePromises.push(parsePromise); parsePromise.then(resolvedFiles => { resolvedFiles.forEach(file => { let translatedFile = createI18nFile(file.originalFilePath, file.messages); stream.queue(translatedFile); }); }); }, function () { Promise.all(parsePromises) .then(() => { this.queue(null); }) .catch(reason => { throw new Error(reason); }); }); } exports.prepareI18nFiles = prepareI18nFiles; function createI18nFile(originalFilePath, messages) { let result = Object.create(null); result[''] = [ '--------------------------------------------------------------------------------------------', '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.' ]; for (let key of Object.keys(messages)) { result[key] = messages[key]; } let content = JSON.stringify(result, null, '\t'); if (process.platform === 'win32') { content = content.replace(/\n/g, '\r\n'); } return new File({ path: path.join(originalFilePath + '.i18n.json'), contents: Buffer.from(content, 'utf8') }); } const i18nPackVersion = "1.0.0"; function pullI18nPackFiles(apiHostname, username, password, language, resultingTranslationPaths) { return pullCoreAndExtensionsXlfFiles(apiHostname, username, password, language, exports.externalExtensionsWithTranslations) .pipe(prepareI18nPackFiles(exports.externalExtensionsWithTranslations, resultingTranslationPaths, language.id === 'ps')); } exports.pullI18nPackFiles = pullI18nPackFiles; function prepareI18nPackFiles(externalExtensions, resultingTranslationPaths, pseudo = false) { let parsePromises = []; let mainPack = { version: i18nPackVersion, contents: {} }; let extensionsPacks = {}; let errors = []; return event_stream_1.through(function (xlf) { let project = path.basename(path.dirname(xlf.relative)); let resource = path.basename(xlf.relative, '.xlf'); let contents = xlf.contents.toString(); let parsePromise = pseudo ? XLF.parsePseudo(contents) : XLF.parse(contents); parsePromises.push(parsePromise); parsePromise.then(resolvedFiles => { resolvedFiles.forEach(file => { const path = file.originalFilePath; const firstSlash = path.indexOf('/'); if (project === extensionsProject) { let extPack = extensionsPacks[resource]; if (!extPack) { extPack = extensionsPacks[resource] = { version: i18nPackVersion, contents: {} }; } const externalId = externalExtensions[resource]; if (!externalId) { // internal extension: remove 'extensions/extensionId/' segnent const secondSlash = path.indexOf('/', firstSlash + 1); extPack.contents[path.substr(secondSlash + 1)] = file.messages; } else { extPack.contents[path] = file.messages; } } else { mainPack.contents[path.substr(firstSlash + 1)] = file.messages; } }); }).catch(reason => { errors.push(reason); }); }, function () { Promise.all(parsePromises) .then(() => { if (errors.length > 0) { throw errors; } const translatedMainFile = createI18nFile('./main', mainPack); resultingTranslationPaths.push({ id: 'vscode', resourceName: 'main.i18n.json' }); this.queue(translatedMainFile); for (let extension in extensionsPacks) { const translatedExtFile = createI18nFile(`extensions/${extension}`, extensionsPacks[extension]); this.queue(translatedExtFile); const externalExtensionId = externalExtensions[extension]; if (externalExtensionId) { resultingTranslationPaths.push({ id: externalExtensionId, resourceName: `extensions/${extension}.i18n.json` }); } else { resultingTranslationPaths.push({ id: `vscode.${extension}`, resourceName: `extensions/${extension}.i18n.json` }); } } this.queue(null); }) .catch((reason) => { this.emit('error', reason); }); }); } exports.prepareI18nPackFiles = prepareI18nPackFiles; function prepareIslFiles(language, innoSetupConfig) { let parsePromises = []; return event_stream_1.through(function (xlf) { let stream = this; let parsePromise = XLF.parse(xlf.contents.toString()); parsePromises.push(parsePromise); parsePromise.then(resolvedFiles => { resolvedFiles.forEach(file => { if (path.basename(file.originalFilePath) === 'Default' && !innoSetupConfig.defaultInfo) { return; } let translatedFile = createIslFile(file.originalFilePath, file.messages, language, innoSetupConfig); stream.queue(translatedFile); }); }).catch(reason => { this.emit('error', reason); }); }, function () { Promise.all(parsePromises) .then(() => { this.queue(null); }) .catch(reason => { this.emit('error', reason); }); }); } exports.prepareIslFiles = prepareIslFiles; function createIslFile(originalFilePath, messages, language, innoSetup) { let content = []; let originalContent; if (path.basename(originalFilePath) === 'Default') { originalContent = new TextModel(fs.readFileSync(originalFilePath + '.isl', 'utf8')); } else { originalContent = new TextModel(fs.readFileSync(originalFilePath + '.en.isl', 'utf8')); } originalContent.lines.forEach(line => { if (line.length > 0) { let firstChar = line.charAt(0); if (firstChar === '[' || firstChar === ';') { content.push(line); } else { let sections = line.split('='); let key = sections[0]; let translated = line; if (key) { if (key === 'LanguageName') { translated = `${key}=${innoSetup.defaultInfo.name}`; } else if (key === 'LanguageID') { translated = `${key}=${innoSetup.defaultInfo.id}`; } else if (key === 'LanguageCodePage') { translated = `${key}=${innoSetup.codePage.substr(2)}`; } else { let translatedMessage = messages[key]; if (translatedMessage) { translated = `${key}=${translatedMessage}`; } } } content.push(translated); } } }); const basename = path.basename(originalFilePath); const filePath = `${basename}.${language.id}.isl`; const encoded = iconv.encode(Buffer.from(content.join('\r\n'), 'utf8').toString(), innoSetup.codePage); return new File({ path: filePath, contents: Buffer.from(encoded), }); } function encodeEntities(value) { let result = []; for (let i = 0; i < value.length; i++) { let ch = value[i]; switch (ch) { case '<': result.push('&lt;'); break; case '>': result.push('&gt;'); break; case '&': result.push('&amp;'); break; default: result.push(ch); } } return result.join(''); } function decodeEntities(value) { return value.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&'); } function pseudify(message) { return '\uFF3B' + message.replace(/[aouei]/g, '$&$&') + '\uFF3D'; }
build/lib/i18n.js
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.0001792245457181707, 0.0001726498012430966, 0.0001646187447477132, 0.00017288842354901135, 0.0000028449326237023342 ]
{ "id": 5, "code_window": [ "const FocusSearchListCommand: ICommandAction = {\n", "\tid: Constants.FocusSearchListCommandID,\n", "\ttitle: focusSearchListCommandLabel,\n", "\tcategory\n", "};\n", "MenuRegistry.addCommand(FocusSearchListCommand);\n", "\n", "const searchInFolderCommand: ICommandHandler = (accessor, resource?: URI) => {\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\ttitle: { value: nls.localize('focusSearchListCommandLabel', \"Focus List\"), original: 'Focus List' },\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 386 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IMainContext, MainContext, MainThreadClipboardShape } from 'vs/workbench/api/common/extHost.protocol'; import type * as vscode from 'vscode'; export class ExtHostClipboard implements vscode.Clipboard { private readonly _proxy: MainThreadClipboardShape; constructor(mainContext: IMainContext) { this._proxy = mainContext.getProxy(MainContext.MainThreadClipboard); } readText(): Promise<string> { return this._proxy.$readText(); } writeText(value: string): Promise<void> { return this._proxy.$writeText(value); } }
src/vs/workbench/api/common/extHostClipboard.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.0001745558256516233, 0.0001725486508803442, 0.000169093138538301, 0.00017399698845110834, 0.0000024540440790588036 ]
{ "id": 6, "code_window": [ "\t},\n", "\torder: 1\n", "});\n", "\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusNextSearchResultAction, { primary: KeyCode.F4 }), 'Focus Next Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor));\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusPreviousSearchResultAction, { primary: KeyMod.Shift | KeyCode.F4 }), 'Focus Previous Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor));\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusNextSearchResultAction, { primary: KeyCode.F4 }), 'Search: Focus Next Search Result', category.value, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor));\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusPreviousSearchResultAction, { primary: KeyMod.Shift | KeyCode.F4 }), 'Search: Focus Previous Search Result', category.value, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor));\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 585 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Action } from 'vs/base/common/actions'; import { distinct } from 'vs/base/common/arrays'; import { onUnexpectedError } from 'vs/base/common/errors'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import * as objects from 'vs/base/common/objects'; import * as platform from 'vs/base/common/platform'; import { dirname } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { ToggleCaseSensitiveKeybinding, ToggleRegexKeybinding, ToggleWholeWordKeybinding } from 'vs/editor/contrib/find/findModel'; import * as nls from 'vs/nls'; import { ICommandAction, MenuId, MenuRegistry, SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { CommandsRegistry, ICommandHandler } from 'vs/platform/commands/common/commands'; import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry'; import { ContextKeyExpr, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IFileService } from 'vs/platform/files/common/files'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { IListService, WorkbenchListFocusContextKey, WorkbenchObjectTree } from 'vs/platform/list/browser/listService'; import { Registry } from 'vs/platform/registry/common/platform'; import { defaultQuickAccessContextKeyValue } from 'vs/workbench/browser/quickaccess'; import { Extensions as ActionExtensions, IWorkbenchActionRegistry } from 'vs/workbench/common/actions'; import { Extensions as WorkbenchExtensions, IWorkbenchContribution, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions'; import { Extensions as ViewExtensions, IViewsRegistry, IViewContainersRegistry, ViewContainerLocation, IViewDescriptorService, IViewsService } from 'vs/workbench/common/views'; import { getMultiSelectedResources } from 'vs/workbench/contrib/files/browser/files'; import { ExplorerFolderContext, ExplorerRootContext, FilesExplorerFocusCondition, IExplorerService, VIEWLET_ID as VIEWLET_ID_FILES } from 'vs/workbench/contrib/files/common/files'; import { registerContributions as replaceContributions } from 'vs/workbench/contrib/search/browser/replaceContributions'; import { clearHistoryCommand, ClearSearchResultsAction, CloseReplaceAction, CollapseDeepestExpandedLevelAction, copyAllCommand, copyMatchCommand, copyPathCommand, FocusNextInputAction, FocusNextSearchResultAction, FocusPreviousInputAction, FocusPreviousSearchResultAction, focusSearchListCommand, getSearchView, openSearchView, OpenSearchViewletAction, RefreshAction, RemoveAction, ReplaceAction, ReplaceAllAction, ReplaceAllInFolderAction, ReplaceInFilesAction, toggleCaseSensitiveCommand, toggleRegexCommand, toggleWholeWordCommand, FindInFilesCommand, ToggleSearchOnTypeAction, ExpandAllAction } from 'vs/workbench/contrib/search/browser/searchActions'; import { SearchView } from 'vs/workbench/contrib/search/browser/searchView'; import { registerContributions as searchWidgetContributions } from 'vs/workbench/contrib/search/browser/searchWidget'; import * as Constants from 'vs/workbench/contrib/search/common/constants'; import * as SearchEditorConstants from 'vs/workbench/contrib/searchEditor/browser/constants'; import { getWorkspaceSymbols } from 'vs/workbench/contrib/search/common/search'; import { ISearchHistoryService, SearchHistoryService } from 'vs/workbench/contrib/search/common/searchHistoryService'; import { FileMatchOrMatch, ISearchWorkbenchService, RenderableMatch, SearchWorkbenchService, FileMatch, Match, FolderMatch } from 'vs/workbench/contrib/search/common/searchModel'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { VIEWLET_ID, VIEW_ID, SEARCH_EXCLUDE_CONFIG, SearchSortOrder } from 'vs/workbench/services/search/common/search'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { ExplorerViewPaneContainer } from 'vs/workbench/contrib/files/browser/explorerViewlet'; import { assertType, assertIsDefined } from 'vs/base/common/types'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { SearchEditor } from 'vs/workbench/contrib/searchEditor/browser/searchEditor'; import { ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { IQuickAccessRegistry, Extensions as QuickAccessExtensions } from 'vs/platform/quickinput/common/quickAccess'; import { SymbolsQuickAccessProvider } from 'vs/workbench/contrib/search/browser/symbolsQuickAccess'; import { AnythingQuickAccessProvider } from 'vs/workbench/contrib/search/browser/anythingQuickAccess'; import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { AbstractGotoLineQuickAccessProvider } from 'vs/editor/contrib/quickAccess/gotoLineQuickAccess'; import { GotoSymbolQuickAccessProvider } from 'vs/workbench/contrib/codeEditor/browser/quickaccess/gotoSymbolQuickAccess'; import { searchViewIcon } from 'vs/workbench/contrib/search/browser/searchIcons'; registerSingleton(ISearchWorkbenchService, SearchWorkbenchService, true); registerSingleton(ISearchHistoryService, SearchHistoryService, true); replaceContributions(); searchWidgetContributions(); const category = nls.localize('search', "Search"); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'workbench.action.search.toggleQueryDetails', weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or(Constants.SearchViewFocusedKey, SearchEditorConstants.InSearchEditor), primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_J, handler: accessor => { const contextService = accessor.get(IContextKeyService).getContext(document.activeElement); if (contextService.getValue(SearchEditorConstants.InSearchEditor.serialize())) { (accessor.get(IEditorService).activeEditorPane as SearchEditor).toggleQueryDetails(); } else if (contextService.getValue(Constants.SearchViewFocusedKey.serialize())) { const searchView = getSearchView(accessor.get(IViewsService)); assertIsDefined(searchView).toggleQueryDetails(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.FocusSearchFromResults, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FirstMatchFocusKey), primary: KeyMod.CtrlCmd | KeyCode.UpArrow, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { searchView.focusPreviousInputBox(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.OpenMatchToSide, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyMod.CtrlCmd | KeyCode.Enter, mac: { primary: KeyMod.WinCtrl | KeyCode.Enter }, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); searchView.open(<FileMatchOrMatch>tree.getFocus()[0], false, true, true); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CancelActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, WorkbenchListFocusContextKey), primary: KeyCode.Escape, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { searchView.cancelSearch(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.RemoveActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyCode.Delete, mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace, }, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(RemoveAction, tree, tree.getFocus()[0]!).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.MatchFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAction, tree, tree.getFocus()[0] as Match, searchView).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceAllInFileActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.FileFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter], handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAllAction, searchView, tree.getFocus()[0] as FileMatch).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceAllInFolderActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.FolderFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter], handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAllInFolderAction, tree, tree.getFocus()[0] as FolderMatch).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CloseReplaceWidgetActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceInputBoxFocusedKey), primary: KeyCode.Escape, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(CloseReplaceAction, Constants.CloseReplaceWidgetActionId, '').run(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FocusNextInputAction.ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or( ContextKeyExpr.and(SearchEditorConstants.InSearchEditor, Constants.InputBoxFocusedKey), ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.InputBoxFocusedKey)), primary: KeyMod.CtrlCmd | KeyCode.DownArrow, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(FocusNextInputAction, FocusNextInputAction.ID, '').run(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FocusPreviousInputAction.ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or( ContextKeyExpr.and(SearchEditorConstants.InSearchEditor, Constants.InputBoxFocusedKey), ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.InputBoxFocusedKey, Constants.SearchInputBoxFocusedKey.toNegated())), primary: KeyMod.CtrlCmd | KeyCode.UpArrow, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(FocusPreviousInputAction, FocusPreviousInputAction.ID, '').run(); } }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceActionId, title: ReplaceAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.MatchFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceAllInFolderActionId, title: ReplaceAllInFolderAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.FolderFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceAllInFileActionId, title: ReplaceAllAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.FileFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.RemoveActionId, title: RemoveAction.LABEL }, when: Constants.FileMatchOrMatchFocusKey, group: 'search', order: 2 }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CopyMatchCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.FileMatchOrMatchFocusKey, primary: KeyMod.CtrlCmd | KeyCode.KEY_C, handler: copyMatchCommand }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyMatchCommandId, title: nls.localize('copyMatchLabel', "Copy") }, when: Constants.FileMatchOrMatchFocusKey, group: 'search_2', order: 1 }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CopyPathCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.FileMatchOrFolderMatchWithResourceFocusKey, primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_C, win: { primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_C }, handler: copyPathCommand }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyPathCommandId, title: nls.localize('copyPathLabel', "Copy Path") }, when: Constants.FileMatchOrFolderMatchWithResourceFocusKey, group: 'search_2', order: 2 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyAllCommandId, title: nls.localize('copyAllLabel', "Copy All") }, when: Constants.HasSearchResults, group: 'search_2', order: 3 }); CommandsRegistry.registerCommand({ id: Constants.CopyAllCommandId, handler: copyAllCommand }); CommandsRegistry.registerCommand({ id: Constants.ClearSearchHistoryCommandId, handler: clearHistoryCommand }); CommandsRegistry.registerCommand({ id: Constants.RevealInSideBarForSearchResults, handler: (accessor, args: any) => { const viewletService = accessor.get(IViewletService); const explorerService = accessor.get(IExplorerService); const contextService = accessor.get(IWorkspaceContextService); const searchView = getSearchView(accessor.get(IViewsService)); if (!searchView) { return; } let fileMatch: FileMatch; if (!(args instanceof FileMatch)) { args = searchView.getControl().getFocus()[0]; } if (args instanceof FileMatch) { fileMatch = args; } else { return; } viewletService.openViewlet(VIEWLET_ID_FILES, false).then((viewlet) => { if (!viewlet) { return; } const explorerViewContainer = viewlet.getViewPaneContainer() as ExplorerViewPaneContainer; const uri = fileMatch.resource; if (uri && contextService.isInsideWorkspace(uri)) { const explorerView = explorerViewContainer.getExplorerView(); explorerView.setExpanded(true); explorerService.select(uri, true).then(() => explorerView.focus(), onUnexpectedError); } }); } }); const RevealInSideBarForSearchResultsCommand: ICommandAction = { id: Constants.RevealInSideBarForSearchResults, title: nls.localize('revealInSideBar', "Reveal in Side Bar") }; MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: RevealInSideBarForSearchResultsCommand, when: ContextKeyExpr.and(Constants.FileFocusKey, Constants.HasSearchResults), group: 'search_3', order: 1 }); const clearSearchHistoryLabel = nls.localize('clearSearchHistoryLabel', "Clear Search History"); const ClearSearchHistoryCommand: ICommandAction = { id: Constants.ClearSearchHistoryCommandId, title: clearSearchHistoryLabel, category }; MenuRegistry.addCommand(ClearSearchHistoryCommand); CommandsRegistry.registerCommand({ id: Constants.FocusSearchListCommandID, handler: focusSearchListCommand }); const focusSearchListCommandLabel = nls.localize('focusSearchListCommandLabel', "Focus List"); const FocusSearchListCommand: ICommandAction = { id: Constants.FocusSearchListCommandID, title: focusSearchListCommandLabel, category }; MenuRegistry.addCommand(FocusSearchListCommand); const searchInFolderCommand: ICommandHandler = (accessor, resource?: URI) => { const listService = accessor.get(IListService); const fileService = accessor.get(IFileService); const viewsService = accessor.get(IViewsService); const resources = getMultiSelectedResources(resource, listService, accessor.get(IEditorService), accessor.get(IExplorerService)); return openSearchView(viewsService, true).then(searchView => { if (resources && resources.length && searchView) { return fileService.resolveAll(resources.map(resource => ({ resource }))).then(results => { const folders: URI[] = []; results.forEach(result => { if (result.success && result.stat) { folders.push(result.stat.isDirectory ? result.stat.resource : dirname(result.stat.resource)); } }); searchView.searchInFolders(distinct(folders, folder => folder.toString())); }); } return undefined; }); }; const FIND_IN_FOLDER_ID = 'filesExplorer.findInFolder'; KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FIND_IN_FOLDER_ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(FilesExplorerFocusCondition, ExplorerFolderContext), primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_F, handler: searchInFolderCommand }); CommandsRegistry.registerCommand({ id: ClearSearchResultsAction.ID, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(ClearSearchResultsAction, ClearSearchResultsAction.ID, '').run(); } }); CommandsRegistry.registerCommand({ id: RefreshAction.ID, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(RefreshAction, RefreshAction.ID, '').run(); } }); const FIND_IN_WORKSPACE_ID = 'filesExplorer.findInWorkspace'; CommandsRegistry.registerCommand({ id: FIND_IN_WORKSPACE_ID, handler: (accessor) => { return openSearchView(accessor.get(IViewsService), true).then(searchView => { if (searchView) { searchView.searchInFolders(); } }); } }); MenuRegistry.appendMenuItem(MenuId.ExplorerContext, { group: '4_search', order: 10, command: { id: FIND_IN_FOLDER_ID, title: nls.localize('findInFolder', "Find in Folder...") }, when: ContextKeyExpr.and(ExplorerFolderContext) }); MenuRegistry.appendMenuItem(MenuId.ExplorerContext, { group: '4_search', order: 10, command: { id: FIND_IN_WORKSPACE_ID, title: nls.localize('findInWorkspace', "Find in Workspace...") }, when: ContextKeyExpr.and(ExplorerRootContext, ExplorerFolderContext.toNegated()) }); class ShowAllSymbolsAction extends Action { static readonly ID = 'workbench.action.showAllSymbols'; static readonly LABEL = nls.localize('showTriggerActions', "Go to Symbol in Workspace..."); static readonly ALL_SYMBOLS_PREFIX = '#'; constructor( actionId: string, actionLabel: string, @IQuickInputService private readonly quickInputService: IQuickInputService ) { super(actionId, actionLabel); } async run(): Promise<void> { this.quickInputService.quickAccess.show(ShowAllSymbolsAction.ALL_SYMBOLS_PREFIX); } } const viewContainer = Registry.as<IViewContainersRegistry>(ViewExtensions.ViewContainersRegistry).registerViewContainer({ id: VIEWLET_ID, name: nls.localize('name', "Search"), ctorDescriptor: new SyncDescriptor(ViewPaneContainer, [VIEWLET_ID, { mergeViewWithContainerWhenSingleView: true, donotShowContainerTitleWhenMergedWithContainer: true }]), hideIfEmpty: true, icon: searchViewIcon.classNames, order: 1 }, ViewContainerLocation.Sidebar); const viewDescriptor = { id: VIEW_ID, containerIcon: 'codicon-search', name: nls.localize('search', "Search"), ctorDescriptor: new SyncDescriptor(SearchView), canToggleVisibility: false, canMoveView: true }; // Register search default location to sidebar Registry.as<IViewsRegistry>(ViewExtensions.ViewsRegistry).registerViews([viewDescriptor], viewContainer); // Migrate search location setting to new model class RegisterSearchViewContribution implements IWorkbenchContribution { constructor( @IConfigurationService configurationService: IConfigurationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService ) { const data = configurationService.inspect('search.location'); if (data.value === 'panel') { viewDescriptorService.moveViewToLocation(viewDescriptor, ViewContainerLocation.Panel); } if (data.userValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER); } if (data.userLocalValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER_LOCAL); } if (data.userRemoteValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER_REMOTE); } if (data.workspaceFolderValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.WORKSPACE_FOLDER); } if (data.workspaceValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.WORKSPACE); } } } Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(RegisterSearchViewContribution, LifecyclePhase.Starting); // Actions const registry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions); // Show Search and Find in Files are redundant, but we can't break keybindings by removing one. So it's the same action, same keybinding, registered to different IDs. // Show Search 'when' is redundant but if the two conflict with exactly the same keybinding and 'when' clause, then they can show up as "unbound" - #51780 registry.registerWorkbenchAction(SyncActionDescriptor.from(OpenSearchViewletAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_F }, Constants.SearchViewVisibleKey.toNegated()), 'View: Show Search', nls.localize('view', "View")); KeybindingsRegistry.registerCommandAndKeybindingRule({ description: { description: nls.localize('findInFiles.description', "Open the search viewlet"), args: [ { name: nls.localize('findInFiles.args', "A set of options for the search viewlet"), schema: { type: 'object', properties: { query: { 'type': 'string' }, replace: { 'type': 'string' }, triggerSearch: { 'type': 'boolean' }, filesToInclude: { 'type': 'string' }, filesToExclude: { 'type': 'string' }, isRegex: { 'type': 'boolean' }, isCaseSensitive: { 'type': 'boolean' }, matchWholeWord: { 'type': 'boolean' }, } } }, ] }, id: Constants.FindInFilesActionId, weight: KeybindingWeight.WorkbenchContrib, when: null, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_F, handler: FindInFilesCommand }); MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: Constants.FindInFilesActionId, title: { value: nls.localize('findInFiles', "Find in Files"), original: 'Find in Files' }, category } }); MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { group: '4_find_global', command: { id: Constants.FindInFilesActionId, title: nls.localize({ key: 'miFindInFiles', comment: ['&& denotes a mnemonic'] }, "Find &&in Files") }, order: 1 }); registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusNextSearchResultAction, { primary: KeyCode.F4 }), 'Focus Next Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor)); registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusPreviousSearchResultAction, { primary: KeyMod.Shift | KeyCode.F4 }), 'Focus Previous Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor)); registry.registerWorkbenchAction(SyncActionDescriptor.from(ReplaceInFilesAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_H }), 'Replace in Files', category); MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { group: '4_find_global', command: { id: ReplaceInFilesAction.ID, title: nls.localize({ key: 'miReplaceInFiles', comment: ['&& denotes a mnemonic'] }, "Replace &&in Files") }, order: 2 }); if (platform.isMacintosh) { // Register this with a more restrictive `when` on mac to avoid conflict with "copy path" KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleCaseSensitiveCommandId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewFocusedKey, Constants.FileMatchOrFolderMatchFocusKey.toNegated()), handler: toggleCaseSensitiveCommand }, ToggleCaseSensitiveKeybinding)); } else { KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleCaseSensitiveCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleCaseSensitiveCommand }, ToggleCaseSensitiveKeybinding)); } KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleWholeWordCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleWholeWordCommand }, ToggleWholeWordKeybinding)); KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleRegexCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleRegexCommand }, ToggleRegexKeybinding)); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.AddCursorsAtSearchResults, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_L, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); searchView.openEditorWithMultiCursor(<FileMatchOrMatch>tree.getFocus()[0]); } } }); registry.registerWorkbenchAction(SyncActionDescriptor.from(CollapseDeepestExpandedLevelAction), 'Search: Collapse All', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ExpandAllAction), 'Search: Expand All', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ShowAllSymbolsAction, { primary: KeyMod.CtrlCmd | KeyCode.KEY_T }), 'Go to Symbol in Workspace...'); registry.registerWorkbenchAction(SyncActionDescriptor.from(ToggleSearchOnTypeAction), 'Search: Toggle Search on Type', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(RefreshAction), 'Search: Refresh', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ClearSearchResultsAction), 'Search: Clear Search Results', category); // Register Quick Access Handler const quickAccessRegistry = Registry.as<IQuickAccessRegistry>(QuickAccessExtensions.Quickaccess); quickAccessRegistry.registerQuickAccessProvider({ ctor: AnythingQuickAccessProvider, prefix: AnythingQuickAccessProvider.PREFIX, placeholder: nls.localize('anythingQuickAccessPlaceholder', "Search files by name (append {0} to go to line or {1} to go to symbol)", AbstractGotoLineQuickAccessProvider.PREFIX, GotoSymbolQuickAccessProvider.PREFIX), contextKey: defaultQuickAccessContextKeyValue, helpEntries: [{ description: nls.localize('anythingQuickAccess', "Go to File"), needsEditor: false }] }); quickAccessRegistry.registerQuickAccessProvider({ ctor: SymbolsQuickAccessProvider, prefix: SymbolsQuickAccessProvider.PREFIX, placeholder: nls.localize('symbolsQuickAccessPlaceholder', "Type the name of a symbol to open."), contextKey: 'inWorkspaceSymbolsPicker', helpEntries: [{ description: nls.localize('symbolsQuickAccess', "Go to Symbol in Workspace"), needsEditor: false }] }); // Configuration const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration); configurationRegistry.registerConfiguration({ id: 'search', order: 13, title: nls.localize('searchConfigurationTitle', "Search"), type: 'object', properties: { [SEARCH_EXCLUDE_CONFIG]: { type: 'object', markdownDescription: nls.localize('exclude', "Configure glob patterns for excluding files and folders in fulltext searches and quick open. Inherits all glob patterns from the `#files.exclude#` setting. Read more about glob patterns [here](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options)."), default: { '**/node_modules': true, '**/bower_components': true, '**/*.code-search': true }, additionalProperties: { anyOf: [ { type: 'boolean', description: nls.localize('exclude.boolean', "The glob pattern to match file paths against. Set to true or false to enable or disable the pattern."), }, { type: 'object', properties: { when: { type: 'string', // expression ({ "**/*.js": { "when": "$(basename).js" } }) pattern: '\\w*\\$\\(basename\\)\\w*', default: '$(basename).ext', description: nls.localize('exclude.when', 'Additional check on the siblings of a matching file. Use $(basename) as variable for the matching file name.') } } } ] }, scope: ConfigurationScope.RESOURCE }, 'search.useRipgrep': { type: 'boolean', description: nls.localize('useRipgrep', "This setting is deprecated and now falls back on \"search.usePCRE2\"."), deprecationMessage: nls.localize('useRipgrepDeprecated', "Deprecated. Consider \"search.usePCRE2\" for advanced regex feature support."), default: true }, 'search.maintainFileSearchCache': { type: 'boolean', description: nls.localize('search.maintainFileSearchCache', "When enabled, the searchService process will be kept alive instead of being shut down after an hour of inactivity. This will keep the file search cache in memory."), default: false }, 'search.useIgnoreFiles': { type: 'boolean', markdownDescription: nls.localize('useIgnoreFiles', "Controls whether to use `.gitignore` and `.ignore` files when searching for files."), default: true, scope: ConfigurationScope.RESOURCE }, 'search.useGlobalIgnoreFiles': { type: 'boolean', markdownDescription: nls.localize('useGlobalIgnoreFiles', "Controls whether to use global `.gitignore` and `.ignore` files when searching for files."), default: false, scope: ConfigurationScope.RESOURCE }, 'search.quickOpen.includeSymbols': { type: 'boolean', description: nls.localize('search.quickOpen.includeSymbols', "Whether to include results from a global symbol search in the file results for Quick Open."), default: false }, 'search.quickOpen.includeHistory': { type: 'boolean', description: nls.localize('search.quickOpen.includeHistory', "Whether to include results from recently opened files in the file results for Quick Open."), default: true }, 'search.quickOpen.history.filterSortOrder': { 'type': 'string', 'enum': ['default', 'recency'], 'default': 'default', 'enumDescriptions': [ nls.localize('filterSortOrder.default', 'History entries are sorted by relevance based on the filter value used. More relevant entries appear first.'), nls.localize('filterSortOrder.recency', 'History entries are sorted by recency. More recently opened entries appear first.') ], 'description': nls.localize('filterSortOrder', "Controls sorting order of editor history in quick open when filtering.") }, 'search.followSymlinks': { type: 'boolean', description: nls.localize('search.followSymlinks', "Controls whether to follow symlinks while searching."), default: true }, 'search.smartCase': { type: 'boolean', description: nls.localize('search.smartCase', "Search case-insensitively if the pattern is all lowercase, otherwise, search case-sensitively."), default: false }, 'search.globalFindClipboard': { type: 'boolean', default: false, description: nls.localize('search.globalFindClipboard', "Controls whether the search view should read or modify the shared find clipboard on macOS."), included: platform.isMacintosh }, 'search.location': { type: 'string', enum: ['sidebar', 'panel'], default: 'sidebar', description: nls.localize('search.location', "Controls whether the search will be shown as a view in the sidebar or as a panel in the panel area for more horizontal space."), deprecationMessage: nls.localize('search.location.deprecationMessage', "This setting is deprecated. Please use drag and drop instead by dragging the search icon.") }, 'search.collapseResults': { type: 'string', enum: ['auto', 'alwaysCollapse', 'alwaysExpand'], enumDescriptions: [ nls.localize('search.collapseResults.auto', "Files with less than 10 results are expanded. Others are collapsed."), '', '' ], default: 'alwaysExpand', description: nls.localize('search.collapseAllResults', "Controls whether the search results will be collapsed or expanded."), }, 'search.useReplacePreview': { type: 'boolean', default: true, description: nls.localize('search.useReplacePreview', "Controls whether to open Replace Preview when selecting or replacing a match."), }, 'search.showLineNumbers': { type: 'boolean', default: false, description: nls.localize('search.showLineNumbers', "Controls whether to show line numbers for search results."), }, 'search.usePCRE2': { type: 'boolean', default: false, description: nls.localize('search.usePCRE2', "Whether to use the PCRE2 regex engine in text search. This enables using some advanced regex features like lookahead and backreferences. However, not all PCRE2 features are supported - only features that are also supported by JavaScript."), deprecationMessage: nls.localize('usePCRE2Deprecated', "Deprecated. PCRE2 will be used automatically when using regex features that are only supported by PCRE2."), }, 'search.actionsPosition': { type: 'string', enum: ['auto', 'right'], enumDescriptions: [ nls.localize('search.actionsPositionAuto', "Position the actionbar to the right when the search view is narrow, and immediately after the content when the search view is wide."), nls.localize('search.actionsPositionRight', "Always position the actionbar to the right."), ], default: 'auto', description: nls.localize('search.actionsPosition', "Controls the positioning of the actionbar on rows in the search view.") }, 'search.searchOnType': { type: 'boolean', default: true, description: nls.localize('search.searchOnType', "Search all files as you type.") }, 'search.seedWithNearestWord': { type: 'boolean', default: false, description: nls.localize('search.seedWithNearestWord', "Enable seeding search from the word nearest the cursor when the active editor has no selection.") }, 'search.seedOnFocus': { type: 'boolean', default: false, description: nls.localize('search.seedOnFocus', "Update workspace search query to the editor's selected text when focusing the search view. This happens either on click or when triggering the `workbench.views.search.focus` command.") }, 'search.searchOnTypeDebouncePeriod': { type: 'number', default: 300, markdownDescription: nls.localize('search.searchOnTypeDebouncePeriod', "When `#search.searchOnType#` is enabled, controls the timeout in milliseconds between a character being typed and the search starting. Has no effect when `search.searchOnType` is disabled.") }, 'search.searchEditor.doubleClickBehaviour': { type: 'string', enum: ['selectWord', 'goToLocation', 'openLocationToSide'], default: 'goToLocation', enumDescriptions: [ nls.localize('search.searchEditor.doubleClickBehaviour.selectWord', "Double clicking selects the word under the cursor."), nls.localize('search.searchEditor.doubleClickBehaviour.goToLocation', "Double clicking opens the result in the active editor group."), nls.localize('search.searchEditor.doubleClickBehaviour.openLocationToSide', "Double clicking opens the result in the editor group to the side, creating one if it does not yet exist."), ], markdownDescription: nls.localize('search.searchEditor.doubleClickBehaviour', "Configure effect of double clicking a result in a search editor.") }, 'search.searchEditor.reusePriorSearchConfiguration': { type: 'boolean', default: false, markdownDescription: nls.localize({ key: 'search.searchEditor.reusePriorSearchConfiguration', comment: ['"Search Editor" is a type that editor that can display search results. "includes, excludes, and flags" just refers to settings that affect search. For example, the "search.exclude" setting.'] }, "When enabled, new Search Editors will reuse the includes, excludes, and flags of the previously opened Search Editor") }, 'search.searchEditor.defaultNumberOfContextLines': { type: ['number', 'null'], default: 1, markdownDescription: nls.localize('search.searchEditor.defaultNumberOfContextLines', "The default number of surrounding context lines to use when creating new Search Editors. If using `#search.searchEditor.reusePriorSearchConfiguration#`, this can be set to `null` (empty) to use the prior Search Editor's configuration.") }, 'search.sortOrder': { 'type': 'string', 'enum': [SearchSortOrder.Default, SearchSortOrder.FileNames, SearchSortOrder.Type, SearchSortOrder.Modified, SearchSortOrder.CountDescending, SearchSortOrder.CountAscending], 'default': SearchSortOrder.Default, 'enumDescriptions': [ nls.localize('searchSortOrder.default', "Results are sorted by folder and file names, in alphabetical order."), nls.localize('searchSortOrder.filesOnly', "Results are sorted by file names ignoring folder order, in alphabetical order."), nls.localize('searchSortOrder.type', "Results are sorted by file extensions, in alphabetical order."), nls.localize('searchSortOrder.modified', "Results are sorted by file last modified date, in descending order."), nls.localize('searchSortOrder.countDescending', "Results are sorted by count per file, in descending order."), nls.localize('searchSortOrder.countAscending', "Results are sorted by count per file, in ascending order.") ], 'description': nls.localize('search.sortOrder', "Controls sorting order of search results.") }, } }); CommandsRegistry.registerCommand('_executeWorkspaceSymbolProvider', function (accessor, ...args) { const [query] = args; assertType(typeof query === 'string'); return getWorkspaceSymbols(query); }); // View menu MenuRegistry.appendMenuItem(MenuId.MenubarViewMenu, { group: '3_views', command: { id: VIEWLET_ID, title: nls.localize({ key: 'miViewSearch', comment: ['&& denotes a mnemonic'] }, "&&Search") }, order: 2 }); // Go to menu MenuRegistry.appendMenuItem(MenuId.MenubarGoMenu, { group: '3_global_nav', command: { id: 'workbench.action.showAllSymbols', title: nls.localize({ key: 'miGotoSymbolInWorkspace', comment: ['&& denotes a mnemonic'] }, "Go to Symbol in &&Workspace...") }, order: 2 });
src/vs/workbench/contrib/search/browser/search.contribution.ts
1
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.05442124977707863, 0.0008635213016532362, 0.00016361408052034676, 0.0001715247635729611, 0.005687559023499489 ]
{ "id": 6, "code_window": [ "\t},\n", "\torder: 1\n", "});\n", "\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusNextSearchResultAction, { primary: KeyCode.F4 }), 'Focus Next Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor));\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusPreviousSearchResultAction, { primary: KeyMod.Shift | KeyCode.F4 }), 'Focus Previous Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor));\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusNextSearchResultAction, { primary: KeyCode.F4 }), 'Search: Focus Next Search Result', category.value, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor));\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusPreviousSearchResultAction, { primary: KeyMod.Shift | KeyCode.F4 }), 'Search: Focus Previous Search Result', category.value, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor));\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 585 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI } from 'vs/base/common/uri'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { IDisposable, Disposable } from 'vs/base/common/lifecycle'; import { equalsIgnoreCase, startsWithIgnoreCase } from 'vs/base/common/strings'; export const IOpenerService = createDecorator<IOpenerService>('openerService'); type OpenInternalOptions = { /** * Signals that the intent is to open an editor to the side * of the currently active editor. */ readonly openToSide?: boolean; /** * Signals that the editor to open was triggered through a user * action, such as keyboard or mouse usage. */ readonly fromUserGesture?: boolean; }; type OpenExternalOptions = { readonly openExternal?: boolean; readonly allowTunneling?: boolean }; export type OpenOptions = OpenInternalOptions & OpenExternalOptions; export type ResolveExternalUriOptions = { readonly allowTunneling?: boolean }; export interface IResolvedExternalUri extends IDisposable { resolved: URI; } export interface IOpener { open(resource: URI | string, options?: OpenInternalOptions | OpenExternalOptions): Promise<boolean>; } export interface IExternalOpener { openExternal(href: string): Promise<boolean>; } export interface IValidator { shouldOpen(resource: URI | string): Promise<boolean>; } export interface IExternalUriResolver { resolveExternalUri(resource: URI, options?: OpenOptions): Promise<{ resolved: URI, dispose(): void } | undefined>; } export interface IOpenerService { readonly _serviceBrand: undefined; /** * Register a participant that can handle the open() call. */ registerOpener(opener: IOpener): IDisposable; /** * Register a participant that can validate if the URI resource be opened. * Validators are run before openers. */ registerValidator(validator: IValidator): IDisposable; /** * Register a participant that can resolve an external URI resource to be opened. */ registerExternalUriResolver(resolver: IExternalUriResolver): IDisposable; /** * Sets the handler for opening externally. If not provided, * a default handler will be used. */ setExternalOpener(opener: IExternalOpener): void; /** * Opens a resource, like a webaddress, a document uri, or executes command. * * @param resource A resource * @return A promise that resolves when the opening is done. */ open(resource: URI | string, options?: OpenInternalOptions | OpenExternalOptions): Promise<boolean>; /** * Resolve a resource to its external form. */ resolveExternalUri(resource: URI, options?: ResolveExternalUriOptions): Promise<IResolvedExternalUri>; } export const NullOpenerService: IOpenerService = Object.freeze({ _serviceBrand: undefined, registerOpener() { return Disposable.None; }, registerValidator() { return Disposable.None; }, registerExternalUriResolver() { return Disposable.None; }, setExternalOpener() { }, async open() { return false; }, async resolveExternalUri(uri: URI) { return { resolved: uri, dispose() { } }; }, }); export function matchesScheme(target: URI | string, scheme: string) { if (URI.isUri(target)) { return equalsIgnoreCase(target.scheme, scheme); } else { return startsWithIgnoreCase(target, scheme + ':'); } }
src/vs/platform/opener/common/opener.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00017498726083431393, 0.00017052394105121493, 0.00016538541240151972, 0.00017124603618867695, 0.0000029919240205344977 ]
{ "id": 6, "code_window": [ "\t},\n", "\torder: 1\n", "});\n", "\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusNextSearchResultAction, { primary: KeyCode.F4 }), 'Focus Next Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor));\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusPreviousSearchResultAction, { primary: KeyMod.Shift | KeyCode.F4 }), 'Focus Previous Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor));\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusNextSearchResultAction, { primary: KeyCode.F4 }), 'Search: Focus Next Search Result', category.value, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor));\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusPreviousSearchResultAction, { primary: KeyMod.Shift | KeyCode.F4 }), 'Search: Focus Previous Search Result', category.value, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor));\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 585 }
test/** cgmanifest.json
extensions/perl/.vscodeignore
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00017477499204687774, 0.00017477499204687774, 0.00017477499204687774, 0.00017477499204687774, 0 ]
{ "id": 6, "code_window": [ "\t},\n", "\torder: 1\n", "});\n", "\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusNextSearchResultAction, { primary: KeyCode.F4 }), 'Focus Next Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor));\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusPreviousSearchResultAction, { primary: KeyMod.Shift | KeyCode.F4 }), 'Focus Previous Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor));\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusNextSearchResultAction, { primary: KeyCode.F4 }), 'Search: Focus Next Search Result', category.value, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor));\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusPreviousSearchResultAction, { primary: KeyMod.Shift | KeyCode.F4 }), 'Search: Focus Previous Search Result', category.value, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor));\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 585 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; export const ICredentialsService = createDecorator<ICredentialsService>('ICredentialsService'); export interface ICredentialsService { readonly _serviceBrand: undefined; getPassword(service: string, account: string): Promise<string | null>; setPassword(service: string, account: string, password: string): Promise<void>; deletePassword(service: string, account: string): Promise<boolean>; findPassword(service: string): Promise<string | null>; findCredentials(service: string): Promise<Array<{ account: string, password: string }>>; }
src/vs/workbench/services/credentials/common/credentials.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00017558276886120439, 0.00017408307758159935, 0.00017258340085390955, 0.00017408307758159935, 0.0000014996840036474168 ]
{ "id": 7, "code_window": [ "\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ReplaceInFilesAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_H }), 'Replace in Files', category);\n", "MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, {\n", "\tgroup: '4_find_global',\n", "\tcommand: {\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "registry.registerWorkbenchAction(SyncActionDescriptor.from(ReplaceInFilesAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_H }), 'Search: Replace in Files', category.value);\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.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 { Action } from 'vs/base/common/actions'; import { distinct } from 'vs/base/common/arrays'; import { onUnexpectedError } from 'vs/base/common/errors'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import * as objects from 'vs/base/common/objects'; import * as platform from 'vs/base/common/platform'; import { dirname } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { ToggleCaseSensitiveKeybinding, ToggleRegexKeybinding, ToggleWholeWordKeybinding } from 'vs/editor/contrib/find/findModel'; import * as nls from 'vs/nls'; import { ICommandAction, MenuId, MenuRegistry, SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { CommandsRegistry, ICommandHandler } from 'vs/platform/commands/common/commands'; import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry'; import { ContextKeyExpr, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IFileService } from 'vs/platform/files/common/files'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { IListService, WorkbenchListFocusContextKey, WorkbenchObjectTree } from 'vs/platform/list/browser/listService'; import { Registry } from 'vs/platform/registry/common/platform'; import { defaultQuickAccessContextKeyValue } from 'vs/workbench/browser/quickaccess'; import { Extensions as ActionExtensions, IWorkbenchActionRegistry } from 'vs/workbench/common/actions'; import { Extensions as WorkbenchExtensions, IWorkbenchContribution, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions'; import { Extensions as ViewExtensions, IViewsRegistry, IViewContainersRegistry, ViewContainerLocation, IViewDescriptorService, IViewsService } from 'vs/workbench/common/views'; import { getMultiSelectedResources } from 'vs/workbench/contrib/files/browser/files'; import { ExplorerFolderContext, ExplorerRootContext, FilesExplorerFocusCondition, IExplorerService, VIEWLET_ID as VIEWLET_ID_FILES } from 'vs/workbench/contrib/files/common/files'; import { registerContributions as replaceContributions } from 'vs/workbench/contrib/search/browser/replaceContributions'; import { clearHistoryCommand, ClearSearchResultsAction, CloseReplaceAction, CollapseDeepestExpandedLevelAction, copyAllCommand, copyMatchCommand, copyPathCommand, FocusNextInputAction, FocusNextSearchResultAction, FocusPreviousInputAction, FocusPreviousSearchResultAction, focusSearchListCommand, getSearchView, openSearchView, OpenSearchViewletAction, RefreshAction, RemoveAction, ReplaceAction, ReplaceAllAction, ReplaceAllInFolderAction, ReplaceInFilesAction, toggleCaseSensitiveCommand, toggleRegexCommand, toggleWholeWordCommand, FindInFilesCommand, ToggleSearchOnTypeAction, ExpandAllAction } from 'vs/workbench/contrib/search/browser/searchActions'; import { SearchView } from 'vs/workbench/contrib/search/browser/searchView'; import { registerContributions as searchWidgetContributions } from 'vs/workbench/contrib/search/browser/searchWidget'; import * as Constants from 'vs/workbench/contrib/search/common/constants'; import * as SearchEditorConstants from 'vs/workbench/contrib/searchEditor/browser/constants'; import { getWorkspaceSymbols } from 'vs/workbench/contrib/search/common/search'; import { ISearchHistoryService, SearchHistoryService } from 'vs/workbench/contrib/search/common/searchHistoryService'; import { FileMatchOrMatch, ISearchWorkbenchService, RenderableMatch, SearchWorkbenchService, FileMatch, Match, FolderMatch } from 'vs/workbench/contrib/search/common/searchModel'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { VIEWLET_ID, VIEW_ID, SEARCH_EXCLUDE_CONFIG, SearchSortOrder } from 'vs/workbench/services/search/common/search'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { ExplorerViewPaneContainer } from 'vs/workbench/contrib/files/browser/explorerViewlet'; import { assertType, assertIsDefined } from 'vs/base/common/types'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { SearchEditor } from 'vs/workbench/contrib/searchEditor/browser/searchEditor'; import { ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { IQuickAccessRegistry, Extensions as QuickAccessExtensions } from 'vs/platform/quickinput/common/quickAccess'; import { SymbolsQuickAccessProvider } from 'vs/workbench/contrib/search/browser/symbolsQuickAccess'; import { AnythingQuickAccessProvider } from 'vs/workbench/contrib/search/browser/anythingQuickAccess'; import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { AbstractGotoLineQuickAccessProvider } from 'vs/editor/contrib/quickAccess/gotoLineQuickAccess'; import { GotoSymbolQuickAccessProvider } from 'vs/workbench/contrib/codeEditor/browser/quickaccess/gotoSymbolQuickAccess'; import { searchViewIcon } from 'vs/workbench/contrib/search/browser/searchIcons'; registerSingleton(ISearchWorkbenchService, SearchWorkbenchService, true); registerSingleton(ISearchHistoryService, SearchHistoryService, true); replaceContributions(); searchWidgetContributions(); const category = nls.localize('search', "Search"); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'workbench.action.search.toggleQueryDetails', weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or(Constants.SearchViewFocusedKey, SearchEditorConstants.InSearchEditor), primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_J, handler: accessor => { const contextService = accessor.get(IContextKeyService).getContext(document.activeElement); if (contextService.getValue(SearchEditorConstants.InSearchEditor.serialize())) { (accessor.get(IEditorService).activeEditorPane as SearchEditor).toggleQueryDetails(); } else if (contextService.getValue(Constants.SearchViewFocusedKey.serialize())) { const searchView = getSearchView(accessor.get(IViewsService)); assertIsDefined(searchView).toggleQueryDetails(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.FocusSearchFromResults, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FirstMatchFocusKey), primary: KeyMod.CtrlCmd | KeyCode.UpArrow, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { searchView.focusPreviousInputBox(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.OpenMatchToSide, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyMod.CtrlCmd | KeyCode.Enter, mac: { primary: KeyMod.WinCtrl | KeyCode.Enter }, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); searchView.open(<FileMatchOrMatch>tree.getFocus()[0], false, true, true); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CancelActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, WorkbenchListFocusContextKey), primary: KeyCode.Escape, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { searchView.cancelSearch(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.RemoveActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyCode.Delete, mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace, }, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(RemoveAction, tree, tree.getFocus()[0]!).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.MatchFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAction, tree, tree.getFocus()[0] as Match, searchView).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceAllInFileActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.FileFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter], handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAllAction, searchView, tree.getFocus()[0] as FileMatch).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceAllInFolderActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.FolderFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter], handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAllInFolderAction, tree, tree.getFocus()[0] as FolderMatch).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CloseReplaceWidgetActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceInputBoxFocusedKey), primary: KeyCode.Escape, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(CloseReplaceAction, Constants.CloseReplaceWidgetActionId, '').run(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FocusNextInputAction.ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or( ContextKeyExpr.and(SearchEditorConstants.InSearchEditor, Constants.InputBoxFocusedKey), ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.InputBoxFocusedKey)), primary: KeyMod.CtrlCmd | KeyCode.DownArrow, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(FocusNextInputAction, FocusNextInputAction.ID, '').run(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FocusPreviousInputAction.ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or( ContextKeyExpr.and(SearchEditorConstants.InSearchEditor, Constants.InputBoxFocusedKey), ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.InputBoxFocusedKey, Constants.SearchInputBoxFocusedKey.toNegated())), primary: KeyMod.CtrlCmd | KeyCode.UpArrow, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(FocusPreviousInputAction, FocusPreviousInputAction.ID, '').run(); } }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceActionId, title: ReplaceAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.MatchFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceAllInFolderActionId, title: ReplaceAllInFolderAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.FolderFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceAllInFileActionId, title: ReplaceAllAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.FileFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.RemoveActionId, title: RemoveAction.LABEL }, when: Constants.FileMatchOrMatchFocusKey, group: 'search', order: 2 }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CopyMatchCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.FileMatchOrMatchFocusKey, primary: KeyMod.CtrlCmd | KeyCode.KEY_C, handler: copyMatchCommand }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyMatchCommandId, title: nls.localize('copyMatchLabel', "Copy") }, when: Constants.FileMatchOrMatchFocusKey, group: 'search_2', order: 1 }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CopyPathCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.FileMatchOrFolderMatchWithResourceFocusKey, primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_C, win: { primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_C }, handler: copyPathCommand }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyPathCommandId, title: nls.localize('copyPathLabel', "Copy Path") }, when: Constants.FileMatchOrFolderMatchWithResourceFocusKey, group: 'search_2', order: 2 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyAllCommandId, title: nls.localize('copyAllLabel', "Copy All") }, when: Constants.HasSearchResults, group: 'search_2', order: 3 }); CommandsRegistry.registerCommand({ id: Constants.CopyAllCommandId, handler: copyAllCommand }); CommandsRegistry.registerCommand({ id: Constants.ClearSearchHistoryCommandId, handler: clearHistoryCommand }); CommandsRegistry.registerCommand({ id: Constants.RevealInSideBarForSearchResults, handler: (accessor, args: any) => { const viewletService = accessor.get(IViewletService); const explorerService = accessor.get(IExplorerService); const contextService = accessor.get(IWorkspaceContextService); const searchView = getSearchView(accessor.get(IViewsService)); if (!searchView) { return; } let fileMatch: FileMatch; if (!(args instanceof FileMatch)) { args = searchView.getControl().getFocus()[0]; } if (args instanceof FileMatch) { fileMatch = args; } else { return; } viewletService.openViewlet(VIEWLET_ID_FILES, false).then((viewlet) => { if (!viewlet) { return; } const explorerViewContainer = viewlet.getViewPaneContainer() as ExplorerViewPaneContainer; const uri = fileMatch.resource; if (uri && contextService.isInsideWorkspace(uri)) { const explorerView = explorerViewContainer.getExplorerView(); explorerView.setExpanded(true); explorerService.select(uri, true).then(() => explorerView.focus(), onUnexpectedError); } }); } }); const RevealInSideBarForSearchResultsCommand: ICommandAction = { id: Constants.RevealInSideBarForSearchResults, title: nls.localize('revealInSideBar', "Reveal in Side Bar") }; MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: RevealInSideBarForSearchResultsCommand, when: ContextKeyExpr.and(Constants.FileFocusKey, Constants.HasSearchResults), group: 'search_3', order: 1 }); const clearSearchHistoryLabel = nls.localize('clearSearchHistoryLabel', "Clear Search History"); const ClearSearchHistoryCommand: ICommandAction = { id: Constants.ClearSearchHistoryCommandId, title: clearSearchHistoryLabel, category }; MenuRegistry.addCommand(ClearSearchHistoryCommand); CommandsRegistry.registerCommand({ id: Constants.FocusSearchListCommandID, handler: focusSearchListCommand }); const focusSearchListCommandLabel = nls.localize('focusSearchListCommandLabel', "Focus List"); const FocusSearchListCommand: ICommandAction = { id: Constants.FocusSearchListCommandID, title: focusSearchListCommandLabel, category }; MenuRegistry.addCommand(FocusSearchListCommand); const searchInFolderCommand: ICommandHandler = (accessor, resource?: URI) => { const listService = accessor.get(IListService); const fileService = accessor.get(IFileService); const viewsService = accessor.get(IViewsService); const resources = getMultiSelectedResources(resource, listService, accessor.get(IEditorService), accessor.get(IExplorerService)); return openSearchView(viewsService, true).then(searchView => { if (resources && resources.length && searchView) { return fileService.resolveAll(resources.map(resource => ({ resource }))).then(results => { const folders: URI[] = []; results.forEach(result => { if (result.success && result.stat) { folders.push(result.stat.isDirectory ? result.stat.resource : dirname(result.stat.resource)); } }); searchView.searchInFolders(distinct(folders, folder => folder.toString())); }); } return undefined; }); }; const FIND_IN_FOLDER_ID = 'filesExplorer.findInFolder'; KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FIND_IN_FOLDER_ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(FilesExplorerFocusCondition, ExplorerFolderContext), primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_F, handler: searchInFolderCommand }); CommandsRegistry.registerCommand({ id: ClearSearchResultsAction.ID, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(ClearSearchResultsAction, ClearSearchResultsAction.ID, '').run(); } }); CommandsRegistry.registerCommand({ id: RefreshAction.ID, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(RefreshAction, RefreshAction.ID, '').run(); } }); const FIND_IN_WORKSPACE_ID = 'filesExplorer.findInWorkspace'; CommandsRegistry.registerCommand({ id: FIND_IN_WORKSPACE_ID, handler: (accessor) => { return openSearchView(accessor.get(IViewsService), true).then(searchView => { if (searchView) { searchView.searchInFolders(); } }); } }); MenuRegistry.appendMenuItem(MenuId.ExplorerContext, { group: '4_search', order: 10, command: { id: FIND_IN_FOLDER_ID, title: nls.localize('findInFolder', "Find in Folder...") }, when: ContextKeyExpr.and(ExplorerFolderContext) }); MenuRegistry.appendMenuItem(MenuId.ExplorerContext, { group: '4_search', order: 10, command: { id: FIND_IN_WORKSPACE_ID, title: nls.localize('findInWorkspace', "Find in Workspace...") }, when: ContextKeyExpr.and(ExplorerRootContext, ExplorerFolderContext.toNegated()) }); class ShowAllSymbolsAction extends Action { static readonly ID = 'workbench.action.showAllSymbols'; static readonly LABEL = nls.localize('showTriggerActions', "Go to Symbol in Workspace..."); static readonly ALL_SYMBOLS_PREFIX = '#'; constructor( actionId: string, actionLabel: string, @IQuickInputService private readonly quickInputService: IQuickInputService ) { super(actionId, actionLabel); } async run(): Promise<void> { this.quickInputService.quickAccess.show(ShowAllSymbolsAction.ALL_SYMBOLS_PREFIX); } } const viewContainer = Registry.as<IViewContainersRegistry>(ViewExtensions.ViewContainersRegistry).registerViewContainer({ id: VIEWLET_ID, name: nls.localize('name', "Search"), ctorDescriptor: new SyncDescriptor(ViewPaneContainer, [VIEWLET_ID, { mergeViewWithContainerWhenSingleView: true, donotShowContainerTitleWhenMergedWithContainer: true }]), hideIfEmpty: true, icon: searchViewIcon.classNames, order: 1 }, ViewContainerLocation.Sidebar); const viewDescriptor = { id: VIEW_ID, containerIcon: 'codicon-search', name: nls.localize('search', "Search"), ctorDescriptor: new SyncDescriptor(SearchView), canToggleVisibility: false, canMoveView: true }; // Register search default location to sidebar Registry.as<IViewsRegistry>(ViewExtensions.ViewsRegistry).registerViews([viewDescriptor], viewContainer); // Migrate search location setting to new model class RegisterSearchViewContribution implements IWorkbenchContribution { constructor( @IConfigurationService configurationService: IConfigurationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService ) { const data = configurationService.inspect('search.location'); if (data.value === 'panel') { viewDescriptorService.moveViewToLocation(viewDescriptor, ViewContainerLocation.Panel); } if (data.userValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER); } if (data.userLocalValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER_LOCAL); } if (data.userRemoteValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER_REMOTE); } if (data.workspaceFolderValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.WORKSPACE_FOLDER); } if (data.workspaceValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.WORKSPACE); } } } Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(RegisterSearchViewContribution, LifecyclePhase.Starting); // Actions const registry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions); // Show Search and Find in Files are redundant, but we can't break keybindings by removing one. So it's the same action, same keybinding, registered to different IDs. // Show Search 'when' is redundant but if the two conflict with exactly the same keybinding and 'when' clause, then they can show up as "unbound" - #51780 registry.registerWorkbenchAction(SyncActionDescriptor.from(OpenSearchViewletAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_F }, Constants.SearchViewVisibleKey.toNegated()), 'View: Show Search', nls.localize('view', "View")); KeybindingsRegistry.registerCommandAndKeybindingRule({ description: { description: nls.localize('findInFiles.description', "Open the search viewlet"), args: [ { name: nls.localize('findInFiles.args', "A set of options for the search viewlet"), schema: { type: 'object', properties: { query: { 'type': 'string' }, replace: { 'type': 'string' }, triggerSearch: { 'type': 'boolean' }, filesToInclude: { 'type': 'string' }, filesToExclude: { 'type': 'string' }, isRegex: { 'type': 'boolean' }, isCaseSensitive: { 'type': 'boolean' }, matchWholeWord: { 'type': 'boolean' }, } } }, ] }, id: Constants.FindInFilesActionId, weight: KeybindingWeight.WorkbenchContrib, when: null, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_F, handler: FindInFilesCommand }); MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: Constants.FindInFilesActionId, title: { value: nls.localize('findInFiles', "Find in Files"), original: 'Find in Files' }, category } }); MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { group: '4_find_global', command: { id: Constants.FindInFilesActionId, title: nls.localize({ key: 'miFindInFiles', comment: ['&& denotes a mnemonic'] }, "Find &&in Files") }, order: 1 }); registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusNextSearchResultAction, { primary: KeyCode.F4 }), 'Focus Next Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor)); registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusPreviousSearchResultAction, { primary: KeyMod.Shift | KeyCode.F4 }), 'Focus Previous Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor)); registry.registerWorkbenchAction(SyncActionDescriptor.from(ReplaceInFilesAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_H }), 'Replace in Files', category); MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { group: '4_find_global', command: { id: ReplaceInFilesAction.ID, title: nls.localize({ key: 'miReplaceInFiles', comment: ['&& denotes a mnemonic'] }, "Replace &&in Files") }, order: 2 }); if (platform.isMacintosh) { // Register this with a more restrictive `when` on mac to avoid conflict with "copy path" KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleCaseSensitiveCommandId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewFocusedKey, Constants.FileMatchOrFolderMatchFocusKey.toNegated()), handler: toggleCaseSensitiveCommand }, ToggleCaseSensitiveKeybinding)); } else { KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleCaseSensitiveCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleCaseSensitiveCommand }, ToggleCaseSensitiveKeybinding)); } KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleWholeWordCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleWholeWordCommand }, ToggleWholeWordKeybinding)); KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleRegexCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleRegexCommand }, ToggleRegexKeybinding)); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.AddCursorsAtSearchResults, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_L, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); searchView.openEditorWithMultiCursor(<FileMatchOrMatch>tree.getFocus()[0]); } } }); registry.registerWorkbenchAction(SyncActionDescriptor.from(CollapseDeepestExpandedLevelAction), 'Search: Collapse All', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ExpandAllAction), 'Search: Expand All', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ShowAllSymbolsAction, { primary: KeyMod.CtrlCmd | KeyCode.KEY_T }), 'Go to Symbol in Workspace...'); registry.registerWorkbenchAction(SyncActionDescriptor.from(ToggleSearchOnTypeAction), 'Search: Toggle Search on Type', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(RefreshAction), 'Search: Refresh', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ClearSearchResultsAction), 'Search: Clear Search Results', category); // Register Quick Access Handler const quickAccessRegistry = Registry.as<IQuickAccessRegistry>(QuickAccessExtensions.Quickaccess); quickAccessRegistry.registerQuickAccessProvider({ ctor: AnythingQuickAccessProvider, prefix: AnythingQuickAccessProvider.PREFIX, placeholder: nls.localize('anythingQuickAccessPlaceholder', "Search files by name (append {0} to go to line or {1} to go to symbol)", AbstractGotoLineQuickAccessProvider.PREFIX, GotoSymbolQuickAccessProvider.PREFIX), contextKey: defaultQuickAccessContextKeyValue, helpEntries: [{ description: nls.localize('anythingQuickAccess', "Go to File"), needsEditor: false }] }); quickAccessRegistry.registerQuickAccessProvider({ ctor: SymbolsQuickAccessProvider, prefix: SymbolsQuickAccessProvider.PREFIX, placeholder: nls.localize('symbolsQuickAccessPlaceholder', "Type the name of a symbol to open."), contextKey: 'inWorkspaceSymbolsPicker', helpEntries: [{ description: nls.localize('symbolsQuickAccess', "Go to Symbol in Workspace"), needsEditor: false }] }); // Configuration const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration); configurationRegistry.registerConfiguration({ id: 'search', order: 13, title: nls.localize('searchConfigurationTitle', "Search"), type: 'object', properties: { [SEARCH_EXCLUDE_CONFIG]: { type: 'object', markdownDescription: nls.localize('exclude', "Configure glob patterns for excluding files and folders in fulltext searches and quick open. Inherits all glob patterns from the `#files.exclude#` setting. Read more about glob patterns [here](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options)."), default: { '**/node_modules': true, '**/bower_components': true, '**/*.code-search': true }, additionalProperties: { anyOf: [ { type: 'boolean', description: nls.localize('exclude.boolean', "The glob pattern to match file paths against. Set to true or false to enable or disable the pattern."), }, { type: 'object', properties: { when: { type: 'string', // expression ({ "**/*.js": { "when": "$(basename).js" } }) pattern: '\\w*\\$\\(basename\\)\\w*', default: '$(basename).ext', description: nls.localize('exclude.when', 'Additional check on the siblings of a matching file. Use $(basename) as variable for the matching file name.') } } } ] }, scope: ConfigurationScope.RESOURCE }, 'search.useRipgrep': { type: 'boolean', description: nls.localize('useRipgrep', "This setting is deprecated and now falls back on \"search.usePCRE2\"."), deprecationMessage: nls.localize('useRipgrepDeprecated', "Deprecated. Consider \"search.usePCRE2\" for advanced regex feature support."), default: true }, 'search.maintainFileSearchCache': { type: 'boolean', description: nls.localize('search.maintainFileSearchCache', "When enabled, the searchService process will be kept alive instead of being shut down after an hour of inactivity. This will keep the file search cache in memory."), default: false }, 'search.useIgnoreFiles': { type: 'boolean', markdownDescription: nls.localize('useIgnoreFiles', "Controls whether to use `.gitignore` and `.ignore` files when searching for files."), default: true, scope: ConfigurationScope.RESOURCE }, 'search.useGlobalIgnoreFiles': { type: 'boolean', markdownDescription: nls.localize('useGlobalIgnoreFiles', "Controls whether to use global `.gitignore` and `.ignore` files when searching for files."), default: false, scope: ConfigurationScope.RESOURCE }, 'search.quickOpen.includeSymbols': { type: 'boolean', description: nls.localize('search.quickOpen.includeSymbols', "Whether to include results from a global symbol search in the file results for Quick Open."), default: false }, 'search.quickOpen.includeHistory': { type: 'boolean', description: nls.localize('search.quickOpen.includeHistory', "Whether to include results from recently opened files in the file results for Quick Open."), default: true }, 'search.quickOpen.history.filterSortOrder': { 'type': 'string', 'enum': ['default', 'recency'], 'default': 'default', 'enumDescriptions': [ nls.localize('filterSortOrder.default', 'History entries are sorted by relevance based on the filter value used. More relevant entries appear first.'), nls.localize('filterSortOrder.recency', 'History entries are sorted by recency. More recently opened entries appear first.') ], 'description': nls.localize('filterSortOrder', "Controls sorting order of editor history in quick open when filtering.") }, 'search.followSymlinks': { type: 'boolean', description: nls.localize('search.followSymlinks', "Controls whether to follow symlinks while searching."), default: true }, 'search.smartCase': { type: 'boolean', description: nls.localize('search.smartCase', "Search case-insensitively if the pattern is all lowercase, otherwise, search case-sensitively."), default: false }, 'search.globalFindClipboard': { type: 'boolean', default: false, description: nls.localize('search.globalFindClipboard', "Controls whether the search view should read or modify the shared find clipboard on macOS."), included: platform.isMacintosh }, 'search.location': { type: 'string', enum: ['sidebar', 'panel'], default: 'sidebar', description: nls.localize('search.location', "Controls whether the search will be shown as a view in the sidebar or as a panel in the panel area for more horizontal space."), deprecationMessage: nls.localize('search.location.deprecationMessage', "This setting is deprecated. Please use drag and drop instead by dragging the search icon.") }, 'search.collapseResults': { type: 'string', enum: ['auto', 'alwaysCollapse', 'alwaysExpand'], enumDescriptions: [ nls.localize('search.collapseResults.auto', "Files with less than 10 results are expanded. Others are collapsed."), '', '' ], default: 'alwaysExpand', description: nls.localize('search.collapseAllResults', "Controls whether the search results will be collapsed or expanded."), }, 'search.useReplacePreview': { type: 'boolean', default: true, description: nls.localize('search.useReplacePreview', "Controls whether to open Replace Preview when selecting or replacing a match."), }, 'search.showLineNumbers': { type: 'boolean', default: false, description: nls.localize('search.showLineNumbers', "Controls whether to show line numbers for search results."), }, 'search.usePCRE2': { type: 'boolean', default: false, description: nls.localize('search.usePCRE2', "Whether to use the PCRE2 regex engine in text search. This enables using some advanced regex features like lookahead and backreferences. However, not all PCRE2 features are supported - only features that are also supported by JavaScript."), deprecationMessage: nls.localize('usePCRE2Deprecated', "Deprecated. PCRE2 will be used automatically when using regex features that are only supported by PCRE2."), }, 'search.actionsPosition': { type: 'string', enum: ['auto', 'right'], enumDescriptions: [ nls.localize('search.actionsPositionAuto', "Position the actionbar to the right when the search view is narrow, and immediately after the content when the search view is wide."), nls.localize('search.actionsPositionRight', "Always position the actionbar to the right."), ], default: 'auto', description: nls.localize('search.actionsPosition', "Controls the positioning of the actionbar on rows in the search view.") }, 'search.searchOnType': { type: 'boolean', default: true, description: nls.localize('search.searchOnType', "Search all files as you type.") }, 'search.seedWithNearestWord': { type: 'boolean', default: false, description: nls.localize('search.seedWithNearestWord', "Enable seeding search from the word nearest the cursor when the active editor has no selection.") }, 'search.seedOnFocus': { type: 'boolean', default: false, description: nls.localize('search.seedOnFocus', "Update workspace search query to the editor's selected text when focusing the search view. This happens either on click or when triggering the `workbench.views.search.focus` command.") }, 'search.searchOnTypeDebouncePeriod': { type: 'number', default: 300, markdownDescription: nls.localize('search.searchOnTypeDebouncePeriod', "When `#search.searchOnType#` is enabled, controls the timeout in milliseconds between a character being typed and the search starting. Has no effect when `search.searchOnType` is disabled.") }, 'search.searchEditor.doubleClickBehaviour': { type: 'string', enum: ['selectWord', 'goToLocation', 'openLocationToSide'], default: 'goToLocation', enumDescriptions: [ nls.localize('search.searchEditor.doubleClickBehaviour.selectWord', "Double clicking selects the word under the cursor."), nls.localize('search.searchEditor.doubleClickBehaviour.goToLocation', "Double clicking opens the result in the active editor group."), nls.localize('search.searchEditor.doubleClickBehaviour.openLocationToSide', "Double clicking opens the result in the editor group to the side, creating one if it does not yet exist."), ], markdownDescription: nls.localize('search.searchEditor.doubleClickBehaviour', "Configure effect of double clicking a result in a search editor.") }, 'search.searchEditor.reusePriorSearchConfiguration': { type: 'boolean', default: false, markdownDescription: nls.localize({ key: 'search.searchEditor.reusePriorSearchConfiguration', comment: ['"Search Editor" is a type that editor that can display search results. "includes, excludes, and flags" just refers to settings that affect search. For example, the "search.exclude" setting.'] }, "When enabled, new Search Editors will reuse the includes, excludes, and flags of the previously opened Search Editor") }, 'search.searchEditor.defaultNumberOfContextLines': { type: ['number', 'null'], default: 1, markdownDescription: nls.localize('search.searchEditor.defaultNumberOfContextLines', "The default number of surrounding context lines to use when creating new Search Editors. If using `#search.searchEditor.reusePriorSearchConfiguration#`, this can be set to `null` (empty) to use the prior Search Editor's configuration.") }, 'search.sortOrder': { 'type': 'string', 'enum': [SearchSortOrder.Default, SearchSortOrder.FileNames, SearchSortOrder.Type, SearchSortOrder.Modified, SearchSortOrder.CountDescending, SearchSortOrder.CountAscending], 'default': SearchSortOrder.Default, 'enumDescriptions': [ nls.localize('searchSortOrder.default', "Results are sorted by folder and file names, in alphabetical order."), nls.localize('searchSortOrder.filesOnly', "Results are sorted by file names ignoring folder order, in alphabetical order."), nls.localize('searchSortOrder.type', "Results are sorted by file extensions, in alphabetical order."), nls.localize('searchSortOrder.modified', "Results are sorted by file last modified date, in descending order."), nls.localize('searchSortOrder.countDescending', "Results are sorted by count per file, in descending order."), nls.localize('searchSortOrder.countAscending', "Results are sorted by count per file, in ascending order.") ], 'description': nls.localize('search.sortOrder', "Controls sorting order of search results.") }, } }); CommandsRegistry.registerCommand('_executeWorkspaceSymbolProvider', function (accessor, ...args) { const [query] = args; assertType(typeof query === 'string'); return getWorkspaceSymbols(query); }); // View menu MenuRegistry.appendMenuItem(MenuId.MenubarViewMenu, { group: '3_views', command: { id: VIEWLET_ID, title: nls.localize({ key: 'miViewSearch', comment: ['&& denotes a mnemonic'] }, "&&Search") }, order: 2 }); // Go to menu MenuRegistry.appendMenuItem(MenuId.MenubarGoMenu, { group: '3_global_nav', command: { id: 'workbench.action.showAllSymbols', title: nls.localize({ key: 'miGotoSymbolInWorkspace', comment: ['&& denotes a mnemonic'] }, "Go to Symbol in &&Workspace...") }, order: 2 });
src/vs/workbench/contrib/search/browser/search.contribution.ts
1
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.08394622057676315, 0.001272282563149929, 0.00016196069191209972, 0.00017653603572398424, 0.008774643763899803 ]
{ "id": 7, "code_window": [ "\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ReplaceInFilesAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_H }), 'Replace in Files', category);\n", "MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, {\n", "\tgroup: '4_find_global',\n", "\tcommand: {\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "registry.registerWorkbenchAction(SyncActionDescriptor.from(ReplaceInFilesAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_H }), 'Search: Replace in Files', category.value);\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.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 assert from 'assert'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { assertType } from 'vs/base/common/types'; import { URI } from 'vs/base/common/uri'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { Selection } from 'vs/editor/common/core/selection'; import { TextModel } from 'vs/editor/common/model/textModel'; import * as modes from 'vs/editor/common/modes'; import { CodeActionModel, CodeActionsState } from 'vs/editor/contrib/codeAction/codeActionModel'; import { createTestCodeEditor } from 'vs/editor/test/browser/testCodeEditor'; import { MockContextKeyService } from 'vs/platform/keybinding/test/common/mockKeybindingService'; import { MarkerService } from 'vs/platform/markers/common/markerService'; import { createTextModel } from 'vs/editor/test/common/editorTestUtils'; const testProvider = { provideCodeActions(): modes.CodeActionList { return { actions: [ { title: 'test', command: { id: 'test-command', title: 'test', arguments: [] } } ], dispose() { /* noop*/ } }; } }; suite('CodeActionModel', () => { const languageIdentifier = new modes.LanguageIdentifier('foo-lang', 3); let uri = URI.parse('untitled:path'); let model: TextModel; let markerService: MarkerService; let editor: ICodeEditor; const disposables = new DisposableStore(); setup(() => { disposables.clear(); markerService = new MarkerService(); model = createTextModel('foobar foo bar\nfarboo far boo', undefined, languageIdentifier, uri); editor = createTestCodeEditor({ model: model }); editor.setPosition({ lineNumber: 1, column: 1 }); }); teardown(() => { disposables.clear(); editor.dispose(); model.dispose(); markerService.dispose(); }); test('Orcale -> marker added', done => { const reg = modes.CodeActionProviderRegistry.register(languageIdentifier.language, testProvider); disposables.add(reg); const contextKeys = new MockContextKeyService(); const model = disposables.add(new CodeActionModel(editor, markerService, contextKeys, undefined)); disposables.add(model.onDidChangeState((e: CodeActionsState.State) => { assertType(e.type === CodeActionsState.Type.Triggered); assert.strictEqual(e.trigger.type, modes.CodeActionTriggerType.Auto); assert.ok(e.actions); e.actions.then(fixes => { model.dispose(); assert.equal(fixes.validActions.length, 1); done(); }, done); })); // start here markerService.changeOne('fake', uri, [{ startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 6, message: 'error', severity: 1, code: '', source: '' }]); }); test('Orcale -> position changed', () => { const reg = modes.CodeActionProviderRegistry.register(languageIdentifier.language, testProvider); disposables.add(reg); markerService.changeOne('fake', uri, [{ startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 6, message: 'error', severity: 1, code: '', source: '' }]); editor.setPosition({ lineNumber: 2, column: 1 }); return new Promise((resolve, reject) => { const contextKeys = new MockContextKeyService(); const model = disposables.add(new CodeActionModel(editor, markerService, contextKeys, undefined)); disposables.add(model.onDidChangeState((e: CodeActionsState.State) => { assertType(e.type === CodeActionsState.Type.Triggered); assert.equal(e.trigger.type, modes.CodeActionTriggerType.Auto); assert.ok(e.actions); e.actions.then(fixes => { model.dispose(); assert.equal(fixes.validActions.length, 1); resolve(undefined); }, reject); })); // start here editor.setPosition({ lineNumber: 1, column: 1 }); }); }); test('Lightbulb is in the wrong place, #29933', async function () { const reg = modes.CodeActionProviderRegistry.register(languageIdentifier.language, { provideCodeActions(_doc, _range): modes.CodeActionList { return { actions: [], dispose() { /* noop*/ } }; } }); disposables.add(reg); editor.getModel()!.setValue('// @ts-check\n2\ncon\n'); markerService.changeOne('fake', uri, [{ startLineNumber: 3, startColumn: 1, endLineNumber: 3, endColumn: 4, message: 'error', severity: 1, code: '', source: '' }]); // case 1 - drag selection over multiple lines -> range of enclosed marker, position or marker await new Promise(resolve => { const contextKeys = new MockContextKeyService(); const model = disposables.add(new CodeActionModel(editor, markerService, contextKeys, undefined)); disposables.add(model.onDidChangeState((e: CodeActionsState.State) => { assertType(e.type === CodeActionsState.Type.Triggered); assert.equal(e.trigger.type, modes.CodeActionTriggerType.Auto); const selection = <Selection>e.rangeOrSelection; assert.deepEqual(selection.selectionStartLineNumber, 1); assert.deepEqual(selection.selectionStartColumn, 1); assert.deepEqual(selection.endLineNumber, 4); assert.deepEqual(selection.endColumn, 1); assert.deepEqual(e.position, { lineNumber: 3, column: 1 }); model.dispose(); resolve(undefined); }, 5)); editor.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 4, endColumn: 1 }); }); }); test('Orcale -> should only auto trigger once for cursor and marker update right after each other', done => { const reg = modes.CodeActionProviderRegistry.register(languageIdentifier.language, testProvider); disposables.add(reg); let triggerCount = 0; const contextKeys = new MockContextKeyService(); const model = disposables.add(new CodeActionModel(editor, markerService, contextKeys, undefined)); disposables.add(model.onDidChangeState((e: CodeActionsState.State) => { assertType(e.type === CodeActionsState.Type.Triggered); assert.equal(e.trigger.type, modes.CodeActionTriggerType.Auto); ++triggerCount; // give time for second trigger before completing test setTimeout(() => { model.dispose(); assert.strictEqual(triggerCount, 1); done(); }, 50); }, 5 /*delay*/)); markerService.changeOne('fake', uri, [{ startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 6, message: 'error', severity: 1, code: '', source: '' }]); editor.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 4, endColumn: 1 }); }); });
src/vs/editor/contrib/codeAction/test/codeActionModel.test.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00017827759438659996, 0.00017314952856395394, 0.0001648617471801117, 0.0001732387754600495, 0.0000034483675790397683 ]
{ "id": 7, "code_window": [ "\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ReplaceInFilesAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_H }), 'Replace in Files', category);\n", "MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, {\n", "\tgroup: '4_find_global',\n", "\tcommand: {\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "registry.registerWorkbenchAction(SyncActionDescriptor.from(ReplaceInFilesAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_H }), 'Search: Replace in Files', category.value);\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 588 }
{ insidersLabel: 'insiders', insidersColor: '006b75', action: 'remove', perform: true }
.github/insiders.yml
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00017461874813307077, 0.00017461874813307077, 0.00017461874813307077, 0.00017461874813307077, 0 ]
{ "id": 7, "code_window": [ "\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ReplaceInFilesAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_H }), 'Replace in Files', category);\n", "MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, {\n", "\tgroup: '4_find_global',\n", "\tcommand: {\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "registry.registerWorkbenchAction(SyncActionDescriptor.from(ReplaceInFilesAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_H }), 'Search: Replace in Files', category.value);\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.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. *--------------------------------------------------------------------------------------------*/ @keyframes codicon-spin { 100% { transform:rotate(360deg); } } .codicon-animation-spin { /* Use steps to throttle FPS to reduce CPU usage */ animation: codicon-spin 1.5s steps(30) infinite; }
src/vs/base/browser/ui/codicons/codicon/codicon-animations.css
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00017820145876612514, 0.00017603022570256144, 0.00017385899263899773, 0.00017603022570256144, 0.0000021712330635637045 ]
{ "id": 8, "code_window": [ "\t}\n", "});\n", "\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(CollapseDeepestExpandedLevelAction), 'Search: Collapse All', category);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ExpandAllAction), 'Search: Expand All', category);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ShowAllSymbolsAction, { primary: KeyMod.CtrlCmd | KeyCode.KEY_T }), 'Go to Symbol in Workspace...');\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "registry.registerWorkbenchAction(SyncActionDescriptor.from(CollapseDeepestExpandedLevelAction), 'Search: Collapse All', category.value);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ExpandAllAction), 'Search: Expand All', category.value);\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 643 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Action } from 'vs/base/common/actions'; import { distinct } from 'vs/base/common/arrays'; import { onUnexpectedError } from 'vs/base/common/errors'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import * as objects from 'vs/base/common/objects'; import * as platform from 'vs/base/common/platform'; import { dirname } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { ToggleCaseSensitiveKeybinding, ToggleRegexKeybinding, ToggleWholeWordKeybinding } from 'vs/editor/contrib/find/findModel'; import * as nls from 'vs/nls'; import { ICommandAction, MenuId, MenuRegistry, SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { CommandsRegistry, ICommandHandler } from 'vs/platform/commands/common/commands'; import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry'; import { ContextKeyExpr, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IFileService } from 'vs/platform/files/common/files'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { IListService, WorkbenchListFocusContextKey, WorkbenchObjectTree } from 'vs/platform/list/browser/listService'; import { Registry } from 'vs/platform/registry/common/platform'; import { defaultQuickAccessContextKeyValue } from 'vs/workbench/browser/quickaccess'; import { Extensions as ActionExtensions, IWorkbenchActionRegistry } from 'vs/workbench/common/actions'; import { Extensions as WorkbenchExtensions, IWorkbenchContribution, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions'; import { Extensions as ViewExtensions, IViewsRegistry, IViewContainersRegistry, ViewContainerLocation, IViewDescriptorService, IViewsService } from 'vs/workbench/common/views'; import { getMultiSelectedResources } from 'vs/workbench/contrib/files/browser/files'; import { ExplorerFolderContext, ExplorerRootContext, FilesExplorerFocusCondition, IExplorerService, VIEWLET_ID as VIEWLET_ID_FILES } from 'vs/workbench/contrib/files/common/files'; import { registerContributions as replaceContributions } from 'vs/workbench/contrib/search/browser/replaceContributions'; import { clearHistoryCommand, ClearSearchResultsAction, CloseReplaceAction, CollapseDeepestExpandedLevelAction, copyAllCommand, copyMatchCommand, copyPathCommand, FocusNextInputAction, FocusNextSearchResultAction, FocusPreviousInputAction, FocusPreviousSearchResultAction, focusSearchListCommand, getSearchView, openSearchView, OpenSearchViewletAction, RefreshAction, RemoveAction, ReplaceAction, ReplaceAllAction, ReplaceAllInFolderAction, ReplaceInFilesAction, toggleCaseSensitiveCommand, toggleRegexCommand, toggleWholeWordCommand, FindInFilesCommand, ToggleSearchOnTypeAction, ExpandAllAction } from 'vs/workbench/contrib/search/browser/searchActions'; import { SearchView } from 'vs/workbench/contrib/search/browser/searchView'; import { registerContributions as searchWidgetContributions } from 'vs/workbench/contrib/search/browser/searchWidget'; import * as Constants from 'vs/workbench/contrib/search/common/constants'; import * as SearchEditorConstants from 'vs/workbench/contrib/searchEditor/browser/constants'; import { getWorkspaceSymbols } from 'vs/workbench/contrib/search/common/search'; import { ISearchHistoryService, SearchHistoryService } from 'vs/workbench/contrib/search/common/searchHistoryService'; import { FileMatchOrMatch, ISearchWorkbenchService, RenderableMatch, SearchWorkbenchService, FileMatch, Match, FolderMatch } from 'vs/workbench/contrib/search/common/searchModel'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { VIEWLET_ID, VIEW_ID, SEARCH_EXCLUDE_CONFIG, SearchSortOrder } from 'vs/workbench/services/search/common/search'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { ExplorerViewPaneContainer } from 'vs/workbench/contrib/files/browser/explorerViewlet'; import { assertType, assertIsDefined } from 'vs/base/common/types'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { SearchEditor } from 'vs/workbench/contrib/searchEditor/browser/searchEditor'; import { ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { IQuickAccessRegistry, Extensions as QuickAccessExtensions } from 'vs/platform/quickinput/common/quickAccess'; import { SymbolsQuickAccessProvider } from 'vs/workbench/contrib/search/browser/symbolsQuickAccess'; import { AnythingQuickAccessProvider } from 'vs/workbench/contrib/search/browser/anythingQuickAccess'; import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { AbstractGotoLineQuickAccessProvider } from 'vs/editor/contrib/quickAccess/gotoLineQuickAccess'; import { GotoSymbolQuickAccessProvider } from 'vs/workbench/contrib/codeEditor/browser/quickaccess/gotoSymbolQuickAccess'; import { searchViewIcon } from 'vs/workbench/contrib/search/browser/searchIcons'; registerSingleton(ISearchWorkbenchService, SearchWorkbenchService, true); registerSingleton(ISearchHistoryService, SearchHistoryService, true); replaceContributions(); searchWidgetContributions(); const category = nls.localize('search', "Search"); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'workbench.action.search.toggleQueryDetails', weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or(Constants.SearchViewFocusedKey, SearchEditorConstants.InSearchEditor), primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_J, handler: accessor => { const contextService = accessor.get(IContextKeyService).getContext(document.activeElement); if (contextService.getValue(SearchEditorConstants.InSearchEditor.serialize())) { (accessor.get(IEditorService).activeEditorPane as SearchEditor).toggleQueryDetails(); } else if (contextService.getValue(Constants.SearchViewFocusedKey.serialize())) { const searchView = getSearchView(accessor.get(IViewsService)); assertIsDefined(searchView).toggleQueryDetails(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.FocusSearchFromResults, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FirstMatchFocusKey), primary: KeyMod.CtrlCmd | KeyCode.UpArrow, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { searchView.focusPreviousInputBox(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.OpenMatchToSide, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyMod.CtrlCmd | KeyCode.Enter, mac: { primary: KeyMod.WinCtrl | KeyCode.Enter }, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); searchView.open(<FileMatchOrMatch>tree.getFocus()[0], false, true, true); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CancelActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, WorkbenchListFocusContextKey), primary: KeyCode.Escape, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { searchView.cancelSearch(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.RemoveActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyCode.Delete, mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace, }, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(RemoveAction, tree, tree.getFocus()[0]!).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.MatchFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAction, tree, tree.getFocus()[0] as Match, searchView).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceAllInFileActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.FileFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter], handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAllAction, searchView, tree.getFocus()[0] as FileMatch).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceAllInFolderActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.FolderFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter], handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAllInFolderAction, tree, tree.getFocus()[0] as FolderMatch).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CloseReplaceWidgetActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceInputBoxFocusedKey), primary: KeyCode.Escape, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(CloseReplaceAction, Constants.CloseReplaceWidgetActionId, '').run(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FocusNextInputAction.ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or( ContextKeyExpr.and(SearchEditorConstants.InSearchEditor, Constants.InputBoxFocusedKey), ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.InputBoxFocusedKey)), primary: KeyMod.CtrlCmd | KeyCode.DownArrow, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(FocusNextInputAction, FocusNextInputAction.ID, '').run(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FocusPreviousInputAction.ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or( ContextKeyExpr.and(SearchEditorConstants.InSearchEditor, Constants.InputBoxFocusedKey), ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.InputBoxFocusedKey, Constants.SearchInputBoxFocusedKey.toNegated())), primary: KeyMod.CtrlCmd | KeyCode.UpArrow, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(FocusPreviousInputAction, FocusPreviousInputAction.ID, '').run(); } }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceActionId, title: ReplaceAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.MatchFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceAllInFolderActionId, title: ReplaceAllInFolderAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.FolderFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceAllInFileActionId, title: ReplaceAllAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.FileFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.RemoveActionId, title: RemoveAction.LABEL }, when: Constants.FileMatchOrMatchFocusKey, group: 'search', order: 2 }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CopyMatchCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.FileMatchOrMatchFocusKey, primary: KeyMod.CtrlCmd | KeyCode.KEY_C, handler: copyMatchCommand }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyMatchCommandId, title: nls.localize('copyMatchLabel', "Copy") }, when: Constants.FileMatchOrMatchFocusKey, group: 'search_2', order: 1 }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CopyPathCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.FileMatchOrFolderMatchWithResourceFocusKey, primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_C, win: { primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_C }, handler: copyPathCommand }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyPathCommandId, title: nls.localize('copyPathLabel', "Copy Path") }, when: Constants.FileMatchOrFolderMatchWithResourceFocusKey, group: 'search_2', order: 2 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyAllCommandId, title: nls.localize('copyAllLabel', "Copy All") }, when: Constants.HasSearchResults, group: 'search_2', order: 3 }); CommandsRegistry.registerCommand({ id: Constants.CopyAllCommandId, handler: copyAllCommand }); CommandsRegistry.registerCommand({ id: Constants.ClearSearchHistoryCommandId, handler: clearHistoryCommand }); CommandsRegistry.registerCommand({ id: Constants.RevealInSideBarForSearchResults, handler: (accessor, args: any) => { const viewletService = accessor.get(IViewletService); const explorerService = accessor.get(IExplorerService); const contextService = accessor.get(IWorkspaceContextService); const searchView = getSearchView(accessor.get(IViewsService)); if (!searchView) { return; } let fileMatch: FileMatch; if (!(args instanceof FileMatch)) { args = searchView.getControl().getFocus()[0]; } if (args instanceof FileMatch) { fileMatch = args; } else { return; } viewletService.openViewlet(VIEWLET_ID_FILES, false).then((viewlet) => { if (!viewlet) { return; } const explorerViewContainer = viewlet.getViewPaneContainer() as ExplorerViewPaneContainer; const uri = fileMatch.resource; if (uri && contextService.isInsideWorkspace(uri)) { const explorerView = explorerViewContainer.getExplorerView(); explorerView.setExpanded(true); explorerService.select(uri, true).then(() => explorerView.focus(), onUnexpectedError); } }); } }); const RevealInSideBarForSearchResultsCommand: ICommandAction = { id: Constants.RevealInSideBarForSearchResults, title: nls.localize('revealInSideBar', "Reveal in Side Bar") }; MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: RevealInSideBarForSearchResultsCommand, when: ContextKeyExpr.and(Constants.FileFocusKey, Constants.HasSearchResults), group: 'search_3', order: 1 }); const clearSearchHistoryLabel = nls.localize('clearSearchHistoryLabel', "Clear Search History"); const ClearSearchHistoryCommand: ICommandAction = { id: Constants.ClearSearchHistoryCommandId, title: clearSearchHistoryLabel, category }; MenuRegistry.addCommand(ClearSearchHistoryCommand); CommandsRegistry.registerCommand({ id: Constants.FocusSearchListCommandID, handler: focusSearchListCommand }); const focusSearchListCommandLabel = nls.localize('focusSearchListCommandLabel', "Focus List"); const FocusSearchListCommand: ICommandAction = { id: Constants.FocusSearchListCommandID, title: focusSearchListCommandLabel, category }; MenuRegistry.addCommand(FocusSearchListCommand); const searchInFolderCommand: ICommandHandler = (accessor, resource?: URI) => { const listService = accessor.get(IListService); const fileService = accessor.get(IFileService); const viewsService = accessor.get(IViewsService); const resources = getMultiSelectedResources(resource, listService, accessor.get(IEditorService), accessor.get(IExplorerService)); return openSearchView(viewsService, true).then(searchView => { if (resources && resources.length && searchView) { return fileService.resolveAll(resources.map(resource => ({ resource }))).then(results => { const folders: URI[] = []; results.forEach(result => { if (result.success && result.stat) { folders.push(result.stat.isDirectory ? result.stat.resource : dirname(result.stat.resource)); } }); searchView.searchInFolders(distinct(folders, folder => folder.toString())); }); } return undefined; }); }; const FIND_IN_FOLDER_ID = 'filesExplorer.findInFolder'; KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FIND_IN_FOLDER_ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(FilesExplorerFocusCondition, ExplorerFolderContext), primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_F, handler: searchInFolderCommand }); CommandsRegistry.registerCommand({ id: ClearSearchResultsAction.ID, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(ClearSearchResultsAction, ClearSearchResultsAction.ID, '').run(); } }); CommandsRegistry.registerCommand({ id: RefreshAction.ID, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(RefreshAction, RefreshAction.ID, '').run(); } }); const FIND_IN_WORKSPACE_ID = 'filesExplorer.findInWorkspace'; CommandsRegistry.registerCommand({ id: FIND_IN_WORKSPACE_ID, handler: (accessor) => { return openSearchView(accessor.get(IViewsService), true).then(searchView => { if (searchView) { searchView.searchInFolders(); } }); } }); MenuRegistry.appendMenuItem(MenuId.ExplorerContext, { group: '4_search', order: 10, command: { id: FIND_IN_FOLDER_ID, title: nls.localize('findInFolder', "Find in Folder...") }, when: ContextKeyExpr.and(ExplorerFolderContext) }); MenuRegistry.appendMenuItem(MenuId.ExplorerContext, { group: '4_search', order: 10, command: { id: FIND_IN_WORKSPACE_ID, title: nls.localize('findInWorkspace', "Find in Workspace...") }, when: ContextKeyExpr.and(ExplorerRootContext, ExplorerFolderContext.toNegated()) }); class ShowAllSymbolsAction extends Action { static readonly ID = 'workbench.action.showAllSymbols'; static readonly LABEL = nls.localize('showTriggerActions', "Go to Symbol in Workspace..."); static readonly ALL_SYMBOLS_PREFIX = '#'; constructor( actionId: string, actionLabel: string, @IQuickInputService private readonly quickInputService: IQuickInputService ) { super(actionId, actionLabel); } async run(): Promise<void> { this.quickInputService.quickAccess.show(ShowAllSymbolsAction.ALL_SYMBOLS_PREFIX); } } const viewContainer = Registry.as<IViewContainersRegistry>(ViewExtensions.ViewContainersRegistry).registerViewContainer({ id: VIEWLET_ID, name: nls.localize('name', "Search"), ctorDescriptor: new SyncDescriptor(ViewPaneContainer, [VIEWLET_ID, { mergeViewWithContainerWhenSingleView: true, donotShowContainerTitleWhenMergedWithContainer: true }]), hideIfEmpty: true, icon: searchViewIcon.classNames, order: 1 }, ViewContainerLocation.Sidebar); const viewDescriptor = { id: VIEW_ID, containerIcon: 'codicon-search', name: nls.localize('search', "Search"), ctorDescriptor: new SyncDescriptor(SearchView), canToggleVisibility: false, canMoveView: true }; // Register search default location to sidebar Registry.as<IViewsRegistry>(ViewExtensions.ViewsRegistry).registerViews([viewDescriptor], viewContainer); // Migrate search location setting to new model class RegisterSearchViewContribution implements IWorkbenchContribution { constructor( @IConfigurationService configurationService: IConfigurationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService ) { const data = configurationService.inspect('search.location'); if (data.value === 'panel') { viewDescriptorService.moveViewToLocation(viewDescriptor, ViewContainerLocation.Panel); } if (data.userValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER); } if (data.userLocalValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER_LOCAL); } if (data.userRemoteValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER_REMOTE); } if (data.workspaceFolderValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.WORKSPACE_FOLDER); } if (data.workspaceValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.WORKSPACE); } } } Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(RegisterSearchViewContribution, LifecyclePhase.Starting); // Actions const registry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions); // Show Search and Find in Files are redundant, but we can't break keybindings by removing one. So it's the same action, same keybinding, registered to different IDs. // Show Search 'when' is redundant but if the two conflict with exactly the same keybinding and 'when' clause, then they can show up as "unbound" - #51780 registry.registerWorkbenchAction(SyncActionDescriptor.from(OpenSearchViewletAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_F }, Constants.SearchViewVisibleKey.toNegated()), 'View: Show Search', nls.localize('view', "View")); KeybindingsRegistry.registerCommandAndKeybindingRule({ description: { description: nls.localize('findInFiles.description', "Open the search viewlet"), args: [ { name: nls.localize('findInFiles.args', "A set of options for the search viewlet"), schema: { type: 'object', properties: { query: { 'type': 'string' }, replace: { 'type': 'string' }, triggerSearch: { 'type': 'boolean' }, filesToInclude: { 'type': 'string' }, filesToExclude: { 'type': 'string' }, isRegex: { 'type': 'boolean' }, isCaseSensitive: { 'type': 'boolean' }, matchWholeWord: { 'type': 'boolean' }, } } }, ] }, id: Constants.FindInFilesActionId, weight: KeybindingWeight.WorkbenchContrib, when: null, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_F, handler: FindInFilesCommand }); MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: Constants.FindInFilesActionId, title: { value: nls.localize('findInFiles', "Find in Files"), original: 'Find in Files' }, category } }); MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { group: '4_find_global', command: { id: Constants.FindInFilesActionId, title: nls.localize({ key: 'miFindInFiles', comment: ['&& denotes a mnemonic'] }, "Find &&in Files") }, order: 1 }); registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusNextSearchResultAction, { primary: KeyCode.F4 }), 'Focus Next Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor)); registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusPreviousSearchResultAction, { primary: KeyMod.Shift | KeyCode.F4 }), 'Focus Previous Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor)); registry.registerWorkbenchAction(SyncActionDescriptor.from(ReplaceInFilesAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_H }), 'Replace in Files', category); MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { group: '4_find_global', command: { id: ReplaceInFilesAction.ID, title: nls.localize({ key: 'miReplaceInFiles', comment: ['&& denotes a mnemonic'] }, "Replace &&in Files") }, order: 2 }); if (platform.isMacintosh) { // Register this with a more restrictive `when` on mac to avoid conflict with "copy path" KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleCaseSensitiveCommandId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewFocusedKey, Constants.FileMatchOrFolderMatchFocusKey.toNegated()), handler: toggleCaseSensitiveCommand }, ToggleCaseSensitiveKeybinding)); } else { KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleCaseSensitiveCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleCaseSensitiveCommand }, ToggleCaseSensitiveKeybinding)); } KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleWholeWordCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleWholeWordCommand }, ToggleWholeWordKeybinding)); KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleRegexCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleRegexCommand }, ToggleRegexKeybinding)); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.AddCursorsAtSearchResults, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_L, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); searchView.openEditorWithMultiCursor(<FileMatchOrMatch>tree.getFocus()[0]); } } }); registry.registerWorkbenchAction(SyncActionDescriptor.from(CollapseDeepestExpandedLevelAction), 'Search: Collapse All', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ExpandAllAction), 'Search: Expand All', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ShowAllSymbolsAction, { primary: KeyMod.CtrlCmd | KeyCode.KEY_T }), 'Go to Symbol in Workspace...'); registry.registerWorkbenchAction(SyncActionDescriptor.from(ToggleSearchOnTypeAction), 'Search: Toggle Search on Type', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(RefreshAction), 'Search: Refresh', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ClearSearchResultsAction), 'Search: Clear Search Results', category); // Register Quick Access Handler const quickAccessRegistry = Registry.as<IQuickAccessRegistry>(QuickAccessExtensions.Quickaccess); quickAccessRegistry.registerQuickAccessProvider({ ctor: AnythingQuickAccessProvider, prefix: AnythingQuickAccessProvider.PREFIX, placeholder: nls.localize('anythingQuickAccessPlaceholder', "Search files by name (append {0} to go to line or {1} to go to symbol)", AbstractGotoLineQuickAccessProvider.PREFIX, GotoSymbolQuickAccessProvider.PREFIX), contextKey: defaultQuickAccessContextKeyValue, helpEntries: [{ description: nls.localize('anythingQuickAccess', "Go to File"), needsEditor: false }] }); quickAccessRegistry.registerQuickAccessProvider({ ctor: SymbolsQuickAccessProvider, prefix: SymbolsQuickAccessProvider.PREFIX, placeholder: nls.localize('symbolsQuickAccessPlaceholder', "Type the name of a symbol to open."), contextKey: 'inWorkspaceSymbolsPicker', helpEntries: [{ description: nls.localize('symbolsQuickAccess', "Go to Symbol in Workspace"), needsEditor: false }] }); // Configuration const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration); configurationRegistry.registerConfiguration({ id: 'search', order: 13, title: nls.localize('searchConfigurationTitle', "Search"), type: 'object', properties: { [SEARCH_EXCLUDE_CONFIG]: { type: 'object', markdownDescription: nls.localize('exclude', "Configure glob patterns for excluding files and folders in fulltext searches and quick open. Inherits all glob patterns from the `#files.exclude#` setting. Read more about glob patterns [here](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options)."), default: { '**/node_modules': true, '**/bower_components': true, '**/*.code-search': true }, additionalProperties: { anyOf: [ { type: 'boolean', description: nls.localize('exclude.boolean', "The glob pattern to match file paths against. Set to true or false to enable or disable the pattern."), }, { type: 'object', properties: { when: { type: 'string', // expression ({ "**/*.js": { "when": "$(basename).js" } }) pattern: '\\w*\\$\\(basename\\)\\w*', default: '$(basename).ext', description: nls.localize('exclude.when', 'Additional check on the siblings of a matching file. Use $(basename) as variable for the matching file name.') } } } ] }, scope: ConfigurationScope.RESOURCE }, 'search.useRipgrep': { type: 'boolean', description: nls.localize('useRipgrep', "This setting is deprecated and now falls back on \"search.usePCRE2\"."), deprecationMessage: nls.localize('useRipgrepDeprecated', "Deprecated. Consider \"search.usePCRE2\" for advanced regex feature support."), default: true }, 'search.maintainFileSearchCache': { type: 'boolean', description: nls.localize('search.maintainFileSearchCache', "When enabled, the searchService process will be kept alive instead of being shut down after an hour of inactivity. This will keep the file search cache in memory."), default: false }, 'search.useIgnoreFiles': { type: 'boolean', markdownDescription: nls.localize('useIgnoreFiles', "Controls whether to use `.gitignore` and `.ignore` files when searching for files."), default: true, scope: ConfigurationScope.RESOURCE }, 'search.useGlobalIgnoreFiles': { type: 'boolean', markdownDescription: nls.localize('useGlobalIgnoreFiles', "Controls whether to use global `.gitignore` and `.ignore` files when searching for files."), default: false, scope: ConfigurationScope.RESOURCE }, 'search.quickOpen.includeSymbols': { type: 'boolean', description: nls.localize('search.quickOpen.includeSymbols', "Whether to include results from a global symbol search in the file results for Quick Open."), default: false }, 'search.quickOpen.includeHistory': { type: 'boolean', description: nls.localize('search.quickOpen.includeHistory', "Whether to include results from recently opened files in the file results for Quick Open."), default: true }, 'search.quickOpen.history.filterSortOrder': { 'type': 'string', 'enum': ['default', 'recency'], 'default': 'default', 'enumDescriptions': [ nls.localize('filterSortOrder.default', 'History entries are sorted by relevance based on the filter value used. More relevant entries appear first.'), nls.localize('filterSortOrder.recency', 'History entries are sorted by recency. More recently opened entries appear first.') ], 'description': nls.localize('filterSortOrder', "Controls sorting order of editor history in quick open when filtering.") }, 'search.followSymlinks': { type: 'boolean', description: nls.localize('search.followSymlinks', "Controls whether to follow symlinks while searching."), default: true }, 'search.smartCase': { type: 'boolean', description: nls.localize('search.smartCase', "Search case-insensitively if the pattern is all lowercase, otherwise, search case-sensitively."), default: false }, 'search.globalFindClipboard': { type: 'boolean', default: false, description: nls.localize('search.globalFindClipboard', "Controls whether the search view should read or modify the shared find clipboard on macOS."), included: platform.isMacintosh }, 'search.location': { type: 'string', enum: ['sidebar', 'panel'], default: 'sidebar', description: nls.localize('search.location', "Controls whether the search will be shown as a view in the sidebar or as a panel in the panel area for more horizontal space."), deprecationMessage: nls.localize('search.location.deprecationMessage', "This setting is deprecated. Please use drag and drop instead by dragging the search icon.") }, 'search.collapseResults': { type: 'string', enum: ['auto', 'alwaysCollapse', 'alwaysExpand'], enumDescriptions: [ nls.localize('search.collapseResults.auto', "Files with less than 10 results are expanded. Others are collapsed."), '', '' ], default: 'alwaysExpand', description: nls.localize('search.collapseAllResults', "Controls whether the search results will be collapsed or expanded."), }, 'search.useReplacePreview': { type: 'boolean', default: true, description: nls.localize('search.useReplacePreview', "Controls whether to open Replace Preview when selecting or replacing a match."), }, 'search.showLineNumbers': { type: 'boolean', default: false, description: nls.localize('search.showLineNumbers', "Controls whether to show line numbers for search results."), }, 'search.usePCRE2': { type: 'boolean', default: false, description: nls.localize('search.usePCRE2', "Whether to use the PCRE2 regex engine in text search. This enables using some advanced regex features like lookahead and backreferences. However, not all PCRE2 features are supported - only features that are also supported by JavaScript."), deprecationMessage: nls.localize('usePCRE2Deprecated', "Deprecated. PCRE2 will be used automatically when using regex features that are only supported by PCRE2."), }, 'search.actionsPosition': { type: 'string', enum: ['auto', 'right'], enumDescriptions: [ nls.localize('search.actionsPositionAuto', "Position the actionbar to the right when the search view is narrow, and immediately after the content when the search view is wide."), nls.localize('search.actionsPositionRight', "Always position the actionbar to the right."), ], default: 'auto', description: nls.localize('search.actionsPosition', "Controls the positioning of the actionbar on rows in the search view.") }, 'search.searchOnType': { type: 'boolean', default: true, description: nls.localize('search.searchOnType', "Search all files as you type.") }, 'search.seedWithNearestWord': { type: 'boolean', default: false, description: nls.localize('search.seedWithNearestWord', "Enable seeding search from the word nearest the cursor when the active editor has no selection.") }, 'search.seedOnFocus': { type: 'boolean', default: false, description: nls.localize('search.seedOnFocus', "Update workspace search query to the editor's selected text when focusing the search view. This happens either on click or when triggering the `workbench.views.search.focus` command.") }, 'search.searchOnTypeDebouncePeriod': { type: 'number', default: 300, markdownDescription: nls.localize('search.searchOnTypeDebouncePeriod', "When `#search.searchOnType#` is enabled, controls the timeout in milliseconds between a character being typed and the search starting. Has no effect when `search.searchOnType` is disabled.") }, 'search.searchEditor.doubleClickBehaviour': { type: 'string', enum: ['selectWord', 'goToLocation', 'openLocationToSide'], default: 'goToLocation', enumDescriptions: [ nls.localize('search.searchEditor.doubleClickBehaviour.selectWord', "Double clicking selects the word under the cursor."), nls.localize('search.searchEditor.doubleClickBehaviour.goToLocation', "Double clicking opens the result in the active editor group."), nls.localize('search.searchEditor.doubleClickBehaviour.openLocationToSide', "Double clicking opens the result in the editor group to the side, creating one if it does not yet exist."), ], markdownDescription: nls.localize('search.searchEditor.doubleClickBehaviour', "Configure effect of double clicking a result in a search editor.") }, 'search.searchEditor.reusePriorSearchConfiguration': { type: 'boolean', default: false, markdownDescription: nls.localize({ key: 'search.searchEditor.reusePriorSearchConfiguration', comment: ['"Search Editor" is a type that editor that can display search results. "includes, excludes, and flags" just refers to settings that affect search. For example, the "search.exclude" setting.'] }, "When enabled, new Search Editors will reuse the includes, excludes, and flags of the previously opened Search Editor") }, 'search.searchEditor.defaultNumberOfContextLines': { type: ['number', 'null'], default: 1, markdownDescription: nls.localize('search.searchEditor.defaultNumberOfContextLines', "The default number of surrounding context lines to use when creating new Search Editors. If using `#search.searchEditor.reusePriorSearchConfiguration#`, this can be set to `null` (empty) to use the prior Search Editor's configuration.") }, 'search.sortOrder': { 'type': 'string', 'enum': [SearchSortOrder.Default, SearchSortOrder.FileNames, SearchSortOrder.Type, SearchSortOrder.Modified, SearchSortOrder.CountDescending, SearchSortOrder.CountAscending], 'default': SearchSortOrder.Default, 'enumDescriptions': [ nls.localize('searchSortOrder.default', "Results are sorted by folder and file names, in alphabetical order."), nls.localize('searchSortOrder.filesOnly', "Results are sorted by file names ignoring folder order, in alphabetical order."), nls.localize('searchSortOrder.type', "Results are sorted by file extensions, in alphabetical order."), nls.localize('searchSortOrder.modified', "Results are sorted by file last modified date, in descending order."), nls.localize('searchSortOrder.countDescending', "Results are sorted by count per file, in descending order."), nls.localize('searchSortOrder.countAscending', "Results are sorted by count per file, in ascending order.") ], 'description': nls.localize('search.sortOrder', "Controls sorting order of search results.") }, } }); CommandsRegistry.registerCommand('_executeWorkspaceSymbolProvider', function (accessor, ...args) { const [query] = args; assertType(typeof query === 'string'); return getWorkspaceSymbols(query); }); // View menu MenuRegistry.appendMenuItem(MenuId.MenubarViewMenu, { group: '3_views', command: { id: VIEWLET_ID, title: nls.localize({ key: 'miViewSearch', comment: ['&& denotes a mnemonic'] }, "&&Search") }, order: 2 }); // Go to menu MenuRegistry.appendMenuItem(MenuId.MenubarGoMenu, { group: '3_global_nav', command: { id: 'workbench.action.showAllSymbols', title: nls.localize({ key: 'miGotoSymbolInWorkspace', comment: ['&& denotes a mnemonic'] }, "Go to Symbol in &&Workspace...") }, order: 2 });
src/vs/workbench/contrib/search/browser/search.contribution.ts
1
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.5423311591148376, 0.0062806978821754456, 0.00016147372662089765, 0.00017174294043798, 0.05682247504591942 ]
{ "id": 8, "code_window": [ "\t}\n", "});\n", "\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(CollapseDeepestExpandedLevelAction), 'Search: Collapse All', category);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ExpandAllAction), 'Search: Expand All', category);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ShowAllSymbolsAction, { primary: KeyMod.CtrlCmd | KeyCode.KEY_T }), 'Go to Symbol in Workspace...');\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "registry.registerWorkbenchAction(SyncActionDescriptor.from(CollapseDeepestExpandedLevelAction), 'Search: Collapse All', category.value);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ExpandAllAction), 'Search: Expand All', category.value);\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 643 }
/*--------------------------------------------------------------------------------------------- * 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 * as platform from 'vs/base/common/platform'; import { fixDriveC, getAbsoluteGlob } from 'vs/workbench/services/search/node/ripgrepFileSearch'; suite('RipgrepFileSearch - etc', () => { function testGetAbsGlob(params: string[]): void { const [folder, glob, expectedResult] = params; assert.equal(fixDriveC(getAbsoluteGlob(folder, glob)), expectedResult, JSON.stringify(params)); } test('getAbsoluteGlob_win', () => { if (!platform.isWindows) { return; } [ ['C:/foo/bar', 'glob/**', '/foo\\bar\\glob\\**'], ['c:/', 'glob/**', '/glob\\**'], ['C:\\foo\\bar', 'glob\\**', '/foo\\bar\\glob\\**'], ['c:\\foo\\bar', 'glob\\**', '/foo\\bar\\glob\\**'], ['c:\\', 'glob\\**', '/glob\\**'], ['\\\\localhost\\c$\\foo\\bar', 'glob/**', '\\\\localhost\\c$\\foo\\bar\\glob\\**'], // absolute paths are not resolved further ['c:/foo/bar', '/path/something', '/path/something'], ['c:/foo/bar', 'c:\\project\\folder', '/project\\folder'] ].forEach(testGetAbsGlob); }); test('getAbsoluteGlob_posix', () => { if (platform.isWindows) { return; } [ ['/foo/bar', 'glob/**', '/foo/bar/glob/**'], ['/', 'glob/**', '/glob/**'], // absolute paths are not resolved further ['/', '/project/folder', '/project/folder'], ].forEach(testGetAbsGlob); }); });
src/vs/workbench/services/search/test/node/ripgrepFileSearch.test.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00017392134759575129, 0.00017294973076786846, 0.00017158250557258725, 0.00017334616859443486, 8.836362894726335e-7 ]
{ "id": 8, "code_window": [ "\t}\n", "});\n", "\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(CollapseDeepestExpandedLevelAction), 'Search: Collapse All', category);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ExpandAllAction), 'Search: Expand All', category);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ShowAllSymbolsAction, { primary: KeyMod.CtrlCmd | KeyCode.KEY_T }), 'Go to Symbol in Workspace...');\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "registry.registerWorkbenchAction(SyncActionDescriptor.from(CollapseDeepestExpandedLevelAction), 'Search: Collapse All', category.value);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ExpandAllAction), 'Search: Expand All', category.value);\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 643 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IWebviewService, WebviewContentOptions, WebviewOverlay, WebviewElement, WebviewIcons, WebviewOptions, WebviewExtensionDescription } from 'vs/workbench/contrib/webview/browser/webview'; import { IFrameWebview } from 'vs/workbench/contrib/webview/browser/webviewElement'; import { WebviewThemeDataProvider } from 'vs/workbench/contrib/webview/browser/themeing'; import { DynamicWebviewEditorOverlay } from './dynamicWebviewEditorOverlay'; import { WebviewIconManager } from './webviewIconManager'; export class WebviewService implements IWebviewService { declare readonly _serviceBrand: undefined; private readonly _webviewThemeDataProvider: WebviewThemeDataProvider; private readonly _iconManager: WebviewIconManager; constructor( @IInstantiationService private readonly _instantiationService: IInstantiationService, ) { this._webviewThemeDataProvider = this._instantiationService.createInstance(WebviewThemeDataProvider); this._iconManager = this._instantiationService.createInstance(WebviewIconManager); } createWebviewElement( id: string, options: WebviewOptions, contentOptions: WebviewContentOptions, extension: WebviewExtensionDescription | undefined, ): WebviewElement { return this._instantiationService.createInstance(IFrameWebview, id, options, contentOptions, extension, this._webviewThemeDataProvider); } createWebviewOverlay( id: string, options: WebviewOptions, contentOptions: WebviewContentOptions, extension: WebviewExtensionDescription | undefined, ): WebviewOverlay { return this._instantiationService.createInstance(DynamicWebviewEditorOverlay, id, options, contentOptions, extension); } setIcons(id: string, iconPath: WebviewIcons | undefined): void { this._iconManager.setIcons(id, iconPath); } } registerSingleton(IWebviewService, WebviewService, true);
src/vs/workbench/contrib/webview/browser/webviewService.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00017558812396600842, 0.00017443537944927812, 0.00017258570005651563, 0.00017457630019634962, 9.053650842361094e-7 ]
{ "id": 8, "code_window": [ "\t}\n", "});\n", "\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(CollapseDeepestExpandedLevelAction), 'Search: Collapse All', category);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ExpandAllAction), 'Search: Expand All', category);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ShowAllSymbolsAction, { primary: KeyMod.CtrlCmd | KeyCode.KEY_T }), 'Go to Symbol in Workspace...');\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "registry.registerWorkbenchAction(SyncActionDescriptor.from(CollapseDeepestExpandedLevelAction), 'Search: Collapse All', category.value);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ExpandAllAction), 'Search: Expand All', category.value);\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 643 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ export const enum ValidationState { OK = 0, Info = 1, Warning = 2, Error = 3, Fatal = 4 } export class ValidationStatus { private _state: ValidationState; constructor() { this._state = ValidationState.OK; } public get state(): ValidationState { return this._state; } public set state(value: ValidationState) { if (value > this._state) { this._state = value; } } public isOK(): boolean { return this._state === ValidationState.OK; } public isFatal(): boolean { return this._state === ValidationState.Fatal; } } export interface IProblemReporter { info(message: string): void; warn(message: string): void; error(message: string): void; fatal(message: string): void; status: ValidationStatus; } export abstract class Parser { private _problemReporter: IProblemReporter; constructor(problemReporter: IProblemReporter) { this._problemReporter = problemReporter; } public reset(): void { this._problemReporter.status.state = ValidationState.OK; } public get problemReporter(): IProblemReporter { return this._problemReporter; } public info(message: string): void { this._problemReporter.info(message); } public warn(message: string): void { this._problemReporter.warn(message); } public error(message: string): void { this._problemReporter.error(message); } public fatal(message: string): void { this._problemReporter.fatal(message); } }
src/vs/base/common/parsers.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.0001753789692884311, 0.00017315495642833412, 0.00016963267989922315, 0.00017335021402686834, 0.0000016244382550212322 ]
{ "id": 9, "code_window": [ "registry.registerWorkbenchAction(SyncActionDescriptor.from(ShowAllSymbolsAction, { primary: KeyMod.CtrlCmd | KeyCode.KEY_T }), 'Go to Symbol in Workspace...');\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ToggleSearchOnTypeAction), 'Search: Toggle Search on Type', category);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(RefreshAction), 'Search: Refresh', category);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ClearSearchResultsAction), 'Search: Clear Search Results', category);\n", "\n", "// Register Quick Access Handler\n", "const quickAccessRegistry = Registry.as<IQuickAccessRegistry>(QuickAccessExtensions.Quickaccess);\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "registry.registerWorkbenchAction(SyncActionDescriptor.from(ToggleSearchOnTypeAction), 'Search: Toggle Search on Type', category.value);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(RefreshAction), 'Search: Refresh', category.value);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ClearSearchResultsAction), 'Search: Clear Search Results', category.value);\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 646 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Action } from 'vs/base/common/actions'; import { distinct } from 'vs/base/common/arrays'; import { onUnexpectedError } from 'vs/base/common/errors'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import * as objects from 'vs/base/common/objects'; import * as platform from 'vs/base/common/platform'; import { dirname } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { ToggleCaseSensitiveKeybinding, ToggleRegexKeybinding, ToggleWholeWordKeybinding } from 'vs/editor/contrib/find/findModel'; import * as nls from 'vs/nls'; import { ICommandAction, MenuId, MenuRegistry, SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { CommandsRegistry, ICommandHandler } from 'vs/platform/commands/common/commands'; import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry'; import { ContextKeyExpr, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IFileService } from 'vs/platform/files/common/files'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { IListService, WorkbenchListFocusContextKey, WorkbenchObjectTree } from 'vs/platform/list/browser/listService'; import { Registry } from 'vs/platform/registry/common/platform'; import { defaultQuickAccessContextKeyValue } from 'vs/workbench/browser/quickaccess'; import { Extensions as ActionExtensions, IWorkbenchActionRegistry } from 'vs/workbench/common/actions'; import { Extensions as WorkbenchExtensions, IWorkbenchContribution, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions'; import { Extensions as ViewExtensions, IViewsRegistry, IViewContainersRegistry, ViewContainerLocation, IViewDescriptorService, IViewsService } from 'vs/workbench/common/views'; import { getMultiSelectedResources } from 'vs/workbench/contrib/files/browser/files'; import { ExplorerFolderContext, ExplorerRootContext, FilesExplorerFocusCondition, IExplorerService, VIEWLET_ID as VIEWLET_ID_FILES } from 'vs/workbench/contrib/files/common/files'; import { registerContributions as replaceContributions } from 'vs/workbench/contrib/search/browser/replaceContributions'; import { clearHistoryCommand, ClearSearchResultsAction, CloseReplaceAction, CollapseDeepestExpandedLevelAction, copyAllCommand, copyMatchCommand, copyPathCommand, FocusNextInputAction, FocusNextSearchResultAction, FocusPreviousInputAction, FocusPreviousSearchResultAction, focusSearchListCommand, getSearchView, openSearchView, OpenSearchViewletAction, RefreshAction, RemoveAction, ReplaceAction, ReplaceAllAction, ReplaceAllInFolderAction, ReplaceInFilesAction, toggleCaseSensitiveCommand, toggleRegexCommand, toggleWholeWordCommand, FindInFilesCommand, ToggleSearchOnTypeAction, ExpandAllAction } from 'vs/workbench/contrib/search/browser/searchActions'; import { SearchView } from 'vs/workbench/contrib/search/browser/searchView'; import { registerContributions as searchWidgetContributions } from 'vs/workbench/contrib/search/browser/searchWidget'; import * as Constants from 'vs/workbench/contrib/search/common/constants'; import * as SearchEditorConstants from 'vs/workbench/contrib/searchEditor/browser/constants'; import { getWorkspaceSymbols } from 'vs/workbench/contrib/search/common/search'; import { ISearchHistoryService, SearchHistoryService } from 'vs/workbench/contrib/search/common/searchHistoryService'; import { FileMatchOrMatch, ISearchWorkbenchService, RenderableMatch, SearchWorkbenchService, FileMatch, Match, FolderMatch } from 'vs/workbench/contrib/search/common/searchModel'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { VIEWLET_ID, VIEW_ID, SEARCH_EXCLUDE_CONFIG, SearchSortOrder } from 'vs/workbench/services/search/common/search'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { ExplorerViewPaneContainer } from 'vs/workbench/contrib/files/browser/explorerViewlet'; import { assertType, assertIsDefined } from 'vs/base/common/types'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { SearchEditor } from 'vs/workbench/contrib/searchEditor/browser/searchEditor'; import { ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { IQuickAccessRegistry, Extensions as QuickAccessExtensions } from 'vs/platform/quickinput/common/quickAccess'; import { SymbolsQuickAccessProvider } from 'vs/workbench/contrib/search/browser/symbolsQuickAccess'; import { AnythingQuickAccessProvider } from 'vs/workbench/contrib/search/browser/anythingQuickAccess'; import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { AbstractGotoLineQuickAccessProvider } from 'vs/editor/contrib/quickAccess/gotoLineQuickAccess'; import { GotoSymbolQuickAccessProvider } from 'vs/workbench/contrib/codeEditor/browser/quickaccess/gotoSymbolQuickAccess'; import { searchViewIcon } from 'vs/workbench/contrib/search/browser/searchIcons'; registerSingleton(ISearchWorkbenchService, SearchWorkbenchService, true); registerSingleton(ISearchHistoryService, SearchHistoryService, true); replaceContributions(); searchWidgetContributions(); const category = nls.localize('search', "Search"); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'workbench.action.search.toggleQueryDetails', weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or(Constants.SearchViewFocusedKey, SearchEditorConstants.InSearchEditor), primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_J, handler: accessor => { const contextService = accessor.get(IContextKeyService).getContext(document.activeElement); if (contextService.getValue(SearchEditorConstants.InSearchEditor.serialize())) { (accessor.get(IEditorService).activeEditorPane as SearchEditor).toggleQueryDetails(); } else if (contextService.getValue(Constants.SearchViewFocusedKey.serialize())) { const searchView = getSearchView(accessor.get(IViewsService)); assertIsDefined(searchView).toggleQueryDetails(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.FocusSearchFromResults, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FirstMatchFocusKey), primary: KeyMod.CtrlCmd | KeyCode.UpArrow, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { searchView.focusPreviousInputBox(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.OpenMatchToSide, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyMod.CtrlCmd | KeyCode.Enter, mac: { primary: KeyMod.WinCtrl | KeyCode.Enter }, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); searchView.open(<FileMatchOrMatch>tree.getFocus()[0], false, true, true); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CancelActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, WorkbenchListFocusContextKey), primary: KeyCode.Escape, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { searchView.cancelSearch(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.RemoveActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyCode.Delete, mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace, }, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(RemoveAction, tree, tree.getFocus()[0]!).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.MatchFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAction, tree, tree.getFocus()[0] as Match, searchView).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceAllInFileActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.FileFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter], handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAllAction, searchView, tree.getFocus()[0] as FileMatch).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceAllInFolderActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.FolderFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter], handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAllInFolderAction, tree, tree.getFocus()[0] as FolderMatch).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CloseReplaceWidgetActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceInputBoxFocusedKey), primary: KeyCode.Escape, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(CloseReplaceAction, Constants.CloseReplaceWidgetActionId, '').run(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FocusNextInputAction.ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or( ContextKeyExpr.and(SearchEditorConstants.InSearchEditor, Constants.InputBoxFocusedKey), ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.InputBoxFocusedKey)), primary: KeyMod.CtrlCmd | KeyCode.DownArrow, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(FocusNextInputAction, FocusNextInputAction.ID, '').run(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FocusPreviousInputAction.ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or( ContextKeyExpr.and(SearchEditorConstants.InSearchEditor, Constants.InputBoxFocusedKey), ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.InputBoxFocusedKey, Constants.SearchInputBoxFocusedKey.toNegated())), primary: KeyMod.CtrlCmd | KeyCode.UpArrow, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(FocusPreviousInputAction, FocusPreviousInputAction.ID, '').run(); } }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceActionId, title: ReplaceAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.MatchFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceAllInFolderActionId, title: ReplaceAllInFolderAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.FolderFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceAllInFileActionId, title: ReplaceAllAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.FileFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.RemoveActionId, title: RemoveAction.LABEL }, when: Constants.FileMatchOrMatchFocusKey, group: 'search', order: 2 }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CopyMatchCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.FileMatchOrMatchFocusKey, primary: KeyMod.CtrlCmd | KeyCode.KEY_C, handler: copyMatchCommand }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyMatchCommandId, title: nls.localize('copyMatchLabel', "Copy") }, when: Constants.FileMatchOrMatchFocusKey, group: 'search_2', order: 1 }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CopyPathCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.FileMatchOrFolderMatchWithResourceFocusKey, primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_C, win: { primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_C }, handler: copyPathCommand }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyPathCommandId, title: nls.localize('copyPathLabel', "Copy Path") }, when: Constants.FileMatchOrFolderMatchWithResourceFocusKey, group: 'search_2', order: 2 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyAllCommandId, title: nls.localize('copyAllLabel', "Copy All") }, when: Constants.HasSearchResults, group: 'search_2', order: 3 }); CommandsRegistry.registerCommand({ id: Constants.CopyAllCommandId, handler: copyAllCommand }); CommandsRegistry.registerCommand({ id: Constants.ClearSearchHistoryCommandId, handler: clearHistoryCommand }); CommandsRegistry.registerCommand({ id: Constants.RevealInSideBarForSearchResults, handler: (accessor, args: any) => { const viewletService = accessor.get(IViewletService); const explorerService = accessor.get(IExplorerService); const contextService = accessor.get(IWorkspaceContextService); const searchView = getSearchView(accessor.get(IViewsService)); if (!searchView) { return; } let fileMatch: FileMatch; if (!(args instanceof FileMatch)) { args = searchView.getControl().getFocus()[0]; } if (args instanceof FileMatch) { fileMatch = args; } else { return; } viewletService.openViewlet(VIEWLET_ID_FILES, false).then((viewlet) => { if (!viewlet) { return; } const explorerViewContainer = viewlet.getViewPaneContainer() as ExplorerViewPaneContainer; const uri = fileMatch.resource; if (uri && contextService.isInsideWorkspace(uri)) { const explorerView = explorerViewContainer.getExplorerView(); explorerView.setExpanded(true); explorerService.select(uri, true).then(() => explorerView.focus(), onUnexpectedError); } }); } }); const RevealInSideBarForSearchResultsCommand: ICommandAction = { id: Constants.RevealInSideBarForSearchResults, title: nls.localize('revealInSideBar', "Reveal in Side Bar") }; MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: RevealInSideBarForSearchResultsCommand, when: ContextKeyExpr.and(Constants.FileFocusKey, Constants.HasSearchResults), group: 'search_3', order: 1 }); const clearSearchHistoryLabel = nls.localize('clearSearchHistoryLabel', "Clear Search History"); const ClearSearchHistoryCommand: ICommandAction = { id: Constants.ClearSearchHistoryCommandId, title: clearSearchHistoryLabel, category }; MenuRegistry.addCommand(ClearSearchHistoryCommand); CommandsRegistry.registerCommand({ id: Constants.FocusSearchListCommandID, handler: focusSearchListCommand }); const focusSearchListCommandLabel = nls.localize('focusSearchListCommandLabel', "Focus List"); const FocusSearchListCommand: ICommandAction = { id: Constants.FocusSearchListCommandID, title: focusSearchListCommandLabel, category }; MenuRegistry.addCommand(FocusSearchListCommand); const searchInFolderCommand: ICommandHandler = (accessor, resource?: URI) => { const listService = accessor.get(IListService); const fileService = accessor.get(IFileService); const viewsService = accessor.get(IViewsService); const resources = getMultiSelectedResources(resource, listService, accessor.get(IEditorService), accessor.get(IExplorerService)); return openSearchView(viewsService, true).then(searchView => { if (resources && resources.length && searchView) { return fileService.resolveAll(resources.map(resource => ({ resource }))).then(results => { const folders: URI[] = []; results.forEach(result => { if (result.success && result.stat) { folders.push(result.stat.isDirectory ? result.stat.resource : dirname(result.stat.resource)); } }); searchView.searchInFolders(distinct(folders, folder => folder.toString())); }); } return undefined; }); }; const FIND_IN_FOLDER_ID = 'filesExplorer.findInFolder'; KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FIND_IN_FOLDER_ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(FilesExplorerFocusCondition, ExplorerFolderContext), primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_F, handler: searchInFolderCommand }); CommandsRegistry.registerCommand({ id: ClearSearchResultsAction.ID, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(ClearSearchResultsAction, ClearSearchResultsAction.ID, '').run(); } }); CommandsRegistry.registerCommand({ id: RefreshAction.ID, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(RefreshAction, RefreshAction.ID, '').run(); } }); const FIND_IN_WORKSPACE_ID = 'filesExplorer.findInWorkspace'; CommandsRegistry.registerCommand({ id: FIND_IN_WORKSPACE_ID, handler: (accessor) => { return openSearchView(accessor.get(IViewsService), true).then(searchView => { if (searchView) { searchView.searchInFolders(); } }); } }); MenuRegistry.appendMenuItem(MenuId.ExplorerContext, { group: '4_search', order: 10, command: { id: FIND_IN_FOLDER_ID, title: nls.localize('findInFolder', "Find in Folder...") }, when: ContextKeyExpr.and(ExplorerFolderContext) }); MenuRegistry.appendMenuItem(MenuId.ExplorerContext, { group: '4_search', order: 10, command: { id: FIND_IN_WORKSPACE_ID, title: nls.localize('findInWorkspace', "Find in Workspace...") }, when: ContextKeyExpr.and(ExplorerRootContext, ExplorerFolderContext.toNegated()) }); class ShowAllSymbolsAction extends Action { static readonly ID = 'workbench.action.showAllSymbols'; static readonly LABEL = nls.localize('showTriggerActions', "Go to Symbol in Workspace..."); static readonly ALL_SYMBOLS_PREFIX = '#'; constructor( actionId: string, actionLabel: string, @IQuickInputService private readonly quickInputService: IQuickInputService ) { super(actionId, actionLabel); } async run(): Promise<void> { this.quickInputService.quickAccess.show(ShowAllSymbolsAction.ALL_SYMBOLS_PREFIX); } } const viewContainer = Registry.as<IViewContainersRegistry>(ViewExtensions.ViewContainersRegistry).registerViewContainer({ id: VIEWLET_ID, name: nls.localize('name', "Search"), ctorDescriptor: new SyncDescriptor(ViewPaneContainer, [VIEWLET_ID, { mergeViewWithContainerWhenSingleView: true, donotShowContainerTitleWhenMergedWithContainer: true }]), hideIfEmpty: true, icon: searchViewIcon.classNames, order: 1 }, ViewContainerLocation.Sidebar); const viewDescriptor = { id: VIEW_ID, containerIcon: 'codicon-search', name: nls.localize('search', "Search"), ctorDescriptor: new SyncDescriptor(SearchView), canToggleVisibility: false, canMoveView: true }; // Register search default location to sidebar Registry.as<IViewsRegistry>(ViewExtensions.ViewsRegistry).registerViews([viewDescriptor], viewContainer); // Migrate search location setting to new model class RegisterSearchViewContribution implements IWorkbenchContribution { constructor( @IConfigurationService configurationService: IConfigurationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService ) { const data = configurationService.inspect('search.location'); if (data.value === 'panel') { viewDescriptorService.moveViewToLocation(viewDescriptor, ViewContainerLocation.Panel); } if (data.userValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER); } if (data.userLocalValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER_LOCAL); } if (data.userRemoteValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER_REMOTE); } if (data.workspaceFolderValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.WORKSPACE_FOLDER); } if (data.workspaceValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.WORKSPACE); } } } Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(RegisterSearchViewContribution, LifecyclePhase.Starting); // Actions const registry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions); // Show Search and Find in Files are redundant, but we can't break keybindings by removing one. So it's the same action, same keybinding, registered to different IDs. // Show Search 'when' is redundant but if the two conflict with exactly the same keybinding and 'when' clause, then they can show up as "unbound" - #51780 registry.registerWorkbenchAction(SyncActionDescriptor.from(OpenSearchViewletAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_F }, Constants.SearchViewVisibleKey.toNegated()), 'View: Show Search', nls.localize('view', "View")); KeybindingsRegistry.registerCommandAndKeybindingRule({ description: { description: nls.localize('findInFiles.description', "Open the search viewlet"), args: [ { name: nls.localize('findInFiles.args', "A set of options for the search viewlet"), schema: { type: 'object', properties: { query: { 'type': 'string' }, replace: { 'type': 'string' }, triggerSearch: { 'type': 'boolean' }, filesToInclude: { 'type': 'string' }, filesToExclude: { 'type': 'string' }, isRegex: { 'type': 'boolean' }, isCaseSensitive: { 'type': 'boolean' }, matchWholeWord: { 'type': 'boolean' }, } } }, ] }, id: Constants.FindInFilesActionId, weight: KeybindingWeight.WorkbenchContrib, when: null, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_F, handler: FindInFilesCommand }); MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: Constants.FindInFilesActionId, title: { value: nls.localize('findInFiles', "Find in Files"), original: 'Find in Files' }, category } }); MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { group: '4_find_global', command: { id: Constants.FindInFilesActionId, title: nls.localize({ key: 'miFindInFiles', comment: ['&& denotes a mnemonic'] }, "Find &&in Files") }, order: 1 }); registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusNextSearchResultAction, { primary: KeyCode.F4 }), 'Focus Next Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor)); registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusPreviousSearchResultAction, { primary: KeyMod.Shift | KeyCode.F4 }), 'Focus Previous Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor)); registry.registerWorkbenchAction(SyncActionDescriptor.from(ReplaceInFilesAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_H }), 'Replace in Files', category); MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { group: '4_find_global', command: { id: ReplaceInFilesAction.ID, title: nls.localize({ key: 'miReplaceInFiles', comment: ['&& denotes a mnemonic'] }, "Replace &&in Files") }, order: 2 }); if (platform.isMacintosh) { // Register this with a more restrictive `when` on mac to avoid conflict with "copy path" KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleCaseSensitiveCommandId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewFocusedKey, Constants.FileMatchOrFolderMatchFocusKey.toNegated()), handler: toggleCaseSensitiveCommand }, ToggleCaseSensitiveKeybinding)); } else { KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleCaseSensitiveCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleCaseSensitiveCommand }, ToggleCaseSensitiveKeybinding)); } KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleWholeWordCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleWholeWordCommand }, ToggleWholeWordKeybinding)); KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleRegexCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleRegexCommand }, ToggleRegexKeybinding)); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.AddCursorsAtSearchResults, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_L, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); searchView.openEditorWithMultiCursor(<FileMatchOrMatch>tree.getFocus()[0]); } } }); registry.registerWorkbenchAction(SyncActionDescriptor.from(CollapseDeepestExpandedLevelAction), 'Search: Collapse All', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ExpandAllAction), 'Search: Expand All', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ShowAllSymbolsAction, { primary: KeyMod.CtrlCmd | KeyCode.KEY_T }), 'Go to Symbol in Workspace...'); registry.registerWorkbenchAction(SyncActionDescriptor.from(ToggleSearchOnTypeAction), 'Search: Toggle Search on Type', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(RefreshAction), 'Search: Refresh', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ClearSearchResultsAction), 'Search: Clear Search Results', category); // Register Quick Access Handler const quickAccessRegistry = Registry.as<IQuickAccessRegistry>(QuickAccessExtensions.Quickaccess); quickAccessRegistry.registerQuickAccessProvider({ ctor: AnythingQuickAccessProvider, prefix: AnythingQuickAccessProvider.PREFIX, placeholder: nls.localize('anythingQuickAccessPlaceholder', "Search files by name (append {0} to go to line or {1} to go to symbol)", AbstractGotoLineQuickAccessProvider.PREFIX, GotoSymbolQuickAccessProvider.PREFIX), contextKey: defaultQuickAccessContextKeyValue, helpEntries: [{ description: nls.localize('anythingQuickAccess', "Go to File"), needsEditor: false }] }); quickAccessRegistry.registerQuickAccessProvider({ ctor: SymbolsQuickAccessProvider, prefix: SymbolsQuickAccessProvider.PREFIX, placeholder: nls.localize('symbolsQuickAccessPlaceholder', "Type the name of a symbol to open."), contextKey: 'inWorkspaceSymbolsPicker', helpEntries: [{ description: nls.localize('symbolsQuickAccess', "Go to Symbol in Workspace"), needsEditor: false }] }); // Configuration const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration); configurationRegistry.registerConfiguration({ id: 'search', order: 13, title: nls.localize('searchConfigurationTitle', "Search"), type: 'object', properties: { [SEARCH_EXCLUDE_CONFIG]: { type: 'object', markdownDescription: nls.localize('exclude', "Configure glob patterns for excluding files and folders in fulltext searches and quick open. Inherits all glob patterns from the `#files.exclude#` setting. Read more about glob patterns [here](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options)."), default: { '**/node_modules': true, '**/bower_components': true, '**/*.code-search': true }, additionalProperties: { anyOf: [ { type: 'boolean', description: nls.localize('exclude.boolean', "The glob pattern to match file paths against. Set to true or false to enable or disable the pattern."), }, { type: 'object', properties: { when: { type: 'string', // expression ({ "**/*.js": { "when": "$(basename).js" } }) pattern: '\\w*\\$\\(basename\\)\\w*', default: '$(basename).ext', description: nls.localize('exclude.when', 'Additional check on the siblings of a matching file. Use $(basename) as variable for the matching file name.') } } } ] }, scope: ConfigurationScope.RESOURCE }, 'search.useRipgrep': { type: 'boolean', description: nls.localize('useRipgrep', "This setting is deprecated and now falls back on \"search.usePCRE2\"."), deprecationMessage: nls.localize('useRipgrepDeprecated', "Deprecated. Consider \"search.usePCRE2\" for advanced regex feature support."), default: true }, 'search.maintainFileSearchCache': { type: 'boolean', description: nls.localize('search.maintainFileSearchCache', "When enabled, the searchService process will be kept alive instead of being shut down after an hour of inactivity. This will keep the file search cache in memory."), default: false }, 'search.useIgnoreFiles': { type: 'boolean', markdownDescription: nls.localize('useIgnoreFiles', "Controls whether to use `.gitignore` and `.ignore` files when searching for files."), default: true, scope: ConfigurationScope.RESOURCE }, 'search.useGlobalIgnoreFiles': { type: 'boolean', markdownDescription: nls.localize('useGlobalIgnoreFiles', "Controls whether to use global `.gitignore` and `.ignore` files when searching for files."), default: false, scope: ConfigurationScope.RESOURCE }, 'search.quickOpen.includeSymbols': { type: 'boolean', description: nls.localize('search.quickOpen.includeSymbols', "Whether to include results from a global symbol search in the file results for Quick Open."), default: false }, 'search.quickOpen.includeHistory': { type: 'boolean', description: nls.localize('search.quickOpen.includeHistory', "Whether to include results from recently opened files in the file results for Quick Open."), default: true }, 'search.quickOpen.history.filterSortOrder': { 'type': 'string', 'enum': ['default', 'recency'], 'default': 'default', 'enumDescriptions': [ nls.localize('filterSortOrder.default', 'History entries are sorted by relevance based on the filter value used. More relevant entries appear first.'), nls.localize('filterSortOrder.recency', 'History entries are sorted by recency. More recently opened entries appear first.') ], 'description': nls.localize('filterSortOrder', "Controls sorting order of editor history in quick open when filtering.") }, 'search.followSymlinks': { type: 'boolean', description: nls.localize('search.followSymlinks', "Controls whether to follow symlinks while searching."), default: true }, 'search.smartCase': { type: 'boolean', description: nls.localize('search.smartCase', "Search case-insensitively if the pattern is all lowercase, otherwise, search case-sensitively."), default: false }, 'search.globalFindClipboard': { type: 'boolean', default: false, description: nls.localize('search.globalFindClipboard', "Controls whether the search view should read or modify the shared find clipboard on macOS."), included: platform.isMacintosh }, 'search.location': { type: 'string', enum: ['sidebar', 'panel'], default: 'sidebar', description: nls.localize('search.location', "Controls whether the search will be shown as a view in the sidebar or as a panel in the panel area for more horizontal space."), deprecationMessage: nls.localize('search.location.deprecationMessage', "This setting is deprecated. Please use drag and drop instead by dragging the search icon.") }, 'search.collapseResults': { type: 'string', enum: ['auto', 'alwaysCollapse', 'alwaysExpand'], enumDescriptions: [ nls.localize('search.collapseResults.auto', "Files with less than 10 results are expanded. Others are collapsed."), '', '' ], default: 'alwaysExpand', description: nls.localize('search.collapseAllResults', "Controls whether the search results will be collapsed or expanded."), }, 'search.useReplacePreview': { type: 'boolean', default: true, description: nls.localize('search.useReplacePreview', "Controls whether to open Replace Preview when selecting or replacing a match."), }, 'search.showLineNumbers': { type: 'boolean', default: false, description: nls.localize('search.showLineNumbers', "Controls whether to show line numbers for search results."), }, 'search.usePCRE2': { type: 'boolean', default: false, description: nls.localize('search.usePCRE2', "Whether to use the PCRE2 regex engine in text search. This enables using some advanced regex features like lookahead and backreferences. However, not all PCRE2 features are supported - only features that are also supported by JavaScript."), deprecationMessage: nls.localize('usePCRE2Deprecated', "Deprecated. PCRE2 will be used automatically when using regex features that are only supported by PCRE2."), }, 'search.actionsPosition': { type: 'string', enum: ['auto', 'right'], enumDescriptions: [ nls.localize('search.actionsPositionAuto', "Position the actionbar to the right when the search view is narrow, and immediately after the content when the search view is wide."), nls.localize('search.actionsPositionRight', "Always position the actionbar to the right."), ], default: 'auto', description: nls.localize('search.actionsPosition', "Controls the positioning of the actionbar on rows in the search view.") }, 'search.searchOnType': { type: 'boolean', default: true, description: nls.localize('search.searchOnType', "Search all files as you type.") }, 'search.seedWithNearestWord': { type: 'boolean', default: false, description: nls.localize('search.seedWithNearestWord', "Enable seeding search from the word nearest the cursor when the active editor has no selection.") }, 'search.seedOnFocus': { type: 'boolean', default: false, description: nls.localize('search.seedOnFocus', "Update workspace search query to the editor's selected text when focusing the search view. This happens either on click or when triggering the `workbench.views.search.focus` command.") }, 'search.searchOnTypeDebouncePeriod': { type: 'number', default: 300, markdownDescription: nls.localize('search.searchOnTypeDebouncePeriod', "When `#search.searchOnType#` is enabled, controls the timeout in milliseconds between a character being typed and the search starting. Has no effect when `search.searchOnType` is disabled.") }, 'search.searchEditor.doubleClickBehaviour': { type: 'string', enum: ['selectWord', 'goToLocation', 'openLocationToSide'], default: 'goToLocation', enumDescriptions: [ nls.localize('search.searchEditor.doubleClickBehaviour.selectWord', "Double clicking selects the word under the cursor."), nls.localize('search.searchEditor.doubleClickBehaviour.goToLocation', "Double clicking opens the result in the active editor group."), nls.localize('search.searchEditor.doubleClickBehaviour.openLocationToSide', "Double clicking opens the result in the editor group to the side, creating one if it does not yet exist."), ], markdownDescription: nls.localize('search.searchEditor.doubleClickBehaviour', "Configure effect of double clicking a result in a search editor.") }, 'search.searchEditor.reusePriorSearchConfiguration': { type: 'boolean', default: false, markdownDescription: nls.localize({ key: 'search.searchEditor.reusePriorSearchConfiguration', comment: ['"Search Editor" is a type that editor that can display search results. "includes, excludes, and flags" just refers to settings that affect search. For example, the "search.exclude" setting.'] }, "When enabled, new Search Editors will reuse the includes, excludes, and flags of the previously opened Search Editor") }, 'search.searchEditor.defaultNumberOfContextLines': { type: ['number', 'null'], default: 1, markdownDescription: nls.localize('search.searchEditor.defaultNumberOfContextLines', "The default number of surrounding context lines to use when creating new Search Editors. If using `#search.searchEditor.reusePriorSearchConfiguration#`, this can be set to `null` (empty) to use the prior Search Editor's configuration.") }, 'search.sortOrder': { 'type': 'string', 'enum': [SearchSortOrder.Default, SearchSortOrder.FileNames, SearchSortOrder.Type, SearchSortOrder.Modified, SearchSortOrder.CountDescending, SearchSortOrder.CountAscending], 'default': SearchSortOrder.Default, 'enumDescriptions': [ nls.localize('searchSortOrder.default', "Results are sorted by folder and file names, in alphabetical order."), nls.localize('searchSortOrder.filesOnly', "Results are sorted by file names ignoring folder order, in alphabetical order."), nls.localize('searchSortOrder.type', "Results are sorted by file extensions, in alphabetical order."), nls.localize('searchSortOrder.modified', "Results are sorted by file last modified date, in descending order."), nls.localize('searchSortOrder.countDescending', "Results are sorted by count per file, in descending order."), nls.localize('searchSortOrder.countAscending', "Results are sorted by count per file, in ascending order.") ], 'description': nls.localize('search.sortOrder', "Controls sorting order of search results.") }, } }); CommandsRegistry.registerCommand('_executeWorkspaceSymbolProvider', function (accessor, ...args) { const [query] = args; assertType(typeof query === 'string'); return getWorkspaceSymbols(query); }); // View menu MenuRegistry.appendMenuItem(MenuId.MenubarViewMenu, { group: '3_views', command: { id: VIEWLET_ID, title: nls.localize({ key: 'miViewSearch', comment: ['&& denotes a mnemonic'] }, "&&Search") }, order: 2 }); // Go to menu MenuRegistry.appendMenuItem(MenuId.MenubarGoMenu, { group: '3_global_nav', command: { id: 'workbench.action.showAllSymbols', title: nls.localize({ key: 'miGotoSymbolInWorkspace', comment: ['&& denotes a mnemonic'] }, "Go to Symbol in &&Workspace...") }, order: 2 });
src/vs/workbench/contrib/search/browser/search.contribution.ts
1
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.44718897342681885, 0.009282400831580162, 0.00016149897419381887, 0.00017121495329774916, 0.059924595057964325 ]
{ "id": 9, "code_window": [ "registry.registerWorkbenchAction(SyncActionDescriptor.from(ShowAllSymbolsAction, { primary: KeyMod.CtrlCmd | KeyCode.KEY_T }), 'Go to Symbol in Workspace...');\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ToggleSearchOnTypeAction), 'Search: Toggle Search on Type', category);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(RefreshAction), 'Search: Refresh', category);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ClearSearchResultsAction), 'Search: Clear Search Results', category);\n", "\n", "// Register Quick Access Handler\n", "const quickAccessRegistry = Registry.as<IQuickAccessRegistry>(QuickAccessExtensions.Quickaccess);\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "registry.registerWorkbenchAction(SyncActionDescriptor.from(ToggleSearchOnTypeAction), 'Search: Toggle Search on Type', category.value);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(RefreshAction), 'Search: Refresh', category.value);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ClearSearchResultsAction), 'Search: Clear Search Results', category.value);\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 646 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable } from 'vs/base/common/lifecycle'; import { join } from 'vs/base/common/path'; import { INativeEnvironmentService } from 'vs/platform/environment/node/environmentService'; import { IExtensionManagementService, DidInstallExtensionEvent, DidUninstallExtensionEvent } from 'vs/platform/extensionManagement/common/extensionManagement'; import { MANIFEST_CACHE_FOLDER, USER_MANIFEST_CACHE_FILE } from 'vs/platform/extensions/common/extensions'; import * as pfs from 'vs/base/node/pfs'; export class ExtensionsManifestCache extends Disposable { private extensionsManifestCache = join(this.environmentService.userDataPath, MANIFEST_CACHE_FOLDER, USER_MANIFEST_CACHE_FILE); constructor( private readonly environmentService: INativeEnvironmentService, extensionsManagementService: IExtensionManagementService ) { super(); this._register(extensionsManagementService.onDidInstallExtension(e => this.onDidInstallExtension(e))); this._register(extensionsManagementService.onDidUninstallExtension(e => this.onDidUnInstallExtension(e))); } private onDidInstallExtension(e: DidInstallExtensionEvent): void { if (!e.error) { this.invalidate(); } } private onDidUnInstallExtension(e: DidUninstallExtensionEvent): void { if (!e.error) { this.invalidate(); } } invalidate(): void { pfs.rimraf(this.extensionsManifestCache, pfs.RimRafMode.MOVE).then(() => { }, () => { }); } }
src/vs/platform/extensionManagement/node/extensionsManifestCache.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.0001740973675623536, 0.00017229831428267062, 0.00016856947331689298, 0.00017338403267785907, 0.000002109262140947976 ]
{ "id": 9, "code_window": [ "registry.registerWorkbenchAction(SyncActionDescriptor.from(ShowAllSymbolsAction, { primary: KeyMod.CtrlCmd | KeyCode.KEY_T }), 'Go to Symbol in Workspace...');\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ToggleSearchOnTypeAction), 'Search: Toggle Search on Type', category);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(RefreshAction), 'Search: Refresh', category);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ClearSearchResultsAction), 'Search: Clear Search Results', category);\n", "\n", "// Register Quick Access Handler\n", "const quickAccessRegistry = Registry.as<IQuickAccessRegistry>(QuickAccessExtensions.Quickaccess);\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "registry.registerWorkbenchAction(SyncActionDescriptor.from(ToggleSearchOnTypeAction), 'Search: Toggle Search on Type', category.value);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(RefreshAction), 'Search: Refresh', category.value);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ClearSearchResultsAction), 'Search: Clear Search Results', category.value);\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 646 }
/*--------------------------------------------------------------------------------------------- * 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!./media/scm'; import { localize } from 'vs/nls'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { VIEWLET_ID, ISCMService } from 'vs/workbench/contrib/scm/common/scm'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IContextViewService, IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { SCMRepositoryMenus } from './menus'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IViewDescriptorService } from 'vs/workbench/common/views'; import { ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { addClass } from 'vs/base/browser/dom'; export class SCMViewPaneContainer extends ViewPaneContainer { constructor( @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService, @ITelemetryService telemetryService: ITelemetryService, @ISCMService protected scmService: ISCMService, @IInstantiationService protected instantiationService: IInstantiationService, @IContextViewService protected contextViewService: IContextViewService, @IKeybindingService protected keybindingService: IKeybindingService, @INotificationService protected notificationService: INotificationService, @IContextMenuService protected contextMenuService: IContextMenuService, @IThemeService protected themeService: IThemeService, @ICommandService protected commandService: ICommandService, @IStorageService storageService: IStorageService, @IConfigurationService configurationService: IConfigurationService, @IExtensionService extensionService: IExtensionService, @IWorkspaceContextService protected contextService: IWorkspaceContextService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService ) { super(VIEWLET_ID, { mergeViewWithContainerWhenSingleView: true }, instantiationService, configurationService, layoutService, contextMenuService, telemetryService, extensionService, themeService, storageService, contextService, viewDescriptorService); const menus = instantiationService.createInstance(SCMRepositoryMenus, undefined); this._register(menus); this._register(menus.onDidChangeTitle(this.updateTitleArea, this)); } create(parent: HTMLElement): void { super.create(parent); addClass(parent, 'scm-viewlet'); } getOptimalWidth(): number { return 400; } getTitle(): string { return localize('source control', "Source Control"); } }
src/vs/workbench/contrib/scm/browser/scmViewPaneContainer.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00017558209947310388, 0.0001709792559267953, 0.00016399926971644163, 0.00017298852617386729, 0.000004050563347846037 ]
{ "id": 9, "code_window": [ "registry.registerWorkbenchAction(SyncActionDescriptor.from(ShowAllSymbolsAction, { primary: KeyMod.CtrlCmd | KeyCode.KEY_T }), 'Go to Symbol in Workspace...');\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ToggleSearchOnTypeAction), 'Search: Toggle Search on Type', category);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(RefreshAction), 'Search: Refresh', category);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ClearSearchResultsAction), 'Search: Clear Search Results', category);\n", "\n", "// Register Quick Access Handler\n", "const quickAccessRegistry = Registry.as<IQuickAccessRegistry>(QuickAccessExtensions.Quickaccess);\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "registry.registerWorkbenchAction(SyncActionDescriptor.from(ToggleSearchOnTypeAction), 'Search: Toggle Search on Type', category.value);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(RefreshAction), 'Search: Refresh', category.value);\n", "registry.registerWorkbenchAction(SyncActionDescriptor.from(ClearSearchResultsAction), 'Search: Clear Search Results', category.value);\n" ], "file_path": "src/vs/workbench/contrib/search/browser/search.contribution.ts", "type": "replace", "edit_start_line_idx": 646 }
/*--------------------------------------------------------------------------------------------- * 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 { onUnexpectedError } from 'vs/base/common/errors'; import { Selection } from 'vs/editor/common/core/selection'; import { EndOfLineSequence, ICursorStateComputer, IIdentifiedSingleEditOperation, IValidEditOperation, ITextModel } from 'vs/editor/common/model'; import { TextModel } from 'vs/editor/common/model/textModel'; import { IUndoRedoService, IResourceUndoRedoElement, UndoRedoElementType, IWorkspaceUndoRedoElement } from 'vs/platform/undoRedo/common/undoRedo'; import { URI } from 'vs/base/common/uri'; import { TextChange, compressConsecutiveTextChanges } from 'vs/editor/common/model/textChange'; import * as buffer from 'vs/base/common/buffer'; import { IDisposable } from 'vs/base/common/lifecycle'; function uriGetComparisonKey(resource: URI): string { return resource.toString(); } class SingleModelEditStackData { public static create(model: ITextModel, beforeCursorState: Selection[] | null): SingleModelEditStackData { const alternativeVersionId = model.getAlternativeVersionId(); const eol = getModelEOL(model); return new SingleModelEditStackData( alternativeVersionId, alternativeVersionId, eol, eol, beforeCursorState, beforeCursorState, [] ); } constructor( public readonly beforeVersionId: number, public afterVersionId: number, public readonly beforeEOL: EndOfLineSequence, public afterEOL: EndOfLineSequence, public readonly beforeCursorState: Selection[] | null, public afterCursorState: Selection[] | null, public changes: TextChange[] ) { } public append(model: ITextModel, textChanges: TextChange[], afterEOL: EndOfLineSequence, afterVersionId: number, afterCursorState: Selection[] | null): void { if (textChanges.length > 0) { this.changes = compressConsecutiveTextChanges(this.changes, textChanges); } this.afterEOL = afterEOL; this.afterVersionId = afterVersionId; this.afterCursorState = afterCursorState; } private static _writeSelectionsSize(selections: Selection[] | null): number { return 4 + 4 * 4 * (selections ? selections.length : 0); } private static _writeSelections(b: Uint8Array, selections: Selection[] | null, offset: number): number { buffer.writeUInt32BE(b, (selections ? selections.length : 0), offset); offset += 4; if (selections) { for (const selection of selections) { buffer.writeUInt32BE(b, selection.selectionStartLineNumber, offset); offset += 4; buffer.writeUInt32BE(b, selection.selectionStartColumn, offset); offset += 4; buffer.writeUInt32BE(b, selection.positionLineNumber, offset); offset += 4; buffer.writeUInt32BE(b, selection.positionColumn, offset); offset += 4; } } return offset; } private static _readSelections(b: Uint8Array, offset: number, dest: Selection[]): number { const count = buffer.readUInt32BE(b, offset); offset += 4; for (let i = 0; i < count; i++) { const selectionStartLineNumber = buffer.readUInt32BE(b, offset); offset += 4; const selectionStartColumn = buffer.readUInt32BE(b, offset); offset += 4; const positionLineNumber = buffer.readUInt32BE(b, offset); offset += 4; const positionColumn = buffer.readUInt32BE(b, offset); offset += 4; dest.push(new Selection(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn)); } return offset; } public serialize(): ArrayBuffer { let necessarySize = ( + 4 // beforeVersionId + 4 // afterVersionId + 1 // beforeEOL + 1 // afterEOL + SingleModelEditStackData._writeSelectionsSize(this.beforeCursorState) + SingleModelEditStackData._writeSelectionsSize(this.afterCursorState) + 4 // change count ); for (const change of this.changes) { necessarySize += change.writeSize(); } const b = new Uint8Array(necessarySize); let offset = 0; buffer.writeUInt32BE(b, this.beforeVersionId, offset); offset += 4; buffer.writeUInt32BE(b, this.afterVersionId, offset); offset += 4; buffer.writeUInt8(b, this.beforeEOL, offset); offset += 1; buffer.writeUInt8(b, this.afterEOL, offset); offset += 1; offset = SingleModelEditStackData._writeSelections(b, this.beforeCursorState, offset); offset = SingleModelEditStackData._writeSelections(b, this.afterCursorState, offset); buffer.writeUInt32BE(b, this.changes.length, offset); offset += 4; for (const change of this.changes) { offset = change.write(b, offset); } return b.buffer; } public static deserialize(source: ArrayBuffer): SingleModelEditStackData { const b = new Uint8Array(source); let offset = 0; const beforeVersionId = buffer.readUInt32BE(b, offset); offset += 4; const afterVersionId = buffer.readUInt32BE(b, offset); offset += 4; const beforeEOL = buffer.readUInt8(b, offset); offset += 1; const afterEOL = buffer.readUInt8(b, offset); offset += 1; const beforeCursorState: Selection[] = []; offset = SingleModelEditStackData._readSelections(b, offset, beforeCursorState); const afterCursorState: Selection[] = []; offset = SingleModelEditStackData._readSelections(b, offset, afterCursorState); const changeCount = buffer.readUInt32BE(b, offset); offset += 4; const changes: TextChange[] = []; for (let i = 0; i < changeCount; i++) { offset = TextChange.read(b, offset, changes); } return new SingleModelEditStackData( beforeVersionId, afterVersionId, beforeEOL, afterEOL, beforeCursorState, afterCursorState, changes ); } } export interface IUndoRedoDelegate { prepareUndoRedo(element: MultiModelEditStackElement): Promise<IDisposable> | IDisposable | void; } export class SingleModelEditStackElement implements IResourceUndoRedoElement { public model: ITextModel | URI; private _data: SingleModelEditStackData | ArrayBuffer; public get type(): UndoRedoElementType.Resource { return UndoRedoElementType.Resource; } public get resource(): URI { if (URI.isUri(this.model)) { return this.model; } return this.model.uri; } public get label(): string { return nls.localize('edit', "Typing"); } constructor(model: ITextModel, beforeCursorState: Selection[] | null) { this.model = model; this._data = SingleModelEditStackData.create(model, beforeCursorState); } public toString(): string { const data = (this._data instanceof SingleModelEditStackData ? this._data : SingleModelEditStackData.deserialize(this._data)); return data.changes.map(change => change.toString()).join(', '); } public matchesResource(resource: URI): boolean { const uri = (URI.isUri(this.model) ? this.model : this.model.uri); return (uri.toString() === resource.toString()); } public setModel(model: ITextModel | URI): void { this.model = model; } public canAppend(model: ITextModel): boolean { return (this.model === model && this._data instanceof SingleModelEditStackData); } public append(model: ITextModel, textChanges: TextChange[], afterEOL: EndOfLineSequence, afterVersionId: number, afterCursorState: Selection[] | null): void { if (this._data instanceof SingleModelEditStackData) { this._data.append(model, textChanges, afterEOL, afterVersionId, afterCursorState); } } public close(): void { if (this._data instanceof SingleModelEditStackData) { this._data = this._data.serialize(); } } public undo(): void { if (URI.isUri(this.model)) { // don't have a model throw new Error(`Invalid SingleModelEditStackElement`); } if (this._data instanceof SingleModelEditStackData) { this._data = this._data.serialize(); } const data = SingleModelEditStackData.deserialize(this._data); this.model._applyUndo(data.changes, data.beforeEOL, data.beforeVersionId, data.beforeCursorState); } public redo(): void { if (URI.isUri(this.model)) { // don't have a model throw new Error(`Invalid SingleModelEditStackElement`); } if (this._data instanceof SingleModelEditStackData) { this._data = this._data.serialize(); } const data = SingleModelEditStackData.deserialize(this._data); this.model._applyRedo(data.changes, data.afterEOL, data.afterVersionId, data.afterCursorState); } public heapSize(): number { if (this._data instanceof SingleModelEditStackData) { this._data = this._data.serialize(); } return this._data.byteLength + 168/*heap overhead*/; } } export class MultiModelEditStackElement implements IWorkspaceUndoRedoElement { public readonly type = UndoRedoElementType.Workspace; public readonly label: string; private _isOpen: boolean; private readonly _editStackElementsArr: SingleModelEditStackElement[]; private readonly _editStackElementsMap: Map<string, SingleModelEditStackElement>; private _delegate: IUndoRedoDelegate | null; public get resources(): readonly URI[] { return this._editStackElementsArr.map(editStackElement => editStackElement.resource); } constructor( label: string, editStackElements: SingleModelEditStackElement[] ) { this.label = label; this._isOpen = true; this._editStackElementsArr = editStackElements.slice(0); this._editStackElementsMap = new Map<string, SingleModelEditStackElement>(); for (const editStackElement of this._editStackElementsArr) { const key = uriGetComparisonKey(editStackElement.resource); this._editStackElementsMap.set(key, editStackElement); } this._delegate = null; } public setDelegate(delegate: IUndoRedoDelegate): void { this._delegate = delegate; } public prepareUndoRedo(): Promise<IDisposable> | IDisposable | void { if (this._delegate) { return this._delegate.prepareUndoRedo(this); } } public getMissingModels(): URI[] { const result: URI[] = []; for (const editStackElement of this._editStackElementsArr) { if (URI.isUri(editStackElement.model)) { result.push(editStackElement.model); } } return result; } public matchesResource(resource: URI): boolean { const key = uriGetComparisonKey(resource); return (this._editStackElementsMap.has(key)); } public setModel(model: ITextModel | URI): void { const key = uriGetComparisonKey(URI.isUri(model) ? model : model.uri); if (this._editStackElementsMap.has(key)) { this._editStackElementsMap.get(key)!.setModel(model); } } public canAppend(model: ITextModel): boolean { if (!this._isOpen) { return false; } const key = uriGetComparisonKey(model.uri); if (this._editStackElementsMap.has(key)) { const editStackElement = this._editStackElementsMap.get(key)!; return editStackElement.canAppend(model); } return false; } public append(model: ITextModel, textChanges: TextChange[], afterEOL: EndOfLineSequence, afterVersionId: number, afterCursorState: Selection[] | null): void { const key = uriGetComparisonKey(model.uri); const editStackElement = this._editStackElementsMap.get(key)!; editStackElement.append(model, textChanges, afterEOL, afterVersionId, afterCursorState); } public close(): void { this._isOpen = false; } public undo(): void { this._isOpen = false; for (const editStackElement of this._editStackElementsArr) { editStackElement.undo(); } } public redo(): void { for (const editStackElement of this._editStackElementsArr) { editStackElement.redo(); } } public heapSize(resource: URI): number { const key = uriGetComparisonKey(resource); if (this._editStackElementsMap.has(key)) { const editStackElement = this._editStackElementsMap.get(key)!; return editStackElement.heapSize(); } return 0; } public split(): IResourceUndoRedoElement[] { return this._editStackElementsArr; } } export type EditStackElement = SingleModelEditStackElement | MultiModelEditStackElement; function getModelEOL(model: ITextModel): EndOfLineSequence { const eol = model.getEOL(); if (eol === '\n') { return EndOfLineSequence.LF; } else { return EndOfLineSequence.CRLF; } } export function isEditStackElement(element: IResourceUndoRedoElement | IWorkspaceUndoRedoElement | null): element is EditStackElement { if (!element) { return false; } return ((element instanceof SingleModelEditStackElement) || (element instanceof MultiModelEditStackElement)); } export class EditStack { private readonly _model: TextModel; private readonly _undoRedoService: IUndoRedoService; constructor(model: TextModel, undoRedoService: IUndoRedoService) { this._model = model; this._undoRedoService = undoRedoService; } public pushStackElement(): void { const lastElement = this._undoRedoService.getLastElement(this._model.uri); if (isEditStackElement(lastElement)) { lastElement.close(); } } public clear(): void { this._undoRedoService.removeElements(this._model.uri); } private _getOrCreateEditStackElement(beforeCursorState: Selection[] | null): EditStackElement { const lastElement = this._undoRedoService.getLastElement(this._model.uri); if (isEditStackElement(lastElement) && lastElement.canAppend(this._model)) { return lastElement; } const newElement = new SingleModelEditStackElement(this._model, beforeCursorState); this._undoRedoService.pushElement(newElement); return newElement; } public pushEOL(eol: EndOfLineSequence): void { const editStackElement = this._getOrCreateEditStackElement(null); this._model.setEOL(eol); editStackElement.append(this._model, [], getModelEOL(this._model), this._model.getAlternativeVersionId(), null); } public pushEditOperation(beforeCursorState: Selection[] | null, editOperations: IIdentifiedSingleEditOperation[], cursorStateComputer: ICursorStateComputer | null): Selection[] | null { const editStackElement = this._getOrCreateEditStackElement(beforeCursorState); const inverseEditOperations = this._model.applyEdits(editOperations, true); const afterCursorState = EditStack._computeCursorState(cursorStateComputer, inverseEditOperations); const textChanges = inverseEditOperations.map((op, index) => ({ index: index, textChange: op.textChange })); textChanges.sort((a, b) => { if (a.textChange.oldPosition === b.textChange.oldPosition) { return a.index - b.index; } return a.textChange.oldPosition - b.textChange.oldPosition; }); editStackElement.append(this._model, textChanges.map(op => op.textChange), getModelEOL(this._model), this._model.getAlternativeVersionId(), afterCursorState); return afterCursorState; } private static _computeCursorState(cursorStateComputer: ICursorStateComputer | null, inverseEditOperations: IValidEditOperation[]): Selection[] | null { try { return cursorStateComputer ? cursorStateComputer(inverseEditOperations) : null; } catch (e) { onUnexpectedError(e); return null; } } }
src/vs/editor/common/model/editStack.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.0001787535147741437, 0.0001735823752824217, 0.00016643361595924944, 0.00017411363660357893, 0.0000027424132440501126 ]
{ "id": 10, "code_window": [ "import { IQuickAccessRegistry, Extensions as QuickAccessExtensions } from 'vs/platform/quickinput/common/quickAccess';\n", "import { TasksQuickAccessProvider } from 'vs/workbench/contrib/tasks/browser/tasksQuickAccess';\n", "\n", "let tasksCategory = nls.localize('tasksCategory', \"Tasks\");\n", "\n", "const workbenchRegistry = Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench);\n", "workbenchRegistry.registerWorkbenchContribution(RunAutomaticTasks, LifecyclePhase.Eventually);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "let tasksCategory = { value: nls.localize('tasksCategory', \"Tasks\"), original: 'Tasks' };\n" ], "file_path": "src/vs/workbench/contrib/tasks/browser/task.contribution.ts", "type": "replace", "edit_start_line_idx": 39 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Action } from 'vs/base/common/actions'; import { distinct } from 'vs/base/common/arrays'; import { onUnexpectedError } from 'vs/base/common/errors'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import * as objects from 'vs/base/common/objects'; import * as platform from 'vs/base/common/platform'; import { dirname } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { ToggleCaseSensitiveKeybinding, ToggleRegexKeybinding, ToggleWholeWordKeybinding } from 'vs/editor/contrib/find/findModel'; import * as nls from 'vs/nls'; import { ICommandAction, MenuId, MenuRegistry, SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { CommandsRegistry, ICommandHandler } from 'vs/platform/commands/common/commands'; import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry'; import { ContextKeyExpr, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IFileService } from 'vs/platform/files/common/files'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { IListService, WorkbenchListFocusContextKey, WorkbenchObjectTree } from 'vs/platform/list/browser/listService'; import { Registry } from 'vs/platform/registry/common/platform'; import { defaultQuickAccessContextKeyValue } from 'vs/workbench/browser/quickaccess'; import { Extensions as ActionExtensions, IWorkbenchActionRegistry } from 'vs/workbench/common/actions'; import { Extensions as WorkbenchExtensions, IWorkbenchContribution, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions'; import { Extensions as ViewExtensions, IViewsRegistry, IViewContainersRegistry, ViewContainerLocation, IViewDescriptorService, IViewsService } from 'vs/workbench/common/views'; import { getMultiSelectedResources } from 'vs/workbench/contrib/files/browser/files'; import { ExplorerFolderContext, ExplorerRootContext, FilesExplorerFocusCondition, IExplorerService, VIEWLET_ID as VIEWLET_ID_FILES } from 'vs/workbench/contrib/files/common/files'; import { registerContributions as replaceContributions } from 'vs/workbench/contrib/search/browser/replaceContributions'; import { clearHistoryCommand, ClearSearchResultsAction, CloseReplaceAction, CollapseDeepestExpandedLevelAction, copyAllCommand, copyMatchCommand, copyPathCommand, FocusNextInputAction, FocusNextSearchResultAction, FocusPreviousInputAction, FocusPreviousSearchResultAction, focusSearchListCommand, getSearchView, openSearchView, OpenSearchViewletAction, RefreshAction, RemoveAction, ReplaceAction, ReplaceAllAction, ReplaceAllInFolderAction, ReplaceInFilesAction, toggleCaseSensitiveCommand, toggleRegexCommand, toggleWholeWordCommand, FindInFilesCommand, ToggleSearchOnTypeAction, ExpandAllAction } from 'vs/workbench/contrib/search/browser/searchActions'; import { SearchView } from 'vs/workbench/contrib/search/browser/searchView'; import { registerContributions as searchWidgetContributions } from 'vs/workbench/contrib/search/browser/searchWidget'; import * as Constants from 'vs/workbench/contrib/search/common/constants'; import * as SearchEditorConstants from 'vs/workbench/contrib/searchEditor/browser/constants'; import { getWorkspaceSymbols } from 'vs/workbench/contrib/search/common/search'; import { ISearchHistoryService, SearchHistoryService } from 'vs/workbench/contrib/search/common/searchHistoryService'; import { FileMatchOrMatch, ISearchWorkbenchService, RenderableMatch, SearchWorkbenchService, FileMatch, Match, FolderMatch } from 'vs/workbench/contrib/search/common/searchModel'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { VIEWLET_ID, VIEW_ID, SEARCH_EXCLUDE_CONFIG, SearchSortOrder } from 'vs/workbench/services/search/common/search'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { ExplorerViewPaneContainer } from 'vs/workbench/contrib/files/browser/explorerViewlet'; import { assertType, assertIsDefined } from 'vs/base/common/types'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { SearchEditor } from 'vs/workbench/contrib/searchEditor/browser/searchEditor'; import { ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { IQuickAccessRegistry, Extensions as QuickAccessExtensions } from 'vs/platform/quickinput/common/quickAccess'; import { SymbolsQuickAccessProvider } from 'vs/workbench/contrib/search/browser/symbolsQuickAccess'; import { AnythingQuickAccessProvider } from 'vs/workbench/contrib/search/browser/anythingQuickAccess'; import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { AbstractGotoLineQuickAccessProvider } from 'vs/editor/contrib/quickAccess/gotoLineQuickAccess'; import { GotoSymbolQuickAccessProvider } from 'vs/workbench/contrib/codeEditor/browser/quickaccess/gotoSymbolQuickAccess'; import { searchViewIcon } from 'vs/workbench/contrib/search/browser/searchIcons'; registerSingleton(ISearchWorkbenchService, SearchWorkbenchService, true); registerSingleton(ISearchHistoryService, SearchHistoryService, true); replaceContributions(); searchWidgetContributions(); const category = nls.localize('search', "Search"); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'workbench.action.search.toggleQueryDetails', weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or(Constants.SearchViewFocusedKey, SearchEditorConstants.InSearchEditor), primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_J, handler: accessor => { const contextService = accessor.get(IContextKeyService).getContext(document.activeElement); if (contextService.getValue(SearchEditorConstants.InSearchEditor.serialize())) { (accessor.get(IEditorService).activeEditorPane as SearchEditor).toggleQueryDetails(); } else if (contextService.getValue(Constants.SearchViewFocusedKey.serialize())) { const searchView = getSearchView(accessor.get(IViewsService)); assertIsDefined(searchView).toggleQueryDetails(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.FocusSearchFromResults, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FirstMatchFocusKey), primary: KeyMod.CtrlCmd | KeyCode.UpArrow, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { searchView.focusPreviousInputBox(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.OpenMatchToSide, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyMod.CtrlCmd | KeyCode.Enter, mac: { primary: KeyMod.WinCtrl | KeyCode.Enter }, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); searchView.open(<FileMatchOrMatch>tree.getFocus()[0], false, true, true); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CancelActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, WorkbenchListFocusContextKey), primary: KeyCode.Escape, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { searchView.cancelSearch(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.RemoveActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyCode.Delete, mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace, }, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(RemoveAction, tree, tree.getFocus()[0]!).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.MatchFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAction, tree, tree.getFocus()[0] as Match, searchView).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceAllInFileActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.FileFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter], handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAllAction, searchView, tree.getFocus()[0] as FileMatch).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.ReplaceAllInFolderActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceActiveKey, Constants.FolderFocusKey), primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.KEY_1, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter], handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); accessor.get(IInstantiationService).createInstance(ReplaceAllInFolderAction, tree, tree.getFocus()[0] as FolderMatch).run(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CloseReplaceWidgetActionId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.ReplaceInputBoxFocusedKey), primary: KeyCode.Escape, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(CloseReplaceAction, Constants.CloseReplaceWidgetActionId, '').run(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FocusNextInputAction.ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or( ContextKeyExpr.and(SearchEditorConstants.InSearchEditor, Constants.InputBoxFocusedKey), ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.InputBoxFocusedKey)), primary: KeyMod.CtrlCmd | KeyCode.DownArrow, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(FocusNextInputAction, FocusNextInputAction.ID, '').run(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FocusPreviousInputAction.ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.or( ContextKeyExpr.and(SearchEditorConstants.InSearchEditor, Constants.InputBoxFocusedKey), ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.InputBoxFocusedKey, Constants.SearchInputBoxFocusedKey.toNegated())), primary: KeyMod.CtrlCmd | KeyCode.UpArrow, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(FocusPreviousInputAction, FocusPreviousInputAction.ID, '').run(); } }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceActionId, title: ReplaceAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.MatchFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceAllInFolderActionId, title: ReplaceAllInFolderAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.FolderFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.ReplaceAllInFileActionId, title: ReplaceAllAction.LABEL }, when: ContextKeyExpr.and(Constants.ReplaceActiveKey, Constants.FileFocusKey), group: 'search', order: 1 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.RemoveActionId, title: RemoveAction.LABEL }, when: Constants.FileMatchOrMatchFocusKey, group: 'search', order: 2 }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CopyMatchCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.FileMatchOrMatchFocusKey, primary: KeyMod.CtrlCmd | KeyCode.KEY_C, handler: copyMatchCommand }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyMatchCommandId, title: nls.localize('copyMatchLabel', "Copy") }, when: Constants.FileMatchOrMatchFocusKey, group: 'search_2', order: 1 }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.CopyPathCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.FileMatchOrFolderMatchWithResourceFocusKey, primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_C, win: { primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_C }, handler: copyPathCommand }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyPathCommandId, title: nls.localize('copyPathLabel', "Copy Path") }, when: Constants.FileMatchOrFolderMatchWithResourceFocusKey, group: 'search_2', order: 2 }); MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: { id: Constants.CopyAllCommandId, title: nls.localize('copyAllLabel', "Copy All") }, when: Constants.HasSearchResults, group: 'search_2', order: 3 }); CommandsRegistry.registerCommand({ id: Constants.CopyAllCommandId, handler: copyAllCommand }); CommandsRegistry.registerCommand({ id: Constants.ClearSearchHistoryCommandId, handler: clearHistoryCommand }); CommandsRegistry.registerCommand({ id: Constants.RevealInSideBarForSearchResults, handler: (accessor, args: any) => { const viewletService = accessor.get(IViewletService); const explorerService = accessor.get(IExplorerService); const contextService = accessor.get(IWorkspaceContextService); const searchView = getSearchView(accessor.get(IViewsService)); if (!searchView) { return; } let fileMatch: FileMatch; if (!(args instanceof FileMatch)) { args = searchView.getControl().getFocus()[0]; } if (args instanceof FileMatch) { fileMatch = args; } else { return; } viewletService.openViewlet(VIEWLET_ID_FILES, false).then((viewlet) => { if (!viewlet) { return; } const explorerViewContainer = viewlet.getViewPaneContainer() as ExplorerViewPaneContainer; const uri = fileMatch.resource; if (uri && contextService.isInsideWorkspace(uri)) { const explorerView = explorerViewContainer.getExplorerView(); explorerView.setExpanded(true); explorerService.select(uri, true).then(() => explorerView.focus(), onUnexpectedError); } }); } }); const RevealInSideBarForSearchResultsCommand: ICommandAction = { id: Constants.RevealInSideBarForSearchResults, title: nls.localize('revealInSideBar', "Reveal in Side Bar") }; MenuRegistry.appendMenuItem(MenuId.SearchContext, { command: RevealInSideBarForSearchResultsCommand, when: ContextKeyExpr.and(Constants.FileFocusKey, Constants.HasSearchResults), group: 'search_3', order: 1 }); const clearSearchHistoryLabel = nls.localize('clearSearchHistoryLabel', "Clear Search History"); const ClearSearchHistoryCommand: ICommandAction = { id: Constants.ClearSearchHistoryCommandId, title: clearSearchHistoryLabel, category }; MenuRegistry.addCommand(ClearSearchHistoryCommand); CommandsRegistry.registerCommand({ id: Constants.FocusSearchListCommandID, handler: focusSearchListCommand }); const focusSearchListCommandLabel = nls.localize('focusSearchListCommandLabel', "Focus List"); const FocusSearchListCommand: ICommandAction = { id: Constants.FocusSearchListCommandID, title: focusSearchListCommandLabel, category }; MenuRegistry.addCommand(FocusSearchListCommand); const searchInFolderCommand: ICommandHandler = (accessor, resource?: URI) => { const listService = accessor.get(IListService); const fileService = accessor.get(IFileService); const viewsService = accessor.get(IViewsService); const resources = getMultiSelectedResources(resource, listService, accessor.get(IEditorService), accessor.get(IExplorerService)); return openSearchView(viewsService, true).then(searchView => { if (resources && resources.length && searchView) { return fileService.resolveAll(resources.map(resource => ({ resource }))).then(results => { const folders: URI[] = []; results.forEach(result => { if (result.success && result.stat) { folders.push(result.stat.isDirectory ? result.stat.resource : dirname(result.stat.resource)); } }); searchView.searchInFolders(distinct(folders, folder => folder.toString())); }); } return undefined; }); }; const FIND_IN_FOLDER_ID = 'filesExplorer.findInFolder'; KeybindingsRegistry.registerCommandAndKeybindingRule({ id: FIND_IN_FOLDER_ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(FilesExplorerFocusCondition, ExplorerFolderContext), primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_F, handler: searchInFolderCommand }); CommandsRegistry.registerCommand({ id: ClearSearchResultsAction.ID, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(ClearSearchResultsAction, ClearSearchResultsAction.ID, '').run(); } }); CommandsRegistry.registerCommand({ id: RefreshAction.ID, handler: (accessor, args: any) => { accessor.get(IInstantiationService).createInstance(RefreshAction, RefreshAction.ID, '').run(); } }); const FIND_IN_WORKSPACE_ID = 'filesExplorer.findInWorkspace'; CommandsRegistry.registerCommand({ id: FIND_IN_WORKSPACE_ID, handler: (accessor) => { return openSearchView(accessor.get(IViewsService), true).then(searchView => { if (searchView) { searchView.searchInFolders(); } }); } }); MenuRegistry.appendMenuItem(MenuId.ExplorerContext, { group: '4_search', order: 10, command: { id: FIND_IN_FOLDER_ID, title: nls.localize('findInFolder', "Find in Folder...") }, when: ContextKeyExpr.and(ExplorerFolderContext) }); MenuRegistry.appendMenuItem(MenuId.ExplorerContext, { group: '4_search', order: 10, command: { id: FIND_IN_WORKSPACE_ID, title: nls.localize('findInWorkspace', "Find in Workspace...") }, when: ContextKeyExpr.and(ExplorerRootContext, ExplorerFolderContext.toNegated()) }); class ShowAllSymbolsAction extends Action { static readonly ID = 'workbench.action.showAllSymbols'; static readonly LABEL = nls.localize('showTriggerActions', "Go to Symbol in Workspace..."); static readonly ALL_SYMBOLS_PREFIX = '#'; constructor( actionId: string, actionLabel: string, @IQuickInputService private readonly quickInputService: IQuickInputService ) { super(actionId, actionLabel); } async run(): Promise<void> { this.quickInputService.quickAccess.show(ShowAllSymbolsAction.ALL_SYMBOLS_PREFIX); } } const viewContainer = Registry.as<IViewContainersRegistry>(ViewExtensions.ViewContainersRegistry).registerViewContainer({ id: VIEWLET_ID, name: nls.localize('name', "Search"), ctorDescriptor: new SyncDescriptor(ViewPaneContainer, [VIEWLET_ID, { mergeViewWithContainerWhenSingleView: true, donotShowContainerTitleWhenMergedWithContainer: true }]), hideIfEmpty: true, icon: searchViewIcon.classNames, order: 1 }, ViewContainerLocation.Sidebar); const viewDescriptor = { id: VIEW_ID, containerIcon: 'codicon-search', name: nls.localize('search', "Search"), ctorDescriptor: new SyncDescriptor(SearchView), canToggleVisibility: false, canMoveView: true }; // Register search default location to sidebar Registry.as<IViewsRegistry>(ViewExtensions.ViewsRegistry).registerViews([viewDescriptor], viewContainer); // Migrate search location setting to new model class RegisterSearchViewContribution implements IWorkbenchContribution { constructor( @IConfigurationService configurationService: IConfigurationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService ) { const data = configurationService.inspect('search.location'); if (data.value === 'panel') { viewDescriptorService.moveViewToLocation(viewDescriptor, ViewContainerLocation.Panel); } if (data.userValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER); } if (data.userLocalValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER_LOCAL); } if (data.userRemoteValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.USER_REMOTE); } if (data.workspaceFolderValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.WORKSPACE_FOLDER); } if (data.workspaceValue) { configurationService.updateValue('search.location', undefined, ConfigurationTarget.WORKSPACE); } } } Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(RegisterSearchViewContribution, LifecyclePhase.Starting); // Actions const registry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions); // Show Search and Find in Files are redundant, but we can't break keybindings by removing one. So it's the same action, same keybinding, registered to different IDs. // Show Search 'when' is redundant but if the two conflict with exactly the same keybinding and 'when' clause, then they can show up as "unbound" - #51780 registry.registerWorkbenchAction(SyncActionDescriptor.from(OpenSearchViewletAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_F }, Constants.SearchViewVisibleKey.toNegated()), 'View: Show Search', nls.localize('view', "View")); KeybindingsRegistry.registerCommandAndKeybindingRule({ description: { description: nls.localize('findInFiles.description', "Open the search viewlet"), args: [ { name: nls.localize('findInFiles.args', "A set of options for the search viewlet"), schema: { type: 'object', properties: { query: { 'type': 'string' }, replace: { 'type': 'string' }, triggerSearch: { 'type': 'boolean' }, filesToInclude: { 'type': 'string' }, filesToExclude: { 'type': 'string' }, isRegex: { 'type': 'boolean' }, isCaseSensitive: { 'type': 'boolean' }, matchWholeWord: { 'type': 'boolean' }, } } }, ] }, id: Constants.FindInFilesActionId, weight: KeybindingWeight.WorkbenchContrib, when: null, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_F, handler: FindInFilesCommand }); MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: Constants.FindInFilesActionId, title: { value: nls.localize('findInFiles', "Find in Files"), original: 'Find in Files' }, category } }); MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { group: '4_find_global', command: { id: Constants.FindInFilesActionId, title: nls.localize({ key: 'miFindInFiles', comment: ['&& denotes a mnemonic'] }, "Find &&in Files") }, order: 1 }); registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusNextSearchResultAction, { primary: KeyCode.F4 }), 'Focus Next Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor)); registry.registerWorkbenchAction(SyncActionDescriptor.from(FocusPreviousSearchResultAction, { primary: KeyMod.Shift | KeyCode.F4 }), 'Focus Previous Search Result', category, ContextKeyExpr.or(Constants.HasSearchResults, SearchEditorConstants.InSearchEditor)); registry.registerWorkbenchAction(SyncActionDescriptor.from(ReplaceInFilesAction, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_H }), 'Replace in Files', category); MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { group: '4_find_global', command: { id: ReplaceInFilesAction.ID, title: nls.localize({ key: 'miReplaceInFiles', comment: ['&& denotes a mnemonic'] }, "Replace &&in Files") }, order: 2 }); if (platform.isMacintosh) { // Register this with a more restrictive `when` on mac to avoid conflict with "copy path" KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleCaseSensitiveCommandId, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewFocusedKey, Constants.FileMatchOrFolderMatchFocusKey.toNegated()), handler: toggleCaseSensitiveCommand }, ToggleCaseSensitiveKeybinding)); } else { KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleCaseSensitiveCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleCaseSensitiveCommand }, ToggleCaseSensitiveKeybinding)); } KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleWholeWordCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleWholeWordCommand }, ToggleWholeWordKeybinding)); KeybindingsRegistry.registerCommandAndKeybindingRule(objects.assign({ id: Constants.ToggleRegexCommandId, weight: KeybindingWeight.WorkbenchContrib, when: Constants.SearchViewFocusedKey, handler: toggleRegexCommand }, ToggleRegexKeybinding)); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.AddCursorsAtSearchResults, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.SearchViewVisibleKey, Constants.FileMatchOrMatchFocusKey), primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_L, handler: (accessor, args: any) => { const searchView = getSearchView(accessor.get(IViewsService)); if (searchView) { const tree: WorkbenchObjectTree<RenderableMatch> = searchView.getControl(); searchView.openEditorWithMultiCursor(<FileMatchOrMatch>tree.getFocus()[0]); } } }); registry.registerWorkbenchAction(SyncActionDescriptor.from(CollapseDeepestExpandedLevelAction), 'Search: Collapse All', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ExpandAllAction), 'Search: Expand All', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ShowAllSymbolsAction, { primary: KeyMod.CtrlCmd | KeyCode.KEY_T }), 'Go to Symbol in Workspace...'); registry.registerWorkbenchAction(SyncActionDescriptor.from(ToggleSearchOnTypeAction), 'Search: Toggle Search on Type', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(RefreshAction), 'Search: Refresh', category); registry.registerWorkbenchAction(SyncActionDescriptor.from(ClearSearchResultsAction), 'Search: Clear Search Results', category); // Register Quick Access Handler const quickAccessRegistry = Registry.as<IQuickAccessRegistry>(QuickAccessExtensions.Quickaccess); quickAccessRegistry.registerQuickAccessProvider({ ctor: AnythingQuickAccessProvider, prefix: AnythingQuickAccessProvider.PREFIX, placeholder: nls.localize('anythingQuickAccessPlaceholder', "Search files by name (append {0} to go to line or {1} to go to symbol)", AbstractGotoLineQuickAccessProvider.PREFIX, GotoSymbolQuickAccessProvider.PREFIX), contextKey: defaultQuickAccessContextKeyValue, helpEntries: [{ description: nls.localize('anythingQuickAccess', "Go to File"), needsEditor: false }] }); quickAccessRegistry.registerQuickAccessProvider({ ctor: SymbolsQuickAccessProvider, prefix: SymbolsQuickAccessProvider.PREFIX, placeholder: nls.localize('symbolsQuickAccessPlaceholder', "Type the name of a symbol to open."), contextKey: 'inWorkspaceSymbolsPicker', helpEntries: [{ description: nls.localize('symbolsQuickAccess', "Go to Symbol in Workspace"), needsEditor: false }] }); // Configuration const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration); configurationRegistry.registerConfiguration({ id: 'search', order: 13, title: nls.localize('searchConfigurationTitle', "Search"), type: 'object', properties: { [SEARCH_EXCLUDE_CONFIG]: { type: 'object', markdownDescription: nls.localize('exclude', "Configure glob patterns for excluding files and folders in fulltext searches and quick open. Inherits all glob patterns from the `#files.exclude#` setting. Read more about glob patterns [here](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options)."), default: { '**/node_modules': true, '**/bower_components': true, '**/*.code-search': true }, additionalProperties: { anyOf: [ { type: 'boolean', description: nls.localize('exclude.boolean', "The glob pattern to match file paths against. Set to true or false to enable or disable the pattern."), }, { type: 'object', properties: { when: { type: 'string', // expression ({ "**/*.js": { "when": "$(basename).js" } }) pattern: '\\w*\\$\\(basename\\)\\w*', default: '$(basename).ext', description: nls.localize('exclude.when', 'Additional check on the siblings of a matching file. Use $(basename) as variable for the matching file name.') } } } ] }, scope: ConfigurationScope.RESOURCE }, 'search.useRipgrep': { type: 'boolean', description: nls.localize('useRipgrep', "This setting is deprecated and now falls back on \"search.usePCRE2\"."), deprecationMessage: nls.localize('useRipgrepDeprecated', "Deprecated. Consider \"search.usePCRE2\" for advanced regex feature support."), default: true }, 'search.maintainFileSearchCache': { type: 'boolean', description: nls.localize('search.maintainFileSearchCache', "When enabled, the searchService process will be kept alive instead of being shut down after an hour of inactivity. This will keep the file search cache in memory."), default: false }, 'search.useIgnoreFiles': { type: 'boolean', markdownDescription: nls.localize('useIgnoreFiles', "Controls whether to use `.gitignore` and `.ignore` files when searching for files."), default: true, scope: ConfigurationScope.RESOURCE }, 'search.useGlobalIgnoreFiles': { type: 'boolean', markdownDescription: nls.localize('useGlobalIgnoreFiles', "Controls whether to use global `.gitignore` and `.ignore` files when searching for files."), default: false, scope: ConfigurationScope.RESOURCE }, 'search.quickOpen.includeSymbols': { type: 'boolean', description: nls.localize('search.quickOpen.includeSymbols', "Whether to include results from a global symbol search in the file results for Quick Open."), default: false }, 'search.quickOpen.includeHistory': { type: 'boolean', description: nls.localize('search.quickOpen.includeHistory', "Whether to include results from recently opened files in the file results for Quick Open."), default: true }, 'search.quickOpen.history.filterSortOrder': { 'type': 'string', 'enum': ['default', 'recency'], 'default': 'default', 'enumDescriptions': [ nls.localize('filterSortOrder.default', 'History entries are sorted by relevance based on the filter value used. More relevant entries appear first.'), nls.localize('filterSortOrder.recency', 'History entries are sorted by recency. More recently opened entries appear first.') ], 'description': nls.localize('filterSortOrder', "Controls sorting order of editor history in quick open when filtering.") }, 'search.followSymlinks': { type: 'boolean', description: nls.localize('search.followSymlinks', "Controls whether to follow symlinks while searching."), default: true }, 'search.smartCase': { type: 'boolean', description: nls.localize('search.smartCase', "Search case-insensitively if the pattern is all lowercase, otherwise, search case-sensitively."), default: false }, 'search.globalFindClipboard': { type: 'boolean', default: false, description: nls.localize('search.globalFindClipboard', "Controls whether the search view should read or modify the shared find clipboard on macOS."), included: platform.isMacintosh }, 'search.location': { type: 'string', enum: ['sidebar', 'panel'], default: 'sidebar', description: nls.localize('search.location', "Controls whether the search will be shown as a view in the sidebar or as a panel in the panel area for more horizontal space."), deprecationMessage: nls.localize('search.location.deprecationMessage', "This setting is deprecated. Please use drag and drop instead by dragging the search icon.") }, 'search.collapseResults': { type: 'string', enum: ['auto', 'alwaysCollapse', 'alwaysExpand'], enumDescriptions: [ nls.localize('search.collapseResults.auto', "Files with less than 10 results are expanded. Others are collapsed."), '', '' ], default: 'alwaysExpand', description: nls.localize('search.collapseAllResults', "Controls whether the search results will be collapsed or expanded."), }, 'search.useReplacePreview': { type: 'boolean', default: true, description: nls.localize('search.useReplacePreview', "Controls whether to open Replace Preview when selecting or replacing a match."), }, 'search.showLineNumbers': { type: 'boolean', default: false, description: nls.localize('search.showLineNumbers', "Controls whether to show line numbers for search results."), }, 'search.usePCRE2': { type: 'boolean', default: false, description: nls.localize('search.usePCRE2', "Whether to use the PCRE2 regex engine in text search. This enables using some advanced regex features like lookahead and backreferences. However, not all PCRE2 features are supported - only features that are also supported by JavaScript."), deprecationMessage: nls.localize('usePCRE2Deprecated', "Deprecated. PCRE2 will be used automatically when using regex features that are only supported by PCRE2."), }, 'search.actionsPosition': { type: 'string', enum: ['auto', 'right'], enumDescriptions: [ nls.localize('search.actionsPositionAuto', "Position the actionbar to the right when the search view is narrow, and immediately after the content when the search view is wide."), nls.localize('search.actionsPositionRight', "Always position the actionbar to the right."), ], default: 'auto', description: nls.localize('search.actionsPosition', "Controls the positioning of the actionbar on rows in the search view.") }, 'search.searchOnType': { type: 'boolean', default: true, description: nls.localize('search.searchOnType', "Search all files as you type.") }, 'search.seedWithNearestWord': { type: 'boolean', default: false, description: nls.localize('search.seedWithNearestWord', "Enable seeding search from the word nearest the cursor when the active editor has no selection.") }, 'search.seedOnFocus': { type: 'boolean', default: false, description: nls.localize('search.seedOnFocus', "Update workspace search query to the editor's selected text when focusing the search view. This happens either on click or when triggering the `workbench.views.search.focus` command.") }, 'search.searchOnTypeDebouncePeriod': { type: 'number', default: 300, markdownDescription: nls.localize('search.searchOnTypeDebouncePeriod', "When `#search.searchOnType#` is enabled, controls the timeout in milliseconds between a character being typed and the search starting. Has no effect when `search.searchOnType` is disabled.") }, 'search.searchEditor.doubleClickBehaviour': { type: 'string', enum: ['selectWord', 'goToLocation', 'openLocationToSide'], default: 'goToLocation', enumDescriptions: [ nls.localize('search.searchEditor.doubleClickBehaviour.selectWord', "Double clicking selects the word under the cursor."), nls.localize('search.searchEditor.doubleClickBehaviour.goToLocation', "Double clicking opens the result in the active editor group."), nls.localize('search.searchEditor.doubleClickBehaviour.openLocationToSide', "Double clicking opens the result in the editor group to the side, creating one if it does not yet exist."), ], markdownDescription: nls.localize('search.searchEditor.doubleClickBehaviour', "Configure effect of double clicking a result in a search editor.") }, 'search.searchEditor.reusePriorSearchConfiguration': { type: 'boolean', default: false, markdownDescription: nls.localize({ key: 'search.searchEditor.reusePriorSearchConfiguration', comment: ['"Search Editor" is a type that editor that can display search results. "includes, excludes, and flags" just refers to settings that affect search. For example, the "search.exclude" setting.'] }, "When enabled, new Search Editors will reuse the includes, excludes, and flags of the previously opened Search Editor") }, 'search.searchEditor.defaultNumberOfContextLines': { type: ['number', 'null'], default: 1, markdownDescription: nls.localize('search.searchEditor.defaultNumberOfContextLines', "The default number of surrounding context lines to use when creating new Search Editors. If using `#search.searchEditor.reusePriorSearchConfiguration#`, this can be set to `null` (empty) to use the prior Search Editor's configuration.") }, 'search.sortOrder': { 'type': 'string', 'enum': [SearchSortOrder.Default, SearchSortOrder.FileNames, SearchSortOrder.Type, SearchSortOrder.Modified, SearchSortOrder.CountDescending, SearchSortOrder.CountAscending], 'default': SearchSortOrder.Default, 'enumDescriptions': [ nls.localize('searchSortOrder.default', "Results are sorted by folder and file names, in alphabetical order."), nls.localize('searchSortOrder.filesOnly', "Results are sorted by file names ignoring folder order, in alphabetical order."), nls.localize('searchSortOrder.type', "Results are sorted by file extensions, in alphabetical order."), nls.localize('searchSortOrder.modified', "Results are sorted by file last modified date, in descending order."), nls.localize('searchSortOrder.countDescending', "Results are sorted by count per file, in descending order."), nls.localize('searchSortOrder.countAscending', "Results are sorted by count per file, in ascending order.") ], 'description': nls.localize('search.sortOrder', "Controls sorting order of search results.") }, } }); CommandsRegistry.registerCommand('_executeWorkspaceSymbolProvider', function (accessor, ...args) { const [query] = args; assertType(typeof query === 'string'); return getWorkspaceSymbols(query); }); // View menu MenuRegistry.appendMenuItem(MenuId.MenubarViewMenu, { group: '3_views', command: { id: VIEWLET_ID, title: nls.localize({ key: 'miViewSearch', comment: ['&& denotes a mnemonic'] }, "&&Search") }, order: 2 }); // Go to menu MenuRegistry.appendMenuItem(MenuId.MenubarGoMenu, { group: '3_global_nav', command: { id: 'workbench.action.showAllSymbols', title: nls.localize({ key: 'miGotoSymbolInWorkspace', comment: ['&& denotes a mnemonic'] }, "Go to Symbol in &&Workspace...") }, order: 2 });
src/vs/workbench/contrib/search/browser/search.contribution.ts
1
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.12318409234285355, 0.002529523801058531, 0.00016441763727925718, 0.00017366284737363458, 0.013505268841981888 ]
{ "id": 10, "code_window": [ "import { IQuickAccessRegistry, Extensions as QuickAccessExtensions } from 'vs/platform/quickinput/common/quickAccess';\n", "import { TasksQuickAccessProvider } from 'vs/workbench/contrib/tasks/browser/tasksQuickAccess';\n", "\n", "let tasksCategory = nls.localize('tasksCategory', \"Tasks\");\n", "\n", "const workbenchRegistry = Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench);\n", "workbenchRegistry.registerWorkbenchContribution(RunAutomaticTasks, LifecyclePhase.Eventually);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "let tasksCategory = { value: nls.localize('tasksCategory', \"Tasks\"), original: 'Tasks' };\n" ], "file_path": "src/vs/workbench/contrib/tasks/browser/task.contribution.ts", "type": "replace", "edit_start_line_idx": 39 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IExtensionDescription } from 'vs/platform/extensions/common/extensions'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService'; import { ILogService } from 'vs/platform/log/common/log'; import { IEnvironment, IStaticWorkspaceData } from 'vs/workbench/api/common/extHost.protocol'; import { IExtHostConsumerFileSystem } from 'vs/workbench/api/common/extHostFileSystemConsumer'; import { URI } from 'vs/base/common/uri'; export const IExtensionStoragePaths = createDecorator<IExtensionStoragePaths>('IExtensionStoragePaths'); export interface IExtensionStoragePaths { readonly _serviceBrand: undefined; whenReady: Promise<any>; workspaceValue(extension: IExtensionDescription): URI | undefined; globalValue(extension: IExtensionDescription): URI; } export class ExtensionStoragePaths implements IExtensionStoragePaths { readonly _serviceBrand: undefined; private readonly _workspace?: IStaticWorkspaceData; private readonly _environment: IEnvironment; readonly whenReady: Promise<URI | undefined>; private _value?: URI; constructor( @IExtHostInitDataService initData: IExtHostInitDataService, @ILogService private readonly _logService: ILogService, @IExtHostConsumerFileSystem private readonly _extHostFileSystem: IExtHostConsumerFileSystem ) { this._workspace = initData.workspace ?? undefined; this._environment = initData.environment; this.whenReady = this._getOrCreateWorkspaceStoragePath().then(value => this._value = value); } private async _getOrCreateWorkspaceStoragePath(): Promise<URI | undefined> { if (!this._workspace) { return Promise.resolve(undefined); } const storageName = this._workspace.id; const storageUri = URI.joinPath(this._environment.workspaceStorageHome, storageName); try { await this._extHostFileSystem.stat(storageUri); this._logService.trace('[ExtHostStorage] storage dir already exists', storageUri); return storageUri; } catch { // doesn't exist, that's OK } try { this._logService.trace('[ExtHostStorage] creating dir and metadata-file', storageUri); await this._extHostFileSystem.createDirectory(storageUri); await this._extHostFileSystem.writeFile( URI.joinPath(storageUri, 'meta.json'), new TextEncoder().encode(JSON.stringify({ id: this._workspace.id, configuration: URI.revive(this._workspace.configuration)?.toString(), name: this._workspace.name }, undefined, 2)) ); return storageUri; } catch (e) { this._logService.error('[ExtHostStorage]', e); return undefined; } } workspaceValue(extension: IExtensionDescription): URI | undefined { if (this._value) { return URI.joinPath(this._value, extension.identifier.value); } return undefined; } globalValue(extension: IExtensionDescription): URI { return URI.joinPath(this._environment.globalStorageHome, extension.identifier.value.toLowerCase()); } }
src/vs/workbench/api/common/extHostStoragePaths.ts
0
https://github.com/microsoft/vscode/commit/d1d6eaeb3e6ddba16536f0b437a6a1ba6309f930
[ 0.00018175935838371515, 0.00017257060972042382, 0.00016521204088348895, 0.00017240691522601992, 0.000004323692792240763 ]