Merge Microsoft/master into branch

This commit is contained in:
David Storey 2015-12-12 00:04:07 -08:00
commit 206f9a84d2
273 changed files with 7744 additions and 24102 deletions

23
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,23 @@
## Contributing Issues
### Before Submitting an Issue
First, please do a search in open issues to see if the issue or feature request has already been filed. If there is an issue add your comments to this issue.
The Code project is distributed across multiple repositories, try to file the issue against the correct repository [Related Projects](https://github.com/Microsoft/vscode/wiki/Related-Projects).
If your issue is a question then please ask the question on [Stack Overflow](https://stackoverflow.com/questions/tagged/vscode) using the tag `vscode`.
## Writing Good Bug Reports and Feature Requests
File a single issue per problem and feature request, do not file combo issues.
The more information you can provide, the more likely someone will be successful reproducing the issue and finding a fix. Therefore:
* Provide reproducable steps, what the result of the steps was, an what you would have expected.
* Description of what you expect to happen
* Animated GIFs
* Code that demonstrates the issue
* Version of VS Code
* Errors in the Dev Tools Console (Help | Toggle Developer Tools)
* When you have extensions installed, can you reproduce the issue when starting vscode without extensions by using the `--disable-extensions` command line argument?

View file

@ -31,8 +31,7 @@ exports.loaderConfig = function (emptyPaths) {
paths: {
'vs': 'out-build/vs',
'vs/extensions': 'extensions',
'vscode': 'empty:',
'lib': 'out-build/lib'
'vscode': 'empty:'
},
'vs/text': {
paths: {

View file

@ -41,7 +41,7 @@ var baseModules = [
// Build
var builtInExtensions = {
'jrieken.vscode-omnisharp': '0.1.0',
'jrieken.vscode-omnisharp': '0.3.0',
};
var vscodeEntryPoints = _.flatten([

View file

@ -1,7 +1,6 @@
{
"comments": {
"lineComment": ";",
"blockComment": [ "(comment", ")" ]
"lineComment": ";"
},
"brackets": [
["{", "}"],

View file

@ -1,7 +0,0 @@
// ATTENTION - THIS DIRECTORY CONTAINS THIRD PARTY OPEN SOURCE MATERIALS:
[{
"name": "language-csharp",
"version": "0.11.0",
"license": "Dual-licensed under MIT and GPL",
"repositoryURL": "https://github.com/atom/language-csharp"
}]

View file

@ -1,11 +0,0 @@
{
"comments": {
"lineComment": "//",
"blockComment": ["/*", "*/"]
},
"brackets": [
["{", "}"],
["[", "]"],
["(", ")"]
]
}

View file

@ -1,19 +0,0 @@
{
"name": "csharp",
"version": "0.1.0",
"publisher": "vscode",
"engines": { "vscode": "*" },
"contributes": {
"languages": [{
"id": "csharp",
"extensions": [ ".cs", ".csx" ],
"aliases": [ "C#", "csharp" ],
"configuration": "./csharp.configuration.json"
}],
"grammars": [{
"language": "csharp",
"scopeName": "source.cs",
"path": "./syntaxes/csharp.json"
}]
}
}

View file

@ -1,566 +0,0 @@
{
"scopeName": "source.cs",
"name": "C#",
"fileTypes": [
"cs"
],
"foldingStartMarker": "^\\s*#\\s*region|^\\s*/\\*|^(?![^{]*?//|[^{]*?/\\*(?!.*?\\*/.*?\\{)).*?\\{\\s*($|//|/\\*(?!.*?\\*/.*\\S))",
"foldingStopMarker": "^\\s*#\\s*endregion|^\\s*\\*/|^\\s*\\}",
"patterns": [
{
"captures": {
"1": {
"name": "keyword.other.using.cs"
}
},
"begin": "^\\s*(using)\\b\\s*",
"end": "\\s*(?:$|(;))",
"name": "meta.keyword.using.cs"
},
{
"begin": "^\\s*((namespace)\\s+([\\w.]+))",
"beginCaptures": {
"1": {
"name": "meta.namespace.identifier.cs"
},
"2": {
"name": "keyword.other.namespace.cs"
},
"3": {
"name": "entity.name.type.namespace.cs"
}
},
"end": "}",
"endCaptures": {
"0": {
"name": "punctuation.section.namespace.end.cs"
}
},
"name": "meta.namespace.cs",
"patterns": [
{
"begin": "{",
"beginCaptures": {
"0": {
"name": "punctuation.section.namespace.begin.cs"
}
},
"end": "(?=})",
"name": "meta.namespace.body.cs",
"patterns": [
{
"include": "#code"
}
]
}
]
},
{
"include": "#code"
}
],
"repository": {
"block": {
"patterns": [
{
"begin": "{",
"beginCaptures": {
"0": {
"name": "punctuation.section.block.begin.cs"
}
},
"end": "}",
"endCaptures": {
"0": {
"name": "punctuation.section.block.end.cs"
}
},
"name": "meta.block.cs",
"patterns": [
{
"include": "#code"
}
]
}
]
},
"builtinTypes": {
"patterns": [
{
"match": "\\b(bool|byte|sbyte|char|decimal|double|float|int|uint|long|ulong|object|short|ushort|string|void|class|struct|enum|interface)\\b",
"name": "storage.type.cs"
}
]
},
"class": {
"begin": "(?=\\w?[\\w\\s]*(?:class|struct|interface|enum)\\s+\\w+)",
"end": "}",
"endCaptures": {
"0": {
"name": "punctuation.section.class.end.cs"
}
},
"name": "meta.class.cs",
"patterns": [
{
"include": "#storage-modifiers"
},
{
"include": "#comments"
},
{
"captures": {
"1": {
"name": "storage.modifier.cs"
},
"2": {
"name": "entity.name.type.class.cs"
}
},
"match": "(class|struct|interface|enum)\\s+(\\w+)",
"name": "meta.class.identifier.cs"
},
{
"begin": ":",
"end": "(?={)",
"patterns": [
{
"captures": {
"1": {
"name": "storage.type.cs"
}
},
"match": "\\s*,?([A-Za-z_]\\w*)\\b"
}
]
},
{
"begin": "{",
"beginCaptures": {
"0": {
"name": "punctuation.section.class.begin.cs"
}
},
"end": "(?=})",
"name": "meta.class.body.cs",
"patterns": [
{
"include": "#method"
},
{
"include": "#code"
}
]
}
]
},
"code": {
"patterns": [
{
"include": "#block"
},
{
"include": "#comments"
},
{
"include": "#class"
},
{
"include": "#constants"
},
{
"include": "#storage-modifiers"
},
{
"include": "#keywords"
},
{
"include": "#preprocessor"
},
{
"include": "#method-call"
},
{
"include": "#builtinTypes"
},
{
"include": "#documentation"
}
]
},
"comments": {
"patterns": [
{
"begin": "///",
"captures": {
"0": {
"name": "punctuation.definition.comment.cs"
}
},
"end": "$\\n?",
"name": "comment.block.documentation.cs",
"patterns": [
{
"include": "text.xml"
}
]
},
{
"begin": "/\\*",
"captures": {
"0": {
"name": "punctuation.definition.comment.cs"
}
},
"end": "\\*/\\n?",
"name": "comment.block.cs"
},
{
"begin": "//",
"captures": {
"1": {
"name": "punctuation.definition.comment.cs"
}
},
"end": "$\\n?",
"name": "comment.line.double-slash.cs"
}
]
},
"constants": {
"patterns": [
{
"match": "\\b(true|false|null|this|base)\\b",
"name": "constant.language.cs"
},
{
"match": "\\b((0(x|X)[0-9a-fA-F]*)|(([0-9]+\\.?[0-9]*)|(\\.[0-9]+))((e|E)(\\+|-)?[0-9]+)?)(L|l|UL|ul|u|U|F|f|ll|LL|ull|ULL)?\\b",
"name": "constant.numeric.cs"
},
{
"captures": {
"0": {
"name": "punctuation.definition.string.begin.cs"
}
},
"match": "@\"([^\"]|\"\")*\"",
"name": "string.quoted.double.literal.cs"
},
{
"begin": "\"",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.cs"
}
},
"end": "\"",
"endCaptures": {
"0": {
"name": "punctuation.definition.string.end.cs"
}
},
"name": "string.quoted.double.cs",
"patterns": [
{
"match": "\\\\.",
"name": "constant.character.escape.cs"
}
]
},
{
"begin": "'",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.cs"
}
},
"end": "'",
"endCaptures": {
"0": {
"name": "punctuation.definition.string.end.cs"
}
},
"name": "string.quoted.single.cs",
"patterns": [
{
"match": "\\\\.",
"name": "constant.character.escape.cs"
}
]
}
]
},
"keywords": {
"patterns": [
{
"match": "\\b(if|else|while|for|foreach|in|do|return|continue|break|switch|case|default|goto|throw|try|catch|finally|lock|yield|await)\\b",
"name": "keyword.control.cs"
},
{
"match": "\\b(from|where|select|group|into|orderby|join|let|on|equals|by|ascending|descending)\\b",
"name": "keyword.linq.cs"
},
{
"match": "\\b(new|is|as|using|checked|unchecked|typeof|sizeof|override|readonly|stackalloc)\\b",
"name": "keyword.operator.cs"
},
{
"match": "\\b(event|delegate|fixed|add|remove|set|get|value)\\b",
"name": "keyword.other.cs"
},
{
"match": "\\b(var)\\b",
"name": "storage.type.var.cs"
},
{
"match": "[@]\\b(var|event|delegate|add|remove|set|get|value|new|is|as|using|checked|unchecked|typeof|sizeof |override|readonly|stackalloc|from|where|select|group|into|orderby|join|let|on|equals|by|ascending|descending |if|else|while|for|foreach|in|do|return|continue|break|switch|case|default|goto|throw|try|catch|finally|lock|yield|await)\\b",
"name": "meta.class.body.cs"
}
]
},
"method": {
"patterns": [
{
"begin": "\\[",
"end": "\\]",
"name": "meta.method.annotation.cs",
"patterns": [
{
"include": "#constants"
},
{
"include": "#preprocessor"
},
{
"include": "#builtinTypes"
}
]
},
{
"begin": "(?=\\bnew\\s+)(?=[\\w<].*\\s+)(?=[^=]+\\()",
"end": "(?={|;)",
"name": "meta.new-object.cs",
"patterns": [
{
"include": "#code"
}
]
},
{
"begin": "(?<!=|=\\s)(?!new)(?!.*(=|\\/\\/|\\/\\*).*\\()(?=[\\w<].*\\s+.+\\()",
"end": "(})|(?=;)",
"endCaptures": {
"1": {
"name": "punctuation.section.method.end.cs"
}
},
"name": "meta.method.cs",
"patterns": [
{
"include": "#storage-modifiers"
},
{
"include": "#builtinTypes"
},
{
"begin": "([\\w.]+)\\s*\\(",
"beginCaptures": {
"1": {
"name": "entity.name.function.cs"
}
},
"end": "\\)",
"name": "meta.method.identifier.cs",
"patterns": [
{
"include": "#parameters"
},
{
"include": "#constants"
}
]
},
{
"begin": "(?=\\w.*\\s+[\\w.]+\\s*\\()",
"end": "(?=[\\w.]+\\s*\\()",
"name": "meta.method.return-type.cs",
"patterns": [
{
"include": "#builtinTypes"
}
]
},
{
"begin": ":\\s*(this|base)\\s*\\(",
"beginCaptures": {
"1": {
"name": "constant.language.cs"
}
},
"end": "\\)",
"name": "meta.method.base-call.cs",
"patterns": [
{
"include": "#builtinTypes"
}
]
},
{
"begin": "{",
"beginCaptures": {
"0": {
"name": "punctuation.section.method.begin.cs"
}
},
"end": "(?=})",
"name": "meta.method.body.cs",
"patterns": [
{
"include": "#code"
}
]
}
]
},
{
"begin": "(?!new)(?=[\\w<].*\\s+)(?=[^=]+\\{)",
"end": "}",
"endCaptures": {
"0": {
"name": "punctuation.section.property.end.cs"
}
},
"name": "meta.property.cs",
"patterns": [
{
"include": "#storage-modifiers"
},
{
"begin": "([\\w.]+)\\s*(?={)",
"captures": {
"1": {
"name": "entity.name.function.cs"
}
},
"end": "(?={)",
"name": "meta.method.identifier.cs"
},
{
"begin": "(?=\\w.*\\s+[\\w.]+\\s*\\{)",
"end": "(?=[\\w.]+\\s*\\{)",
"name": "meta.method.return-type.cs",
"patterns": [
{
"include": "#builtinTypes"
}
]
},
{
"begin": "{",
"beginCaptures": {
"0": {
"name": "punctuation.section.property.begin.cs"
}
},
"end": "(?=})",
"name": "meta.method.body.cs",
"patterns": [
{
"include": "#code"
}
]
}
]
}
]
},
"method-call": {
"begin": "([\\w$]+)\\s*(\\()",
"beginCaptures": {
"1": {
"name": "meta.method.cs"
},
"2": {
"name": "punctuation.definition.method-parameters.begin.cs"
}
},
"end": "\\)",
"endCaptures": {
"0": {
"name": "punctuation.definition.method-parameters.end.cs"
}
},
"name": "meta.method-call.cs",
"patterns": [
{
"match": ",",
"name": "punctuation.definition.seperator.parameter.cs"
},
{
"include": "#code"
}
]
},
"parameters": {
"begin": "\\b(ref|params|out)?\\s*\\b([\\w.\\[\\]]+)\\s+(\\w+)\\s*(=)?",
"beginCaptures": {
"1": {
"name": "storage.type.modifier.cs"
},
"2": {
"name": "storage.type.generic.cs"
},
"3": {
"name": "variable.parameter.function.cs"
},
"4": {
"name": "keyword.operator.assignment.cs"
}
},
"end": "(?:(,)|(?=[\\)]))",
"endCaptures": {
"1": {
"name": "punctuation.definition.separator.parameter.cs"
}
},
"patterns": [
{
"include": "#constants"
},
{
"include": "#block"
}
]
},
"preprocessor": {
"patterns": [
{
"captures": {
"2": {
"name": "meta.toc-list.region.cs"
}
},
"match": "^\\s*#\\s*(region)\\b\\s*([^\\/]+)\\s",
"name": "meta.preprocessor.cs"
},
{
"captures": {
"2": {
"name": "entity.name.function.preprocessor.cs"
}
},
"match": "^\\s*#\\s*(define|undef|if|elif)\\b\\s*(\\S*)",
"name": "meta.preprocessor.cs"
},
{
"match": "^\\s*#\\s*(if|else|elif|endif|define|undef|warning|error|line|pragma|region|endregion)\\b\\s*([^\\/]+)\\s",
"name": "meta.preprocessor.cs"
}
]
},
"storage-modifiers": {
"match": "\\b(event|delegate|internal|public|protected|private|static|const|new|sealed|abstract|virtual|override|extern|unsafe|readonly|volatile|implicit|explicit|operator|async|partial)\\b",
"name": "storage.modifier.cs"
}
}
}

View file

@ -2,37 +2,86 @@
"name": "javascript",
"version": "0.1.0",
"publisher": "vscode",
"engines": { "vscode": "*" },
"engines": {
"vscode": "*"
},
"contributes": {
"languages": [{
"id": "javascriptreact",
"aliases": ["JavaScript React","jsx"],
"extensions": [".jsx"],
"configuration": "./javascript.configuration.json"
},{
"id": "javascript",
"aliases": ["JavaScript", "javascript", "js"],
"extensions": [".js", ".es6"],
"filenames": ["jakefile"],
"firstLine": "^#!.*\\bnode",
"mimetypes": ["text/javascript"]
}],
"grammars": [{
"language": "javascriptreact",
"scopeName": "source.jsx",
"path": "./syntaxes/JavaScriptReact.tmLanguage"
},{
"language": "javascript",
"scopeName": "source.js",
"path": "./syntaxes/JavaScript.tmLanguage"
},{
// referenced by other grammars
"scopeName": "source.js.regexp",
"path": "./syntaxes/Regular Expressions (JavaScript).tmLanguage"
}],
"snippets": [{
"language": "javascript",
"path": "./snippets/javascript.json"
}]
"languages": [
{
"id": "javascriptreact",
"aliases": [
"JavaScript React",
"jsx"
],
"extensions": [
".jsx"
],
"configuration": "./javascript.configuration.json"
},
{
"id": "javascript",
"aliases": [
"JavaScript",
"javascript",
"js"
],
"extensions": [
".js",
".es6"
],
"filenames": [
"jakefile"
],
"firstLine": "^#!.*\\bnode",
"mimetypes": [
"text/javascript"
]
}
],
"grammars": [
{
"language": "javascriptreact",
"scopeName": "source.jsx",
"path": "./syntaxes/JavaScriptReact.tmLanguage"
},
{
"language": "javascript",
"scopeName": "source.js",
"path": "./syntaxes/JavaScript.tmLanguage"
},
{
// referenced by other grammars
"scopeName": "source.js.regexp",
"path": "./syntaxes/Regular Expressions (JavaScript).tmLanguage"
}
],
"snippets": [
{
"language": "javascript",
"path": "./snippets/javascript.json"
}
],
"jsonValidation": [
{
"fileMatch": "package.json",
"url": "http://json.schemastore.org/project"
},
{
"fileMatch": "bower.json",
"url": "http://json.schemastore.org/bower"
},
{
"fileMatch": ".bower.json",
"url": "http://json.schemastore.org/bower"
},
{
"fileMatch": ".bowerrc",
"url": "http://json.schemastore.org/bowerrc"
},
{
"fileMatch": "jsconfig.json",
"url": "./schemas/jsconfig.schema.json"
}
]
}
}

View file

@ -0,0 +1,79 @@
{
"title": "JSON schema for the JavaScript configuration file",
"type": "object",
"default": {
"compilerOptions": {
"target": "ES6"
}
},
"properties": {
"compilerOptions": {
"type": "object",
"description": "Instructs the JavaScript language service how to validate .js files",
"properties": {
"charset": {
"description": "The character set of the input files",
"type": "string"
},
"diagnostics": {
"description": "Show diagnostic information.",
"type": "boolean"
},
"locale": {
"description": "The locale to use to show error messages, e.g. en-us.",
"type": "string"
},
"mapRoot": {
"description": "Specifies the location where debugger should locate map files instead of generated locations",
"type": "string",
"format": "uri"
},
"module": {
"description": "Module code generation to resolve against: 'commonjs', 'amd', 'system', or 'umd'.",
"enum": [
"commonjs",
"amd",
"system",
"umd"
]
},
"noLib": {
"description": "Do not include the default library file (lib.d.ts).",
"type": "boolean"
},
"target": {
"description": "Specify ECMAScript target version: 'ES3', 'ES5', or 'ES6' (default).",
"enum": [
"ES3",
"ES5",
"ES6",
"es3",
"es5",
"es6"
],
"default": "ES6"
},
"experimentalDecorators": {
"description": "Enables experimental support for ES7 decorators.",
"type": "boolean"
}
}
},
"files": {
"type": "array",
"description": "If no 'files' property is present in a jsconfig.json, the language service defaults to including all files the containing directory and subdirectories. When a 'files' property is specified, only those files are included.",
"items": {
"type": "string",
"format": "uri"
}
},
"exclude": {
"type": "array",
"description": "List files and folders that should not be included. This property is not honored when the 'files' property is present.",
"items": {
"type": "string",
"format": "uri"
}
}
}
}

View file

@ -70,6 +70,13 @@
<key>name</key>
<string>keyword.operator.assignment.js</string>
</dict>
<key>await-modifier</key>
<dict>
<key>match</key>
<string>await</string>
<key>name</key>
<string>storage.modifier.js</string>
</dict>
<key>block</key>
<dict>
<key>begin</key>
@ -98,11 +105,11 @@
<array>
<dict>
<key>include</key>
<string>#expression</string>
<string>#object-member</string>
</dict>
<dict>
<key>include</key>
<string>#object-member</string>
<string>#expression</string>
</dict>
</array>
</dict>
@ -116,7 +123,7 @@
<key>cast</key>
<dict>
<key>begin</key>
<string>(?:(?&lt;=return|throw|yield|[=(,:&gt;]))\s*(&lt;)(?!&lt;?\=)</string>
<string>(?:(?&lt;=return|throw|yield|await|[=(,:&gt;]))\s*(&lt;)(?!&lt;?\=)</string>
<key>beginCaptures</key>
<dict>
<key>1</key>
@ -380,7 +387,7 @@
<key>field-declaration</key>
<dict>
<key>begin</key>
<string>(?&lt;!\()\s*\b([a-zA-Z_$][\w$]*)\s*(\?\s*)?(?=(=|:))</string>
<string>(?&lt;!\()\s*((?:\b[a-zA-Z_$][\w$]*)|(?:\'[^']*\')|(?:\"[^"]*\"))\s*(\?\s*)?(?=(=|:))</string>
<key>beginCaptures</key>
<dict>
<key>1</key>
@ -432,6 +439,10 @@
<string>functioncall.expr.js</string>
<key>patterns</key>
<array>
<dict>
<key>include</key>
<string>#await-modifier</string>
</dict>
<dict>
<key>include</key>
<string>#type-parameters</string>
@ -445,7 +456,7 @@
<key>function-declaration</key>
<dict>
<key>begin</key>
<string>\b(?:(export)\s+)?(function\b)(?:\s+([a-zA-Z_$][\w$]*))?\s*</string>
<string>\b(?:(export)\s+)?(?:(async)\s+)?(function\b)(?:\s+([a-zA-Z_$][\w$]*))?\s*</string>
<key>beginCaptures</key>
<dict>
<key>1</key>
@ -456,9 +467,14 @@
<key>2</key>
<dict>
<key>name</key>
<string>storage.type.function.js</string>
<string>storage.modifier.js</string>
</dict>
<key>3</key>
<dict>
<key>name</key>
<string>storage.type.function.js</string>
</dict>
<key>4</key>
<dict>
<key>name</key>
<string>entity.name.function.js</string>
@ -667,7 +683,7 @@
<key>method-declaration</key>
<dict>
<key>begin</key>
<string>\b(?:(abstract)\s+)?\b(?:(public|private|protected)\s+)?(?:(get|set)\s+)?(?:(new)|(?:([a-zA-Z_$][\.\w$]*)\s*(\??)))?\s*(?=\(|\&lt;)</string>
<string>\b(?:(abstract)\s+)?\b(?:(public|private|protected)\s+)?\b(?:(async)\s+)?(?:(get|set)\s+)?(?:(new)|(?:([a-zA-Z_$][\.\w$]*)\s*(\??)))?\s*(?=\(|\&lt;)</string>
<key>beginCaptures</key>
<dict>
<key>1</key>
@ -683,19 +699,24 @@
<key>3</key>
<dict>
<key>name</key>
<string>storage.type.property.js</string>
<string>storage.modifier.js</string>
</dict>
<key>4</key>
<dict>
<key>name</key>
<string>keyword.operator.js</string>
<string>storage.type.property.js</string>
</dict>
<key>5</key>
<dict>
<key>name</key>
<string>entity.name.function.js</string>
<string>keyword.operator.js</string>
</dict>
<key>6</key>
<dict>
<key>name</key>
<string>entity.name.function.js</string>
</dict>
<key>7</key>
<dict>
<key>name</key>
<string>keyword.operator.js</string>

File diff suppressed because it is too large Load diff

View file

@ -2,18 +2,41 @@
"name": "json",
"version": "0.1.0",
"publisher": "vscode",
"engines": { "vscode": "*" },
"engines": {
"vscode": "*"
},
"contributes": {
"languages": [{
"id": "json",
"aliases": ["JSON", "json"],
"extensions": [".json", ".bowerrc", ".jshintrc", ".jscsrc", ".eslintrc"],
"mimetypes": ["application/json"]
}],
"grammars": [{
"language": "json",
"scopeName": "source.json",
"path": "./syntaxes/JSON.tmLanguage"
}]
"languages": [
{
"id": "json",
"aliases": [
"JSON",
"json"
],
"extensions": [
".json",
".bowerrc",
".jshintrc",
".jscsrc",
".eslintrc"
],
"mimetypes": [
"application/json"
]
}
],
"grammars": [
{
"language": "json",
"scopeName": "source.json",
"path": "./syntaxes/JSON.tmLanguage"
}
],
"jsonValidation": [
{
"fileMatch": "*.schema.json",
"url": "http://json-schema.org/draft-04/schema#"
}
]
}
}

View file

@ -1,6 +1,6 @@
{
"account": "monacobuild",
"container": "debuggers",
"zip": "32575e3/node-debug.zip",
"zip": "e6b9b29/node-debug.zip",
"output": ""
}
}

View file

@ -6,7 +6,7 @@
"contributes": {
"languages": [{
"id": "ruby",
"extensions": [ ".rb", ".rbx", ".rjs", ".gemspec", ".pp" ],
"extensions": [ ".rb", ".rbx", ".rjs", ".gemspec", ".pp", ".rake" ],
"filenames": [ "rakefile", "gemfile" ],
"aliases": [ "Ruby", "rb" ],
"configuration": "./ruby.configuration.json"

View file

@ -101,6 +101,12 @@
"language": "typescriptreact",
"path": "./snippets/typescriptreact.json"
}
],
"jsonValidation": [
{
"fileMatch": "tsconfig.json",
"url": "http://json.schemastore.org/tsconfig"
}
]
}
}

View file

@ -21,8 +21,8 @@ class SyncedBuffer {
private diagnosticRequestor: IDiagnosticRequestor;
private client: ITypescriptServiceClient;
constructor(model: TextDocument, filepath: string, diagnosticRequestor: IDiagnosticRequestor, client: ITypescriptServiceClient) {
this.document = model;
constructor(document: TextDocument, filepath: string, diagnosticRequestor: IDiagnosticRequestor, client: ITypescriptServiceClient) {
this.document = document;
this.filepath = filepath;
this.diagnosticRequestor = diagnosticRequestor;
this.client = client;
@ -30,26 +30,10 @@ class SyncedBuffer {
public open(): void {
let args: Proto.OpenRequestArgs = {
file: this.filepath
file: this.filepath,
fileContent: this.document.getText()
};
this.client.execute('open', args, false);
// The last line never has a new line character at the end. So we use range.
// Sending a replace doesn't work if the buffer is newer then on disk and
// if changes are on the last line. In this case the tsserver has less characters
// which makes the tsserver bail since the range is invalid
/*
let lastLineRange = this.document.lineAt(this.document.lineCount - 1).range;
let text = this.document.getText();
let changeArgs: Proto.ChangeRequestArgs = {
file: this.filepath,
line: 1,
offset: 1,
endLine: lastLineRange.end.line + 1,
endOffset: lastLineRange.end.character + 1,
insertString: text
}
this.client.execute('change', changeArgs, false);
*/
}
public close(): void {

File diff suppressed because it is too large Load diff

View file

@ -40,7 +40,7 @@ interface RequestItem {
export default class TypeScriptServiceClient implements ITypescriptServiceClient {
public static Trace: boolean = false;
public static Trace: boolean = process.env.TSS_TRACE || false;
private host: ITypescriptServiceClientHost;
private pathSeparator: string;

View file

@ -70,6 +70,13 @@
<key>name</key>
<string>keyword.operator.assignment.ts</string>
</dict>
<key>await-modifier</key>
<dict>
<key>match</key>
<string>await</string>
<key>name</key>
<string>storage.modifier.ts</string>
</dict>
<key>block</key>
<dict>
<key>begin</key>
@ -98,11 +105,11 @@
<array>
<dict>
<key>include</key>
<string>#expression</string>
<string>#object-member</string>
</dict>
<dict>
<key>include</key>
<string>#object-member</string>
<string>#expression</string>
</dict>
</array>
</dict>
@ -116,7 +123,7 @@
<key>cast</key>
<dict>
<key>begin</key>
<string>(?:(?&lt;=return|throw|yield|[=(,:&gt;]))\s*(&lt;)(?!&lt;?\=)</string>
<string>(?:(?&lt;=return|throw|yield|await|[=(,:&gt;]))\s*(&lt;)(?!&lt;?\=)</string>
<key>beginCaptures</key>
<dict>
<key>1</key>
@ -380,7 +387,7 @@
<key>field-declaration</key>
<dict>
<key>begin</key>
<string>(?&lt;!\()\s*\b([a-zA-Z_$][\w$]*)\s*(\?\s*)?(?=(=|:))</string>
<string>(?&lt;!\()\s*((?:\b[a-zA-Z_$][\w$]*)|(?:\'[^']*\')|(?:\"[^"]*\"))\s*(\?\s*)?(?=(=|:))</string>
<key>beginCaptures</key>
<dict>
<key>1</key>
@ -432,6 +439,10 @@
<string>functioncall.expr.ts</string>
<key>patterns</key>
<array>
<dict>
<key>include</key>
<string>#await-modifier</string>
</dict>
<dict>
<key>include</key>
<string>#type-parameters</string>
@ -445,7 +456,7 @@
<key>function-declaration</key>
<dict>
<key>begin</key>
<string>\b(?:(export)\s+)?(function\b)(?:\s+([a-zA-Z_$][\w$]*))?\s*</string>
<string>\b(?:(export)\s+)?(?:(async)\s+)?(function\b)(?:\s+([a-zA-Z_$][\w$]*))?\s*</string>
<key>beginCaptures</key>
<dict>
<key>1</key>
@ -456,9 +467,14 @@
<key>2</key>
<dict>
<key>name</key>
<string>storage.type.function.ts</string>
<string>storage.modifier.ts</string>
</dict>
<key>3</key>
<dict>
<key>name</key>
<string>storage.type.function.ts</string>
</dict>
<key>4</key>
<dict>
<key>name</key>
<string>entity.name.function.ts</string>
@ -667,7 +683,7 @@
<key>method-declaration</key>
<dict>
<key>begin</key>
<string>\b(?:(abstract)\s+)?\b(?:(public|private|protected)\s+)?(?:(get|set)\s+)?(?:(new)|(?:([a-zA-Z_$][\.\w$]*)\s*(\??)))?\s*(?=\(|\&lt;)</string>
<string>\b(?:(abstract)\s+)?\b(?:(public|private|protected)\s+)?\b(?:(async)\s+)?(?:(get|set)\s+)?(?:(new)|(?:([a-zA-Z_$][\.\w$]*)\s*(\??)))?\s*(?=\(|\&lt;)</string>
<key>beginCaptures</key>
<dict>
<key>1</key>
@ -683,19 +699,24 @@
<key>3</key>
<dict>
<key>name</key>
<string>storage.type.property.ts</string>
<string>storage.modifier.ts</string>
</dict>
<key>4</key>
<dict>
<key>name</key>
<string>keyword.operator.ts</string>
<string>storage.type.property.ts</string>
</dict>
<key>5</key>
<dict>
<key>name</key>
<string>entity.name.function.ts</string>
<string>keyword.operator.ts</string>
</dict>
<key>6</key>
<dict>
<key>name</key>
<string>entity.name.function.ts</string>
</dict>
<key>7</key>
<dict>
<key>name</key>
<string>keyword.operator.ts</string>

View file

@ -98,11 +98,11 @@
<array>
<dict>
<key>include</key>
<string>#expression</string>
<string>#object-member</string>
</dict>
<dict>
<key>include</key>
<string>#object-member</string>
<string>#expression</string>
</dict>
</array>
</dict>
@ -348,7 +348,7 @@
<key>field-declaration</key>
<dict>
<key>begin</key>
<string>(?&lt;!\()\s*\b([a-zA-Z_$][\w$]*)\s*(\?\s*)?(?=(=|:))</string>
<string>(?&lt;!\()\s*((?:\b[a-zA-Z_$][\w$]*)|(?:\'[^']*\')|(?:\"[^"]*\"))\s*(\?\s*)?(?=(=|:))</string>
<key>beginCaptures</key>
<dict>
<key>1</key>

View file

@ -1,7 +1,6 @@
{
"comments": {
"lineComment": "'",
"blockComment": [ "/*", "*/" ]
"lineComment": "'"
},
"brackets": [
["{", "}"],

View file

@ -6,24 +6,37 @@
'use strict';
import * as assert from 'assert';
import * as fs from 'fs';
import * as os from 'os';
import {workspace, window, Position, commands} from 'vscode';
import {createRandomFile, deleteFile, cleanUp} from './utils';
import {commands} from 'vscode';
import {join} from 'path';
suite("editor tests", () => {
suite("commands namespace tests", () => {
teardown(cleanUp);
test('getCommands', function(done) {
// test('calling command completes with the extension host updated properly', () => {
// return workspace.openTextDocument(join(workspace.rootPath, './far.js')).then(doc => {
// return window.showTextDocument(doc).then(editor => {
// assert.equal(window.visibleTextEditors.length, 1);
// return commands.executeCommand('workbench.action.closeAllEditors').then(() => {
// assert.equal(window.visibleTextEditors.length, 0);
// });
// });
// });
// });
let p1 = commands.getCommands().then(commands => {
let hasOneWithUnderscore = false;
for (let command of commands) {
if (command[0] === '_') {
hasOneWithUnderscore = true;
break;
}
}
assert.ok(hasOneWithUnderscore);
}, done);
let p2 = commands.getCommands(true).then(commands => {
let hasOneWithUnderscore = false;
for (let command of commands) {
if (command[0] === '_') {
hasOneWithUnderscore = true;
break;
}
}
assert.ok(!hasOneWithUnderscore);
}, done);
Promise.all([p1, p2]).then(() => {
done();
}, done);
});
});

View file

@ -45,7 +45,7 @@ suite('workspace-namespace', () => {
if (process.platform === 'win32') {
return done(); // TODO@Joh this test fails on windows
}
workspace.openTextDocument(Uri.parse('untitled://' + join(workspace.rootPath, './newfile.txt'))).then(doc => {
assert.equal(doc.uri.scheme, 'untitled');
assert.ok(doc.isDirty);
@ -53,28 +53,26 @@ suite('workspace-namespace', () => {
});
});
// test('openTextDocument, untitled closes on save', function(done) {
// workspace.openTextDocument(Uri.parse('untitled://' + join(workspace.rootPath, './newfile2.txt'))).then(doc => {
// assert.equal(doc.uri.scheme, 'untitled');
// assert.ok(doc.isDirty);
test('openTextDocument, untitled closes on save', function() {
const path = join(workspace.rootPath, './newfile.txt');
// let closed: TextDocument, opened: TextDocument;
// let d0 = workspace.onDidCloseTextDocument(e => closed = e);
// let d1 = workspace.onDidOpenTextDocument(e => opened = e);
return workspace.openTextDocument(Uri.parse('untitled://' + path)).then(doc => {
assert.equal(doc.uri.scheme, 'untitled');
assert.ok(doc.isDirty);
// function donedone() {
// assert.ok(closed === doc);
// assert.equal(opened.uri.scheme, 'file');
// assert.equal(opened.uri.toString(), 'file:///' + join(workspace.rootPath, './newfile2.txt'))
// d0.dispose();
// d1.dispose();
let closed: TextDocument;
let d0 = workspace.onDidCloseTextDocument(e => closed = e);
// deleteFile(opened.uri).then(done, done);
// }
return doc.save().then(() => {
assert.ok(closed === doc);
assert.ok(fs.existsSync(path));
// doc.save().then(donedone, done);
// });
// })
d0.dispose();
return deleteFile(Uri.file(join(workspace.rootPath, './newfile.txt')));
});
});
});
test('events: onDidOpenTextDocument, onDidChangeTextDocument, onDidSaveTextDocument', () => {
return createRandomFile().then(file => {

View file

@ -8,6 +8,7 @@
"id": "xml",
"extensions": [
".ascx",
".atom",
".axml",
".bpmn",
".config",

25
npm-shrinkwrap.json generated
View file

@ -414,16 +414,21 @@
"version": "4.3.6",
"from": "semver@>=4.2.0 <5.0.0",
"resolved": "https://registry.npmjs.org/semver/-/semver-4.3.6.tgz"
},
"vscode-debugprotocol": {
"version": "1.0.1",
"from": "vscode-debugprotocol@>=1.0.1",
"resolved": "https://registry.npmjs.org/vscode-debugprotocol/-/vscode-debugprotocol-1.0.1.tgz"
},
"vscode-textmate": {
"version": "1.0.8",
"from": "vscode-textmate@1.0.8",
"resolved": "https://registry.npmjs.org/vscode-textmate/-/vscode-textmate-1.0.8.tgz",
"version": "1.0.9",
"from": "vscode-textmate@1.0.9",
"resolved": "https://registry.npmjs.org/vscode-textmate/-/vscode-textmate-1.0.9.tgz",
"dependencies": {
"oniguruma": {
"version": "5.1.1",
"from": "oniguruma@>=5.1.1 <6.0.0",
"resolved": "https://registry.npmjs.org/oniguruma/-/oniguruma-5.1.1.tgz",
"alexandrudima-oniguruma": {
"version": "6.0.1",
"from": "alexandrudima-oniguruma@>=6.0.0 <7.0.0",
"resolved": "https://registry.npmjs.org/alexandrudima-oniguruma/-/alexandrudima-oniguruma-6.0.1.tgz",
"dependencies": {
"nan": {
"version": "2.0.9",
@ -440,9 +445,9 @@
}
},
"native-keymap": {
"version": "0.0.2",
"from": "native-keymap@0.0.2",
"resolved": "https://registry.npmjs.org/native-keymap/-/native-keymap-0.0.2.tgz"
"version": "0.1.0",
"from": "native-keymap@0.1.0",
"resolved": "https://registry.npmjs.org/native-keymap/-/native-keymap-0.1.0.tgz"
},
"winreg": {
"version": "0.0.12",

View file

@ -1,6 +1,6 @@
{
"name": "Code",
"version": "0.10.3",
"version": "0.10.4",
"electronVersion": "0.34.5",
"author": {
"name": "Microsoft Corporation"
@ -26,8 +26,9 @@
"iconv-lite": "^0.4.13",
"sax": "^1.1.1",
"semver": "^4.2.0",
"vscode-textmate": "^1.0.8",
"native-keymap": "^0.0.2",
"vscode-debugprotocol": "^1.0.0",
"vscode-textmate": "^1.0.9",
"native-keymap": "^0.1.0",
"winreg": "0.0.12",
"yauzl": "^2.3.1"
},
@ -55,7 +56,7 @@
"gulp-rename": "^1.2.0",
"gulp-sourcemaps": "^1.6.0",
"gulp-symdest": "^1.0.0",
"gulp-tsb": "^1.7.3",
"gulp-tsb": "~1.7.3",
"gulp-uglify": "^1.4.1",
"gulp-util": "^3.0.6",
"gulp-vinyl-zip": "^1.1.0",

View file

@ -2,10 +2,11 @@
"nameShort": "Code [OSS Build]",
"nameLong": "Code [OSS Build]",
"win32ExeBasename": "CodeOSS",
"win32MutexName": "vscodeoss",
"companyName": "Microsoft Corporation",
"copyright": "Copyright (C) 2015 Microsoft. All rights reserved",
"licenseUrl": "https://github.com/Microsoft/vscode/blob/master/LICENSE.txt",
"darwinBundleIdentifier": "code.visualstudio.com.Code",
"darwinBundleIdentifier": "com.visualstudio.code.oss",
"darwinApplicationCategoryType": "public.app-category.developer-tools",
"darwinBundleDocumentTypes": [{
"name": "Code OSS Build document",

5
src/bootstrap.js vendored
View file

@ -119,10 +119,7 @@ function uriFromPath(_path) {
}
loader.config({
baseUrl: uriFromPath(path.join(__dirname, '..')),
paths: {
'vs': path.basename(__dirname) + '/vs'
},
baseUrl: uriFromPath(path.join(__dirname)),
catchError: true,
nodeRequire: require,
nodeMain: __filename

View file

@ -1,8 +0,0 @@
// ATTENTION - THIS DIRECTORY CONTAINS THIRD PARTY OPEN SOURCE MATERIALS:
[{
"name": "react",
"version": "0.12.0",
"license": "BSD",
"repositoryURL": "https://github.com/facebook/react"
}]

622
src/lib/react.d.ts vendored
View file

@ -1,622 +0,0 @@
// Type definitions for React 0.12.RC
// Project: http://facebook.github.io/react/
// Definitions by: Asana <https://asana.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
export declare class BaseComponent<P, S> implements Specification<P, S> {
public state: S;
public props: P;
public setState(substate: any, callback?: () => void): void;
public setProps(subprops:any, callback?: () => void): void;
public render(): RenderResult;
public componentWillReceiveProps(nextProps: P): void;
public shouldComponentUpdate(nextProps: P, nextState: S): boolean;
}
export interface DomReferencer2<T extends Element> {
getDOMNode(): T;
}
export interface RenderResult extends ReactElement<any, any> { }
export declare function createFactoryForTS<P>(specification: Specification<P, any>): ReactComponentFactory<P>;
export declare function createClass<P, S>(specification: Specification<P, S>): ReactComponentFactory<P>;
export declare function createFactory<P>(clazz: ReactComponentFactory<P>): ReactComponentFactory<P>;
export declare function createElement<P>(clazz: ReactComponentFactory<P>, props: P, ...children: any[]): ReactComponentElement<P>;
export declare function createElement(type: string, props: DomAttributes, ...children: any[]): ReactHTMLElement;
export declare function createElement(type: string, props: SvgAttributes, ...children: any[]): ReactSVGElement;
export declare function render<P>(component: ReactComponentElement<P>, container: Element, callback?: () => void): ReactComponentElement<P>;
export declare function render(component: ReactHTMLElement, container: Element, callback?: () => void): ReactHTMLElement;
export declare function render(component: ReactSVGElement, container: Element, callback?: () => void): ReactSVGElement;
export declare function unmountComponentAtNode(container: Element): boolean;
export declare function renderToString<P>(component: ReactComponentElement<P>): string;
export declare function renderToString(component: ReactHTMLElement): string;
export declare function renderToString(component: ReactSVGElement): string;
export declare function renderToStaticMarkup<P>(component: ReactComponentElement<P>): string;
export declare function renderToStaticMarkup(component: ReactHTMLElement): string;
export declare function renderToStaticMarkup(component: ReactSVGElement): string;
export declare function isValidClass(factory: ReactComponentFactory<any>): boolean;
export declare function isValidElement(component: ReactComponentElement<any>): boolean;
export declare function isValidElement(component: ReactHTMLElement): boolean;
export declare function isValidElement(component: ReactSVGElement): boolean;
export declare function initializeTouchEvents(shouldUseTouch: boolean): void;
export interface ReactComponentFactory<P> {
(properties: P, ...children: any[]): ReactComponentElement<P>;
}
export interface ReactElementFactory<P> {
(properties: P, ...children: any[]): ReactDOMElement<P>;
}
export interface DomElement extends ReactElementFactory<DomAttributes> {
}
export interface SvgElement extends ReactElementFactory<SvgAttributes> {
}
export interface ReactClass<P> {
(props: P): ReactComponent<P>;
}
export interface ReactComponent<P> {
props: P;
render(): ReactElement<any, any>;
}
export interface ReactElement<T, P> {
type: T;
props: P;
key: string;
ref: string;
}
export interface ReactDOMElement<P> extends ReactElement<string, P> {
props: P;
}
export interface ReactHTMLElement extends ReactDOMElement<DomAttributes> {
}
export interface ReactSVGElement extends ReactDOMElement<SvgAttributes> {
}
export interface ReactComponentElement<P> extends ReactElement<ReactClass<P>, P> {
props: P;
}
export interface Mixin<P, S> {
componentWillMount?(): void;
componentDidMount?(): void;
componentWillReceiveProps?(nextProps: P): void;
shouldComponentUpdate?(nextProps: P, nextState: S): boolean;
componentWillUpdate?(nextProps: P, nextState: S): void;
componentDidUpdate?(prevProps: P, prevState: S): void;
componentWillUnmount?(): void;
}
export interface Specification<P, S> extends Mixin<P, S> {
displayName?: string;
mixins?: Mixin<P, S>[];
statics?: {
[key: string]: Function;
};
propTypes?: ValidationMap<P>;
getDefaultProps?(): P;
getInitialState?(): S;
render(): ReactElement<any, any>;
}
export interface DomReferencer {
getDOMNode(): Element;
}
export interface Component<P, S> extends DomReferencer {
refs: {
[key: string]: DomReferencer
};
props: P;
state: S;
setState(nextState: S, callback?: () => void): void;
replaceState(nextState: S, callback?: () => void): void;
forceUpdate(callback?: () => void): void;
isMounted(): boolean;
setProps(nextProps: P, callback?: () => void): void;
replaceProps(nextProps: P, callback?: () => void): void;
}
export interface Constructable {
new(): any;
}
export interface Validator<P> {
(props: P, propName: string, componentName: string): Error;
}
export interface Requireable<P> extends Validator<P> {
isRequired: Validator<P>;
}
export interface ValidationMap<P> {
[key: string]: Validator<P>;
}
export declare var PropTypes: {
any: Requireable<any>;
array: Requireable<any>;
bool: Requireable<any>;
func: Requireable<any>;
number: Requireable<any>;
object: Requireable<any>;
string: Requireable<any>;
node: Requireable<any>;
component: Requireable<any>;
instanceOf: (clazz: Constructable) => Requireable<any>;
oneOf: (types: any[]) => Requireable<any>;
oneOfType: (types: Validator<any>[]) => Requireable<any>;
arrayOf: (type: Validator<any>) => Requireable<any>;
objectOf: (type: Validator<any>) => Requireable<any>;
shape: (type: ValidationMap<any>) => Requireable<any>;
};
export declare var Children: {
map(children: any[], fn: (child: any) => any): any[];
forEach(children: any[], fn: (child: any) => any): void;
count(children: any[]): number;
only(children: any[]): any;
};
// Browser Interfaces
// Taken from https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts
export interface AbstractView {
styleMedia: StyleMedia;
document: Document;
}
export interface Touch {
identifier: number;
target: EventTarget;
screenX: number;
screenY: number;
clientX: number;
clientY: number;
pageX: number;
pageY: number;
}
export interface TouchList {
[index: number]: Touch;
length: number;
item(index: number): Touch;
identifiedTouch(identifier: number): Touch;
}
// Events
export interface SyntheticEvent {
bubbles: boolean;
cancelable: boolean;
currentTarget: EventTarget;
defaultPrevented: boolean;
eventPhase: number;
nativeEvent: Event;
preventDefault(): void;
stopPropagation(): void;
target: EventTarget;
timeStamp: number;
type: string;
}
export interface ClipboardEvent extends SyntheticEvent {
clipboardData: DataTransfer;
}
export interface KeyboardEvent extends SyntheticEvent {
altKey: boolean;
charCode: number;
ctrlKey: boolean;
getModifierState(key: string): boolean;
key: string;
keyCode: number;
locale: string;
location: number;
metaKey: boolean;
repeat: boolean;
shiftKey: boolean;
which: number;
}
export interface FocusEvent extends SyntheticEvent {
relatedTarget: EventTarget;
}
export interface MouseEvent extends SyntheticEvent {
altKey: boolean;
button: number;
buttons: number;
clientX: number;
clientY: number;
ctrlKey: boolean;
getModifierState(key: string): boolean;
metaKey: boolean;
pageX: number;
pageY: number;
relatedTarget: EventTarget;
screenX: number;
screenY: number;
shiftKey: boolean;
}
export interface TouchEvent extends SyntheticEvent {
altKey: boolean;
changedTouches: TouchList;
ctrlKey: boolean;
getModifierState(key: string): boolean;
metaKey: boolean;
shiftKey: boolean;
targetTouches: TouchList;
touches: TouchList;
}
export interface UiEvent extends SyntheticEvent {
detail: number;
view: AbstractView;
}
export interface WheelEvent extends SyntheticEvent {
deltaMode: number;
deltaX: number;
deltaY: number;
deltaZ: number;
}
// Attributes
export interface EventAttributes {
onCopy?: (event: ClipboardEvent) => void;
onCut?: (event: ClipboardEvent) => void;
onPaste?: (event: ClipboardEvent) => void;
onKeyDown?: (event: KeyboardEvent) => void;
onKeyPress?: (event: KeyboardEvent) => void;
onKeyUp?: (event: KeyboardEvent) => void;
onFocus?: (event: FocusEvent) => void;
onBlur?: (event: FocusEvent) => void;
onChange?: (event: SyntheticEvent) => void;
onInput?: (event: SyntheticEvent) => void;
onSubmit?: (event: SyntheticEvent) => void;
onClick?: (event: MouseEvent) => void;
onDoubleClick?: (event: MouseEvent) => void;
onDrag?: (event: MouseEvent) => void;
onDragEnd?: (event: MouseEvent) => void;
onDragEnter?: (event: MouseEvent) => void;
onDragExit?: (event: MouseEvent) => void;
onDragLeave?: (event: MouseEvent) => void;
onDragOver?: (event: MouseEvent) => void;
onDragStart?: (event: MouseEvent) => void;
onDrop?: (event: MouseEvent) => void;
onMouseDown?: (event: MouseEvent) => void;
onMouseEnter?: (event: MouseEvent) => void;
onMouseLeave?: (event: MouseEvent) => void;
onMouseMove?: (event: MouseEvent) => void;
onMouseOut?: (event: MouseEvent) => void;
onMouseOver?: (event: MouseEvent) => void;
onMouseUp?: (event: MouseEvent) => void;
onTouchCancel?: (event: TouchEvent) => void;
onTouchEnd?: (event: TouchEvent) => void;
onTouchMove?: (event: TouchEvent) => void;
onTouchStart?: (event: TouchEvent) => void;
onScroll?: (event: UiEvent) => void;
onWheel?: (event: WheelEvent) => void;
}
export interface ReactAttributes {
dangerouslySetInnerHTML?: {
__html: string;
};
children?: any[];
key?: string;
ref?: string;
}
export interface DomAttributes extends EventAttributes, ReactAttributes {
// HTML Attributes
accept?: any;
accessKey?: any;
action?: any;
allowFullScreen?: any;
allowTransparency?: any;
alt?: any;
async?: any;
autoCapitalize?: any;
autoComplete?: any;
autoCorrect?: any;
autoFocus?: any;
autoPlay?: any;
cellPadding?: any;
cellSpacing?: any;
charSet?: any;
checked?: any;
className?: any;
cols?: any;
colSpan?: any;
content?: any;
contentEditable?: any;
contextMenu?: any;
controls?: any;
coords?: any;
crossOrigin?: any;
data?: any;
dateTime?: any;
defer?: any;
dir?: any;
disabled?: any;
download?: any;
draggable?: any;
encType?: any;
form?: any;
formNoValidate?: any;
frameBorder?: any;
height?: any;
hidden?: any;
href?: any;
hrefLang?: any;
htmlFor?: any;
httpEquiv?: any;
icon?: any;
id?: any;
itemProp?: any;
itemScope?: any;
itemType?: any;
label?: any;
lang?: any;
list?: any;
loop?: any;
max?: any;
maxLength?: any;
mediaGroup?: any;
method?: any;
min?: any;
multiple?: any;
muted?: any;
name?: any;
noValidate?: any;
open?: any;
pattern?: any;
placeholder?: any;
poster?: any;
preload?: any;
property?: any;
radioGroup?: any;
readOnly?: any;
rel?: any;
required?: any;
role?: any;
rows?: any;
rowSpan?: any;
sandbox?: any;
scope?: any;
scrollLeft?: any;
scrolling?: any;
scrollTop?: any;
seamless?: any;
selected?: any;
shape?: any;
size?: any;
span?: any;
spellCheck?: any;
src?: any;
srcDoc?: any;
srcSet?: any;
start?: any;
step?: any;
style?: any;
tabIndex?: any;
target?: any;
title?: any;
type?: any;
useMap?: any;
value?: any;
width?: any;
wmode?: any;
}
export interface SvgAttributes extends EventAttributes, ReactAttributes {
cx?: any;
cy?: any;
d?: any;
dx?: any;
dy?: any;
fill?: any;
fillOpacity?: any;
fontFamily?: any;
fontSize?: any;
fx?: any;
fy?: any;
gradientTransform?: any;
gradientUnits?: any;
markerEnd?: any;
markerMid?: any;
markerStart?: any;
offset?: any;
opacity?: any;
patternContentUnits?: any;
patternUnits?: any;
points?: any;
preserveAspectRatio?: any;
r?: any;
rx?: any;
ry?: any;
spreadMethod?: any;
stopColor?: any;
stopOpacity?: any;
stroke?: any;
strokeDasharray?: any;
strokeLinecap?: any;
strokeOpacity?: any;
strokeWidth?: any;
textAnchor?: any;
transform?: any;
version?: any;
viewBox?: any;
x1?: any;
x2?: any;
x?: any;
y1?: any;
y2?: any;
y?: any;
}
export declare var DOM: {
// HTML
a: DomElement;
abbr: DomElement;
address: DomElement;
area: DomElement;
article: DomElement;
aside: DomElement;
audio: DomElement;
b: DomElement;
base: DomElement;
bdi: DomElement;
bdo: DomElement;
big: DomElement;
blockquote: DomElement;
body: DomElement;
br: DomElement;
button: DomElement;
canvas: DomElement;
caption: DomElement;
cite: DomElement;
code: DomElement;
col: DomElement;
colgroup: DomElement;
data: DomElement;
datalist: DomElement;
dd: DomElement;
del: DomElement;
details: DomElement;
dfn: DomElement;
dialog: DomElement;
div: DomElement;
dl: DomElement;
dt: DomElement;
em: DomElement;
embed: DomElement;
fieldset: DomElement;
figcaption: DomElement;
figure: DomElement;
footer: DomElement;
form: DomElement;
h1: DomElement;
h2: DomElement;
h3: DomElement;
h4: DomElement;
h5: DomElement;
h6: DomElement;
head: DomElement;
header: DomElement;
hr: DomElement;
html: DomElement;
i: DomElement;
iframe: DomElement;
img: DomElement;
input: DomElement;
ins: DomElement;
kbd: DomElement;
keygen: DomElement;
label: DomElement;
legend: DomElement;
li: DomElement;
link: DomElement;
main: DomElement;
map: DomElement;
mark: DomElement;
menu: DomElement;
menuitem: DomElement;
meta: DomElement;
meter: DomElement;
nav: DomElement;
noscript: DomElement;
object: DomElement;
ol: DomElement;
optgroup: DomElement;
option: DomElement;
output: DomElement;
p: DomElement;
param: DomElement;
pre: DomElement;
progress: DomElement;
q: DomElement;
rp: DomElement;
rt: DomElement;
ruby: DomElement;
s: DomElement;
samp: DomElement;
script: DomElement;
section: DomElement;
select: DomElement;
small: DomElement;
source: DomElement;
span: DomElement;
strong: DomElement;
style: DomElement;
sub: DomElement;
summary: DomElement;
sup: DomElement;
table: DomElement;
tbody: DomElement;
td: DomElement;
textarea: DomElement;
tfoot: DomElement;
th: DomElement;
thead: DomElement;
time: DomElement;
title: DomElement;
tr: DomElement;
track: DomElement;
u: DomElement;
ul: DomElement;
'var': DomElement;
video: DomElement;
wbr: DomElement;
// SVG
circle: SvgElement;
defs: SvgElement;
ellipse: SvgElement;
g: SvgElement;
line: SvgElement;
linearGradient: SvgElement;
mask: SvgElement;
path: SvgElement;
pattern: SvgElement;
polygon: SvgElement;
polyline: SvgElement;
radialGradient: SvgElement;
rect: SvgElement;
stop: SvgElement;
svg: SvgElement;
text: SvgElement;
tspan: SvgElement;
};

95
src/lib/react.js vendored
View file

@ -1,95 +0,0 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
define(['./react.raw'], function(React) {
if (!React.isProxy) {
// Patch the real React to prevent immutable fields when handling events asynchronously
var wrapFormElement = function(ctor, displayName) {
return React.createClass({
getDisplayName: function() {
return displayName;
},
getInitialState: function() {
return {
value: this.props.value
};
},
onChange: function(e) {
this.setState({
value: e.target.value
});
if (this.props.onChange) {
this.props.onChange(e);
}
},
componentWillReceiveProps: function(newProps) {
this.setState({
value: newProps.value
});
},
render: function() {
var clone = {};
for (var key in this.props) {
if (this.props.hasOwnProperty(key)) {
clone[key] = this.props[key];
}
}
clone.value = this.state.value;
clone.onChange = this.onChange;
return ctor(clone);
}
});
}
React.DOM.input = React.createFactory(wrapFormElement(React.DOM.input, 'input'));
React.DOM.textarea = React.createFactory(wrapFormElement(React.DOM.textarea, 'textarea'));
React.DOM.option = React.createFactory(wrapFormElement(React.DOM.option, 'option'));
}
if (typeof React.DOM.webview === 'undefined') {
if (typeof self.process !== 'undefined') {
React.DOM.webview = React.createFactory(React.createClass({
componentDidMount: function() {
var webview = document.createElement('webview');
webview.src = this.props.src;
var el = this.getDOMNode();
el.appendChild(webview);
},
render: function() {
return React.DOM.div();
}
}));
} else {
React.DOM.webview = React.createFactory(React.createClass({
render: function() {
return React.DOM.iframe({
src: this.props.src
});
}
}));
}
}
var exports = React;
// Utils for easy usage of React in TS
exports.BaseComponent = function() { };
exports.createFactoryForTS = function(klass) {
var r = {};
for (var p in klass) {
if (p !== 'constructor' && klass.hasOwnProperty(p) && typeof klass[p] === 'function') {
r[p] = klass[p];
}
}
return React.createFactory(React.createClass(r));
}
return exports;
});

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,18 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'native-keymap' {
export interface INativeKeyMap {
key_code: string;
value: string;
withShift: string;
withAltGr: string;
withShiftAltGr: string;
}
export function getKeyMap(): INativeKeyMap[];
}

View file

@ -0,0 +1,18 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'native-keymap' {
export interface INativeKeyMap {
key_code: string;
value: string;
withShift: string;
withAltGr: string;
withShiftAltGr: string;
}
export function getKeyMap(): INativeKeyMap[];
}

View file

@ -0,0 +1,12 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'windows-mutex' {
export class Mutex {
constructor(name: string);
isActive(): boolean;
release(): void;
}
}

View file

@ -0,0 +1,12 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'windows-mutex' {
export class Mutex {
constructor(name: string);
isActive(): boolean;
release(): void;
}
}

View file

@ -1067,3 +1067,11 @@ export function emmet(description: string):HTMLElement {
return result;
};
export function show(element: HTMLElement): void {
element.style.display = null;
}
export function hide(element: HTMLElement): void {
element.style.display = 'none';
}

View file

@ -72,6 +72,22 @@ let KEY_CODE_MAP: {[keyCode:number]:KeyCode} = {};
KEY_CODE_MAP[93] = KeyCode.ContextMenu;
KEY_CODE_MAP[96] = KeyCode.NUMPAD_0;
KEY_CODE_MAP[97] = KeyCode.NUMPAD_1;
KEY_CODE_MAP[98] = KeyCode.NUMPAD_2;
KEY_CODE_MAP[99] = KeyCode.NUMPAD_3;
KEY_CODE_MAP[100] = KeyCode.NUMPAD_4;
KEY_CODE_MAP[101] = KeyCode.NUMPAD_5;
KEY_CODE_MAP[102] = KeyCode.NUMPAD_6;
KEY_CODE_MAP[103] = KeyCode.NUMPAD_7;
KEY_CODE_MAP[104] = KeyCode.NUMPAD_8;
KEY_CODE_MAP[105] = KeyCode.NUMPAD_9;
KEY_CODE_MAP[106] = KeyCode.NUMPAD_MULTIPLY;
KEY_CODE_MAP[107] = KeyCode.NUMPAD_ADD;
KEY_CODE_MAP[109] = KeyCode.NUMPAD_SUBTRACT;
KEY_CODE_MAP[110] = KeyCode.NUMPAD_DECIMAL;
KEY_CODE_MAP[111] = KeyCode.NUMPAD_DIVIDE;
KEY_CODE_MAP[112] = KeyCode.F1;
KEY_CODE_MAP[113] = KeyCode.F2;
KEY_CODE_MAP[114] = KeyCode.F3;
@ -125,20 +141,13 @@ interface INormalizedKeyCode {
key: string;
}
function extractKeyCode(e:KeyboardEvent): INormalizedKeyCode {
function extractKeyCode(e:KeyboardEvent): KeyCode {
if (e.charCode) {
// "keypress" events mostly
let char = String.fromCharCode(e.charCode).toUpperCase();
return {
keyCode: KeyCode.fromString(char),
key: char
};
return KeyCode.fromString(char);
}
let keyCode = KEY_CODE_MAP[e.keyCode] || KeyCode.Unknown;
return {
keyCode: keyCode,
key: KeyCode.toString(keyCode)
};
return KEY_CODE_MAP[e.keyCode] || KeyCode.Unknown;
}
export interface IKeyboardEvent {
@ -159,6 +168,11 @@ export interface IKeyboardEvent {
stopPropagation(): void;
}
const ctrlKeyMod = (Platform.isMacintosh ? KeyMod.WinCtrl : KeyMod.CtrlCmd);
const altKeyMod = KeyMod.Alt;
const shiftKeyMod = KeyMod.Shift;
const metaKeyMod = (Platform.isMacintosh ? KeyMod.CtrlCmd : KeyMod.WinCtrl);
export class StandardKeyboardEvent implements IKeyboardEvent {
public browserEvent: KeyboardEvent;
@ -170,44 +184,40 @@ export class StandardKeyboardEvent implements IKeyboardEvent {
public metaKey: boolean;
public keyCode: KeyCode;
private key: string;
private __asKeybinding: number;
private _asKeybinding: number;
constructor(source:StandardKeyboardEvent|KeyboardEvent) {
if (source instanceof StandardKeyboardEvent) {
let e = <StandardKeyboardEvent>source;
this.browserEvent = null;
this.ctrlKey = e.ctrlKey;
this.shiftKey = e.shiftKey;
this.altKey = e.altKey;
this.metaKey = e.metaKey;
this.target = e.target;
this.key = e.key;
this.keyCode = e.keyCode;
this.__asKeybinding = e.__asKeybinding;
this.target = source.target;
this.ctrlKey = source.ctrlKey;
this.shiftKey = source.shiftKey;
this.altKey = source.altKey;
this.metaKey = source.metaKey;
this.keyCode = source.keyCode;
this._asKeybinding = source._asKeybinding;
} else {
let e = <KeyboardEvent>source;
this.browserEvent = e;
this.target = e.target || (<any>e).targetNode;
this.ctrlKey = e.ctrlKey;
this.shiftKey = e.shiftKey;
this.altKey = e.altKey;
this.metaKey = e.metaKey;
this.target = e.target || (<any>e).targetNode;
let standardKeyCode = extractKeyCode(e);
this.key = standardKeyCode.key;
this.keyCode = standardKeyCode.keyCode;
this.keyCode = extractKeyCode(e);
// console.info(e.type + ": keyCode: " + e.keyCode + ", which: " + e.which + ", charCode: " + e.charCode + ", detail: " + e.detail + " ====> " + this.key + ' -- ' + KeyCode[this.keyCode]);
this.ctrlKey = this.ctrlKey || this.key === 'Ctrl';
this.altKey = this.altKey || this.key === 'Alt';
this.shiftKey = this.shiftKey || this.key === 'Shift';
this.metaKey = this.metaKey || this.key === 'Meta';
this.ctrlKey = this.ctrlKey || this.keyCode === KeyCode.Ctrl;
this.altKey = this.altKey || this.keyCode === KeyCode.Alt;
this.shiftKey = this.shiftKey || this.keyCode === KeyCode.Shift;
this.metaKey = this.metaKey || this.keyCode === KeyCode.Meta;
this.__asKeybinding = this._asKeybinding();
this._asKeybinding = this._computeKeybinding();
}
}
@ -228,56 +238,31 @@ export class StandardKeyboardEvent implements IKeyboardEvent {
}
public asKeybinding(): number {
return this.__asKeybinding;
return this._asKeybinding;
}
public equals(other:number): boolean {
return (this.__asKeybinding === other);
return (this._asKeybinding === other);
}
private _asKeybinding(): number {
var ctrlCmd = false,
shift = false,
alt = false,
winCtrl = false,
key = KeyCode.Unknown;
if (this.ctrlKey) {
if (Platform.isMacintosh) {
winCtrl = true;
} else {
ctrlCmd = true;
}
}
if (this.shiftKey) {
shift = true;
}
if (this.altKey) {
alt = true;
}
if (this.metaKey) {
if (Platform.isMacintosh) {
ctrlCmd = true;
} else {
winCtrl = true;
}
}
private _computeKeybinding(): number {
let key = KeyCode.Unknown;
if (this.keyCode !== KeyCode.Ctrl && this.keyCode !== KeyCode.Shift && this.keyCode !== KeyCode.Alt && this.keyCode !== KeyCode.Meta) {
key = this.keyCode;
}
let result = 0;
if (ctrlCmd) {
result |= KeyMod.CtrlCmd;
if (this.ctrlKey) {
result |= ctrlKeyMod;
}
if (shift) {
result |= KeyMod.Shift;
if (this.altKey) {
result |= altKeyMod;
}
if (alt) {
result |= KeyMod.Alt;
if (this.shiftKey) {
result |= shiftKeyMod;
}
if (winCtrl) {
result |= KeyMod.WinCtrl;
if (this.metaKey) {
result |= metaKeyMod;
}
result |= key;

View file

@ -20,8 +20,17 @@ export interface IOptions {
width?:number;
validation?:InputBox.IInputValidator;
label:string;
appendCaseSensitiveLabel?: string;
appendWholeWordsLabel?: string;
appendRegexLabel?: string;
}
const NLS_REGEX_CHECKBOX_LABEL = nls.localize('regexDescription', "Use Regular Expression");
const NLS_WHOLE_WORD_CHECKBOX_LABEL = nls.localize('wordsDescription', "Match Whole Word");
const NLS_CASE_SENSITIVE_CHECKBOX_LABEL = nls.localize('caseDescription', "Match Case");
const NLS_DEFAULT_LABEL = nls.localize('defaultLabel', "input");
export class FindInput {
static OPTION_CHANGE:string = 'optionChange';
@ -48,7 +57,7 @@ export class FindInput {
this.width = options.width || 100;
this.placeholder = options.placeholder || '';
this.validation = options.validation;
this.label = options.label || nls.localize('defaultLabel', "input");
this.label = options.label || NLS_DEFAULT_LABEL;
this.listenersToRemove = [];
this.regex = null;
@ -59,7 +68,7 @@ export class FindInput {
this.inputBox = null;
this.validationNode = null;
this.buildDomNode();
this.buildDomNode(options.appendCaseSensitiveLabel || '', options.appendWholeWordsLabel || '', options.appendRegexLabel || '');
if(Boolean(parent)) {
parent.appendChild(this.domNode);
@ -172,7 +181,7 @@ export class FindInput {
this.inputBox.width = w;
}
private buildDomNode(): void {
private buildDomNode(appendCaseSensitiveLabel:string, appendWholeWordsLabel: string, appendRegexLabel: string): void {
this.domNode = document.createElement('div');
this.domNode.style.width = this.width + 'px';
$(this.domNode).addClass('monaco-findInput');
@ -186,19 +195,19 @@ export class FindInput {
}
});
this.regex = new Checkbox.Checkbox('regex', nls.localize('regexDescription', "Use Regular Expression"), false, () => {
this.regex = new Checkbox.Checkbox('regex', NLS_REGEX_CHECKBOX_LABEL + appendRegexLabel, false, () => {
this.onOptionChange(null);
this.inputBox.focus();
this.setInputWidth();
this.validate();
});
this.wholeWords = new Checkbox.Checkbox('whole-word', nls.localize('wordsDescription', "Match Whole Word"), false, () => {
this.wholeWords = new Checkbox.Checkbox('whole-word', NLS_WHOLE_WORD_CHECKBOX_LABEL + appendWholeWordsLabel, false, () => {
this.onOptionChange(null);
this.inputBox.focus();
this.setInputWidth();
this.validate();
});
this.caseSensitive = new Checkbox.Checkbox('case-sensitive', nls.localize('caseDescription', "Match Case"), false, () => {
this.caseSensitive = new Checkbox.Checkbox('case-sensitive', NLS_CASE_SENSITIVE_CHECKBOX_LABEL + appendCaseSensitiveLabel, false, () => {
this.onOptionChange(null);
this.inputBox.focus();
this.setInputWidth();

View file

@ -5,15 +5,15 @@
'use strict';
import DomUtils = require('vs/base/browser/dom');
import Mouse = require('vs/base/browser/mouseEvent');
import Common = require('vs/base/browser/ui/scrollbar/impl/common');
import Lifecycle = require('vs/base/common/lifecycle');
import GlobalMouseMoveMonitor = require('vs/base/browser/globalMouseMoveMonitor');
import {StandardMouseEvent} from 'vs/base/browser/mouseEvent';
import {IMouseWheelEvent, IParent, Visibility, IScrollbar} from 'vs/base/browser/ui/scrollbar/impl/common';
import {IDisposable, disposeAll} from 'vs/base/common/lifecycle';
import {GlobalMouseMoveMonitor, IStandardMouseMoveEventData, standardMouseMoveMerger} from 'vs/base/browser/globalMouseMoveMonitor';
import Browser = require('vs/base/browser/browser');
import Platform = require('vs/base/common/platform');
export interface IMouseWheelEventFactory {
():Common.IMouseWheelEvent;
():IMouseWheelEvent;
}
export class ScrollbarState {
@ -166,16 +166,16 @@ export class ScrollbarState {
}
class ScrollbarArrow {
private parent:Common.IParent;
private parent:IParent;
private mouseWheelEventFactory:IMouseWheelEventFactory;
public bgDomNode:HTMLElement;
public domNode:HTMLElement;
private toDispose:Lifecycle.IDisposable[];
private toDispose:IDisposable[];
private interval:number;
private timeout:number;
private mouseMoveMonitor:GlobalMouseMoveMonitor.GlobalMouseMoveMonitor<GlobalMouseMoveMonitor.IStandardMouseMoveEventData>;
private mouseMoveMonitor:GlobalMouseMoveMonitor<IStandardMouseMoveEventData>;
constructor(className:string, top:number, left:number, bottom:number, right:number, bgWidth:number, bgHeight:number, mouseWheelEventFactory:IMouseWheelEventFactory, parent:Common.IParent) {
constructor(className:string, top:number, left:number, bottom:number, right:number, bgWidth:number, bgHeight:number, mouseWheelEventFactory:IMouseWheelEventFactory, parent:IParent) {
this.parent = parent;
this.mouseWheelEventFactory = mouseWheelEventFactory;
@ -192,7 +192,7 @@ class ScrollbarArrow {
setSize(this.domNode, AbstractScrollbar.ARROW_IMG_SIZE, AbstractScrollbar.ARROW_IMG_SIZE);
setPosition(this.domNode, top, left, bottom, right);
this.mouseMoveMonitor = new GlobalMouseMoveMonitor.GlobalMouseMoveMonitor<GlobalMouseMoveMonitor.IStandardMouseMoveEventData>();
this.mouseMoveMonitor = new GlobalMouseMoveMonitor<IStandardMouseMoveEventData>();
this.toDispose = [];
this.toDispose.push(DomUtils.addDisposableListener(this.bgDomNode, 'mousedown', (e:MouseEvent) => this._arrowMouseDown(e)));
@ -203,7 +203,7 @@ class ScrollbarArrow {
}
public dispose(): void {
this.toDispose = Lifecycle.disposeAll(this.toDispose);
this.toDispose = disposeAll(this.toDispose);
this._clearArrowTimers();
}
@ -221,8 +221,8 @@ class ScrollbarArrow {
this.timeout = window.setTimeout(scheduleRepeater, 200);
this.mouseMoveMonitor.startMonitoring(
GlobalMouseMoveMonitor.standardMouseMoveMerger,
(mouseMoveData:GlobalMouseMoveMonitor.IStandardMouseMoveEventData) => {
standardMouseMoveMerger,
(mouseMoveData:IStandardMouseMoveEventData) => {
/* Intentional empty */
},
() => {
@ -230,7 +230,7 @@ class ScrollbarArrow {
}
);
var mouseEvent = new Mouse.StandardMouseEvent(browserEvent);
var mouseEvent = new StandardMouseEvent(browserEvent);
mouseEvent.preventDefault();
}
@ -246,8 +246,8 @@ class ScrollbarArrow {
}
}
class VisibilityController implements Lifecycle.IDisposable {
private visibility:Common.Visibility;
class VisibilityController implements IDisposable {
private visibility:Visibility;
private visibleClassName:string;
private invisibleClassName:string;
private domNode:HTMLElement;
@ -256,7 +256,7 @@ class VisibilityController implements Lifecycle.IDisposable {
private isVisible:boolean;
private fadeAwayTimeout:number;
constructor(visibility:Common.Visibility, visibleClassName:string, invisibleClassName:string) {
constructor(visibility:Visibility, visibleClassName:string, invisibleClassName:string) {
this.visibility = visibility;
this.visibleClassName = visibleClassName;
this.invisibleClassName = invisibleClassName;
@ -281,10 +281,10 @@ class VisibilityController implements Lifecycle.IDisposable {
// ----------------- Hide / Reveal
private applyVisibilitySetting(shouldBeVisible:boolean): boolean {
if (this.visibility === Common.Visibility.Hidden) {
if (this.visibility === Visibility.Hidden) {
return false;
}
if (this.visibility === Common.Visibility.Visible) {
if (this.visibility === Visibility.Visible) {
return true;
}
return shouldBeVisible;
@ -369,7 +369,7 @@ export interface IMouseMoveEventData {
posy:number;
}
export class AbstractScrollbar implements Common.IScrollbar {
export abstract class AbstractScrollbar implements IScrollbar {
static ARROW_IMG_SIZE = 11;
/**
@ -378,22 +378,22 @@ export class AbstractScrollbar implements Common.IScrollbar {
static MOUSE_DRAG_RESET_DISTANCE = 140;
protected forbidTranslate3dUse:boolean;
private parent:Common.IParent;
private parent:IParent;
private scrollbarState:ScrollbarState;
private visibilityController:VisibilityController;
private mouseMoveMonitor:GlobalMouseMoveMonitor.GlobalMouseMoveMonitor<GlobalMouseMoveMonitor.IStandardMouseMoveEventData>;
private mouseMoveMonitor:GlobalMouseMoveMonitor<IStandardMouseMoveEventData>;
private toDispose:Lifecycle.IDisposable[];
private toDispose:IDisposable[];
public domNode:HTMLElement;
public slider:HTMLElement;
constructor(forbidTranslate3dUse:boolean, parent:Common.IParent, scrollbarState:ScrollbarState, visibility:Common.Visibility, extraScrollbarClassName:string) {
constructor(forbidTranslate3dUse:boolean, parent:IParent, scrollbarState:ScrollbarState, visibility:Visibility, extraScrollbarClassName:string) {
this.forbidTranslate3dUse = forbidTranslate3dUse;
this.parent = parent;
this.scrollbarState = scrollbarState;
this.visibilityController = new VisibilityController(visibility, 'visible scrollbar ' + extraScrollbarClassName, 'invisible scrollbar ' + extraScrollbarClassName);
this.mouseMoveMonitor = new GlobalMouseMoveMonitor.GlobalMouseMoveMonitor<GlobalMouseMoveMonitor.IStandardMouseMoveEventData>();
this.mouseMoveMonitor = new GlobalMouseMoveMonitor<IStandardMouseMoveEventData>();
this.toDispose = [];
this.toDispose.push(this.visibilityController);
@ -439,14 +439,14 @@ export class AbstractScrollbar implements Common.IScrollbar {
setSize(this.slider, width, height);
this.domNode.appendChild(this.slider);
this.toDispose.push(DomUtils.addDisposableListener(this.slider, 'mousedown', (e:MouseEvent) => this._sliderMouseDown(new Mouse.StandardMouseEvent(e))));
this.toDispose.push(DomUtils.addDisposableListener(this.slider, 'mousedown', (e:MouseEvent) => this._sliderMouseDown(new StandardMouseEvent(e))));
}
/**
* Clean-up
*/
public destroy(): void {
this.toDispose = Lifecycle.disposeAll(this.toDispose);
this.toDispose = disposeAll(this.toDispose);
}
// ----------------- Update state
@ -490,7 +490,7 @@ export class AbstractScrollbar implements Common.IScrollbar {
// ----------------- DOM events
private _domNodeMouseDown(browserEvent:MouseEvent): void {
var e = new Mouse.StandardMouseEvent(browserEvent);
var e = new StandardMouseEvent(browserEvent);
if (e.target !== this.domNode) {
return;
}
@ -498,7 +498,7 @@ export class AbstractScrollbar implements Common.IScrollbar {
}
public delegateMouseDown(browserEvent:MouseEvent): void {
var e = new Mouse.StandardMouseEvent(browserEvent);
var e = new StandardMouseEvent(browserEvent);
var domTop = this.domNode.getClientRects()[0].top;
var sliderStart = domTop + this.scrollbarState.getSliderPosition();
var sliderStop = domTop + this.scrollbarState.getSliderPosition() + this.scrollbarState.getSliderSize();
@ -512,14 +512,14 @@ export class AbstractScrollbar implements Common.IScrollbar {
}
}
private _onMouseDown(e:Mouse.StandardMouseEvent): void {
private _onMouseDown(e:StandardMouseEvent): void {
var domNodePosition = DomUtils.getDomNodePosition(this.domNode);
var desiredSliderPosition = this._mouseDownRelativePosition(e, domNodePosition) - this.scrollbarState.getArrowSize() - this.scrollbarState.getSliderSize() / 2;
this.setDesiredScrollPosition(this.scrollbarState.convertSliderPositionToScrollPosition(desiredSliderPosition));
this._sliderMouseDown(e);
}
private _sliderMouseDown(e:Mouse.StandardMouseEvent): void {
private _sliderMouseDown(e:StandardMouseEvent): void {
if (e.leftButton) {
var initialMouseOrthogonalPosition = this._sliderOrthogonalMousePosition(e);
var initialScrollPosition = this._getScrollPosition();
@ -527,8 +527,8 @@ export class AbstractScrollbar implements Common.IScrollbar {
DomUtils.toggleClass(this.slider, 'active', true);
this.mouseMoveMonitor.startMonitoring(
GlobalMouseMoveMonitor.standardMouseMoveMerger,
(mouseMoveData:GlobalMouseMoveMonitor.IStandardMouseMoveEventData) => {
standardMouseMoveMerger,
(mouseMoveData:IStandardMouseMoveEventData) => {
var mouseOrthogonalPosition = this._sliderOrthogonalMousePosition(mouseMoveData);
var mouseOrthogonalDelta = Math.abs(mouseOrthogonalPosition - initialMouseOrthogonalPosition);
// console.log(initialMouseOrthogonalPosition + ' -> ' + mouseOrthogonalPosition + ': ' + mouseOrthogonalDelta);
@ -571,7 +571,7 @@ export class AbstractScrollbar implements Common.IScrollbar {
public _updateSlider(sliderSize:number, sliderPosition:number): void {
}
public _mouseDownRelativePosition(e:Mouse.StandardMouseEvent, domNodePosition:DomUtils.IDomNodePosition): number {
public _mouseDownRelativePosition(e:StandardMouseEvent, domNodePosition:DomUtils.IDomNodePosition): number {
return 0;
}

View file

@ -4,7 +4,6 @@
*--------------------------------------------------------------------------------------------*/
'use strict';
import ScrollableElement = require('vs/base/browser/ui/scrollbar/scrollableElement');
import {IScrollable} from 'vs/base/common/scrollable';
export interface IMouseWheelEvent {

View file

@ -5,22 +5,21 @@
'use strict';
import DomUtils = require('vs/base/browser/dom');
import Touch = require('vs/base/browser/touch');
import EventEmitter = require('vs/base/common/eventEmitter');
import ScrollableElement = require('vs/base/browser/ui/scrollbar/scrollableElement');
import Lifecycle = require('vs/base/common/lifecycle');
import {Gesture} from 'vs/base/browser/touch';
import {EventEmitter} from 'vs/base/common/eventEmitter';
import {IDisposable} from 'vs/base/common/lifecycle';
import {IScrollable} from 'vs/base/common/scrollable';
export class DomNodeScrollable implements IScrollable {
private eventEmitterHelper: EventEmitter.EventEmitter;
private eventEmitterHelper: EventEmitter;
private domNode: HTMLElement;
private gestureHandler: Touch.Gesture;
private gestureHandler: Gesture;
constructor(domNode:HTMLElement) {
this.eventEmitterHelper = new EventEmitter.EventEmitter();
this.eventEmitterHelper = new EventEmitter();
this.domNode = domNode;
this.gestureHandler = new Touch.Gesture(this.domNode);
this.gestureHandler = new Gesture(this.domNode);
}
public getScrollHeight(): number {
@ -47,7 +46,7 @@ export class DomNodeScrollable implements IScrollable {
this.domNode.scrollTop = scrollTop;
}
public addScrollListener(callback:()=>void):Lifecycle.IDisposable {
public addScrollListener(callback:()=>void): IDisposable {
var localDisposable = this.eventEmitterHelper.addListener2('scroll', callback);
var domDisposable = DomUtils.addDisposableListener(this.domNode, 'scroll', (e:Event) => {
this.eventEmitterHelper.emit('scroll', { browserEvent: e });

View file

@ -4,31 +4,30 @@
*--------------------------------------------------------------------------------------------*/
'use strict';
import AbstractScrollbar = require('vs/base/browser/ui/scrollbar/impl/abstractScrollbar');
import Mouse = require('vs/base/browser/mouseEvent');
import {AbstractScrollbar, ScrollbarState, IMouseMoveEventData} from 'vs/base/browser/ui/scrollbar/impl/abstractScrollbar';
import {StandardMouseEvent, StandardMouseWheelEvent} from 'vs/base/browser/mouseEvent';
import DomUtils = require('vs/base/browser/dom');
import Common = require('vs/base/browser/ui/scrollbar/impl/common');
import ScrollableElement = require('vs/base/browser/ui/scrollbar/scrollableElement');
import {IParent, IOptions, Visibility} from 'vs/base/browser/ui/scrollbar/impl/common';
import Browser = require('vs/base/browser/browser');
import {IScrollable} from 'vs/base/common/scrollable';
export class HorizontalScrollbar extends AbstractScrollbar.AbstractScrollbar {
export class HorizontalScrollbar extends AbstractScrollbar {
private scrollable:IScrollable;
constructor(scrollable:IScrollable, parent:Common.IParent, options:Common.IOptions) {
var s = new AbstractScrollbar.ScrollbarState(
constructor(scrollable:IScrollable, parent:IParent, options:IOptions) {
var s = new ScrollbarState(
(options.horizontalHasArrows ? options.arrowSize : 0),
(options.horizontal === Common.Visibility.Hidden ? 0 : options.horizontalScrollbarSize),
(options.vertical === Common.Visibility.Hidden ? 0 : options.verticalScrollbarSize)
(options.horizontal === Visibility.Hidden ? 0 : options.horizontalScrollbarSize),
(options.vertical === Visibility.Hidden ? 0 : options.verticalScrollbarSize)
);
super(options.forbidTranslate3dUse, parent, s, options.horizontal, 'horizontal');
this.scrollable = scrollable;
this._createDomNode();
if (options.horizontalHasArrows) {
var arrowDelta = (options.arrowSize - AbstractScrollbar.AbstractScrollbar.ARROW_IMG_SIZE) / 2;
var scrollbarDelta = (options.horizontalScrollbarSize - AbstractScrollbar.AbstractScrollbar.ARROW_IMG_SIZE) / 2;
var arrowDelta = (options.arrowSize - AbstractScrollbar.ARROW_IMG_SIZE) / 2;
var scrollbarDelta = (options.horizontalScrollbarSize - AbstractScrollbar.ARROW_IMG_SIZE) / 2;
this._createArrow('left-arrow', scrollbarDelta, arrowDelta, null, null, options.arrowSize, options.horizontalScrollbarSize, () => this._createMouseWheelEvent(1));
this._createArrow('right-arrow', scrollbarDelta, null, null, arrowDelta, options.arrowSize, options.horizontalScrollbarSize, () => this._createMouseWheelEvent(-1));
@ -38,7 +37,7 @@ export class HorizontalScrollbar extends AbstractScrollbar.AbstractScrollbar {
}
public _createMouseWheelEvent(sign:number) {
return new Mouse.StandardMouseWheelEvent(null, sign, 0);
return new StandardMouseWheelEvent(null, sign, 0);
}
public _updateSlider(sliderSize:number, sliderPosition:number): void {
@ -57,15 +56,15 @@ export class HorizontalScrollbar extends AbstractScrollbar.AbstractScrollbar {
DomUtils.StyleMutator.setBottom(this.domNode, 0);
}
public _mouseDownRelativePosition(e:Mouse.StandardMouseEvent, domNodePosition:DomUtils.IDomNodePosition): number {
public _mouseDownRelativePosition(e:StandardMouseEvent, domNodePosition:DomUtils.IDomNodePosition): number {
return e.posx - domNodePosition.left;
}
public _sliderMousePosition(e:AbstractScrollbar.IMouseMoveEventData): number {
public _sliderMousePosition(e:IMouseMoveEventData): number {
return e.posx;
}
public _sliderOrthogonalMousePosition(e:AbstractScrollbar.IMouseMoveEventData): number {
public _sliderOrthogonalMousePosition(e:IMouseMoveEventData): number {
return e.posy;
}

View file

@ -6,14 +6,14 @@
import 'vs/css!./scrollbars';
import DomUtils = require('vs/base/browser/dom');
import Mouse = require('vs/base/browser/mouseEvent');
import {StandardMouseWheelEvent} from 'vs/base/browser/mouseEvent';
import Platform = require('vs/base/common/platform');
import Common = require('vs/base/browser/ui/scrollbar/impl/common');
import DomNodeScrollable = require('vs/base/browser/ui/scrollbar/impl/domNodeScrollable');
import HorizontalScrollbar = require('vs/base/browser/ui/scrollbar/impl/horizontalScrollbar');
import VerticalScrollbar = require('vs/base/browser/ui/scrollbar/impl/verticalScrollbar');
import {IOptions,IScrollbar,IDimensions,IMouseWheelEvent,visibilityFromString} from 'vs/base/browser/ui/scrollbar/impl/common';
import {DomNodeScrollable} from 'vs/base/browser/ui/scrollbar/impl/domNodeScrollable';
import {HorizontalScrollbar} from 'vs/base/browser/ui/scrollbar/impl/horizontalScrollbar';
import {VerticalScrollbar} from 'vs/base/browser/ui/scrollbar/impl/verticalScrollbar';
import ScrollableElementInt = require('vs/base/browser/ui/scrollbar/scrollableElement');
import Lifecycle = require('vs/base/common/lifecycle');
import {IDisposable,disposeAll} from 'vs/base/common/lifecycle';
import {IScrollable} from 'vs/base/common/scrollable';
var HIDE_TIMEOUT = 500;
@ -22,12 +22,12 @@ var SCROLL_WHEEL_SENSITIVITY = 50;
export class ScrollableElement implements ScrollableElementInt.IScrollableElement {
private originalElement:HTMLElement;
private options:Common.IOptions;
private options:IOptions;
private scrollable:IScrollable;
public verticalScrollbarWidth:number;
public horizontalScrollbarHeight:number;
private verticalScrollbar:Common.IScrollbar;
private horizontalScrollbar:Common.IScrollbar;
private verticalScrollbar:IScrollbar;
private horizontalScrollbar:IScrollbar;
private domNode:HTMLElement;
private leftShadowDomNode:HTMLElement;
@ -35,15 +35,15 @@ export class ScrollableElement implements ScrollableElementInt.IScrollableElemen
private topLeftShadowDomNode:HTMLElement;
private listenOnDomNode:HTMLElement;
private toDispose:Lifecycle.IDisposable[];
private _mouseWheelToDispose:Lifecycle.IDisposable[];
private toDispose:IDisposable[];
private _mouseWheelToDispose:IDisposable[];
private onElementDimensionsTimeout:number;
private onElementInternalDimensionsTimeout:number;
private isDragging:boolean;
private mouseIsOver:boolean;
private dimensions:Common.IDimensions;
private dimensions:IDimensions;
private hideTimeout:number;
constructor(element:HTMLElement, options:ScrollableElementInt.ICreationOptions, dimensions:ScrollableElementInt.IDimensions = null) {
@ -54,14 +54,14 @@ export class ScrollableElement implements ScrollableElementInt.IScrollableElemen
if (this.options.scrollable) {
this.scrollable = this.options.scrollable;
} else {
this.scrollable = new DomNodeScrollable.DomNodeScrollable(this.originalElement);
this.scrollable = new DomNodeScrollable(this.originalElement);
}
this.verticalScrollbarWidth = this.options.verticalScrollbarSize;
this.horizontalScrollbarHeight = this.options.horizontalScrollbarSize;
this.verticalScrollbar = new VerticalScrollbar.VerticalScrollbar(this.scrollable, this, this.options);
this.horizontalScrollbar = new HorizontalScrollbar.HorizontalScrollbar(this.scrollable, this, this.options);
this.verticalScrollbar = new VerticalScrollbar(this.scrollable, this, this.options);
this.horizontalScrollbar = new HorizontalScrollbar(this.scrollable, this, this.options);
this.domNode = document.createElement('div');
this.domNode.className = 'monaco-scrollable-element ' + this.options.className;
@ -110,8 +110,8 @@ export class ScrollableElement implements ScrollableElementInt.IScrollableElemen
}
public dispose(): void {
this.toDispose = Lifecycle.disposeAll(this.toDispose);
this._mouseWheelToDispose = Lifecycle.disposeAll(this._mouseWheelToDispose);
this.toDispose = disposeAll(this.toDispose);
this._mouseWheelToDispose = disposeAll(this._mouseWheelToDispose);
this.verticalScrollbar.destroy();
this.horizontalScrollbar.destroy();
if (this.onElementDimensionsTimeout !== -1) {
@ -123,9 +123,6 @@ export class ScrollableElement implements ScrollableElementInt.IScrollableElemen
this.onElementInternalDimensionsTimeout = -1;
}
}
public destroy(): void {
this.dispose();
}
public getDomNode():HTMLElement {
return this.domNode;
@ -213,12 +210,12 @@ export class ScrollableElement implements ScrollableElementInt.IScrollableElemen
}
// Stop listening (if necessary)
this._mouseWheelToDispose = Lifecycle.disposeAll(this._mouseWheelToDispose);
this._mouseWheelToDispose = disposeAll(this._mouseWheelToDispose);
// Start listening (if necessary)
if (shouldListen) {
var onMouseWheel = (browserEvent:MouseWheelEvent) => {
var e = new Mouse.StandardMouseWheelEvent(browserEvent);
var e = new StandardMouseWheelEvent(browserEvent);
this.onMouseWheel(e);
};
@ -227,7 +224,7 @@ export class ScrollableElement implements ScrollableElementInt.IScrollableElemen
}
}
public onMouseWheel(e: Common.IMouseWheelEvent): void {
public onMouseWheel(e: IMouseWheelEvent): void {
if (Platform.isMacintosh && e.browserEvent && this.options.saveLastScrollTimeOnClassName) {
// Mark dom node with timestamp of wheel event
var target = <HTMLElement>e.browserEvent.target;
@ -369,7 +366,7 @@ export class ScrollableElement implements ScrollableElementInt.IScrollableElemen
// -------------------- size & layout --------------------
private _computeDimensions(clientWidth:number, clientHeight:number): Common.IDimensions {
private _computeDimensions(clientWidth:number, clientHeight:number): IDimensions {
var width = clientWidth;
var height = clientHeight;
@ -379,7 +376,7 @@ export class ScrollableElement implements ScrollableElementInt.IScrollableElemen
};
}
private _createOptions(options:ScrollableElementInt.ICreationOptions): Common.IOptions {
private _createOptions(options:ScrollableElementInt.ICreationOptions): IOptions {
function ensureValue<V>(source:any, prop:string, value:V) {
if (source.hasOwnProperty(prop)) {
@ -388,7 +385,7 @@ export class ScrollableElement implements ScrollableElementInt.IScrollableElemen
return value;
}
var result:Common.IOptions = {
var result:IOptions = {
forbidTranslate3dUse: ensureValue(options, 'forbidTranslate3dUse', false),
className: ensureValue(options, 'className', ''),
useShadows: ensureValue(options, 'useShadows', true),
@ -400,12 +397,12 @@ export class ScrollableElement implements ScrollableElementInt.IScrollableElemen
scrollable: ensureValue<IScrollable>(options, 'scrollable', null),
listenOnDomNode: ensureValue<HTMLElement>(options, 'listenOnDomNode', null),
horizontal: Common.visibilityFromString(ensureValue(options, 'horizontal', 'auto')),
horizontal: visibilityFromString(ensureValue(options, 'horizontal', 'auto')),
horizontalScrollbarSize: ensureValue(options, 'horizontalScrollbarSize', 10),
horizontalSliderSize: 0,
horizontalHasArrows: ensureValue(options, 'horizontalHasArrows', false),
vertical: Common.visibilityFromString(ensureValue(options, 'vertical', 'auto')),
vertical: visibilityFromString(ensureValue(options, 'vertical', 'auto')),
verticalScrollbarSize: ensureValue(options, 'verticalScrollbarSize', 10),
verticalHasArrows: ensureValue(options, 'verticalHasArrows', false),
verticalSliderSize: 0,

View file

@ -4,31 +4,30 @@
*--------------------------------------------------------------------------------------------*/
'use strict';
import AbstractScrollbar = require('vs/base/browser/ui/scrollbar/impl/abstractScrollbar');
import Mouse = require('vs/base/browser/mouseEvent');
import {AbstractScrollbar, ScrollbarState, IMouseMoveEventData} from 'vs/base/browser/ui/scrollbar/impl/abstractScrollbar';
import {StandardMouseEvent, StandardMouseWheelEvent} from 'vs/base/browser/mouseEvent';
import DomUtils = require('vs/base/browser/dom');
import Common = require('vs/base/browser/ui/scrollbar/impl/common');
import ScrollableElement = require('vs/base/browser/ui/scrollbar/scrollableElement');
import {IParent, IOptions, Visibility} from 'vs/base/browser/ui/scrollbar/impl/common';
import Browser = require('vs/base/browser/browser');
import {IScrollable} from 'vs/base/common/scrollable';
export class VerticalScrollbar extends AbstractScrollbar.AbstractScrollbar {
export class VerticalScrollbar extends AbstractScrollbar {
private scrollable:IScrollable;
constructor(scrollable:IScrollable, parent:Common.IParent, options:Common.IOptions) {
var s = new AbstractScrollbar.ScrollbarState(
constructor(scrollable:IScrollable, parent:IParent, options:IOptions) {
var s = new ScrollbarState(
(options.verticalHasArrows ? options.arrowSize : 0),
(options.vertical === Common.Visibility.Hidden ? 0 : options.verticalScrollbarSize),
(options.horizontal === Common.Visibility.Hidden ? 0 : options.horizontalScrollbarSize)
(options.vertical === Visibility.Hidden ? 0 : options.verticalScrollbarSize),
(options.horizontal === Visibility.Hidden ? 0 : options.horizontalScrollbarSize)
);
super(options.forbidTranslate3dUse, parent, s, options.vertical, 'vertical');
this.scrollable = scrollable;
this._createDomNode();
if (options.verticalHasArrows) {
var arrowDelta = (options.arrowSize - AbstractScrollbar.AbstractScrollbar.ARROW_IMG_SIZE) / 2;
var scrollbarDelta = (options.verticalScrollbarSize - AbstractScrollbar.AbstractScrollbar.ARROW_IMG_SIZE) / 2;
var arrowDelta = (options.arrowSize - AbstractScrollbar.ARROW_IMG_SIZE) / 2;
var scrollbarDelta = (options.verticalScrollbarSize - AbstractScrollbar.ARROW_IMG_SIZE) / 2;
this._createArrow('up-arrow', arrowDelta, scrollbarDelta, null, null, options.verticalScrollbarSize, options.arrowSize, () => this._createMouseWheelEvent(1));
this._createArrow('down-arrow', null, scrollbarDelta, arrowDelta, null, options.verticalScrollbarSize, options.arrowSize, () => this._createMouseWheelEvent(-1));
@ -38,7 +37,7 @@ export class VerticalScrollbar extends AbstractScrollbar.AbstractScrollbar {
}
public _createMouseWheelEvent(sign:number) {
return new Mouse.StandardMouseWheelEvent(null, 0, sign);
return new StandardMouseWheelEvent(null, 0, sign);
}
public _updateSlider(sliderSize:number, sliderPosition:number): void {
@ -57,15 +56,15 @@ export class VerticalScrollbar extends AbstractScrollbar.AbstractScrollbar {
DomUtils.StyleMutator.setTop(this.domNode, 0);
}
public _mouseDownRelativePosition(e:Mouse.StandardMouseEvent, domNodePosition:DomUtils.IDomNodePosition): number {
public _mouseDownRelativePosition(e:StandardMouseEvent, domNodePosition:DomUtils.IDomNodePosition): number {
return e.posy - domNodePosition.top;
}
public _sliderMousePosition(e:AbstractScrollbar.IMouseMoveEventData): number {
public _sliderMousePosition(e:IMouseMoveEventData): number {
return e.posy;
}
public _sliderOrthogonalMousePosition(e:AbstractScrollbar.IMouseMoveEventData): number {
public _sliderOrthogonalMousePosition(e:IMouseMoveEventData): number {
return e.posx;
}

View file

@ -4,7 +4,6 @@
*--------------------------------------------------------------------------------------------*/
'use strict';
import Lifecycle = require('vs/base/common/lifecycle');
import {IScrollable} from 'vs/base/common/scrollable';
export interface ICreationOptions {
@ -151,9 +150,8 @@ export interface IScrollableElement {
onElementInternalDimensions(): void;
/**
* Destroy.
* Dispose.
*/
destroy(): void;
dispose(): void;
/**

View file

@ -0,0 +1,8 @@
// ATTENTION - THIS DIRECTORY CONTAINS THIRD PARTY OPEN SOURCE MATERIALS:
[{
"name": "string_scorer",
"version": "10 March 2015",
"license": "MIT License",
"repositoryURL": "https://github.com/joshaven/string_score",
"description": "The file scorer.ts was inspired by the string_score algorithm from Joshaven Potter."
}]

View file

@ -4,7 +4,7 @@
*--------------------------------------------------------------------------------------------*/
'use strict';
import diffChange = require('vs/base/common/diff/diffChange');
import {DiffChange} from 'vs/base/common/diff/diffChange';
export interface ISequence {
getLength(): number;
@ -105,7 +105,7 @@ var MaxDifferencesHistory = 1447;
*/
class DiffChangeHelper {
private m_changes:diffChange.DiffChange[];
private m_changes:DiffChange[];
private m_originalStart:number;
private m_modifiedStart:number;
private m_originalCount:number;
@ -129,7 +129,7 @@ class DiffChangeHelper {
// Only add to the list if there is something to add
if (this.m_originalCount > 0 || this.m_modifiedCount > 0) {
// Add the new change to our list
this.m_changes.push(new diffChange.DiffChange(this.m_originalStart, this.m_originalCount,
this.m_changes.push(new DiffChange(this.m_originalStart, this.m_originalCount,
this.m_modifiedStart, this.m_modifiedCount));
}
@ -173,7 +173,7 @@ class DiffChangeHelper {
/**
* Retrieves all of the changes marked by the class.
*/
public getChanges(): diffChange.DiffChange[] {
public getChanges(): DiffChange[] {
if (this.m_originalCount > 0 || this.m_modifiedCount > 0) {
// Finish up on whatever is left
this.MarkNextChange();
@ -182,7 +182,7 @@ class DiffChangeHelper {
return this.m_changes;
}
public getReverseChanges(): diffChange.DiffChange[] {
public getReverseChanges(): DiffChange[] {
/// <summary>
/// Retrieves all of the changes marked by the class in the reverse order
/// </summary>
@ -279,7 +279,7 @@ export class LcsDiff {
* sequences on the bounded range.
* @returns An array of the differences between the two input sequences.
*/
private _ComputeDiff(originalStart:number, originalEnd:number, modifiedStart:number, modifiedEnd:number): diffChange.DiffChange[] {
private _ComputeDiff(originalStart:number, originalEnd:number, modifiedStart:number, modifiedEnd:number): DiffChange[] {
var quitEarlyArr = [ false ];
return this.ComputeDiffRecursive(originalStart, originalEnd, modifiedStart, modifiedEnd, quitEarlyArr);
}
@ -289,7 +289,7 @@ export class LcsDiff {
* recursively.
* @returns An array of the differences between the two input sequences.
*/
private ComputeDiffRecursive(originalStart:number, originalEnd:number, modifiedStart:number, modifiedEnd:number, quitEarlyArr:boolean[]): diffChange.DiffChange[] {
private ComputeDiffRecursive(originalStart:number, originalEnd:number, modifiedStart:number, modifiedEnd:number, quitEarlyArr:boolean[]): DiffChange[] {
quitEarlyArr[0] = false;
// Find the start of the differences
@ -306,21 +306,21 @@ export class LcsDiff {
// In the special case where we either have all insertions or all deletions or the sequences are identical
if (originalStart > originalEnd || modifiedStart > modifiedEnd) {
var changes:diffChange.DiffChange[];
var changes:DiffChange[];
if (modifiedStart <= modifiedEnd) {
Debug.Assert(originalStart === originalEnd + 1, 'originalStart should only be one more than originalEnd');
// All insertions
changes = [
new diffChange.DiffChange(originalStart, 0, modifiedStart, modifiedEnd - modifiedStart + 1)
new DiffChange(originalStart, 0, modifiedStart, modifiedEnd - modifiedStart + 1)
];
} else if (originalStart <= originalEnd) {
Debug.Assert(modifiedStart === modifiedEnd + 1, 'modifiedStart should only be one more than modifiedEnd');
// All deletions
changes = [
new diffChange.DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, 0)
new DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, 0)
];
} else {
Debug.Assert(originalStart === originalEnd + 1, 'originalStart should only be one more than originalEnd');
@ -351,7 +351,7 @@ export class LcsDiff {
// NOTE: ComputeDiff() is inclusive, therefore the second range starts on the next point
var leftChanges = this.ComputeDiffRecursive(originalStart, midOriginal, modifiedStart, midModified, quitEarlyArr);
var rightChanges: diffChange.DiffChange[] = [];
var rightChanges: DiffChange[] = [];
if (!quitEarlyArr[0]) {
rightChanges = this.ComputeDiffRecursive(midOriginal + 1, originalEnd, midModified + 1, modifiedEnd, quitEarlyArr);
@ -359,7 +359,7 @@ export class LcsDiff {
// We did't have time to finish the first half, so we don't have time to compute this half.
// Consider the entire rest of the sequence different.
rightChanges = [
new diffChange.DiffChange(midOriginal + 1, originalEnd - (midOriginal + 1) + 1, midModified + 1, modifiedEnd - (midModified + 1) + 1)
new DiffChange(midOriginal + 1, originalEnd - (midOriginal + 1) + 1, midModified + 1, modifiedEnd - (midModified + 1) + 1)
];
}
@ -368,7 +368,7 @@ export class LcsDiff {
// If we hit here, we quit early, and so can't return anything meaningful
return [
new diffChange.DiffChange(originalStart, originalEnd -originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1)
new DiffChange(originalStart, originalEnd -originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1)
];
}
@ -377,8 +377,8 @@ export class LcsDiff {
forwardPoints:number[], reversePoints:number[],
originalIndex:number, originalEnd:number, midOriginalArr:number[],
modifiedIndex:number, modifiedEnd:number, midModifiedArr:number[],
deltaIsEven:boolean, quitEarlyArr:boolean[]): diffChange.DiffChange[] {
var forwardChanges: diffChange.DiffChange[] = null, reverseChanges: diffChange.DiffChange[] = null;
deltaIsEven:boolean, quitEarlyArr:boolean[]): DiffChange[] {
var forwardChanges: DiffChange[] = null, reverseChanges: DiffChange[] = null;
// First, walk backward through the forward diagonals history
var changeHelper = new DiffChangeHelper();
@ -442,7 +442,7 @@ export class LcsDiff {
}
reverseChanges = [
new diffChange.DiffChange(originalStartPoint, originalEnd - originalStartPoint + 1,
new DiffChange(originalStartPoint, originalEnd - originalStartPoint + 1,
modifiedStartPoint, modifiedEnd - modifiedStartPoint + 1)
];
} else {
@ -666,7 +666,7 @@ export class LcsDiff {
modifiedStart++;
return [
new diffChange.DiffChange(originalStart, originalEnd - originalStart + 1,
new DiffChange(originalStart, originalEnd - originalStart + 1,
modifiedStart, modifiedEnd - modifiedStart + 1)
];
}
@ -760,9 +760,9 @@ export class LcsDiff {
* @param The right changes
* @returns The concatenated list
*/
private ConcatenateChanges(left:diffChange.DiffChange[], right:diffChange.DiffChange[]): diffChange.DiffChange[] {
var mergedChangeArr:diffChange.DiffChange[] = [];
var result:diffChange.DiffChange[] = null;
private ConcatenateChanges(left:DiffChange[], right:DiffChange[]): DiffChange[] {
var mergedChangeArr:DiffChange[] = [];
var result:DiffChange[] = null;
if (left.length === 0 || right.length === 0) {
return (right.length > 0) ? right : left;
@ -771,14 +771,14 @@ export class LcsDiff {
// might recurse in the middle of a change thereby splitting it into
// two changes. Here in the combining stage, we detect and fuse those
// changes back together
result = new Array<diffChange.DiffChange>(left.length + right.length - 1);
result = new Array<DiffChange>(left.length + right.length - 1);
MyArray.Copy(left, 0, result, 0, left.length - 1);
result[left.length - 1] = mergedChangeArr[0];
MyArray.Copy(right, 1, result, left.length, right.length - 1);
return result;
} else {
result = new Array<diffChange.DiffChange>(left.length + right.length);
result = new Array<DiffChange>(left.length + right.length);
MyArray.Copy(left, 0, result, 0, left.length);
MyArray.Copy(right, 0, result, left.length, right.length);
@ -794,7 +794,7 @@ export class LcsDiff {
* @param mergedChange The merged change if the two overlap, null otherwise
* @returns True if the two changes overlap
*/
private ChangesOverlap(left:diffChange.DiffChange, right:diffChange.DiffChange, mergedChangeArr:diffChange.DiffChange[]): boolean {
private ChangesOverlap(left:DiffChange, right:DiffChange, mergedChangeArr:DiffChange[]): boolean {
Debug.Assert(left.originalStart <= right.originalStart, 'Left change is not less than or equal to right change');
Debug.Assert(left.modifiedStart <= right.modifiedStart, 'Left change is not less than or equal to right change');
@ -812,7 +812,7 @@ export class LcsDiff {
modifiedLength = right.modifiedStart + right.modifiedLength - left.modifiedStart;
}
mergedChangeArr[0] = new diffChange.DiffChange(originalStart, originalLength, modifiedStart, modifiedLength);
mergedChangeArr[0] = new DiffChange(originalStart, originalLength, modifiedStart, modifiedLength);
return true;
} else {
mergedChangeArr[0] = null;

View file

@ -4,7 +4,7 @@
*--------------------------------------------------------------------------------------------*/
'use strict';
import diffChange = require('vs/base/common/diff/diffChange');
import {DiffChange} from 'vs/base/common/diff/diffChange';
export interface ISequence {
getLength(): number;
@ -164,14 +164,14 @@ export class LcsDiff2 {
while (j < yLength && !this.resultY[j]) {
j++;
}
changes.push(new diffChange.DiffChange(xChangeStart, i - xChangeStart, yChangeStart, j - yChangeStart));
changes.push(new DiffChange(xChangeStart, i - xChangeStart, yChangeStart, j - yChangeStart));
}
}
if (i < xLength) {
changes.push(new diffChange.DiffChange(i, xLength - i, yLength, 0));
changes.push(new DiffChange(i, xLength - i, yLength, 0));
}
if (j < yLength) {
changes.push(new diffChange.DiffChange(xLength, 0, j, yLength - j));
changes.push(new DiffChange(xLength, 0, j, yLength - j));
}
return changes;
}

View file

@ -4,16 +4,16 @@
*--------------------------------------------------------------------------------------------*/
'use strict';
import Strings = require('vs/base/common/strings');
import strings = require('vs/base/common/strings');
export interface IFilter {
// Returns null if word doesn't match.
(word:string, wordToMatchAgainst:string):IMatch[];
(word: string, wordToMatchAgainst: string): IMatch[];
}
export interface IMatch {
start:number;
end:number;
start: number;
end: number;
}
// Combined filters
@ -24,11 +24,11 @@ export interface IMatch {
* matches defined the return value of the returned
* filter.
*/
export function or(...filter:IFilter[]):IFilter {
return function (word:string, wordToMatchAgainst:string):IMatch[] {
for(var i = 0, len = filter.length; i < len; i++) {
var match = filter[i](word, wordToMatchAgainst);
if(match) {
export function or(...filter: IFilter[]): IFilter {
return function(word: string, wordToMatchAgainst: string): IMatch[] {
for (let i = 0, len = filter.length; i < len; i++) {
let match = filter[i](word, wordToMatchAgainst);
if (match) {
return match;
}
}
@ -41,12 +41,12 @@ export function or(...filter:IFilter[]):IFilter {
* of filters with an and. The combines matches are
* returned if *all* filters match.
*/
export function and(...filter:IFilter[]):IFilter {
return function (word:string, wordToMatchAgainst:string):IMatch[] {
var result:IMatch[] = [];
for(var i = 0, len = filter.length; i < len; i++) {
var match = filter[i](word, wordToMatchAgainst);
if(!match) {
export function and(...filter: IFilter[]): IFilter {
return function(word: string, wordToMatchAgainst: string): IMatch[] {
let result: IMatch[] = [];
for (let i = 0, len = filter.length; i < len; i++) {
let match = filter[i](word, wordToMatchAgainst);
if (!match) {
return null;
}
result = result.concat(match);
@ -57,10 +57,10 @@ export function and(...filter:IFilter[]):IFilter {
// Prefix
export var matchesStrictPrefix:IFilter = (word:string, wordToMatchAgainst:string):IMatch[] => { return _matchesPrefix(false, word, wordToMatchAgainst); };
export var matchesPrefix:IFilter = (word:string, wordToMatchAgainst:string):IMatch[] => { return _matchesPrefix(true, word, wordToMatchAgainst); };
export let matchesStrictPrefix: IFilter = (word: string, wordToMatchAgainst: string): IMatch[] => { return _matchesPrefix(false, word, wordToMatchAgainst); };
export let matchesPrefix: IFilter = (word: string, wordToMatchAgainst: string): IMatch[] => { return _matchesPrefix(true, word, wordToMatchAgainst); };
function _matchesPrefix(ignoreCase:boolean, word:string, wordToMatchAgainst:string):IMatch[] {
function _matchesPrefix(ignoreCase: boolean, word: string, wordToMatchAgainst: string): IMatch[] {
if (wordToMatchAgainst.length === 0 || wordToMatchAgainst.length < word.length) {
return null;
}
@ -68,7 +68,7 @@ function _matchesPrefix(ignoreCase:boolean, word:string, wordToMatchAgainst:stri
word = word.toLowerCase();
wordToMatchAgainst = wordToMatchAgainst.toLowerCase();
}
for (var i = 0; i < word.length; i++) {
for (let i = 0; i < word.length; i++) {
if (word[i] !== wordToMatchAgainst[i]) {
return null;
}
@ -78,8 +78,8 @@ function _matchesPrefix(ignoreCase:boolean, word:string, wordToMatchAgainst:stri
// Contiguous Substring
export function matchesContiguousSubString(word:string, wordToMatchAgainst:string):IMatch[] {
var index = wordToMatchAgainst.toLowerCase().indexOf(word.toLowerCase());
export function matchesContiguousSubString(word: string, wordToMatchAgainst: string): IMatch[] {
let index = wordToMatchAgainst.toLowerCase().indexOf(word.toLowerCase());
if (index === -1) {
return null;
@ -90,18 +90,18 @@ export function matchesContiguousSubString(word:string, wordToMatchAgainst:strin
// Substring
export function matchesSubString(word:string, wordToMatchAgainst:string):IMatch[] {
export function matchesSubString(word: string, wordToMatchAgainst: string): IMatch[] {
return _matchesSubString(word.toLowerCase(), wordToMatchAgainst.toLowerCase(), 0, 0);
}
function _matchesSubString(word:string, wordToMatchAgainst:string, i:number, j:number):IMatch[] {
function _matchesSubString(word: string, wordToMatchAgainst: string, i: number, j: number): IMatch[] {
if (i === word.length) {
return [];
} else if (j === wordToMatchAgainst.length) {
return null;
} else {
if (word[i] === wordToMatchAgainst[j]) {
var result: IMatch[] = null;
let result: IMatch[] = null;
if (result = _matchesSubString(word, wordToMatchAgainst, i + 1, j + 1)) {
return join({ start: j, end: j + 1 }, result);
}
@ -113,27 +113,27 @@ function _matchesSubString(word:string, wordToMatchAgainst:string, i:number, j:n
// CamelCase
function isLower(code:number):boolean {
function isLower(code: number): boolean {
return 97 <= code && code <= 122;
}
function isUpper(code:number):boolean {
function isUpper(code: number): boolean {
return 65 <= code && code <= 90;
}
function isNumber(code:number):boolean {
function isNumber(code: number): boolean {
return 48 <= code && code <= 57;
}
function isWhitespace(code:number):boolean {
function isWhitespace(code: number): boolean {
return [32, 9, 10, 13].indexOf(code) > -1;
}
function isAlphanumeric(code:number):boolean {
function isAlphanumeric(code: number): boolean {
return isLower(code) || isUpper(code) || isNumber(code);
}
function join(head:IMatch, tail:IMatch[]):IMatch[] {
function join(head: IMatch, tail: IMatch[]): IMatch[] {
if (tail.length === 0) {
tail = [head];
} else if (head.end === tail[0].start) {
@ -145,16 +145,16 @@ function join(head:IMatch, tail:IMatch[]):IMatch[] {
}
function nextAnchor(camelCaseWord: string, start: number): number {
for (var i = start; i < camelCaseWord.length; i++) {
var c = camelCaseWord.charCodeAt(i);
if (isUpper(c) || isNumber(c) || (i>0 && !isAlphanumeric(camelCaseWord.charCodeAt(i-1)))) {
for (let i = start; i < camelCaseWord.length; i++) {
let c = camelCaseWord.charCodeAt(i);
if (isUpper(c) || isNumber(c) || (i > 0 && !isAlphanumeric(camelCaseWord.charCodeAt(i - 1)))) {
return i;
}
}
return camelCaseWord.length;
}
function _matchesCamelCase(word:string, camelCaseWord:string, i:number, j:number):IMatch[] {
function _matchesCamelCase(word: string, camelCaseWord: string, i: number, j: number): IMatch[] {
if (i === word.length) {
return [];
} else if (j === camelCaseWord.length) {
@ -162,8 +162,8 @@ function _matchesCamelCase(word:string, camelCaseWord:string, i:number, j:number
} else if (word[i] !== camelCaseWord[j].toLowerCase()) {
return null;
} else {
var result = null;
var nextUpperIndex = j + 1;
let result = null;
let nextUpperIndex = j + 1;
result = _matchesCamelCase(word, camelCaseWord, i + 1, j + 1);
while (!result && (nextUpperIndex = nextAnchor(camelCaseWord, nextUpperIndex)) < camelCaseWord.length) {
result = _matchesCamelCase(word, camelCaseWord, i + 1, nextUpperIndex);
@ -180,9 +180,9 @@ function isCamelCaseWord(word: string): boolean {
return false;
}
var upper = 0, lower = 0, alpha = 0, code = 0;
let upper = 0, lower = 0, alpha = 0, code = 0;
for (var i = 0; i < word.length; i++) {
for (let i = 0; i < word.length; i++) {
code = word.charCodeAt(i);
isUpper(code) && upper++;
@ -190,9 +190,9 @@ function isCamelCaseWord(word: string): boolean {
isAlphanumeric(code) && alpha++;
}
var upperPercent = upper / word.length;
var lowerPercent = lower / word.length;
var alphaPercent = alpha / word.length;
let upperPercent = upper / word.length;
let lowerPercent = lower / word.length;
let alphaPercent = alpha / word.length;
return lowerPercent > 0.2 && upperPercent < 0.8 && alphaPercent > 0.6;
}
@ -200,9 +200,9 @@ function isCamelCaseWord(word: string): boolean {
// Heuristic to avoid computing camel case matcher for words that don't
// look like camel case patterns.
function isCamelCasePattern(word: string): boolean {
var upper = 0, lower = 0, code = 0, whitespace = 0;
let upper = 0, lower = 0, code = 0, whitespace = 0;
for (var i = 0; i < word.length; i++) {
for (let i = 0; i < word.length; i++) {
code = word.charCodeAt(i);
isUpper(code) && upper++;
@ -217,7 +217,7 @@ function isCamelCasePattern(word: string): boolean {
}
}
export function matchesCamelCase(word:string, camelCaseWord:string):IMatch[] {
export function matchesCamelCase(word: string, camelCaseWord: string): IMatch[] {
if (camelCaseWord.length === 0) {
return null;
}
@ -230,8 +230,8 @@ export function matchesCamelCase(word:string, camelCaseWord:string):IMatch[] {
return null;
}
var result: IMatch[] = null;
var i = 0;
let result: IMatch[] = null;
let i = 0;
while (i < camelCaseWord.length && (result = _matchesCamelCase(word.toLowerCase(), camelCaseWord, 0, i)) === null) {
i = nextAnchor(camelCaseWord, i + 1);
@ -242,23 +242,30 @@ export function matchesCamelCase(word:string, camelCaseWord:string):IMatch[] {
// Fuzzy
var fuzzyDefaultFilter = or(matchesPrefix, matchesCamelCase, matchesContiguousSubString);
var fuzzyRegExpCache:{[key:string]:RegExp;} = {};
export enum SubstringMatching {
Contiguous,
Separate
}
const fuzzyContiguousFilter = or(matchesPrefix, matchesCamelCase, matchesContiguousSubString);
const fuzzySeparateFilter = or(matchesPrefix, matchesCamelCase, matchesSubString);
const fuzzyRegExpCache: { [key: string]: RegExp; } = {};
export function matchesFuzzy(word: string, wordToMatchAgainst: string, enableSeparateSubstringMatching = false): IMatch[] {
export function matchesFuzzy(word:string, wordToMatchAgainst:string):IMatch[] {
// Form RegExp for wildcard matches
var regexp = fuzzyRegExpCache[word];
let regexp = fuzzyRegExpCache[word];
if (!regexp) {
regexp = new RegExp(Strings.convertSimple2RegExpPattern(word), 'i');
regexp = new RegExp(strings.convertSimple2RegExpPattern(word), 'i');
fuzzyRegExpCache[word] = regexp;
}
// RegExp Filter
var match:RegExpExecArray = regexp.exec(wordToMatchAgainst);
let match: RegExpExecArray = regexp.exec(wordToMatchAgainst);
if (match) {
return [ { start: match.index , end: match.index + match[0].length } ];
return [{ start: match.index, end: match.index + match[0].length }];
}
// Default Filter
return fuzzyDefaultFilter(word, wordToMatchAgainst);
}
return enableSeparateSubstringMatching ? fuzzySeparateFilter(word, wordToMatchAgainst) : fuzzyContiguousFilter(word, wordToMatchAgainst);
}

View file

@ -36,13 +36,11 @@ export class ArrayIterator<T> implements IIterator<T> {
export class MappedIterator<T, R> implements IIterator<R> {
constructor(private iterator: IIterator<T>, private fn: (item:T)=>R) {
constructor(protected iterator: IIterator<T>, protected fn: (item:T)=>R) {
// noop
}
public next(): R {
return this.fn(this.iterator.next());
}
next() { return this.fn(this.iterator.next()); }
}
export interface INavigator<T> extends IIterator<T> {
@ -52,3 +50,16 @@ export interface INavigator<T> extends IIterator<T> {
first(): T;
last(): T;
}
export class MappedNavigator<T, R> extends MappedIterator<T, R> implements INavigator<R> {
constructor(protected navigator: INavigator<T>, fn: (item:T)=>R) {
super(navigator, fn);
}
current() { return this.fn(this.navigator.current()); }
previous() { return this.fn(this.navigator.previous()); }
parent() { return this.fn(this.navigator.parent()); }
first() { return this.fn(this.navigator.first()); }
last() { return this.fn(this.navigator.last()); }
}

View file

@ -142,6 +142,24 @@ export enum KeyCode {
*/
US_QUOTE,
NUMPAD_0, // VK_NUMPAD0, 0x60, Numeric keypad 0 key
NUMPAD_1, // VK_NUMPAD1, 0x61, Numeric keypad 1 key
NUMPAD_2, // VK_NUMPAD2, 0x62, Numeric keypad 2 key
NUMPAD_3, // VK_NUMPAD3, 0x63, Numeric keypad 3 key
NUMPAD_4, // VK_NUMPAD4, 0x64, Numeric keypad 4 key
NUMPAD_5, // VK_NUMPAD5, 0x65, Numeric keypad 5 key
NUMPAD_6, // VK_NUMPAD6, 0x66, Numeric keypad 6 key
NUMPAD_7, // VK_NUMPAD7, 0x67, Numeric keypad 7 key
NUMPAD_8, // VK_NUMPAD8, 0x68, Numeric keypad 8 key
NUMPAD_9, // VK_NUMPAD9, 0x69, Numeric keypad 9 key
NUMPAD_MULTIPLY, // VK_MULTIPLY, 0x6A, Multiply key
NUMPAD_ADD, // VK_ADD, 0x6B, Add key
// NUMPAD_SEPARATOR, // VK_SEPARATOR, 0x6C, Separator key
NUMPAD_SUBTRACT, // VK_SUBTRACT, 0x6D, Subtract key
NUMPAD_DECIMAL, // VK_DECIMAL, 0x6E, Decimal key
NUMPAD_DIVIDE, // VK_DIVIDE, 0x6F,
/**
* Placed last to cover the length of the enum.
*/
@ -240,13 +258,40 @@ let TO_STRING_MAP: string[] = [];
TO_STRING_MAP[KeyCode.US_BACKSLASH] = '\\';
TO_STRING_MAP[KeyCode.US_CLOSE_SQUARE_BRACKET] = ']';
TO_STRING_MAP[KeyCode.US_QUOTE] = '\'';
TO_STRING_MAP[KeyCode.NUMPAD_0] = 'NumPad0';
TO_STRING_MAP[KeyCode.NUMPAD_1] = 'NumPad1';
TO_STRING_MAP[KeyCode.NUMPAD_2] = 'NumPad2';
TO_STRING_MAP[KeyCode.NUMPAD_3] = 'NumPad3';
TO_STRING_MAP[KeyCode.NUMPAD_4] = 'NumPad4';
TO_STRING_MAP[KeyCode.NUMPAD_5] = 'NumPad5';
TO_STRING_MAP[KeyCode.NUMPAD_6] = 'NumPad6';
TO_STRING_MAP[KeyCode.NUMPAD_7] = 'NumPad7';
TO_STRING_MAP[KeyCode.NUMPAD_8] = 'NumPad8';
TO_STRING_MAP[KeyCode.NUMPAD_9] = 'NumPad9';
TO_STRING_MAP[KeyCode.NUMPAD_MULTIPLY] = 'NumPad_Multiply';
TO_STRING_MAP[KeyCode.NUMPAD_ADD] = 'NumPad_Add';
TO_STRING_MAP[KeyCode.NUMPAD_SUBTRACT] = 'NumPad_Subtract';
TO_STRING_MAP[KeyCode.NUMPAD_DECIMAL] = 'NumPad_Decimal';
TO_STRING_MAP[KeyCode.NUMPAD_DIVIDE] = 'NumPad_Divide';
// for (let i = 0; i < KeyCode.MAX_VALUE; i++) {
// if (!TO_STRING_MAP[i]) {
// console.warn('Missing string representation for ' + KeyCode[i]);
// }
// }
})();
let FROM_STRING_MAP: {[str:string]:KeyCode;} = {};
FROM_STRING_MAP['\r'] = KeyCode.Enter;
(function() {
for (let i = 0, len = TO_STRING_MAP.length; i < len; i++) {
if (!TO_STRING_MAP[i]) {
continue;
}
FROM_STRING_MAP[TO_STRING_MAP[i]] = i;
FROM_STRING_MAP[TO_STRING_MAP[i].toLowerCase()] = i;
}
})();

View file

@ -4,15 +4,15 @@
*--------------------------------------------------------------------------------------------*/
'use strict';
import winjs = require('vs/base/common/winjs.base');
import marshalling = require('vs/base/common/marshalling');
import {TPromise} from 'vs/base/common/winjs.base';
import {IMarshallingContribution} from 'vs/base/common/marshalling';
export interface IManyHandler {
handle(rpcId:string, method:string, args:any[]): any;
}
export interface IProxyHelper {
callOnRemote(proxyId: string, path: string, args:any[]): winjs.Promise;
callOnRemote(proxyId: string, path: string, args:any[]): TPromise<any>;
}
export interface IRemoteCom extends IProxyHelper {
@ -33,7 +33,7 @@ export function createProxyFromCtor(remote:IProxyHelper, id:string, ctor:Functio
return result;
}
function createMethodProxy(remote:IProxyHelper, proxyId: string, path: string): (...myArgs: any[]) => winjs.Promise {
function createMethodProxy(remote:IProxyHelper, proxyId: string, path: string): (...myArgs: any[]) => TPromise<any> {
return (...myArgs: any[]) => {
return remote.callOnRemote(proxyId, path, myArgs);
};
@ -50,7 +50,7 @@ export interface ISerializedProxy {
desc: IObjDescriptor;
}
export class ProxiesMarshallingContribution implements marshalling.IMarshallingContribution {
export class ProxiesMarshallingContribution implements IMarshallingContribution {
private _remoteCom:IProxyHelper;

View file

@ -0,0 +1,96 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
// Based on material from:
/*!
* string_score.js: String Scoring Algorithm 0.1.22
*
* http://joshaven.com/string_score
* https://github.com/joshaven/string_score
*
* Copyright (C) 2009-2014 Joshaven Potter <yourtech@gmail.com>
* Special thanks to all of the contributors listed here https://github.com/joshaven/string_score
* MIT License: http://opensource.org/licenses/MIT
*
* Date: Tue Mar 1 2011
* Updated: Tue Mar 10 2015
*/
/**
* Compute a score for the given string and the given query.
*
* Rules:
* Character score: 1
* Same case bonus: 1
* Upper case bonus: 1
* Start of word/path bonus: 7
* Start of string bonus: 8
*/
const wordPathBoundary = ['-', '_', ' ', '/', '\\', '.'];
export function score(target: string, query: string, cache?: {[id: string]: number}): number {
if (!target || !query) {
return 0; // return early if target or query are undefined
}
const cached = cache && cache[target + query];
if (typeof cached === 'number') {
return cached;
}
const queryLen = query.length;
const targetLower = target.toLowerCase();
const queryLower = query.toLowerCase();
let index = 0;
let lastIndexOf = 0;
let score = 0;
while (index < queryLen) {
var indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);
if (indexOf < 0) {
score = 0; // This makes sure that the query is contained in the target
break;
}
lastIndexOf = indexOf;
// Character Match Bonus
score += 1;
// Same Case Bonous
if (target[indexOf] === query[indexOf]) {
score += 1;
}
// Upper Case Bonus
if (isUpper(target.charCodeAt(indexOf))) {
score += 1;
}
// Prefix Bonus
if (indexOf === 0) {
score += 8;
}
// Start of Word/Path Bonous
if (wordPathBoundary.some(w => w === target[indexOf - 1])) {
score += 7;
}
index++;
}
if (cache) {
cache[target + query] = score;
}
return score;
}
function isUpper(code: number): boolean {
return 65 <= code && code <= 90;
}

View file

@ -131,7 +131,11 @@ export class Server {
if (!method) {
promise = Promise.wrapError(new Error(`${ request.name } is not a valid method on ${ request.serviceName }`));
} else {
promise = method.call(service, ...request.args)
try {
promise = method.call(service, ...request.args);
} catch (err) {
promise = Promise.wrapError(err);
}
}
if (!Promise.is(promise)) {

View file

@ -604,4 +604,4 @@ export var UTF8_BOM_CHARACTER = String.fromCharCode(__utf8_bom);
export function startsWithUTF8BOM(str: string): boolean {
return (str && str.length > 0 && str.charCodeAt(0) === __utf8_bom);
}
}

View file

@ -118,6 +118,35 @@ export function areFunctions(...objects: any[]): boolean {
return objects && objects.length > 0 && objects.every((object) => isFunction(object));
}
export type TypeConstraint = string | Function;
export function validateConstraints(args: any[], constraints: TypeConstraint[]): void {
const len = Math.min(args.length, constraints.length);
for (let i = 0; i < len; i++) {
validateConstraint(args[i], constraints[i])
}
}
export function validateConstraint(arg: any, constraint: TypeConstraint): void {
if (typeof constraint === 'string') {
if (typeof arg !== constraint) {
throw new Error(`argument does not match constraint: typeof ${constraint}`);
}
} else if (typeof constraint === 'function') {
if (arg instanceof constraint) {
return;
}
if (arg && arg.constructor === constraint) {
return;
}
if (constraint.length === 1 && constraint.call(undefined, arg) === true) {
return;
}
throw new Error(`argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true`);
}
}
/**
* Creates a new object of the provided class and will call the constructor with
* any additional argument supplied.

View file

@ -51,6 +51,7 @@ export interface IXHROptions {
export declare function xhr(options:IXHROptions):TPromise<XMLHttpRequest>;
export declare function decoratePromise(promise:Promise, successCallback?:ValueCallback, errorCallback?:ErrorCallback):Promise;
export declare function decoratePromise<T>(promise:TPromise<T>, successCallback?:TValueCallback<T>, errorCallback?:ErrorCallback):TPromise<T>;
// --- Generic promise
export interface TValueCallback<T> {

View file

@ -4,7 +4,7 @@
*--------------------------------------------------------------------------------------------*/
'use strict';
import winjs = require('vs/base/common/winjs.base');
import {TPromise} from 'vs/base/common/winjs.base';
import timer = require('vs/base/common/timer');
import errors = require('vs/base/common/errors');
import protocol = require('vs/base/common/worker/workerProtocol');
@ -26,9 +26,9 @@ export interface IWorkerFactory {
}
interface IActiveRequest {
complete:winjs.ValueCallback;
error:winjs.ErrorCallback;
progress:winjs.ProgressCallback;
complete:(value:any)=>void;
error:(err:any)=>void;
progress:(progress:any)=>void;
type:string;
payload:any;
}
@ -52,7 +52,7 @@ export class WorkerClient {
private _proxiesMarshalling: remote.ProxiesMarshallingContribution;
private _decodeMessageName: (msg: protocol.IClientMessage) => string;
public onModuleLoaded:winjs.Promise;
public onModuleLoaded:TPromise<void>;
constructor(workerFactory:IWorkerFactory, moduleId:string, decodeMessageName:(msg:protocol.IClientMessage)=>string, onCrashCallback:(workerClient:WorkerClient)=>void, workerId:number=++WorkerClient.LAST_WORKER_ID) {
this._decodeMessageName = decodeMessageName;
@ -107,16 +107,16 @@ export class WorkerClient {
return this._messagesQueue.length + (this._waitingForWorkerReply ? 1 : 0);
}
public request(requestName:string, payload:any, forceTimestamp?:number): winjs.Promise {
public request(requestName:string, payload:any, forceTimestamp?:number): TPromise<any> {
if (requestName.charAt(0) === '$') {
throw new Error('Illegal requestName: ' + requestName);
}
var shouldCancelPromise = false,
messagePromise:winjs.Promise;
messagePromise:TPromise<any>;
return new winjs.Promise((c, e, p) => {
return new TPromise<any>((c, e, p) => {
// hide the initialize promise inside this
// promise so that it won't be canceled by accident
@ -162,7 +162,7 @@ export class WorkerClient {
delete this._messageHandlers[message];
}
private _sendMessage(type:string, payload:any, forceTimestamp:number=(new Date()).getTime()):winjs.Promise {
private _sendMessage(type:string, payload:any, forceTimestamp:number=(new Date()).getTime()):TPromise<any> {
var msg = {
id: ++this._lastMessageId,
@ -171,8 +171,8 @@ export class WorkerClient {
payload: payload
};
var pc:winjs.ValueCallback, pe:winjs.ErrorCallback, pp:winjs.ProgressCallback;
var promise = new winjs.Promise((c, e, p) => {
var pc:(value:any)=>void, pe:(err:any)=>void, pp:(progress:any)=>void;
var promise = new TPromise<any>((c, e, p) => {
pc = c;
pe = e;
pp = p;
@ -352,7 +352,7 @@ export class WorkerClient {
});
}
private _handleWorkerRequest(msg:protocol.IServerMessage): winjs.Promise {
private _handleWorkerRequest(msg:protocol.IServerMessage): TPromise<any> {
if (msg.type === '_proxyObj') {
return this._remoteCom.handleMessage(msg.payload);
}
@ -366,14 +366,14 @@ export class WorkerClient {
}
this._onError('Received unexpected message from Worker:', msg);
return winjs.Promise.wrapError(new Error('No handler found'));
return TPromise.wrapError(new Error('No handler found'));
}
private _invokeHandler(handler:Function, handlerCtx:any, payload:any): winjs.Promise {
private _invokeHandler(handler:Function, handlerCtx:any, payload:any): TPromise<any> {
try {
return winjs.Promise.as(handler.call(handlerCtx, payload));
return TPromise.as(handler.call(handlerCtx, payload));
} catch (err) {
return winjs.Promise.wrapError(err);
return TPromise.wrapError(err);
}
}

View file

@ -4,12 +4,12 @@
*--------------------------------------------------------------------------------------------*/
'use strict';
import winjs = require('vs/base/common/winjs.base');
import {TPromise} from 'vs/base/common/winjs.base';
import marshalling = require('vs/base/common/marshalling');
import remote = require('vs/base/common/remote');
/**
* A message sent from the UI thread to a worker
* A message sent from the UI thread to a worker
*/
export interface IClientMessage {
id:number;
@ -73,7 +73,7 @@ export var PrintType = {
};
export interface IRequester {
request(requestName: string, payload: any): winjs.Promise;
request(requestName: string, payload: any): TPromise<any>;
}
export class RemoteCom implements remote.IRemoteCom {
@ -86,7 +86,7 @@ export class RemoteCom implements remote.IRemoteCom {
this._bigHandler = null;
}
public callOnRemote(proxyId: string, path: string, args:any[]): winjs.Promise {
public callOnRemote(proxyId: string, path: string, args:any[]): TPromise<any> {
return this._requester.request('_proxyObj', {
proxyId: proxyId,
path: path,
@ -98,18 +98,18 @@ export class RemoteCom implements remote.IRemoteCom {
this._bigHandler = handler;
}
public handleMessage(msg: { proxyId: string; path: string; args: any[]; }): winjs.Promise {
public handleMessage(msg: { proxyId: string; path: string; args: any[]; }): TPromise<any> {
if (!this._bigHandler) {
throw new Error('got message before big handler attached!');
}
return this._invokeHandler(msg.proxyId, msg.path, msg.args);
}
private _invokeHandler(rpcId:string, method:string, args:any[]): winjs.Promise {
private _invokeHandler(rpcId:string, method:string, args:any[]): TPromise<any> {
try {
return winjs.TPromise.as(this._bigHandler.handle(rpcId, method, args));
return TPromise.as(this._bigHandler.handle(rpcId, method, args));
} catch (err) {
return winjs.Promise.wrapError(err);
return TPromise.wrapError(err);
}
}
}

View file

@ -4,16 +4,16 @@
*--------------------------------------------------------------------------------------------*/
'use strict';
import winjs = require('vs/base/common/winjs.base');
import {TPromise} from 'vs/base/common/winjs.base';
import protocol = require('vs/base/common/worker/workerProtocol');
import errors = require('vs/base/common/errors');
import remote = require('vs/base/common/remote');
import marshalling = require('vs/base/common/marshalling');
interface IReplyCallbacks {
c: winjs.ValueCallback;
e: winjs.ErrorCallback;
p: winjs.ProgressCallback;
c: (value:any)=>void;
e: (err:any)=>void;
p: (progress:any)=>void;
}
export class WorkerServer {
@ -81,7 +81,7 @@ export class WorkerServer {
this._postMessage(msg);
}
public request(requestName:string, payload:any): winjs.Promise {
public request(requestName:string, payload:any): TPromise<any> {
if (requestName.charAt(0) === '$') {
throw new Error('Illegal requestName: ' + requestName);
}
@ -102,7 +102,7 @@ export class WorkerServer {
p: null
};
var r = new winjs.Promise((c, e, p) => {
var r = new TPromise<any>((c, e, p) => {
reply.c = c;
reply.e = e;
reply.p = p;
@ -194,7 +194,7 @@ export class WorkerServer {
}
}
private _handleMessage(msg:protocol.IClientMessage, c:winjs.ValueCallback, e:winjs.ErrorCallback, p:winjs.ProgressCallback): void {
private _handleMessage(msg:protocol.IClientMessage, c:(value:any)=>void, e:(err:any)=>void, p:(progress:any)=>void): void {
if (msg.type === '_proxyObj') {
this._remoteCom.handleMessage(msg.payload).then(c, e, p);

View file

@ -8,9 +8,13 @@ import WinJS = require('vs/base/common/winjs.base');
import Types = require('vs/base/common/types');
import URI from 'vs/base/common/uri';
import Tree = require('vs/base/parts/tree/common/tree');
import { IQuickNavigateConfiguration, IModel, IDataSource, IFilter, IRenderer, IRunner, Mode } from './quickOpen';
import Filters = require('vs/base/common/filters');
import Strings = require('vs/base/common/strings');
import Paths = require('vs/base/common/paths');
import {IQuickNavigateConfiguration, IModel, IDataSource, IFilter, IRenderer, IRunner, Mode} from './quickOpen';
import ActionsRenderer = require('vs/base/parts/tree/browser/actionsRenderer');
import Actions = require('vs/base/common/actions');
import {compareAnything} from 'vs/base/common/comparers';
import ActionBar = require('vs/base/browser/ui/actionbar/actionbar');
import TreeDefaults = require('vs/base/parts/tree/browser/treeDefaults');
import HighlightedLabel = require('vs/base/browser/ui/highlightedlabel/highlightedLabel');
@ -33,6 +37,7 @@ export class QuickOpenEntry {
private labelHighlights: IHighlight[];
private descriptionHighlights: IHighlight[];
private hidden: boolean;
private labelPrefix: string;
constructor(highlights: IHighlight[] = []) {
this.id = (IDS++).toString();
@ -47,6 +52,13 @@ export class QuickOpenEntry {
return this.id;
}
/**
* The prefix to show in front of the label if any
*/
public getPrefix(): string {
return this.labelPrefix;
}
/**
* The label of the entry to identify it from others in the list
*/
@ -97,6 +109,13 @@ export class QuickOpenEntry {
this.hidden = hidden;
}
/**
* Sets the prefix to show in front of the label
*/
public setPrefix(prefix: string): void {
this.labelPrefix = prefix;
}
/**
* Allows to set highlight ranges that should show up for the entry label and optionally description if set.
*/
@ -121,6 +140,113 @@ export class QuickOpenEntry {
public run(mode: Mode, context: IContext): boolean {
return false;
}
/**
* A good default sort implementation for quick open entries respecting highlight information
* as well as associated resources.
*/
public static compare(elementA: QuickOpenEntry, elementB: QuickOpenEntry, lookFor: string): number {
// Normalize
if (lookFor) {
lookFor = Strings.stripWildcards(lookFor).toLowerCase();
}
// Give matches with label highlights higher priority over
// those with only description highlights
const labelHighlightsA = elementA.getHighlights()[0] || [];
const labelHighlightsB = elementB.getHighlights()[0] || [];
if (labelHighlightsA.length && !labelHighlightsB.length) {
return -1;
} else if (!labelHighlightsA.length && labelHighlightsB.length) {
return 1;
}
// Fallback to the full path if labels are identical and we have associated resources
let nameA = elementA.getLabel();
let nameB = elementB.getLabel();
if (nameA === nameB) {
let resourceA = elementA.getResource();
let resourceB = elementB.getResource();
if (resourceA && resourceB) {
nameA = elementA.getResource().fsPath;
nameB = elementB.getResource().fsPath;
}
}
return compareAnything(nameA, nameB, lookFor);
}
/**
* A good default highlight implementation for an entry with label and description.
*/
public static highlight(entry: QuickOpenEntry, lookFor: string, fuzzyHighlight = false): { labelHighlights: IHighlight[], descriptionHighlights: IHighlight[] } {
let labelHighlights: IHighlight[] = [];
let descriptionHighlights: IHighlight[] = [];
// Highlight file aware
if (entry.getResource()) {
// Fuzzy: Highlight is special
if (fuzzyHighlight) {
let candidateLabelHighlights = Filters.matchesFuzzy(lookFor, entry.getLabel(), true);
if (!candidateLabelHighlights) {
const pathPrefix = entry.getDescription() ? (entry.getDescription() + Paths.nativeSep) : '';
const pathPrefixLength = pathPrefix.length;
// If there are no highlights in the label, build a path out of description and highlight and match on both,
// then extract the individual label and description highlights back to the original positions
let pathHighlights = Filters.matchesFuzzy(lookFor, pathPrefix + entry.getLabel(), true);
if (pathHighlights) {
pathHighlights.forEach(h => {
// Match overlaps label and description part, we need to split it up
if (h.start < pathPrefixLength && h.end > pathPrefixLength) {
labelHighlights.push({ start: 0, end: h.end - pathPrefixLength });
descriptionHighlights.push({ start: h.start, end: pathPrefixLength });
}
// Match on label part
else if (h.start >= pathPrefixLength) {
labelHighlights.push({ start: h.start - pathPrefixLength, end: h.end - pathPrefixLength });
}
// Match on description part
else {
descriptionHighlights.push(h);
}
});
}
} else {
labelHighlights = candidateLabelHighlights;
}
}
// Path search: Highlight in label and description
else if (lookFor.indexOf(Paths.nativeSep) >= 0) {
descriptionHighlights = Filters.matchesFuzzy(Strings.trim(lookFor, Paths.nativeSep), entry.getDescription());
// If we have no highlights, assume that the match is split among name and parent folder
if (!descriptionHighlights || !descriptionHighlights.length) {
labelHighlights = Filters.matchesFuzzy(Paths.basename(lookFor), entry.getLabel());
descriptionHighlights = Filters.matchesFuzzy(Strings.trim(Paths.dirname(lookFor), Paths.nativeSep), entry.getDescription());
}
}
// Highlight only inside label
else {
labelHighlights = Filters.matchesFuzzy(lookFor, entry.getLabel());
}
}
// Highlight by label otherwise
else {
labelHighlights = Filters.matchesFuzzy(lookFor, entry.getLabel());
}
return { labelHighlights, descriptionHighlights };
}
}
export class QuickOpenEntryItem extends QuickOpenEntry {
@ -175,6 +301,10 @@ export class QuickOpenEntryGroup extends QuickOpenEntry {
this.withBorder = showBorder;
}
public getPrefix(): string {
return this.entry ? this.entry.getPrefix() : super.getPrefix();
}
public getLabel(): string {
return this.entry ? this.entry.getLabel() : super.getLabel();
}
@ -265,6 +395,7 @@ class NoActionProvider implements ActionsRenderer.IActionProvider {
export interface IQuickOpenEntryTemplateData {
container: HTMLElement;
icon: HTMLSpanElement;
prefix: HTMLSpanElement;
label: HighlightedLabel.HighlightedLabel;
meta: HTMLSpanElement;
description: HighlightedLabel.HighlightedLabel;
@ -346,6 +477,10 @@ class Renderer implements IRenderer<QuickOpenEntry> {
let icon = document.createElement('span');
entry.appendChild(icon);
// Prefix
let prefix = document.createElement('span');
entry.appendChild(prefix);
// Label
let label = new HighlightedLabel.HighlightedLabel(entry);
@ -363,6 +498,7 @@ class Renderer implements IRenderer<QuickOpenEntry> {
return {
container: container,
icon: icon,
prefix: prefix,
label: label,
meta: meta,
description: description,
@ -424,7 +560,10 @@ class Renderer implements IRenderer<QuickOpenEntry> {
let iconClass = entry.getIcon() ? ('quick-open-entry-icon ' + entry.getIcon()) : '';
data.icon.className = iconClass;
// Label
// Prefix
let prefix = entry.getPrefix() || '';
data.prefix.textContent = prefix;
let labelHighlights = highlights[0];
data.label.set(entry.getLabel() || '', labelHighlights || []);

View file

@ -11,6 +11,7 @@ import Events = require('vs/base/common/eventEmitter');
import Model = require('vs/base/parts/tree/common/treeModel');
import View = require('./treeView');
import _ = require('vs/base/parts/tree/common/tree');
import { INavigator, MappedNavigator } from 'vs/base/common/iterator';
export class TreeContext implements _.ITreeContext {
@ -165,6 +166,10 @@ export class Tree extends Events.EventEmitter implements _.ITree {
this.view.setScrollPosition(pos);
}
getContentHeight(): number {
return this.view.getTotalHeight();
}
public setHighlight(element?:any, eventPayload?:any):void {
this.model.setHighlight(element, eventPayload);
}
@ -306,6 +311,10 @@ export class Tree extends Events.EventEmitter implements _.ITree {
return this.view.withFakeRow(fn);
}
getNavigator(): INavigator<any> {
return new MappedNavigator(this.model.getNavigator(), i => i && i.getElement());
}
public dispose(): void {
if (this.model !== null) {
this.model.dispose();

View file

@ -1594,7 +1594,7 @@ export class TreeView extends HeightMap implements IScrollable {
public dispose(): void {
// TODO@joao: improve
this.scrollableElement.destroy();
this.scrollableElement.dispose();
this.releaseModel();
this.modelListeners = null;

View file

@ -9,6 +9,7 @@ import Touch = require('vs/base/browser/touch');
import Events = require('vs/base/common/eventEmitter');
import Mouse = require('vs/base/browser/mouseEvent');
import Keyboard = require('vs/base/browser/keyboardEvent');
import { INavigator } from 'vs/base/common/iterator';
export interface ITree extends Events.IEventEmitter {
@ -132,6 +133,11 @@ export interface ITree extends Events.IEventEmitter {
*/
setScrollPosition(pos: number): void;
/**
* Returns the total height of the tree's content.
*/
getContentHeight(): number;
/**
* Sets the tree's highlight to be the given element.
* Provide no arguments and it clears the tree's highlight.
@ -309,6 +315,12 @@ export interface ITree extends Events.IEventEmitter {
*/
withFakeRow(fn:(container:HTMLElement)=>any):any;
/**
* Returns a navigator which allows to discover the visible and
* expanded elements in the tree.
*/
getNavigator(): INavigator<any>;
/**
* Disposes the tree
*/

View file

@ -458,7 +458,7 @@ export class Item extends Events.EventEmitter {
public getHierarchy(): Item[] {
var result: Item[] = [];
var node = this;
var node: Item = this;
do {
result.push(node);

View file

@ -5,7 +5,7 @@
'use strict';
import * as assert from 'assert';
import { IFilter, or, matchesPrefix, matchesStrictPrefix, matchesCamelCase } from 'vs/base/common/filters';
import { IFilter, or, matchesPrefix, matchesStrictPrefix, matchesCamelCase, matchesSubString, matchesContiguousSubString } from 'vs/base/common/filters';
function filterOk(filter: IFilter, word: string, wordToMatchAgainst: string, highlights?: { start: number; end: number; }[]) {
var r = filter(word, wordToMatchAgainst);
@ -146,4 +146,18 @@ suite("Filters", () => {
assert(matchesCamelCase('Debug console', 'Open: Debug Console'));
assert(matchesCamelCase('debug console', 'Open: Debug Console'));
});
test("matchesContiguousSubString", function () {
filterOk(matchesContiguousSubString, "cela", "cancelAnimationFrame()", [
{ start: 3, end: 7 }
]);
});
test("matchesSubString", function () {
filterOk(matchesSubString, "cmm", "cancelAnimationFrame()", [
{ start: 0, end: 1 },
{ start: 9, end: 10 },
{ start: 18, end: 19 }
]);
});
});

View file

@ -7,13 +7,13 @@
import * as assert from 'assert';
import { marshallObject, demarshallObject } from 'vs/base/common/marshalling';
import { ProxiesMarshallingContribution } from 'vs/base/common/remote';
import { Promise} from 'vs/base/common/winjs.base';
import { TPromise} from 'vs/base/common/winjs.base';
suite('Remote', () => {
test('bug #17587:[plugin] Language plugin can\'t define a TokenTypeClassificationSupport#wordDefinition', () => {
var contrib = new ProxiesMarshallingContribution({
callOnRemote: () => Promise.as(true)
callOnRemote: () => TPromise.as(true)
});
var initial = {

View file

@ -0,0 +1,44 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import scorer = require('vs/base/common/scorer');
suite('Scorer', () => {
test("score", function() {
const target = 'HelLo-World';
const scores = [];
scores.push(scorer.score(target, 'HelLo-World')); // direct case match
scores.push(scorer.score(target, 'hello-world')); // direct mix-case match
scores.push(scorer.score(target, 'HW')); // direct case prefix (multiple)
scores.push(scorer.score(target, 'H')); // direct case prefix
scores.push(scorer.score(target, 'hw')); // direct mix-case prefix (multiple)
scores.push(scorer.score(target, 'h')); // direct mix-case prefix
scores.push(scorer.score(target, 'W')); // direct case word prefix
scores.push(scorer.score(target, 'w')); // direct mix-case word prefix
scores.push(scorer.score(target, 'Ld')); // in-string case match (multiple)
scores.push(scorer.score(target, 'L')); // in-string case match
scores.push(scorer.score(target, 'ld')); // in-string mix-case match
scores.push(scorer.score(target, 'l')); // in-string mix-case match
scores.push(scorer.score(target, '4')); // no match
// Assert scoring order
let sortedScores = scores.sort((a, b) => b - a);
assert.deepEqual(scores, sortedScores);
});
test("cache", function() {
const cache = Object.create(null);
scorer.score('target', 'query', cache);
scorer.score('target', 't', cache);
assert.equal(Object.getOwnPropertyNames(cache).length, 2);
});
});

View file

@ -171,6 +171,27 @@ suite('Types', () => {
assert(types.isUndefinedOrNull(null));
});
test('validateConstraints', () => {
types.validateConstraints([1, 'test', true], [Number, String, Boolean])
types.validateConstraints([1, 'test', true], ['number', 'string', 'boolean'])
types.validateConstraints([console.log], [Function])
types.validateConstraints([undefined], [types.isUndefined])
types.validateConstraints([1], [types.isNumber])
function foo() {}
types.validateConstraints([new foo()], [foo]);
function isFoo(f) {}
assert.throws(() => types.validateConstraints([new foo()], [isFoo]));
function isFoo2(f) { return true}
types.validateConstraints([new foo()], [isFoo2]);
assert.throws(() => types.validateConstraints([1, true], [types.isNumber, types.isString]));
assert.throws(() => types.validateConstraints(['2'], [types.isNumber]));
assert.throws(() => types.validateConstraints([1, 'test', true], [Number, String, Number]));
});
test('create', () => {
var zeroConstructor = function() { /**/ };

View file

@ -272,4 +272,8 @@ export class SimplePluginService extends AbstractPluginService {
console.log(msg);
}
}
public deactivate(pluginId:string): void {
// nothing to do
}
}

View file

@ -40,6 +40,8 @@ import {createAsyncDescriptor0} from 'vs/platform/instantiation/common/descripto
import {LanguageExtensions, ILanguageExtensionPoint} from 'vs/editor/common/modes/languageExtensionPoint';
import {AbstractKeybindingService} from 'vs/platform/keybinding/browser/keybindingServiceImpl';
import {ICodeEditorService} from 'vs/editor/common/services/codeEditorService';
import {IJSONSchema} from 'vs/base/common/jsonSchema';
import * as JSONContributionRegistry from 'vs/platform/jsonschemas/common/jsonContributionRegistry';
// Set defaults for standalone editor
DefaultConfig.editor.wrappingIndent = 'none';
@ -451,6 +453,11 @@ export function registerStandaloneLanguage(language:ILanguageExtensionPoint, def
});
}
export function registerStandaloneSchema(uri:string, schema:IJSONSchema) {
let schemaRegistry = <JSONContributionRegistry.IJSONContributionRegistry>Registry.as(JSONContributionRegistry.Extensions.JSONContribution);
schemaRegistry.registerSchema(uri, schema);
}
export function colorizeElement(domNode:HTMLElement, options:colorizer.IColorizerElementOptions): TPromise<void> {
startup.initStaticServicesIfNecessary();
var modeService = standaloneServices.ensureStaticPlatformServices(null).modeService;

View file

@ -5,12 +5,14 @@
'use strict';
import 'vs/editor/standalone-languages/all';
import './standaloneSchemas';
import Colorizer = require('vs/editor/browser/standalone/colorizer');
import standaloneCodeEditor = require('vs/editor/browser/standalone/standaloneCodeEditor');
import EditorCommon = require('vs/editor/common/editorCommon');
import EditorBrowser = require('vs/editor/browser/editorBrowser');
import {ILanguageDef} from 'vs/editor/standalone-languages/types';
import {IJSONSchema} from 'vs/base/common/jsonSchema';
var global:any = self;
if (!global.Monaco) {
@ -67,4 +69,10 @@ Monaco.Editor.OverlayWidgetPositionPreference = EditorBrowser.OverlayWidgetPosit
let MonacoEditorLanguages: ILanguageDef[] = this.MonacoEditorLanguages || [];
MonacoEditorLanguages.forEach((language) => {
standaloneCodeEditor.registerStandaloneLanguage(language, language.defModule);
});
});
// Register all built-in standalone JSON schemas
let MonacoEditorSchemas: { [url:string]: IJSONSchema } = this.MonacoEditorSchemas || {};
for (var uri in MonacoEditorSchemas) {
standaloneCodeEditor.registerStandaloneSchema(uri, MonacoEditorSchemas[uri]);
};

View file

@ -0,0 +1,849 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import nls = require('vs/nls');
import {IJSONSchema} from 'vs/base/common/jsonSchema';
this.MonacoEditorSchemas = this.MonacoEditorSchemas || {};
let MonacoEditorSchemas: { [uri:string]:IJSONSchema } = this.MonacoEditorSchemas;
MonacoEditorSchemas['http://json.schemastore.org/project'] = {
'title': nls.localize('project.json.title', 'JSON schema for ASP.NET project.json files'),
'$schema': 'http://json-schema.org/draft-04/schema#',
'id': 'http://json.schemastore.org/project',
'type': 'object',
'definitions': {
'compilationOptions': {
'description': nls.localize('project.json.compilationOptions', 'Compilation options that are passed through to Roslyn'),
'type': 'object',
'properties': {
'define': {
'type': 'array',
'items': {
'type': 'string',
'uniqueItems': true
}
},
'warningsAsErrors': {
'type': 'boolean',
'default': false
},
'allowUnsafe': {
'type': 'boolean',
'default': false
},
'optimize': {
'type': 'boolean',
'default': false
},
'languageVersion': {
'type': 'string',
'enum': ['csharp1', 'csharp2', 'csharp3', 'csharp4', 'csharp5', 'csharp6', 'experimental']
}
}
},
'configType': {
'type': 'object',
'properties': {
'dependencies': { '$ref': '#/definitions/dependencies' },
'compilationOptions': { '$ref': '#/definitions/compilationOptions' },
'frameworkAssemblies': { '$ref': '#/definitions/dependencies' }
}
},
'dependencies': {
'type': 'object',
'additionalProperties': {
'type': ['string', 'object'],
'properties': {
'version': {
'type': 'string',
'description': nls.localize('project.json.dependency.name', 'The version of the dependency.')
},
'type': {
'type': 'string',
'default': 'default',
'enum': ['default', 'build'],
'description': nls.localize('project.json.dependency.type', 'The type of the dependency. \'build\' dependencies only exist at build time')
}
},
'id': 'nugget-package'
},
'description': nls.localize('project.json.dependencies', 'The dependencies of the application. Each entry specifes the name and the version of a Nuget package.'),
'id': 'nugget-packages'
},
'script': {
'type': ['string', 'array'],
'items': {
'type': 'string'
},
'description': nls.localize('project.json.script', 'A command line script or scripts.\r\rAvailable variables:\r%project:Directory% - The project directory\r%project:Name% - The project name\r%project:Version% - The project version')
}
},
'properties': {
'authors': {
'description': nls.localize('project.json.authors', 'The author of the application'),
'type': 'array',
'items': {
'type': 'string',
'uniqueItems': true
}
},
'bundleExclude': {
'description': nls.localize('project.json.bundleExclude', 'List of files to exclude from publish output (kpm bundle).'),
'type': [ 'string', 'array' ],
'items': {
'type': 'string'
},
'default': ''
},
'code': {
'description': nls.localize('project.json.code', 'Glob pattern to specify all the code files that needs to be compiled. (data type: string or array with glob pattern(s)). Example: [ \'Folder1\\*.cs\', \'Folder2\\*.cs\' ]'),
'type': ['string', 'array'],
'items': {
'type': 'string'
},
'default': '**\\*.cs'
},
'commands': {
'description': nls.localize('project.json.commands', 'Commands that are available for this application'),
'type': 'object',
'additionalProperties': {
'type': 'string'
}
},
'compilationOptions': { '$ref': '#/definitions/compilationOptions' },
'configurations': {
'type': 'object',
'description': nls.localize('project.json.configurations', 'Configurations are named groups of compilation settings. There are 2 defaults built into the runtime namely \'Debug\' and \'Release\'.'),
'additionalProperties': {
'type': 'object',
'properties': {
'compilationOptions': { '$ref': '#/definitions/compilationOptions' }
}
}
},
'dependencies': { '$ref': '#/definitions/dependencies' },
'description': {
'description': nls.localize('project.json.description', 'The description of the application'),
'type': 'string'
},
'exclude': {
'description': nls.localize('project.json.exclude', 'Glob pattern to indicate all the code files to be excluded from compilation. (data type: string or array with glob pattern(s)).'),
'type': ['string', 'array'],
'items': {
'type': 'string'
},
'default': ['bin/**/*.*', 'obj/**/*.*']
},
'frameworks': {
'description': nls.localize('project.json.frameworks', 'Target frameworks that will be built, and dependencies that are specific to the configuration.'),
'type': 'object',
'additionalProperties': { '$ref': '#/definitions/configType' }
},
'preprocess': {
'description': nls.localize('project.json.preprocess', 'Glob pattern to indicate all the code files to be preprocessed. (data type: string with glob pattern).'),
'type': 'string',
'default': 'Compiler\\Preprocess\\**\\*.cs'
},
'resources': {
'description': nls.localize('project.json.resources', 'Glob pattern to indicate all the files that need to be compiled as resources.'),
'type': ['string', 'array'],
'items': {
'type': 'string'
},
'default': 'Compiler\\Resources\\**\\*.cs'
},
'scripts': {
'type': 'object',
'description': nls.localize('project.json.scripts', 'Scripts to execute during the various stages.'),
'properties': {
'prepack': { '$ref': '#/definitions/script' },
'postpack': { '$ref': '#/definitions/script' },
'prebundle': { '$ref': '#/definitions/script' },
'postbundle': { '$ref': '#/definitions/script' },
'prerestore': { '$ref': '#/definitions/script' },
'postrestore': { '$ref': '#/definitions/script' },
'prepare': { '$ref': '#/definitions/script' }
}
},
'shared': {
'description': nls.localize('project.json.shared', 'Glob pattern to specify the code files to share with dependent projects. Example: [ \'Folder1\\*.cs\', \'Folder2\\*.cs\' ]'),
'type': ['string', 'array'],
'items': {
'type': 'string'
},
'default': 'Compiler\\Shared\\**\\*.cs'
},
'version': {
'description': nls.localize('project.json.version', 'The version of the application. Example: 1.2.0.0'),
'type': 'string'
},
'webroot': {
'description': nls.localize('project.json.webroot', 'Specifying the webroot property in the project.json file specifies the web server root (aka public folder). In visual studio, this folder will be used to root IIS. Static files should be put in here.'),
'type': 'string'
}
}
};
MonacoEditorSchemas['http://json.schemastore.org/bower'] = {
'title': nls.localize('bower.json.title', 'JSON schema for Bower configuration files'),
'$schema': 'http://json-schema.org/draft-04/schema#',
'id': 'http://json.schemastore.org/bower',
'type': 'object',
'required': ['name'],
'patternProperties': {
'^_': {
'description': nls.localize('bower.json.invalidPatternName', 'Any property starting with _ is valid.'),
'additionalProperties': true,
'additionalItems': true
}
},
'properties': {
'name': {
'description': nls.localize('bower.json.packagename', 'The name of your package.'),
'type': 'string',
'maxLength': 50
},
'description': {
'description': nls.localize('bower.json.description', 'Help users identify and search for your package with a brief description.'),
'type': 'string'
},
'version': {
'description': nls.localize('bower.json.version', 'A semantic version number.'),
'type': 'string'
},
'main': {
'description': nls.localize('bower.json.main', 'The primary acting files necessary to use your package.'),
'type': ['string', 'array']
},
'license': {
'description': nls.localize('bower.json.license', 'SPDX license identifier or path/url to a license.'),
'type': ['string', 'array'],
'maxLength': 140
},
'ignore': {
'description': nls.localize('bower.json.ignore', 'A list of files for Bower to ignore when installing your package.'),
'type': ['string', 'array']
},
'keywords': {
'description': nls.localize('bower.json.keywords', 'Used for search by keyword. Helps make your package easier to discover without people needing to know its name.'),
'type': 'array',
'items': {
'type': 'string',
'maxLength': 50
}
},
'authors': {
'description': nls.localize('bower.json.authors', 'A list of people that authored the contents of the package.'),
'type': 'array',
'items': {
'type': ['string', 'object']
}
},
'homepage': {
'description': nls.localize('bower.json.homepage', 'URL to learn more about the package. Falls back to GitHub project if not specified and it\'s a GitHub endpoint.'),
'type': 'string'
},
'repository': {
'description': nls.localize('bower.json.repository', 'The repository in which the source code can be found.'),
'type': 'object',
'properties': {
'type': {
'type': 'string',
'enum': ['git']
},
'url': {
'type': 'string'
}
}
},
'dependencies': {
'id': 'bower-packages',
'description': nls.localize('bower.json.dependencies', 'Dependencies are specified with a simple hash of package name to a semver compatible identifier or URL.'),
'type': 'object',
'additionalProperties': {
'id': 'bower-package',
'type': 'string'
}
},
'devDependencies': {
'id': 'bower-packages',
'description': nls.localize('bower.json.devDependencies', 'Dependencies that are only needed for development of the package, e.g., test framework or building documentation.'),
'type': 'object',
'additionalProperties': {
'id': 'bower-package',
'type': 'string'
}
},
'resolutions': {
'description': nls.localize('bower.json.resolutions', 'Dependency versions to automatically resolve with if conflicts occur between packages.'),
'type': 'object'
},
'private': {
'description': nls.localize('bower.json.private', 'If you set it to true it will refuse to publish it. This is a way to prevent accidental publication of private repositories.'),
'type': 'boolean'
},
'exportsOverride': {
'description': nls.localize('bower.json.exportsOverride', 'Used by grunt-bower-task to specify custom install locations.'),
'type': 'object',
'additionalProperties': {
'type': 'object',
'additionalProperties': {
'type': 'string'
}
}
},
'moduleType': {
'description': nls.localize('bower.json.moduleType', 'The types of modules this package exposes'),
'type': 'array',
'items': {
'enum': ['amd', 'es6', 'globals', 'node', 'yui']
}
}
}
};
MonacoEditorSchemas['http://json.schemastore.org/package'] = {
'id': 'http://json.schemastore.org/package',
'description': nls.localize('package.json.description', 'NPM configuration for this package.'),
'type': 'object',
'required': ['name', 'version'],
'definitions': {
'person': {
'description': nls.localize('package.json.person', 'A person who has been involved in creating or maintaining this package'),
'type': [ 'object', 'string' ],
'required': [ 'name' ],
'properties': {
'name': {
'type': 'string'
},
'url': {
'type': 'string',
'format': 'uri'
},
'email': {
'type': 'string',
'format': 'email'
}
}
},
'dependency': {
'id': 'npm-packages',
'description': nls.localize('package.json.dependency', 'Dependencies are specified with a simple hash of package name to version range. The version range is a string which has one or more space-separated descriptors. Dependencies can also be identified with a tarball or git URL.'),
'type': 'object',
'additionalProperties': {
'type': 'string'
}
}
},
'patternProperties': {
'^_': {
'description': nls.localize('package.json.underscore', 'Any property starting with _ is valid.'),
'additionalProperties': true,
'additionalItems': true
}
},
'properties': {
'name': {
'description': nls.localize('package.json.name', 'The name of the package.'),
'type': 'string'
},
'version': {
'description': nls.localize('package.json.version', 'Version must be parseable by node-semver, which is bundled with npm as a dependency.'),
'type': 'string'
},
'description': {
'description': nls.localize('package.json.descr', 'This helps people discover your package, as it\'s listed in \'npm search\'.'),
'type': 'string'
},
'icon': {
'description': nls.localize('package.json.icon', 'The relative path to the icon of the package.'),
'type': 'string'
},
'keywords': {
'description': nls.localize('package.json.keywords', 'This helps people discover your package as it\'s listed in \'npm search\'.'),
'type': 'array'
},
'homepage': {
'description': nls.localize('package.json.homepage', 'The url to the project homepage.'),
'type': 'string'
},
'bugs': {
'description': nls.localize('package.json.bugs', 'The url to your project\'s issue tracker and / or the email address to which issues should be reported. These are helpful for people who encounter issues with your package.'),
'type': [ 'object', 'string' ],
'properties': {
'url': {
'type': 'string',
'description': nls.localize('package.json.bugs.url', 'The url to your project\'s issue tracker.'),
'format': 'uri'
},
'email': {
'type': 'string',
'description': nls.localize('package.json.bugs.email', 'The email address to which issues should be reported.')
}
}
},
'license': {
'type': 'string',
'description': nls.localize('package.json.license', 'You should specify a license for your package so that people know how they are permitted to use it, and any restrictions you\'re placing on it.')
},
'licenses': {
'description': nls.localize('package.json.licenses', 'You should specify a license for your package so that people know how they are permitted to use it, and any restrictions you\'re placing on it.'),
'type': 'array',
'items': {
'type': 'object',
'properties': {
'type': {
'type': 'string'
},
'url': {
'type': 'string',
'format': 'uri'
}
}
}
},
'author': {
'$ref': '#/definitions/person'
},
'contributors': {
'description': nls.localize('package.json.contributors', 'A list of people who contributed to this package.'),
'type': 'array',
'items': {
'$ref': '#/definitions/person'
}
},
'maintainers': {
'description': nls.localize('package.json.maintainers', 'A list of people who maintains this package.'),
'type': 'array',
'items': {
'$ref': '#/definitions/person'
}
},
'files': {
'description': nls.localize('package.json.files', 'The \'files\' field is an array of files to include in your project. If you name a folder in the array, then it will also include the files inside that folder.'),
'type': 'array',
'items': {
'type': 'string'
}
},
'main': {
'description': nls.localize('package.json.main', 'The main field is a module ID that is the primary entry point to your program.'),
'type': 'string'
},
'bin': {
'type': [ 'string', 'object' ],
'additionalProperties': {
'type': 'string'
}
},
'man': {
'type': [ 'array', 'string' ],
'description': nls.localize('package.json.man', 'Specify either a single file or an array of filenames to put in place for the man program to find.'),
'items': {
'type': 'string'
}
},
'directories': {
'type': 'object',
'properties': {
'bin': {
'description': nls.localize('package.json.directories.bin', 'If you specify a \'bin\' directory, then all the files in that folder will be used as the \'bin\' hash.'),
'type': 'string'
},
'doc': {
'description': nls.localize('package.json.directories.doc', 'Put markdown files in here. Eventually, these will be displayed nicely, maybe, someday.'),
'type': 'string'
},
'example': {
'description': nls.localize('package.json.directories.example', 'Put example scripts in here. Someday, it might be exposed in some clever way.'),
'type': 'string'
},
'lib': {
'description': nls.localize('package.json.directories.lib', 'Tell people where the bulk of your library is. Nothing special is done with the lib folder in any way, but it\'s useful meta info.'),
'type': 'string'
},
'man': {
'description': nls.localize('package.json.directories.man', 'A folder that is full of man pages. Sugar to generate a \'man\' array by walking the folder.'),
'type': 'string'
},
'test': {
'type': 'string'
}
}
},
'repository': {
'description': nls.localize('package.json.repository', 'Specify the place where your code lives. This is helpful for people who want to contribute.'),
'type': 'object',
'properties': {
'type': {
'type': 'string'
},
'url': {
'type': 'string'
}
}
},
'scripts': {
'description': nls.localize('package.json.scripts', 'The \'scripts\' member is an object hash of script commands that are run at various times in the lifecycle of your package. The key is the lifecycle event, and the value is the command to run at that point.'),
'type': 'object',
'additionalProperties': {
'type': 'string'
}
},
'config': {
'description': nls.localize('package.json.config', 'A \'config\' hash can be used to set configuration parameters used in package scripts that persist across upgrades.'),
'type': 'object',
'additionalProperties': true
},
'dependencies': {
'$ref': '#/definitions/dependency'
},
'devDependencies': {
'$ref': '#/definitions/dependency'
},
'bundleDependencies': {
'type': 'array',
'description': nls.localize('package.json.bundleDependencies', 'Array of package names that will be bundled when publishing the package.'),
'items': {
'type': 'string'
}
},
'bundledDependencies': {
'type': 'array',
'description': nls.localize('package.json.bundledDependencies', 'Array of package names that will be bundled when publishing the package.'),
'items': {
'type': 'string'
}
},
'optionalDependencies': {
'$ref': '#/definitions/dependency'
},
'peerDependencies': {
'$ref': '#/definitions/dependency'
},
'engines': {
'type': 'object',
'additionalProperties': {
'type': 'string'
}
},
'engineStrict': {
'type': 'boolean'
},
'os': {
'type': 'array',
'items': {
'type': 'string'
}
},
'cpu': {
'type': 'array',
'items': {
'type': 'string'
}
},
'preferGlobal': {
'type': 'boolean',
'description': nls.localize('package.json.preferGlobal', 'If your package is primarily a command-line application that should be installed globally, then set this value to true to provide a warning if it is installed locally.')
},
'private': {
'type': 'boolean',
'description': nls.localize('package.json.private', 'If set to true, then npm will refuse to publish it.')
},
'publishConfig': {
'type': 'object',
'additionalProperties': true
},
'dist': {
'type': 'object',
'properties': {
'shasum': {
'type': 'string'
},
'tarball': {
'type': 'string'
}
}
},
'readme': {
'type': 'string'
}
}
};
MonacoEditorSchemas['http://json.schemastore.org/global'] = {
'title': nls.localize('global.json.title', 'JSON schema for the ASP.NET global configuration files'),
'type': 'object',
'additionalProperties': true,
'required': [ 'projects' ],
'properties': {
'projects': {
'type': 'array',
'description': nls.localize('global.json.projects', 'A list of project folders relative to this file.'),
'items': {
'type': 'string'
}
},
'sources': {
'type': 'array',
'description': nls.localize('global.json.sources', 'A list of source folders relative to this file.'),
'items': {
'type': 'string'
}
},
'sdk': {
'type': 'object',
'description': nls.localize('global.json.sdk', 'The runtime to use.'),
'properties': {
'version': {
'type': 'string',
'description': nls.localize('global.json.sdk.version', 'The runtime version to use.')
},
'runtime': {
'type': 'string',
'description': nls.localize('global.json.sdk.runtime', 'The runtime to use, e.g. coreclr'),
},
'architecture': {
'type': 'string',
'description': nls.localize('global.json.sdk.architecture', 'The runtime architecture to use, e.g. x64.')
}
}
}
}
};
MonacoEditorSchemas['http://json.schemastore.org/tsconfig'] = {
'title': nls.localize('tsconfig.json.title', "JSON schema for the TypeScript compiler's configuration file"),
'$schema': 'http://json-schema.org/draft-04/schema#',
'type': 'object',
'default': { 'compilerOptions': { 'target': 'ES5', 'module': 'commonjs'} },
'properties': {
'compilerOptions': {
'type': 'object',
'description': nls.localize('tsconfig.json.compilerOptions', 'Instructs the TypeScript compiler how to compile .ts files'),
'properties': {
'charset': {
'description': nls.localize('tsconfig.json.compilerOptions.charset', 'The character set of the input files'),
'type': 'string'
},
'declaration': {
'description': nls.localize('tsconfig.json.compilerOptions.declaration', 'Generates corresponding d.ts files.'),
'type': 'boolean'
},
'diagnostics': {
'description': nls.localize('tsconfig.json.compilerOptions.diagnostics', 'Show diagnostic information.'),
'type': 'boolean'
},
'emitBOM': {
'description': nls.localize('tsconfig.json.compilerOptions.emitBOM', 'Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files.'),
'type': 'boolean'
},
'inlineSourceMap': {
'description': nls.localize('tsconfig.json.compilerOptions.inlineSourceMap', 'Emit a single file with source maps instead of having a separate file.'),
'type': 'boolean'
},
'inlineSources': {
'description': nls.localize('tsconfig.json.compilerOptions.inlineSources', 'Emit the source alongside the sourcemaps within a single file; requires --inlineSourceMap to be set.'),
'type': 'boolean'
},
'listFiles': {
'description': nls.localize('tsconfig.json.compilerOptions.listFiles', 'Print names of files part of the compilation.'),
'type': 'boolean'
},
'locale': {
'description': nls.localize('tsconfig.json.compilerOptions.locale', 'The locale to use to show error messages, e.g. en-us.'),
'type': 'string'
},
'mapRoot': {
'description': nls.localize('tsconfig.json.compilerOptions.mapRoot', 'Specifies the location where debugger should locate map files instead of generated locations'),
'type': 'string',
'format': 'uri'
},
'module': {
'description': nls.localize('tsconfig.json.compilerOptions.module', "Specify module code generation: 'CommonJS', 'Amd', 'System', or 'UMD'."),
'enum': ['commonjs', 'amd', 'umd', 'system']
},
'newLine': {
'description': nls.localize('tsconfig.json.compilerOptions.newLine', "Specifies the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix).)"),
'enum': [ 'CRLF', 'LF' ]
},
'noEmit': {
'description': nls.localize('tsconfig.json.compilerOptions.noEmit', 'Do not emit output.'),
'type': 'boolean'
},
'noEmitOnError': {
'description': nls.localize('tsconfig.json.compilerOptions.noEmitOnError', 'Do not emit outputs if any type checking errors were reported.'),
'type': 'boolean'
},
'noEmitHelpers': {
'description': nls.localize('tsconfig.json.compilerOptions.noEmitHelpers', 'Do not generate custom helper functions like __extends in compiled output.'),
'type': 'boolean'
},
'noImplicitAny': {
'description': nls.localize('tsconfig.json.compilerOptions.noImplicitAny', "Warn on expressions and declarations with an implied 'any' type."),
'type': 'boolean'
},
'noLib': {
'description': nls.localize('tsconfig.json.compilerOptions.noLib', "Do not include the default library file (lib.d.ts)."),
'type': 'boolean'
},
'noResolve': {
'description': nls.localize('tsconfig.json.compilerOptions.noResolve', "Do not add triple-slash references or module import targets to the list of compiled files."),
'type': 'boolean'
},
'out': {
'description': nls.localize('tsconfig.json.compilerOptions.out', 'Concatenate and emit output to single file.'),
'type': 'string',
'format': 'uri'
},
'outDir': {
'description': nls.localize('tsconfig.json.compilerOptions.outDir', 'Redirect output structure to the directory.'),
'type': 'string',
'format': 'uri'
},
'preserveConstEnums': {
'description': nls.localize('tsconfig.json.compilerOptions.preserveConstEnums', 'Do not erase const enum declarations in generated code.'),
'type': 'boolean'
},
'removeComments': {
'description': nls.localize('tsconfig.json.compilerOptions.removeComments', 'Do not emit comments to output.'),
'type': 'boolean'
},
'rootDir': {
'description': nls.localize('tsconfig.json.compilerOptions.rootDir', 'Specifies the root directory of input files. Use to control the output directory structure with --outDir.'),
'type': 'string'
},
'sourceMap': {
'description': nls.localize('tsconfig.json.compilerOptions.sourceMap', "Generates corresponding '.map' file."),
'type': 'boolean'
},
'sourceRoot': {
'description': nls.localize('tsconfig.json.compilerOptions.sourceRoot', 'Specifies the location where debugger should locate TypeScript files instead of source locations.'),
'type': 'string',
'format': 'uri'
},
'suppressImplicitAnyIndexErrors': {
'description': nls.localize('tsconfig.json.compilerOptions.suppressImplicitAnyIndexErrors', 'Suppress noImplicitAny errors for indexing objects lacking index signatures.'),
'type': 'boolean'
},
'target': {
'description': nls.localize('tsconfig.json.compilerOptions.target', "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES6' (experimental)."),
'enum': ['ES3', 'ES5', 'ES6', 'es3', 'es5', 'es6'],
'default': 'ES3'
},
'watch': {
'description': nls.localize('tsconfig.json.compilerOptions.watch', "Watch input files."),
"type": 'boolean'
},
'jsx': {
'description': nls.localize('tsconfig.json.compilerOptions.jsx', "Enable the JSX option (requires TypeScript 1.6): 'preserve', 'react'."),
'enum': ['react', 'preserve'],
'default': 'react'
},
'emitDecoratorMetadata': {
'description': nls.localize('tsconfig.json.compilerOptions.emitDecoratorMetadata', 'Emits meta data.for ES7 decorators.'),
'type': 'boolean'
},
'isolatedModules': {
'description': nls.localize('tsconfig.json.compilerOptions.isolatedModules', 'Supports transpiling single TS files into JS files.'),
'type': 'boolean'
},
'experimentalDecorators': {
'description': nls.localize('tsconfig.json.compilerOptions.experimentalDecorators', 'Enables experimental support for ES7 decorators.'),
'type': 'boolean'
},
'experimentalAsyncFunctions': {
'description': nls.localize('tsconfig.json.compilerOptions.experimentalAsynFunctions', 'Enables experimental support for async functions (requires TypeScript 1.6).'),
'type': 'boolean'
}
}
},
'files': {
'type': 'array',
'description': nls.localize('tsconfig.json.files', "If no 'files' property is present in a tsconfig.json, the compiler defaults to including all files the containing directory and subdirectories. When a 'files' property is specified, only those files are included."),
'items': {
'type': 'string',
'format': 'uri'
}
}
}
};
MonacoEditorSchemas['http://opentools.azurewebsites.net/jsconfig'] = {
'title': nls.localize('jsconfig.json.title', "JSON schema for the JavaScript configuration file"),
'type': 'object',
'default': { 'compilerOptions': { 'target': 'ES6' } },
'properties': {
'compilerOptions': {
'type': 'object',
'description': nls.localize('jsconfig.json.compilerOptions', 'Instructs the JavaScript language service how to validate .js files'),
'properties': {
'charset': {
'description': nls.localize('jsconfig.json.compilerOptions.charset', 'The character set of the input files'),
'type': 'string'
},
'diagnostics': {
'description': nls.localize('jsconfig.json.compilerOptions.diagnostics', 'Show diagnostic information.'),
'type': 'boolean'
},
'locale': {
'description': nls.localize('jsconfig.json.compilerOptions.locale', 'The locale to use to show error messages, e.g. en-us.'),
'type': 'string'
},
'mapRoot': {
'description': nls.localize('jsconfig.json.compilerOptions.mapRoot', 'Specifies the location where debugger should locate map files instead of generated locations'),
'type': 'string',
'format': 'uri'
},
'module': {
'description': nls.localize('jsconfig.json.compilerOptions.module', "Module code generation to resolve against: 'commonjs', 'amd', 'system', or 'umd'."),
'enum': ['commonjs', 'amd', 'system', 'umd']
},
'noLib': {
'description': nls.localize('jsconfig.json.compilerOptions.noLib', "Do not include the default library file (lib.d.ts)."),
'type': 'boolean'
},
'target': {
'description': nls.localize('jsconfig.json.compilerOptions.target', "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES6' (experimental)."),
'enum': ['ES3', 'ES5', 'ES6', 'es3', 'es5', 'es6'],
'default': 'ES3'
},
'experimentalDecorators': {
'description': nls.localize('jsconfig.json.compilerOptions.decorators', "Enables experimental support for ES7 decorators."),
'type': 'boolean'
}
}
},
'files': {
'type': 'array',
'description': nls.localize('jsconfig.json.files', "If no 'files' property is present in a jsconfig.json, the language service defaults to including all files the containing directory and subdirectories. When a 'files' property is specified, only those files are included."),
'items': {
'type': 'string',
'format': 'uri'
}
},
'exclude': {
'type': 'array',
'description': nls.localize('jsconfig.json.exclude', "List files and folders that should not be included. This property is not honored when the 'files' property is present."),
'items': {
'type': 'string',
'format': 'uri'
}
}
}
};

View file

@ -115,6 +115,13 @@ export class ViewLines extends ViewLayer {
return true;
}
public onCursorScrollRequest(e:EditorCommon.IViewScrollRequestEvent): boolean {
let currentScrollTop = this._layoutProvider.getScrollTop();
let newScrollTop = currentScrollTop + e.deltaLines * this._context.configuration.editor.lineHeight;
this._layoutProvider.setScrollTop(newScrollTop);
return true;
}
private _hasVerticalScroll = false;
private _hasHorizontalScroll = false;
public onScrollChanged(e:EditorCommon.IScrollEvent): boolean {

View file

@ -50,10 +50,6 @@
.monaco-editor.vs .token.strong { font-weight: bold; }
.monaco-editor.vs .token.header { color: navy ;}
/* JSON */
.monaco-editor.vs .token.string.key { color: #A31515; }
.monaco-editor.vs .token.string.value { color: #0451A5; }
/* YAML */
.monaco-editor.vs .token.string.yaml { color: #0451A5; }
@ -151,11 +147,6 @@
.monaco-editor.vs-dark .token.strong { font-weight: bold; }
.monaco-editor.vs-dark .token.header { color: navy ;}
/* JSON */
.monaco-editor.vs-dark .token.string.key { color: #9CDCFE; }
.monaco-editor.vs-dark .token.string.value { color: #CE9178; }
/* YAML */
.monaco-editor.vs-dark .token.string.yaml { color: #CE9178; }
@ -252,11 +243,6 @@
.monaco-editor.hc-black .token.strong { font-weight: bold; }
.monaco-editor.hc-black .token.header { color: navy ;}
/* JSON */
.monaco-editor.hc-black .token.string.key { color: #9CDCFE; }
.monaco-editor.hc-black .token.string.value { color: #CE9178; }
/* YAML */
.monaco-editor.hc-black .token.string.yaml { color: #CE9178; }
@ -394,6 +380,7 @@
.monaco-editor.vs .token.meta.cast { color: #2B91AF; }
.monaco-editor.vs .token.meta.parameter.type { color: #2B91AF; }
.monaco-editor.vs .token.meta.parameter.type.variable { color: #000000; }
.monaco-editor.vs .token.meta.dictionary.key { color: #A31515; }
.monaco-editor.vs .token.storage { color: #0000FF; }
.monaco-editor.vs .token.storage.content { color: red; }
@ -406,6 +393,7 @@
.monaco-editor.vs .token.string { color: #A31515; }
.monaco-editor.vs .token.string.tag { color: blue; }
.monaco-editor.vs .token.string.value { color: #0451A5; }
/*.monaco-editor.vs .token.string.quoted
.monaco-editor.vs .token.string.quoted.single
.monaco-editor.vs .token.string.quoted.double
@ -444,12 +432,6 @@
/*.monaco-editor.vs .token.keyword.operator
.monaco-editor.vs .token.keyword.other*/
.monaco-editor.vs .token.punctuation { color: #000000; }
.monaco-editor.vs .token.punctuation.string { color: #A31515; }
.monaco-editor.vs .token.punctuation.string.quoted.variable { color: #001188; }
.monaco-editor.vs .token.punctuation.string.regexp { color: #811f3f; }
.monaco-editor.vs .token.punctuation.tag { color: #800000; }
.monaco-editor.vs .token.punctuation.string.tag { color: blue; }
/* -------------------------------- Begin vs-dark tokens -------------------------------- */
.monaco-editor.vs-dark .token { color: #D4D4D4; }
@ -531,6 +513,7 @@
.monaco-editor.vs-dark .token.meta.cast { color: #569CD6; }
.monaco-editor.vs-dark .token.meta.parameter.type { color: #569CD6; }
.monaco-editor.vs-dark .token.meta.parameter.type.variable { color: #9CDCFE; }
.monaco-editor.vs-dark .token.meta.dictionary.key { color: #569CD6; }
.monaco-editor.vs-dark .token.storage { color: #569CD6; }
.monaco-editor.vs-dark .token.storage.content { color: #9CDCFE; }
@ -545,6 +528,7 @@
.monaco-editor.vs-dark .token.string { color: #CE9178; }
.monaco-editor.vs-dark .token.string.tag { color: #CE9178; }
.monaco-editor.vs-dark .token.string.value { color: #CE9178; }
/*.monaco-editor.vs-dark .token.string.quoted
.monaco-editor.vs-dark .token.string.quoted.single
.monaco-editor.vs-dark .token.string.quoted.double
@ -581,13 +565,6 @@
/*.monaco-editor.vs-dark .token.keyword.operator
.monaco-editor.vs-dark .token.keyword.other*/
.monaco-editor.vs-dark .token.punctuation { color: #DCDCDC; }
.monaco-editor.vs-dark .token.punctuation.string { color: #CE9178; }
.monaco-editor.vs-dark .token.punctuation.string.quoted.variable { color: #74B0DF; }
.monaco-editor.vs-dark .token.punctuation.string.regexp { color: #D16969; }
.monaco-editor.vs-dark .token.punctuation.tag { color: #569CD6; }
.monaco-editor.vs-dark .token.punctuation.string.tag { color: #CE9178; }
/* -------------------------------- End vs-dark tokens -------------------------------- */
@ -671,6 +648,7 @@
.monaco-editor.hc-black .token.meta.cast { color: #569CD6; }
.monaco-editor.hc-black .token.meta.parameter.type { color: #569CD6; }
.monaco-editor.hc-black .token.meta.parameter.type.variable { color: #9CDCFE; }
.monaco-editor.hc-black .token.meta.dictionary.key { color: #569CD6; }
.monaco-editor.hc-black .token.storage { color: #569CD6; }
.monaco-editor.hc-black .token.storage.content { color: #9CDCFE; }
@ -685,6 +663,7 @@
.monaco-editor.hc-black .token.string { color: #CE9178; }
.monaco-editor.hc-black .token.string.tag { color: #CE9178; }
.monaco-editor.hc-black .token.string.value { color: #CE9178; }
/*.monaco-editor.hc-black .token.string.quoted
.monaco-editor.hc-black .token.string.quoted.single
.monaco-editor.hc-black .token.string.quoted.double
@ -722,11 +701,4 @@
/*.monaco-editor.hc-black .token.keyword.operator
.monaco-editor.hc-black .token.keyword.other*/
.monaco-editor.hc-black .token.punctuation { color: #DCDCDC; }
.monaco-editor.hc-black .token.punctuation.string { color: #CE9178; }
.monaco-editor.hc-black .token.punctuation.string.quoted.variable { color: #74B0DF; }
.monaco-editor.hc-black .token.punctuation.string.regexp { color: #D16969; }
.monaco-editor.hc-black .token.punctuation.tag { color: #569CD6; }
.monaco-editor.hc-black .token.punctuation.string.tag { color: #CE9178; }
/* -------------------------------- End hc-black tokens ----------------------------- */

View file

@ -9,6 +9,7 @@ import {Range} from 'vs/editor/common/core/range';
import {Selection} from 'vs/editor/common/core/selection';
import EditorCommon = require('vs/editor/common/editorCommon');
import {CursorMoveHelper} from 'vs/editor/common/controller/cursorMoveHelper';
import {getRawEnterActionAtPosition} from 'vs/editor/common/modes/supports/onEnter';
export interface IShiftCommandOpts {
isUnshift: boolean;
@ -50,19 +51,21 @@ export class ShiftCommand implements EditorCommon.ICommand {
}
public getEditOperations(model: EditorCommon.ITokenizedModel, builder: EditorCommon.IEditOperationBuilder): void {
var startLine = this._selection.startLineNumber,
endLine = this._selection.endLineNumber;
let startLine = this._selection.startLineNumber,
endLine = this._selection.endLineNumber,
_SPACE = ' '.charCodeAt(0);
if (this._selection.endColumn === 1 && startLine !== endLine) {
endLine = endLine - 1;
}
var lineNumber:number,
let lineNumber:number,
tabSize = this._opts.tabSize,
oneIndent = this._opts.oneIndent;
oneIndent = this._opts.oneIndent,
shouldIndentEmptyLines = (startLine === endLine);
// indents[i] represents i * oneIndent
var indents: string[] = ['', oneIndent];
let indents: string[] = ['', oneIndent];
// if indenting or outdenting on a whitespace only line
if (this._selection.isEmpty()) {
@ -71,15 +74,21 @@ export class ShiftCommand implements EditorCommon.ICommand {
}
}
for (lineNumber = startLine; lineNumber <= endLine; lineNumber++) {
var lineText = model.getLineContent(lineNumber);
var indentationEndIndex = Strings.firstNonWhitespaceIndex(lineText);
// keep track of previous line's "miss-alignment"
let previousLineExtraSpaces = 0, extraSpaces = 0;
for (lineNumber = startLine; lineNumber <= endLine; lineNumber++, previousLineExtraSpaces = extraSpaces) {
extraSpaces = 0;
let lineText = model.getLineContent(lineNumber);
let indentationEndIndex = Strings.firstNonWhitespaceIndex(lineText);
if (this._opts.isUnshift) {
if (lineText.length === 0 || indentationEndIndex === 0) {
// empty line or line with no leading whitespace => nothing to do
continue;
}
if (this._opts.isUnshift && (lineText.length === 0 || indentationEndIndex === 0)) {
// empty line or line with no leading whitespace => nothing to do
continue;
}
if (!shouldIndentEmptyLines && !this._opts.isUnshift && lineText.length === 0) {
// do not indent empty lines => nothing to do
continue;
}
if (indentationEndIndex === -1) {
@ -87,7 +96,45 @@ export class ShiftCommand implements EditorCommon.ICommand {
indentationEndIndex = lineText.length;
}
var desiredIndentCount: number;
if (lineNumber > 1) {
let contentStartVisibleColumn = CursorMoveHelper.visibleColumnFromColumn2(lineText, indentationEndIndex + 1, tabSize);
if (contentStartVisibleColumn % tabSize !== 0) {
// The current line is "miss-aligned", so let's see if this is expected...
// This can only happen when it has trailing commas in the indent
let enterAction = getRawEnterActionAtPosition(model, lineNumber - 1, model.getLineMaxColumn(lineNumber - 1));
if (enterAction) {
extraSpaces = previousLineExtraSpaces;
if (enterAction.appendText) {
for (let j = 0, lenJ = enterAction.appendText.length; j < lenJ && extraSpaces < tabSize; j++) {
if (enterAction.appendText.charCodeAt(j) === _SPACE) {
extraSpaces++;
} else {
break;
}
}
}
if (enterAction.removeText) {
extraSpaces = Math.max(0, extraSpaces - enterAction.removeText);
}
// Act as if `prefixSpaces` is not part of the indentation
for (let j = 0; j < extraSpaces; j++) {
if (indentationEndIndex === 0 || lineText.charCodeAt(indentationEndIndex - 1) !== _SPACE) {
break;
}
indentationEndIndex--;
}
}
}
}
if (this._opts.isUnshift && indentationEndIndex === 0) {
// line with no leading whitespace => nothing to do
continue;
}
let desiredIndentCount: number;
if (this._opts.isUnshift) {
desiredIndentCount = ShiftCommand.unshiftIndentCount(lineText, indentationEndIndex + 1, tabSize);
} else {
@ -95,7 +142,7 @@ export class ShiftCommand implements EditorCommon.ICommand {
}
// Fill `indents`, as needed
for (var j = indents.length; j <= desiredIndentCount; j++) {
for (let j = indents.length; j <= desiredIndentCount; j++) {
indents[j] = indents[j-1] + oneIndent;
}

View file

@ -505,7 +505,7 @@ export class CommonEditorConfiguration extends EventEmitter implements EditorCom
tabSizeIsAuto: false,
tabSize: 4,
insertSpacesIsAuto: false,
insertSpaces: false
insertSpaces: true
};
if (opts.tabSize === 'auto') {

View file

@ -168,6 +168,7 @@ registerCoreCommand(H.CursorDownSelect, {
mac: { primary: KeyMod.Shift | KeyCode.DownArrow },
linux: { primary: KeyMod.Shift | KeyCode.DownArrow }
});
registerCoreCommand(H.CursorPageUp, {
primary: KeyCode.PageUp
});
@ -196,6 +197,25 @@ registerCoreCommand(H.CursorEndSelect, {
primary: KeyMod.Shift | KeyCode.End,
mac: { primary: KeyMod.Shift | KeyCode.End, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.RightArrow] }
});
registerCoreCommand(H.ExpandLineSelection, {
primary: KeyMod.CtrlCmd | KeyCode.KEY_I
});
registerCoreCommand(H.ScrollLineUp, {
primary: KeyMod.CtrlCmd | KeyCode.UpArrow,
mac: { primary: KeyMod.WinCtrl | KeyCode.PageUp}
});
registerCoreCommand(H.ScrollLineDown, {
primary: KeyMod.CtrlCmd | KeyCode.DownArrow,
mac: { primary: KeyMod.WinCtrl | KeyCode.PageDown}
});
registerCoreCommand(H.ScrollPageUp, {
primary: KeyMod.CtrlCmd | KeyCode.PageUp
});
registerCoreCommand(H.ScrollPageDown, {
primary: KeyMod.CtrlCmd | KeyCode.PageDown
});
registerCoreCommand(H.Tab, {
primary: KeyCode.Tab

View file

@ -63,8 +63,8 @@ class ConfigClass implements IConfiguration {
referenceInfos: true,
renderWhitespace: false,
tabSize: 'auto',
insertSpaces: 'auto',
tabSize: 4,
insertSpaces: true,
fontFamily: '',
fontSize: 0,
lineHeight: 0

View file

@ -41,6 +41,7 @@ interface IMultipleCursorOperationContext {
isCursorUndo: boolean;
executeCommands: EditorCommon.ICommand[];
postOperationRunnables: IPostOperationRunnable[];
requestScrollDeltaLines: number;
}
interface IExecContext {
@ -85,7 +86,8 @@ export class Cursor extends EventEmitter {
super([
EditorCommon.EventType.CursorPositionChanged,
EditorCommon.EventType.CursorSelectionChanged,
EditorCommon.EventType.CursorRevealRange
EditorCommon.EventType.CursorRevealRange,
EditorCommon.EventType.CursorScrollRequest
]);
this.editorId = editorId;
this.configuration = configuration;
@ -306,7 +308,8 @@ export class Cursor extends EventEmitter {
isCursorUndo: false,
postOperationRunnables: [],
shouldPushStackElementBefore: false,
shouldPushStackElementAfter: false
shouldPushStackElementAfter: false,
requestScrollDeltaLines: 0
};
callback(currentHandlerCtx);
@ -336,6 +339,7 @@ export class Cursor extends EventEmitter {
var shouldRevealHorizontal: boolean;
var shouldRevealTarget: RevealTarget;
var isCursorUndo: boolean;
var requestScrollDeltaLines: number;
var hasExecutedCommands = this._createAndInterpretHandlerCtx(eventSource, e.getData(), (currentHandlerCtx:IMultipleCursorOperationContext) => {
handled = handler(currentHandlerCtx);
@ -346,6 +350,7 @@ export class Cursor extends EventEmitter {
shouldRevealVerticalInCenter = currentHandlerCtx.shouldRevealVerticalInCenter;
shouldRevealHorizontal = currentHandlerCtx.shouldRevealHorizontal;
isCursorUndo = currentHandlerCtx.isCursorUndo;
requestScrollDeltaLines = currentHandlerCtx.requestScrollDeltaLines;
});
if (hasExecutedCommands) {
@ -402,6 +407,10 @@ export class Cursor extends EventEmitter {
}
this.emitCursorSelectionChanged(eventSource, cursorPositionChangeReason);
}
if (requestScrollDeltaLines) {
this.emitCursorScrollRequest(requestScrollDeltaLines);
}
} catch (err) {
Errors.onUnexpectedError(err);
}
@ -845,6 +854,13 @@ export class Cursor extends EventEmitter {
this.emit(EditorCommon.EventType.CursorSelectionChanged, e);
}
private emitCursorScrollRequest(lineScrollOffset: number): void {
var e:EditorCommon.ICursorScrollRequestEvent = {
deltaLines: lineScrollOffset
};
this.emit(EditorCommon.EventType.CursorScrollRequest, e);
}
private emitCursorRevealRange(revealTarget: RevealTarget, verticalType: EditorCommon.VerticalRevealType, revealHorizontal: boolean): void {
var positions = this.cursors.getPositions();
var viewPositions = this.cursors.getViewPositions();
@ -958,6 +974,11 @@ export class Cursor extends EventEmitter {
handlersMap[H.Outdent] = (ctx:IMultipleCursorOperationContext) => this._outdent(ctx);
handlersMap[H.Paste] = (ctx:IMultipleCursorOperationContext) => this._paste(ctx);
handlersMap[H.ScrollLineUp] = (ctx:IMultipleCursorOperationContext) => this._scrollUp(false, ctx);
handlersMap[H.ScrollLineDown] = (ctx:IMultipleCursorOperationContext) => this._scrollDown(false, ctx);
handlersMap[H.ScrollPageUp] = (ctx:IMultipleCursorOperationContext) => this._scrollUp(true, ctx);
handlersMap[H.ScrollPageDown] = (ctx:IMultipleCursorOperationContext) => this._scrollDown(true, ctx);
handlersMap[H.DeleteLeft] = (ctx:IMultipleCursorOperationContext) => this._deleteLeft(ctx);
handlersMap[H.DeleteWordLeft] = (ctx:IMultipleCursorOperationContext) => this._deleteWordLeft(ctx);
handlersMap[H.DeleteRight] = (ctx:IMultipleCursorOperationContext) => this._deleteRight(ctx);
@ -966,6 +987,8 @@ export class Cursor extends EventEmitter {
handlersMap[H.DeleteAllRight] = (ctx:IMultipleCursorOperationContext) => this._deleteAllRight(ctx);
handlersMap[H.Cut] = (ctx:IMultipleCursorOperationContext) => this._cut(ctx);
handlersMap[H.ExpandLineSelection] = (ctx:IMultipleCursorOperationContext) => this._expandLineSelection(ctx);
handlersMap[H.Undo] = (ctx:IMultipleCursorOperationContext) => this._undo(ctx);
handlersMap[H.CursorUndo] = (ctx:IMultipleCursorOperationContext) => this._cursorUndo(ctx);
handlersMap[H.Redo] = (ctx:IMultipleCursorOperationContext) => this._redo(ctx);
@ -1002,7 +1025,8 @@ export class Cursor extends EventEmitter {
executeCommand: null,
postOperationRunnable: null,
shouldPushStackElementBefore: false,
shouldPushStackElementAfter: false
shouldPushStackElementAfter: false,
requestScrollDeltaLines: 0
};
result = callable(i, cursors[i], context) || result;
@ -1012,6 +1036,7 @@ export class Cursor extends EventEmitter {
ctx.shouldRevealHorizontal = context.shouldRevealHorizontal;
ctx.shouldReveal = context.shouldReveal;
ctx.shouldRevealVerticalInCenter = context.shouldRevealVerticalInCenter;
ctx.requestScrollDeltaLines = context.requestScrollDeltaLines;
}
ctx.shouldPushStackElementBefore = ctx.shouldPushStackElementBefore || context.shouldPushStackElementBefore;
@ -1187,6 +1212,10 @@ export class Cursor extends EventEmitter {
return true;
}
private _expandLineSelection(ctx: IMultipleCursorOperationContext): boolean {
return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => OneCursorOp.expandLineSelection(oneCursor, oneCtx));
}
private _lineInsertBefore(ctx: IMultipleCursorOperationContext): boolean {
return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => OneCursorOp.lineInsertBefore(oneCursor, oneCtx));
}
@ -1292,6 +1321,16 @@ export class Cursor extends EventEmitter {
}
}
private _scrollUp(isPaged: boolean, ctx: IMultipleCursorOperationContext): boolean {
ctx.requestScrollDeltaLines = isPaged ? -this.configuration.editor.pageSize : -1;
return true;
}
private _scrollDown(isPaged: boolean, ctx: IMultipleCursorOperationContext): boolean {
ctx.requestScrollDeltaLines = isPaged ? this.configuration.editor.pageSize : 1;
return true;
}
private _distributePasteToCursors(ctx: IMultipleCursorOperationContext): string[] {
if (ctx.eventData.pasteOnNewLine) {
return null;

View file

@ -15,6 +15,7 @@ import {IEnterAction,IndentAction,IElectricAction} from 'vs/editor/common/modes'
import {CursorMoveHelper, ICursorMoveHelperModel, IMoveResult} from 'vs/editor/common/controller/cursorMoveHelper';
import EditorCommon = require('vs/editor/common/editorCommon');
import Errors = require('vs/base/common/errors');
import {getEnterActionAtPosition} from 'vs/editor/common/modes/supports/onEnter';
export interface IPostOperationRunnable {
(ctx: IOneCursorOperationContext): void;
@ -29,6 +30,7 @@ export interface IOneCursorOperationContext {
shouldPushStackElementAfter: boolean;
executeCommand: EditorCommon.ICommand;
postOperationRunnable: IPostOperationRunnable;
requestScrollDeltaLines: number;
}
export interface IModeConfiguration {
@ -491,23 +493,25 @@ export class OneCursorOp {
// -------------------- START handlers that simply change cursor state
public static jumpToBracket(cursor:OneCursor, ctx: IOneCursorOperationContext): boolean {
var bracketDecorations = cursor.getBracketsDecorations();
var len = bracketDecorations.length;
let bracketDecorations = cursor.getBracketsDecorations();
if (len !== 2) {
if (bracketDecorations.length !== 2) {
return false;
}
var position = cursor.getPosition();
let firstBracket = cursor.model.getDecorationRange(bracketDecorations[0]);
let secondBracket = cursor.model.getDecorationRange(bracketDecorations[1]);
for (var i = 0; i < 2; i++) {
var range = cursor.model.getDecorationRange(bracketDecorations[i]);
var otherRange = cursor.model.getDecorationRange(bracketDecorations[1 - i]);
let position = cursor.getPosition();
if (Utils.isPositionAtRangeEdges(position, range) || Utils.isPositionInsideRange(position, range)) {
cursor.moveModelPosition(false, otherRange.startLineNumber, otherRange.startColumn, 0, false);
return true;
}
if (Utils.isPositionAtRangeEdges(position, firstBracket) || Utils.isPositionInsideRange(position, firstBracket)) {
cursor.moveModelPosition(false, secondBracket.endLineNumber, secondBracket.endColumn, 0, false);
return true;
}
if (Utils.isPositionAtRangeEdges(position, secondBracket) || Utils.isPositionInsideRange(position, secondBracket)) {
cursor.moveModelPosition(false, firstBracket.endLineNumber, firstBracket.endColumn, 0, false);
return true;
}
return false;
@ -737,6 +741,31 @@ export class OneCursorOp {
return true;
}
public static expandLineSelection(cursor:OneCursor, ctx: IOneCursorOperationContext): boolean {
ctx.cursorPositionChangeReason = 'explicit';
let viewSel = cursor.getViewSelection();
let viewStartLineNumber = viewSel.startLineNumber;
let viewStartColumn = viewSel.startColumn;
let viewEndLineNumber = viewSel.endLineNumber;
let viewEndColumn = viewSel.endColumn;
let viewEndMaxColumn = cursor.getViewLineMaxColumn(viewEndLineNumber);
if (viewStartColumn !== 1 || viewEndColumn !== viewEndMaxColumn) {
viewStartColumn = 1;
viewEndColumn = viewEndMaxColumn;
} else {
// Expand selection with one more line down
let moveResult = cursor.getViewPositionDown(viewEndLineNumber, viewEndColumn, 0, 1);
viewEndLineNumber = moveResult.lineNumber;
viewEndColumn = cursor.getViewLineMaxColumn(viewEndLineNumber);
}
cursor.moveViewPosition(false, viewStartLineNumber, viewStartColumn, 0, true);
cursor.moveViewPosition(true, viewEndLineNumber, viewEndColumn, 0, true);
return true;
}
public static moveToBeginningOfBuffer(cursor:OneCursor, inSelectionMode: boolean, ctx: IOneCursorOperationContext): boolean {
ctx.cursorPositionChangeReason = 'explicit';
cursor.moveModelPosition(inSelectionMode, 1, 1, 0, true);
@ -925,64 +954,6 @@ export class OneCursorOp {
return this._enter(cursor, true, ctx);
}
private static _getEnterActionAtPosition(model:EditorCommon.IModel, lineNumber:number, column:number): { enterAction: IEnterAction; indentation: string; } {
var lineText = model.getLineContent(lineNumber);
var lineContext = model.getLineContext(lineNumber);
var enterAction:IEnterAction;
if (model.getMode().onEnterSupport) {
try {
enterAction = model.getMode().onEnterSupport.onEnter(model, new Position(lineNumber, column));
} catch (e) {
Errors.onUnexpectedError(e);
}
}
if (!enterAction) {
if (model.getMode().electricCharacterSupport) {
try {
enterAction = model.getMode().electricCharacterSupport.onEnter(lineContext, column - 1);
} catch(e) {
Errors.onUnexpectedError(e);
}
}
} else {
// console.log('USING NEW INDENTATION LOGIC!');
}
var indentation = Strings.getLeadingWhitespace(lineText);
if (indentation.length > column - 1) {
indentation = indentation.substring(0, column - 1);
}
if (!enterAction) {
enterAction = {
indentAction: IndentAction.None,
appendText: '',
};
} else {
if(!enterAction.appendText) {
if (
(enterAction.indentAction === IndentAction.Indent) ||
(enterAction.indentAction === IndentAction.IndentOutdent)
) {
enterAction.appendText = '\t';
} else {
enterAction.appendText = '';
}
}
}
if (enterAction.removeText) {
indentation = indentation.substring(0, indentation.length - 1);
}
return {
enterAction: enterAction,
indentation: indentation
};
}
private static _enter(cursor:OneCursor, keepPosition: boolean, ctx: IOneCursorOperationContext, position?: EditorCommon.IEditorPosition, range?: EditorCommon.IEditorRange): boolean {
if (typeof position === 'undefined') {
position = cursor.getPosition();
@ -992,7 +963,7 @@ export class OneCursorOp {
}
ctx.shouldPushStackElementBefore = true;
var r = this._getEnterActionAtPosition(cursor.model, position.lineNumber, position.column);
var r = getEnterActionAtPosition(cursor.model, position.lineNumber, position.column);
var enterAction = r.enterAction;
var indentation = r.indentation;
@ -1283,7 +1254,7 @@ export class OneCursorOp {
return '\t';
}
var r = this._getEnterActionAtPosition(cursor.model, lastLineNumber, cursor.model.getLineMaxColumn(lastLineNumber));
var r = getEnterActionAtPosition(cursor.model, lastLineNumber, cursor.model.getLineMaxColumn(lastLineNumber));
var indentation: string;
if (r.enterAction.indentAction === IndentAction.Outdent) {

View file

@ -35,4 +35,13 @@ export class EditOperation {
forceMoveMarkers: false
};
}
public static replaceMove(range:EditorCommon.IEditorRange, text:string): EditorCommon.IIdentifiedSingleEditOperation {
return {
identifier: null,
range: range,
text: text,
forceMoveMarkers: true
};
}
}

View file

@ -490,12 +490,14 @@ export interface ICommonEditorOptions {
export interface IEditorOptions extends ICommonEditorOptions {
/**
* Tab size in spaces. This is used for rendering and for editing.
* Defaults to 'auto', meaning the model attached to the editor will be scanned and this property will be guessed.
* 'auto' means the model attached to the editor will be scanned and this property will be guessed.
* Defaults to 4.
*/
tabSize?:any;
/**
* Insert spaces instead of tabs when indenting or when auto-indenting.
* Defaults to 'auto', meaning the model attached to the editor will be scanned and this property will be guessed.
* 'auto' means the model attached to the editor will be scanned and this property will be guessed.
* Defaults to true.
*/
insertSpaces?:any;
/**
@ -2059,6 +2061,10 @@ export interface ICursorRevealRangeEvent {
revealHorizontal:boolean;
}
export interface ICursorScrollRequestEvent {
deltaLines: number;
}
export interface IModelChangedEvent {
oldModelUrl: string;
newModelUrl: string;
@ -2500,7 +2506,8 @@ export var ViewEventNames = {
CursorPositionChangedEvent: 'cursorPositionChangedEvent',
CursorSelectionChangedEvent: 'cursorSelectionChangedEvent',
RevealRangeEvent: 'revealRangeEvent',
LineMappingChangedEvent: 'lineMappingChangedEvent'
LineMappingChangedEvent: 'lineMappingChangedEvent',
ScrollRequestEvent: 'scrollRequestEvent'
};
export interface IScrollEvent {
@ -2597,6 +2604,10 @@ export interface IViewRevealRangeEvent {
revealHorizontal: boolean;
}
export interface IViewScrollRequestEvent {
deltaLines: number;
}
export interface IViewWhitespaceViewportData {
id:number;
afterLineNumber:number;
@ -3229,6 +3240,7 @@ export var EventType = {
CursorPositionChanged: 'positionChanged',
CursorSelectionChanged: 'selectionChanged',
CursorRevealRange: 'revealRange',
CursorScrollRequest: 'scrollRequest',
ViewFocusGained: 'focusGained',
ViewFocusLost: 'focusLost',
@ -3283,6 +3295,8 @@ export var Handler = {
CursorEnd: 'cursorEnd',
CursorEndSelect: 'cursorEndSelect',
ExpandLineSelection: 'expandLineSelection',
CursorTop: 'cursorTop',
CursorTopSelect: 'cursorTopSelect',
CursorBottom: 'cursorBottom',
@ -3334,5 +3348,11 @@ export var Handler = {
LineInsertAfter: 'lineInsertAfter',
LineBreakInsert: 'lineBreakInsert',
SelectAll: 'selectAll'
SelectAll: 'selectAll',
ScrollLineUp: 'scrollLineUp',
ScrollLineDown: 'scrollLineDown',
ScrollPageUp: 'scrollPageUp',
ScrollPageDown: 'scrollPageDown'
};

View file

@ -236,17 +236,20 @@ function triggerEditorActionGlobal(actionId: string, accessor: ServicesAccessor,
var defaultEditorActionKeybindingOptions:IEditorActionKeybindingOptions = { primary: null, context: ContextKey.EditorTextFocus };
function contextRule(needsTextFocus: boolean, needsKey: string): IKeybindingContextRule[]{
function contextRule(needsTextFocus: boolean, needsKey: string): IKeybindingContextRule[] {
let result: IKeybindingContextRule[] = [];
if (needsTextFocus) {
return [
{ key: EditorCommon.KEYBINDING_CONTEXT_EDITOR_TEXT_FOCUS },
{ key: needsKey }
];
result.push({ key: EditorCommon.KEYBINDING_CONTEXT_EDITOR_TEXT_FOCUS });
} else {
result.push({ key: EditorCommon.KEYBINDING_CONTEXT_EDITOR_FOCUS });
}
return [
{ key: EditorCommon.KEYBINDING_CONTEXT_EDITOR_FOCUS },
{ key: needsKey }
];
if (needsKey) {
result.push({ key: needsKey });
}
return result;
}
function createCommandHandler(commandId: string, handler: IEditorCommandHandler): ICommandHandler {

View file

@ -243,18 +243,28 @@ export class ModelLine {
return NO_OP_MARKERS_ADJUSTER;
}
this._markers.sort(ModelLine._compareMarkers);
var markers = this._markers;
var markersLength = markers.length;
var markersIndex = 0;
var marker = markers[markersIndex];
// var printMarker = (m:ILineMarker) => {
// if (m.stickToPreviousCharacter) {
// return '|' + m.column;
// }
// return m.column + '|';
// }
// var printMarkers = () => {
// return '[' + markers.map( m => m.column).join(', ') + ']';
// return '[' + markers.map(printMarker).join(', ') + ']';
// };
let adjust = (toColumn:number, delta:number, minimumAllowedColumn:number, isReplace:boolean, forceMoveMarkers:boolean) => {
// console.log('------------- INITIAL MARKERS: ' + printMarkers());
let adjust = (toColumn:number, delta:number, minimumAllowedColumn:number, forceStickToPrevious:boolean, forceMoveMarkers:boolean) => {
// console.log('------------------------------');
// console.log('adjust called: toColumn: ' + toColumn + ', delta: ' + delta + ', minimumAllowedColumn: ' + minimumAllowedColumn + ', isReplace: ' + isReplace + ', forceMoveMarkers:' + forceMoveMarkers);
// console.log('adjust called: toColumn: ' + toColumn + ', delta: ' + delta + ', minimumAllowedColumn: ' + minimumAllowedColumn + ', forceStickToPrevious: ' + forceStickToPrevious + ', forceMoveMarkers:' + forceMoveMarkers);
// console.log('BEFORE::: markersIndex: ' + markersIndex + ' : ' + printMarkers());
while (
markersIndex < markersLength
@ -263,7 +273,7 @@ export class ModelLine {
|| (
!forceMoveMarkers
&& marker.column === toColumn
&& (isReplace || marker.stickToPreviousCharacter)
&& (forceStickToPrevious || marker.stickToPreviousCharacter)
)
)
) {
@ -287,6 +297,8 @@ export class ModelLine {
let finish = (delta:number, lineTextLength:number) => {
adjust(Number.MAX_VALUE, delta, 1, false, false);
// console.log('------------- FINAL MARKERS: ' + printMarkers());
};
return {
@ -296,39 +308,46 @@ export class ModelLine {
}
public applyEdits(changedMarkers: IChangedMarkers, edits:ILineEdit[]): number {
// console.log('--> applyEdits: ' + JSON.stringify(edits));
var deltaColumn = 0;
var resultText = this.text;
let deltaColumn = 0;
let resultText = this.text;
var tokensAdjuster = this._createTokensAdjuster();
var markersAdjuster = this._createMarkersAdjuster(changedMarkers);
let tokensAdjuster = this._createTokensAdjuster();
let markersAdjuster = this._createMarkersAdjuster(changedMarkers);
for (var i = 0, len = edits.length; i < len; i++) {
let _oldStartColumn = edits[i].startColumn;
let _oldEndColumn = edits[i].endColumn;
// console.log('_oldStartColumn: ' + _oldStartColumn + ', _oldEndColumn: ' + _oldEndColumn);
let startColumn = deltaColumn + edits[i].startColumn;
let endColumn = deltaColumn + edits[i].endColumn;
let text = edits[i].text;
for (let i = 0, len = edits.length; i < len; i++) {
let edit = edits[i];
// console.log();
// console.log('=============================');
// console.log('EDIT #' + i + ' [ ' + edit.startColumn + ' -> ' + edit.endColumn + ' ] : <<<' + edit.text + '>>>, forceMoveMarkers: ' + edit.forceMoveMarkers);
// console.log('deltaColumn: ' + deltaColumn);
let startColumn = deltaColumn + edit.startColumn;
let endColumn = deltaColumn + edit.endColumn;
let deletingCnt = endColumn - startColumn;
let insertingCnt = edit.text.length;
// Adjust tokens & markers before this edit
tokensAdjuster.adjust(_oldStartColumn - 1, deltaColumn, 1);
markersAdjuster.adjust(_oldStartColumn - 1 + 1, deltaColumn, 1, startColumn !== endColumn, edits[i].forceMoveMarkers);
// console.log('Adjust tokens & markers before this edit');
tokensAdjuster.adjust(edit.startColumn - 1, deltaColumn, 1);
markersAdjuster.adjust(edit.startColumn, deltaColumn, 1, deletingCnt > 0, edit.forceMoveMarkers);
// Adjust tokens & markers for the common part of this edit
let commonLength = Math.min(endColumn - startColumn, text.length);
let commonLength = Math.min(deletingCnt, insertingCnt);
if (commonLength > 0) {
tokensAdjuster.adjust(_oldStartColumn - 1 + commonLength, deltaColumn, startColumn);
markersAdjuster.adjust(_oldStartColumn - 1 + 1 + commonLength, deltaColumn, startColumn, true, edits[i].forceMoveMarkers);
// console.log('Adjust tokens & markers for the common part of this edit');
tokensAdjuster.adjust(edit.startColumn - 1 + commonLength, deltaColumn, startColumn);
markersAdjuster.adjust(edit.startColumn + commonLength, deltaColumn, startColumn, deletingCnt > insertingCnt, edit.forceMoveMarkers);
}
// Perform the edit & update `deltaColumn`
resultText = resultText.substring(0, startColumn - 1) + text + resultText.substring(endColumn - 1);
deltaColumn += text.length - (endColumn - startColumn);
resultText = resultText.substring(0, startColumn - 1) + edit.text + resultText.substring(endColumn - 1);
deltaColumn += insertingCnt - deletingCnt;
// Adjust tokens & markers inside this edit
tokensAdjuster.adjust(_oldEndColumn, deltaColumn, startColumn);
markersAdjuster.adjust(_oldEndColumn + 1, deltaColumn, startColumn, false, edits[i].forceMoveMarkers);
// console.log('Adjust tokens & markers inside this edit');
tokensAdjuster.adjust(edit.endColumn, deltaColumn, startColumn);
markersAdjuster.adjust(edit.endColumn, deltaColumn, startColumn, false, edit.forceMoveMarkers);
}
// Wrap up tokens & markers; adjust remaining if needed
@ -453,8 +472,6 @@ export class ModelLine {
} else {
this._markers.push(marker);
}
this._markers.sort(ModelLine._compareMarkers);
}
public addMarkers(markers:ILineMarker[]): void {
@ -474,8 +491,6 @@ export class ModelLine {
} else {
this._markers = this._markers.concat(markers);
}
this._markers.sort(ModelLine._compareMarkers);
}
private static _compareMarkers(a:ILineMarker, b:ILineMarker): number {

View file

@ -486,11 +486,11 @@ export class TextModel extends OrderGuaranteeEventEmitter implements EditorCommo
linesIndentedWithSpaces += (absoluteSpaceCounts[i] || 0);
}
// Give preference to tabs over spaces (when evidence is the same)
// Give preference to spaces over tabs (when evidence is the same)
// or when there are not enough clues (too little indentation in the file)
if (linesIndentedWithTabs >= linesIndentedWithSpaces) {
return {
insertSpaces: false,
insertSpaces: true,
tabSize: defaultTabSize
};
}
@ -498,7 +498,7 @@ export class TextModel extends OrderGuaranteeEventEmitter implements EditorCommo
if (linesWithIndentationCount < 6 && linesIndentedWithTabs > 0) {
// Making a guess with 6 indented lines, of which tabs are used besides spaces is very difficult
return {
insertSpaces: false,
insertSpaces: true,
tabSize: defaultTabSize
};
}

View file

@ -388,20 +388,19 @@ export interface ISuggestion {
label: string;
codeSnippet: string;
type: string;
textEdit?: EditorCommon.ISingleEditOperation;
typeLabel?: string;
documentationLabel?: string;
filterText?: string;
sortText?: string;
noAutoAccept?: boolean;
overwriteBefore?: number;
overwriteAfter?: number;
}
export interface ISuggestResult {
currentWord: string;
suggestions:ISuggestion[];
incomplete?: boolean;
overwriteBefore?: number;
overwriteAfter?: number;
}
export interface ISuggestionFilter {
@ -409,7 +408,7 @@ export interface ISuggestionFilter {
(word: string, suggestion: ISuggestion): IMatch[];
}
export interface ISuggestionSorter {
export interface ISuggestionCompare {
(one: ISuggestion, other: ISuggestion): number;
}
@ -429,7 +428,7 @@ export interface ISuggestSupport {
getSuggestionDetails?:(resource:URI, position:EditorCommon.IPosition, suggestion:ISuggestion)=>TPromise<ISuggestion>;
getFilter():ISuggestionFilter;
getSorter?():ISuggestionSorter;
getSorter?():ISuggestionCompare;
getTriggerCharacters():string[];
shouldShowEmptySuggestionList():boolean;
shouldAutotriggerSuggest(context:ILineContext, offset:number, triggeredByCharacter:string):boolean;

View file

@ -153,9 +153,7 @@ export class AbstractModeWorker {
result.push(<Modes.ISuggestResult> {
currentWord: value.currentWord,
suggestions: value.suggestions.filter((element) => !!accept(values[i].currentWord, element)),
incomplete: value.incomplete,
overwriteBefore: value.overwriteBefore,
overwriteAfter: value.overwriteAfter
incomplete: value.incomplete
});
}
return result;

View file

@ -25,15 +25,11 @@ export var ContiguousSubString: ISuggestionFilter = wrapBaseFilter(Filters.match
// Combined Filters
export function or(first: ISuggestionFilter, second: ISuggestionFilter): ISuggestionFilter {
return (word: string, suggestion: ISuggestion): Filters.IMatch[] => {
return first(word, suggestion) || second(word, suggestion);
};
return (word, suggestion) => first(word, suggestion) || second(word, suggestion);
}
export function and(first: ISuggestionFilter, second: ISuggestionFilter): ISuggestionFilter {
return (word: string, suggestion: ISuggestion): Filters.IMatch[] => {
return first(word, suggestion) && second(word, suggestion);
};
return (word, suggestion) => first(word, suggestion) && second(word, suggestion);
}
export var DefaultFilter = or(or(Prefix, CamelCase), ContiguousSubString);

View file

@ -776,7 +776,7 @@ export class SuggestSupport extends AbstractSupport implements Modes.ISuggestSup
return DefaultFilter;
}
public getSorter(): Modes.ISuggestionSorter {
public getSorter(): Modes.ISuggestionCompare {
return (one, other) => {
if (this.sortByType.length > 0) {
var oneTypeIndex = this.sortByType.indexOf(one.type);

View file

@ -9,6 +9,7 @@ import {IEnterAction, IndentAction, IOnEnterSupport, ILineContext, IMode} from '
import EditorCommon = require('vs/editor/common/editorCommon');
import Errors = require('vs/base/common/errors');
import Strings = require('vs/base/common/strings');
import {Position} from 'vs/editor/common/core/position';
export interface IBracketPair {
open: string;
@ -179,3 +180,66 @@ export class OnEnterSupport implements IOnEnterSupport {
}
}
}
export function getRawEnterActionAtPosition(model:EditorCommon.ITokenizedModel, lineNumber:number, column:number): IEnterAction {
let enterAction:IEnterAction;
if (model.getMode().onEnterSupport) {
try {
enterAction = model.getMode().onEnterSupport.onEnter(model, new Position(lineNumber, column));
} catch (e) {
Errors.onUnexpectedError(e);
}
}
if (!enterAction) {
if (model.getMode().electricCharacterSupport) {
let lineContext = model.getLineContext(lineNumber);
try {
enterAction = model.getMode().electricCharacterSupport.onEnter(lineContext, column - 1);
} catch(e) {
Errors.onUnexpectedError(e);
}
}
} else {
// console.log('USING NEW INDENTATION LOGIC!');
}
return enterAction;
}
export function getEnterActionAtPosition(model:EditorCommon.ITokenizedModel, lineNumber:number, column:number): { enterAction: IEnterAction; indentation: string; } {
let lineText = model.getLineContent(lineNumber);
let indentation = Strings.getLeadingWhitespace(lineText);
if (indentation.length > column - 1) {
indentation = indentation.substring(0, column - 1);
}
let enterAction = getRawEnterActionAtPosition(model, lineNumber, column);
if (!enterAction) {
enterAction = {
indentAction: IndentAction.None,
appendText: '',
};
} else {
if(!enterAction.appendText) {
if (
(enterAction.indentAction === IndentAction.Indent) ||
(enterAction.indentAction === IndentAction.IndentOutdent)
) {
enterAction.appendText = '\t';
} else {
enterAction.appendText = '';
}
}
}
if (enterAction.removeText) {
indentation = indentation.substring(0, indentation.length - 1);
}
return {
enterAction: enterAction,
indentation: indentation
};
}

View file

@ -31,7 +31,7 @@ function _getSafeTokenizationSupport(mode: Modes.IMode): Modes.ITokenizationSupp
function _tokenizeToHtmlContent(text: string, tokenizationSupport: Modes.ITokenizationSupport): IHTMLContentElement {
var result: IHTMLContentElement = {
tagName: 'div',
style: 'white-space: pre',
style: 'white-space: pre-wrap',
children: []
};

View file

@ -12,7 +12,7 @@ import {TPromise} from 'vs/base/common/winjs.base';
import {IEventService} from 'vs/platform/event/common/event';
import {IEditorService} from 'vs/platform/editor/common/editor';
import {IRange, ISelection, IEditorSelection, IModel, IIdentifiedSingleEditOperation} from 'vs/editor/common/editorCommon';
import {ICodeEditor} from 'vs/editor/browser/editorBrowser';
import {ICommonCodeEditor} from 'vs/editor/common/editorCommon';
import {Range} from 'vs/editor/common/core/range';
import {Selection} from 'vs/editor/common/core/selection';
import {IFileChange, EventType as FileEventType, FileChangesEvent} from 'vs/platform/files/common/files';
@ -243,13 +243,13 @@ export interface BulkEdit {
finish(): TPromise<ISelection>;
}
export function bulkEdit(eventService:IEventService, editorService:IEditorService, editor:ICodeEditor, edits:IResourceEdit[]):TPromise<any> {
export function bulkEdit(eventService:IEventService, editorService:IEditorService, editor:ICommonCodeEditor, edits:IResourceEdit[]):TPromise<any> {
let bulk = createBulkEdit(eventService, editorService, editor);
bulk.add(edits);
return bulk.finish();
}
export function createBulkEdit(eventService: IEventService, editorService: IEditorService, editor: ICodeEditor): BulkEdit {
export function createBulkEdit(eventService: IEventService, editorService: IEditorService, editor: ICommonCodeEditor): BulkEdit {
let all: IResourceEdit[] = [];
let recording = new ChangeRecorder(eventService).start();

View file

@ -153,6 +153,10 @@ class ModelMarkerHandler {
htmlMessage = [marker.message];
}
if (marker.source) {
htmlMessage.unshift({ isText: true, text: `[${marker.source}] ` });
}
return {
stickiness: EditorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
className,

View file

@ -47,6 +47,9 @@ export class ViewEventHandler {
public onCursorRevealRange(e:EditorCommon.IViewRevealRangeEvent): boolean {
return false;
}
public onCursorScrollRequest(e:EditorCommon.IViewScrollRequestEvent): boolean {
return false;
}
public onConfigurationChanged(e:EditorCommon.IConfigurationChangedEvent): boolean {
return false;
}
@ -123,6 +126,10 @@ export class ViewEventHandler {
this.shouldRender = this.onCursorRevealRange(<EditorCommon.IViewRevealRangeEvent>data) || this.shouldRender;
break;
case EditorCommon.ViewEventNames.ScrollRequestEvent:
this.shouldRender = this.onCursorScrollRequest(<EditorCommon.IViewScrollRequestEvent>data) || this.shouldRender;
break;
case EditorCommon.EventType.ConfigurationChanged:
this.shouldRender = this.onConfigurationChanged(<EditorCommon.IConfigurationChangedEvent>data) || this.shouldRender;
break;

View file

@ -235,6 +235,10 @@ export class ViewModel extends EventEmitter implements EditorCommon.IViewModel {
this.onCursorRevealRange(<EditorCommon.ICursorRevealRangeEvent>data);
break;
case EditorCommon.EventType.CursorScrollRequest:
this.onCursorScrollRequest(<EditorCommon.ICursorScrollRequestEvent>data);
break;
case EditorCommon.EventType.ConfigurationChanged:
revealPreviousCenteredModelRange = this._onTabSizeChange(this.configuration.getIndentationOptions().tabSize) || revealPreviousCenteredModelRange;
revealPreviousCenteredModelRange = this._onWrappingIndentChange(this.configuration.editor.wrappingIndent) || revealPreviousCenteredModelRange;
@ -339,6 +343,9 @@ export class ViewModel extends EventEmitter implements EditorCommon.IViewModel {
private onCursorRevealRange(e:EditorCommon.ICursorRevealRangeEvent): void {
this.cursors.onCursorRevealRange(e, (eventType:string, payload:any) => this.emit(eventType, payload));
}
private onCursorScrollRequest(e:EditorCommon.ICursorScrollRequestEvent): void {
this.cursors.onCursorScrollRequest(e, (eventType:string, payload:any) => this.emit(eventType, payload));
}
// --- end inbound event conversion
public getLineCount(): number {

View file

@ -105,6 +105,13 @@ export class ViewModelCursors {
emit(EditorCommon.ViewEventNames.RevealRangeEvent, newEvent);
}
public onCursorScrollRequest(e:EditorCommon.ICursorScrollRequestEvent, emit:(eventType:string, payload:any)=>void): void {
var newEvent:EditorCommon.IViewScrollRequestEvent = {
deltaLines: e.deltaLines
};
emit(EditorCommon.ViewEventNames.ScrollRequestEvent, newEvent);
}
public onLineMappingChanged(emit:(eventType:string, payload:any)=>void): void {
if (this.lastCursorPositionChangedEvent) {
this.onCursorPositionChanged(this.lastCursorPositionChangedEvent, emit);

View file

@ -73,6 +73,10 @@ class WorkerPluginService extends AbstractPluginService {
}
}
public deactivate(pluginId:string): void {
// nothing to do
}
}
export class EditorWorkerServer {

Some files were not shown because too many files have changed in this diff Show more