added notes on how to easily interact with usb via terminal

This commit is contained in:
tomit4 2021-12-11 10:36:17 -08:00
parent a28b03afaf
commit 02a76cf9af
19406 changed files with 28 additions and 6211125 deletions

View file

@ -1,3 +0,0 @@
prettier.formatFile
snippets.editSnippets
eslint.showOutputChannel

View file

@ -1 +0,0 @@
{}

View file

@ -1,219 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--- LLVM Exceptions to the Apache 2.0 License ----
As an exception, if, as a result of your compiling your source code, portions
of this Software are embedded into an Object form of such source code, you
may redistribute such embedded portions in such Object form without complying
with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
In addition, if you combine or link compiled forms of this Software with
software that is licensed under the GPLv2 ("Combined Software") and if a
court of competent jurisdiction determines that the patent provision (Section
3), the indemnity provision (Section 9) or other Section of the License
conflicts with the conditions of the GPLv2, you may retroactively and
prospectively choose to deem waived or otherwise exclude such Section(s) of
the License, but only in their entirety and only with respect to the Combined
Software.

View file

@ -1,72 +0,0 @@
# coc-clangd
This extension connects [coc.nvim][] to the [clangd][] language server.
## Quick Start
1. install [Node.js][]. `coc.nvim` and `coc-clangd` run on Node.js.
1. install `coc.nvim`. Instructions using `vim-plug` (check out [coc.nvim Wiki][] other options):
- add to `.vimrc`: `vim Plug 'neoclide/coc.nvim', {'branch': 'release'}`
- in vim, run `:PlugInstall`
1. in vim, run `:CocInstall coc-clangd`
1. `coc-clangd` will try to find `clangd` from your `$PATH`, if not found, you can run `:CocCommand clangd.install` to install the [latest release][] from GitHub
1. follow [Project setup][] to generate `compile_commands.json` for your project
> **Note**: If you've configured `clangd` as a languageServer in `coc-settings.json`, you should remove it to avoid running clangd twice!
## Protocol extensions
`clangd` supports some [extensions][] that are not in the official [Language Server Protocol specification][lsp].
`coc-clangd` adds support for:
- Switching between header and implementation file: `:CocCommand clangd.switchSourceHeader`
- You can open in split buffer by `:CocCommand clangd.switchSourceHeader vsplit`
- File status monitor, shows on NeoVim statusline
- Describe symbol under the cursor: `:CocCommand clangd.symbolInfo`
- Completions that adjust text near the cursor (e.g. correcting `.` to `->`)
## Configurations
`:CocConfig` opens your global `coc-settings.json`, or `:CocLocalConfig` opens local configuration in your project `.vim/coc-settings.json`.
| Configurations | Description | Default |
| -- | -- | -- |
| clangd.enabled | enable `coc-clangd` | `true` |
| clangd.arguments | arguments for `clangd` server | `[]` |
| clangd.checkUpdates | check for clangd language server updates on startup | `false` |
| clangd.disableCompletion | disable completion source from clangd | `false` |
| clangd.disableDiagnostics | disable diagnostics from clangd | `false` |
| clangd.disableSnippetCompletion | disable completion snippet from clangd | `false` |
| clangd.compilationDatabasePath | specifies the directory containing the compilation database | `''` |
| clangd.fallbackFlags | extra clang flags used to parse files when no compilation database is found | `[]` |
| clangd.path | path to `clangd` executable | `clangd` |
| clangd.semanticHighlighting | enable semantic highlighting, requires [jackguo380/vim-lsp-cxx-highlight](https://github.com/jackguo380/vim-lsp-cxx-highlight) to work | `false` |
| clangd.serverCompletionRanking | always rank compilation items on the server as you type | `true` |
## Commands
- `clangd.switchSourceHeader`: switch between source/header files
- `clangd.symbolInfo`: resolve symbol info under the cursor
- `clangd.memoryUsage`: show memory usage
- `clangd.install`: install latest clangd release from GitHub
- `clangd.update`: check for updates to clangd from GitHub
## License
Apache 2.0 with LLVM Exception
This is the [standard LLVM license](https://llvm.org/foundation/relicensing/).
---
> This extension is built with [create-coc-extension](https://github.com/fannheyward/create-coc-extension)
[node.js]: https://nodejs.org/en/
[clangd]: https://clangd.llvm.org/installation.html
[coc.nvim]: https://github.com/neoclide/coc.nvim
[coc.nvim wiki]: https://github.com/neoclide/coc.nvim/wiki/Install-coc.nvim
[lsp]: https://microsoft.github.io/language-server-protocol/specification
[extensions]: https://clangd.llvm.org/extensions.html
[latest release]: https://github.com/clangd/clangd/releases
[project setup]: https://clangd.llvm.org/installation.html#project-setup

File diff suppressed because it is too large Load diff

View file

@ -1,187 +0,0 @@
{
"name": "coc-clangd",
"version": "0.16.0",
"description": "clangd extension for coc.nvim",
"author": "Heyward Fann <fannheyward@gmail.com>",
"license": "Apache-2.0 WITH LLVM-exception",
"main": "lib/index.js",
"keywords": [
"coc.nvim"
],
"engines": {
"coc": "^0.0.80"
},
"repository": {
"type": "git",
"url": "https://github.com/clangd/coc-clangd.git"
},
"scripts": {
"clean": "rimraf lib",
"build": "node esbuild.js",
"watch": "node esbuild.js --watch",
"lint": "eslint src --ext ts",
"prepare": "node esbuild.js"
},
"devDependencies": {
"@clangd/install": "^0.1.4",
"@types/node": "12.12.0",
"@types/which": "^2.0.0",
"@typescript-eslint/eslint-plugin": "^4.31.2",
"@typescript-eslint/parser": "^4.31.2",
"coc.nvim": "^0.0.81-next.5",
"esbuild": "^0.13.2",
"eslint": "^7.11.0",
"rimraf": "^3.0.1",
"typescript": "^4.2.3",
"vscode-languageserver-protocol": "^3.15.3"
},
"activationEvents": [
"onLanguage:c",
"onLanguage:cpp",
"onLanguage:cuda",
"onLanguage:objc",
"onLanguage:objcpp",
"onLanguage:opencl",
"onLanguage:objective-c",
"onLanguage:objective-cpp",
"workspaceContains:**/compile_commands.json",
"workspaceContains:**/compile_flags.txt"
],
"rootPatterns": [
{
"patterns": [
"compile_commands.json",
"compile_flags.txt"
]
}
],
"contributes": {
"configuration": {
"type": "object",
"title": "coc-clangd configuration",
"properties": {
"clangd.enabled": {
"type": "boolean",
"default": true,
"description": "Enable coc-clangd extension"
},
"clangd.disableDiagnostics": {
"type": "boolean",
"default": false,
"description": "Disable diagnostics from clangd"
},
"clangd.disableCompletion": {
"type": "boolean",
"default": false,
"description": "Disable completion source from clangd"
},
"clangd.disableSnippetCompletion": {
"type": "boolean",
"default": false,
"description": "Disable completion snippet from clangd"
},
"clangd.compilationDatabasePath": {
"type": "string",
"default": "",
"description": "Specifies the directory containing the compilation database"
},
"clangd.path": {
"type": "string",
"default": "clangd",
"description": "The path to clangd executable, e.g.: /usr/bin/clangd"
},
"clangd.arguments": {
"type": "array",
"default": [],
"items": {
"type": "string"
},
"description": "Arguments for clangd server"
},
"clangd.trace.file": {
"type": "string",
"default": "",
"description": "Names a file that clangd should log a performance trace to, in chrome trace-viewer JSON format."
},
"clangd.trace.server": {
"type": "string",
"enum": [
"off",
"messages",
"verbose"
],
"default": "off",
"description": "Trace requests to clangd"
},
"clangd.fallbackFlags": {
"type": "array",
"items": {
"type": "string"
},
"default": [],
"description": "Extra clang flags used to parse files when no compilation database is found."
},
"clangd.semanticHighlighting": {
"type": "boolean",
"default": false,
"description": "Enable semantic highlighting in clangd, requires jackguo380/vim-lsp-cxx-highlight to work"
},
"clangd.showDBChangedNotification": {
"type": "boolean",
"default": true,
"description": "Show notifications while DB files changed"
},
"clangd.serverCompletionRanking": {
"type": "boolean",
"default": true,
"description": "Always rank completion items on the server as you type. This produces more accurate results at the cost of higher latency than client-side filtering."
},
"clangd.checkUpdates": {
"type": "boolean",
"default": false,
"description": "Check for clangd language server updates on startup."
},
"suggest.detailMaxLength": {
"type": "number",
"description": "Max length of detail that should be shown in popup menu.",
"default": 50
},
"diagnostic.format": {
"type": "string",
"description": "Define the diagnostic format. Available parts: source, code, severity, message",
"default": "%message\n[%source:%code]"
}
}
},
"commands": [
{
"command": "clangd.switchSourceHeader",
"title": "Switch between source/header"
},
{
"command": "clangd.symbolInfo",
"title": "Resolve symbol info under the cursor"
},
{
"command": "clangd.memoryUsage",
"title": "Show memory usage"
},
{
"command": "clangd.projectConfig",
"title": "Open project configuration file"
},
{
"command": "clangd.userConfig",
"title": "Open user configuration file"
},
{
"command": "clangd.install",
"title": "Install latest clangd language server binary release"
},
{
"command": "clangd.update",
"title": "Check for updates to clangd language server"
}
]
}
}

View file

@ -1,549 +0,0 @@
# coc-css
Css language server extension for [coc.nvim](https://github.com/neoclide/coc.nvim).
Uses [vscode-css-languageservice](https://github.com/Microsoft/vscode-css-languageservice) inside.
## Install
In your vim/neovim, run the command:
```
:CocInstall coc-css
```
## Features
Coc has support for all features that [vscode-css-languageservice](https://www.npmjs.com/package/vscode-css-languageservice) has.
- `doValidation` analyzes an input string and returns syntax and lint errros.
- `doComplete` provides completion proposals for a given location.
- `doHover` provides a hover text for a given location.
- `findDefinition` finds the definition of the symbol at the given location.
- `findReferences` finds all references to the symbol at the given location.
- `findDocumentHighlights` finds all symbols connected to the given location.
- `findDocumentSymbols` provides all symbols in the given document
- `doCodeActions` evaluates code actions for the given location, typically to fix a problem.
- `findColorSymbols` evaluates all color symbols in the given document
- `doRename` renames all symbols connected to the given location.
- `getFoldingRanges` returns folding ranges in the given document.
## Configuration options
- **css.enable**:
default: `true`
- **css.trace.server**:
default: `"off"`
Valid options: ["off","messages","verbose"]
- **css.customData**:
default: `[]`
- **css.completion.triggerPropertyValueCompletion**:
By default, coc.nvim triggers property value completion after selecting a CSS property. Use this setting to disable this behavior., default: `true`
- **css.completion.completePropertyWithSemicolon**:
Insert semicolon at end of line when completing CSS properties, default: `true`
- **css.validate**:
default: `true`
- **css.colorDecorators.enable**:
default: `true`
- **css.lint.compatibleVendorPrefixes**:
When using a vendor-specific prefix make sure to also include all other vendor-specific properties, default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **css.lint.vendorPrefix**:
When using a vendor-specific prefix also include the standard property, default: `"warning"`
Valid options: ["ignore","warning","error"]
- **css.lint.duplicateProperties**:
Do not use duplicate style definitions, default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **css.lint.emptyRules**:
Do not use empty rulesets, default: `"warning"`
Valid options: ["ignore","warning","error"]
- **css.lint.importStatement**:
Avoid using !important. It is an indication that the specificity of the entire CSS has gotten out of control and needs to be refactored., default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **css.lint.boxModel**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **css.lint.universalSelector**:
The universal selector (*) is known to be slow, default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **css.lint.zeroUnits**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **css.lint.fontFaceProperties**:
@font-face rule must define 'src' and 'font-family' properties, default: `"warning"`
Valid options: ["ignore","warning","error"]
- **css.lint.hexColorLength**:
Hex colors must consist of three or six hex numbers, default: `"error"`
Valid options: ["ignore","warning","error"]
- **css.lint.argumentsInColorFunction**:
Invalid number of parameters, default: `"error"`
Valid options: ["ignore","warning","error"]
- **css.lint.unknownProperties**:
Unknown property., default: `"warning"`
Valid options: ["ignore","warning","error"]
- **css.lint.ieHack**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **css.lint.unknownVendorSpecificProperties**:
Unknown vendor specific property., default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **css.lint.propertyIgnoredDueToDisplay**:
Property is ignored due to the display. E.g. with 'display: inline', the width, height, margin-top, margin-bottom, and float properties have no effect, default: `"warning"`
Valid options: ["ignore","warning","error"]
- **css.lint.important**:
Import statements do not load in parallel, default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **css.lint.float**:
Avoid using 'float'. Floats lead to fragile CSS that is easy to break if one aspect of the layout changes., default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **css.lint.idSelector**:
Selectors should not contain IDs because these rules are too tightly coupled with the HTML., default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **css.lint.unknownAtRules**:
Unknown at-rule., default: `"warning"`
Valid options: ["ignore","warning","error"]
- **less.completion.triggerPropertyValueCompletion**:
By default, coc.nvim triggers property value completion after selecting a CSS property. Use this setting to disable this behavior., default: `true`
- **less.completion.completePropertyWithSemicolon**:
Insert semicolon at end of line when completing CSS properties, default: `true`
- **less.validate**:
default: `true`
- **less.colorDecorators.enable**:
default: `true`
- **less.lint.compatibleVendorPrefixes**:
When using a vendor-specific prefix make sure to also include all other vendor-specific properties, default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **less.lint.vendorPrefix**:
When using a vendor-specific prefix also include the standard property, default: `"warning"`
Valid options: ["ignore","warning","error"]
- **less.lint.duplicateProperties**:
Do not use duplicate style definitions, default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **less.lint.emptyRules**:
Do not use empty rulesets, default: `"warning"`
Valid options: ["ignore","warning","error"]
- **less.lint.importStatement**:
Avoid using !important. It is an indication that the specificity of the entire CSS has gotten out of control and needs to be refactored., default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **less.lint.boxModel**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **less.lint.universalSelector**:
The universal selector (*) is known to be slow, default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **less.lint.zeroUnits**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **less.lint.fontFaceProperties**:
@font-face rule must define 'src' and 'font-family' properties, default: `"warning"`
Valid options: ["ignore","warning","error"]
- **less.lint.hexColorLength**:
Hex colors must consist of three or six hex numbers, default: `"error"`
Valid options: ["ignore","warning","error"]
- **less.lint.argumentsInColorFunction**:
Invalid number of parameters, default: `"error"`
Valid options: ["ignore","warning","error"]
- **less.lint.unknownProperties**:
Unknown property., default: `"warning"`
Valid options: ["ignore","warning","error"]
- **less.lint.ieHack**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **less.lint.unknownVendorSpecificProperties**:
Unknown vendor specific property., default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **less.lint.propertyIgnoredDueToDisplay**:
Property is ignored due to the display. E.g. with 'display: inline', the width, height, margin-top, margin-bottom, and float properties have no effect, default: `"warning"`
Valid options: ["ignore","warning","error"]
- **less.lint.important**:
Import statements do not load in parallel, default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **less.lint.float**:
Avoid using 'float'. Floats lead to fragile CSS that is easy to break if one aspect of the layout changes., default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **less.lint.idSelector**:
Selectors should not contain IDs because these rules are too tightly coupled with the HTML., default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **less.lint.unknownAtRules**:
Unknown at-rule., default: `"warning"`
Valid options: ["ignore","warning","error"]
- **scss.completion.triggerPropertyValueCompletion**:
By default, coc.nvim triggers property value completion after selecting a CSS property. Use this setting to disable this behavior., default: `true`
- **scss.completion.completePropertyWithSemicolon**:
Insert semicolon at end of line when completing CSS properties, default: `true`
- **scss.validate**:
default: `true`
- **scss.colorDecorators.enable**:
default: `true`
- **scss.lint.compatibleVendorPrefixes**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **scss.lint.vendorPrefix**:
default: `"warning"`
Valid options: ["ignore","warning","error"]
- **scss.lint.duplicateProperties**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **scss.lint.emptyRules**:
default: `"warning"`
Valid options: ["ignore","warning","error"]
- **scss.lint.importStatement**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **scss.lint.boxModel**:
Do not use width or height when using padding or border, default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **scss.lint.universalSelector**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **scss.lint.zeroUnits**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **scss.lint.fontFaceProperties**:
default: `"warning"`
Valid options: ["ignore","warning","error"]
- **scss.lint.hexColorLength**:
default: `"error"`
Valid options: ["ignore","warning","error"]
- **scss.lint.argumentsInColorFunction**:
default: `"error"`
Valid options: ["ignore","warning","error"]
- **scss.lint.unknownProperties**:
default: `"warning"`
Valid options: ["ignore","warning","error"]
- **scss.lint.ieHack**:
IE hacks are only necessary when supporting IE7 and older, default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **scss.lint.unknownVendorSpecificProperties**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **scss.lint.propertyIgnoredDueToDisplay**:
default: `"warning"`
Valid options: ["ignore","warning","error"]
- **scss.lint.important**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **scss.lint.float**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **scss.lint.idSelector**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **wxss.validate**:
default: `true`
- **wxss.colorDecorators.enable**:
default: `true`
- **wxss.lint.compatibleVendorPrefixes**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **wxss.lint.vendorPrefix**:
default: `"warning"`
Valid options: ["ignore","warning","error"]
- **wxss.lint.duplicateProperties**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **wxss.lint.emptyRules**:
default: `"warning"`
Valid options: ["ignore","warning","error"]
- **wxss.lint.importStatement**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **wxss.lint.boxModel**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **wxss.lint.universalSelector**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **wxss.lint.zeroUnits**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **wxss.lint.fontFaceProperties**:
default: `"warning"`
Valid options: ["ignore","warning","error"]
- **wxss.lint.hexColorLength**:
default: `"error"`
Valid options: ["ignore","warning","error"]
- **wxss.lint.argumentsInColorFunction**:
default: `"error"`
Valid options: ["ignore","warning","error"]
- **wxss.lint.unknownProperties**:
default: `"warning"`
Valid options: ["ignore","warning","error"]
- **wxss.lint.ieHack**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **wxss.lint.unknownVendorSpecificProperties**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **wxss.lint.propertyIgnoredDueToDisplay**:
default: `"warning"`
Valid options: ["ignore","warning","error"]
- **wxss.lint.important**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **wxss.lint.float**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
- **wxss.lint.idSelector**:
default: `"ignore"`
Valid options: ["ignore","warning","error"]
## License
MIT

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,921 +0,0 @@
{
"name": "coc-css",
"version": "1.2.6",
"description": "Css extension for coc",
"main": "lib/index.js",
"publisher": "chemzqm",
"engines": {
"coc": "^0.0.78"
},
"keywords": [
"coc.nvim",
"languageserver"
],
"scripts": {
"clean": "rimraf lib",
"build": "webpack",
"prepare": "npx npm-run-all clean build"
},
"activationEvents": [
"onLanguage:css",
"onLanguage:less",
"onLanguage:scss",
"onLanguage:wxss"
],
"contributes": {
"configuration": {
"type": "object",
"title": "Css",
"properties": {
"css.enable": {
"type": "boolean",
"default": true
},
"css.trace.server": {
"type": "string",
"default": "off",
"enum": [
"off",
"messages",
"verbose"
]
},
"css.customData": {
"type": "array",
"markdownDescription": "A list of relative file paths pointing to JSON files following the [custom data format](https://github.com/Microsoft/vscode-css-languageservice/blob/master/docs/customData.md).\n\ncoc.nvim loads custom data on startup to enhance its CSS support for the custom CSS properties, at directives, pseudo classes and pseudo elements you specify in the JSON files.\n\nThe file paths are relative to workspace and only workspace folder settings are considered.",
"default": [],
"items": {
"type": "string"
},
"scope": "resource"
},
"css.completion.triggerPropertyValueCompletion": {
"type": "boolean",
"scope": "resource",
"default": true,
"description": "By default, coc.nvim triggers property value completion after selecting a CSS property. Use this setting to disable this behavior."
},
"css.completion.completePropertyWithSemicolon": {
"type": "boolean",
"scope": "resource",
"default": true,
"description": "Insert semicolon at end of line when completing CSS properties"
},
"css.validate": {
"type": "boolean",
"scope": "resource",
"default": true
},
"css.colorDecorators.enable": {
"type": "boolean",
"scope": "window",
"default": true
},
"css.lint.compatibleVendorPrefixes": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore",
"description": "When using a vendor-specific prefix make sure to also include all other vendor-specific properties"
},
"css.lint.vendorPrefix": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning",
"description": "When using a vendor-specific prefix also include the standard property"
},
"css.lint.duplicateProperties": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore",
"description": "Do not use duplicate style definitions"
},
"css.lint.emptyRules": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning",
"description": "Do not use empty rulesets"
},
"css.lint.importStatement": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore",
"description": "Avoid using !important. It is an indication that the specificity of the entire CSS has gotten out of control and needs to be refactored."
},
"css.lint.boxModel": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"css.lint.universalSelector": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore",
"description": "The universal selector (*) is known to be slow"
},
"css.lint.zeroUnits": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"css.lint.fontFaceProperties": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning",
"description": "@font-face rule must define 'src' and 'font-family' properties"
},
"css.lint.hexColorLength": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "error",
"description": "Hex colors must consist of three or six hex numbers"
},
"css.lint.argumentsInColorFunction": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "error",
"description": "Invalid number of parameters"
},
"css.lint.unknownProperties": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning",
"description": "Unknown property."
},
"css.lint.ieHack": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"css.lint.unknownVendorSpecificProperties": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore",
"description": "Unknown vendor specific property."
},
"css.lint.propertyIgnoredDueToDisplay": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning",
"description": "Property is ignored due to the display. E.g. with 'display: inline', the width, height, margin-top, margin-bottom, and float properties have no effect"
},
"css.lint.important": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore",
"description": "Import statements do not load in parallel"
},
"css.lint.float": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore",
"description": "Avoid using 'float'. Floats lead to fragile CSS that is easy to break if one aspect of the layout changes."
},
"css.lint.idSelector": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore",
"description": "Selectors should not contain IDs because these rules are too tightly coupled with the HTML."
},
"css.lint.unknownAtRules": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning",
"description": "Unknown at-rule."
},
"less.completion.triggerPropertyValueCompletion": {
"type": "boolean",
"scope": "resource",
"default": true,
"description": "By default, coc.nvim triggers property value completion after selecting a CSS property. Use this setting to disable this behavior."
},
"less.completion.completePropertyWithSemicolon": {
"type": "boolean",
"scope": "resource",
"default": true,
"description": "Insert semicolon at end of line when completing CSS properties"
},
"less.validate": {
"type": "boolean",
"scope": "resource",
"default": true
},
"less.colorDecorators.enable": {
"type": "boolean",
"scope": "window",
"default": true
},
"less.lint.compatibleVendorPrefixes": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore",
"description": "When using a vendor-specific prefix make sure to also include all other vendor-specific properties"
},
"less.lint.vendorPrefix": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning",
"description": "When using a vendor-specific prefix also include the standard property"
},
"less.lint.duplicateProperties": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore",
"description": "Do not use duplicate style definitions"
},
"less.lint.emptyRules": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning",
"description": "Do not use empty rulesets"
},
"less.lint.importStatement": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore",
"description": "Avoid using !important. It is an indication that the specificity of the entire CSS has gotten out of control and needs to be refactored."
},
"less.lint.boxModel": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"less.lint.universalSelector": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore",
"description": "The universal selector (*) is known to be slow"
},
"less.lint.zeroUnits": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"less.lint.fontFaceProperties": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning",
"description": "@font-face rule must define 'src' and 'font-family' properties"
},
"less.lint.hexColorLength": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "error",
"description": "Hex colors must consist of three or six hex numbers"
},
"less.lint.argumentsInColorFunction": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "error",
"description": "Invalid number of parameters"
},
"less.lint.unknownProperties": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning",
"description": "Unknown property."
},
"less.lint.ieHack": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"less.lint.unknownVendorSpecificProperties": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore",
"description": "Unknown vendor specific property."
},
"less.lint.propertyIgnoredDueToDisplay": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning",
"description": "Property is ignored due to the display. E.g. with 'display: inline', the width, height, margin-top, margin-bottom, and float properties have no effect"
},
"less.lint.important": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore",
"description": "Import statements do not load in parallel"
},
"less.lint.float": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore",
"description": "Avoid using 'float'. Floats lead to fragile CSS that is easy to break if one aspect of the layout changes."
},
"less.lint.idSelector": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore",
"description": "Selectors should not contain IDs because these rules are too tightly coupled with the HTML."
},
"less.lint.unknownAtRules": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning",
"description": "Unknown at-rule."
},
"scss.completion.triggerPropertyValueCompletion": {
"type": "boolean",
"scope": "resource",
"default": true,
"description": "By default, coc.nvim triggers property value completion after selecting a CSS property. Use this setting to disable this behavior."
},
"scss.completion.completePropertyWithSemicolon": {
"type": "boolean",
"scope": "resource",
"default": true,
"description": "Insert semicolon at end of line when completing CSS properties"
},
"scss.validate": {
"type": "boolean",
"scope": "resource",
"default": true
},
"scss.colorDecorators.enable": {
"type": "boolean",
"scope": "window",
"default": true
},
"scss.lint.compatibleVendorPrefixes": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"scss.lint.vendorPrefix": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning"
},
"scss.lint.duplicateProperties": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"scss.lint.emptyRules": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning"
},
"scss.lint.importStatement": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"scss.lint.boxModel": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore",
"description": "Do not use width or height when using padding or border"
},
"scss.lint.universalSelector": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"scss.lint.zeroUnits": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"scss.lint.fontFaceProperties": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning"
},
"scss.lint.hexColorLength": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "error"
},
"scss.lint.argumentsInColorFunction": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "error"
},
"scss.lint.unknownProperties": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning"
},
"scss.lint.ieHack": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore",
"description": "IE hacks are only necessary when supporting IE7 and older"
},
"scss.lint.unknownVendorSpecificProperties": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"scss.lint.propertyIgnoredDueToDisplay": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning"
},
"scss.lint.important": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"scss.lint.float": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"scss.lint.idSelector": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"wxss.validate": {
"type": "boolean",
"scope": "resource",
"default": true
},
"wxss.colorDecorators.enable": {
"type": "boolean",
"scope": "window",
"default": true
},
"wxss.lint.compatibleVendorPrefixes": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"wxss.lint.vendorPrefix": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning"
},
"wxss.lint.duplicateProperties": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"wxss.lint.emptyRules": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning"
},
"wxss.lint.importStatement": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"wxss.lint.boxModel": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"wxss.lint.universalSelector": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"wxss.lint.zeroUnits": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"wxss.lint.fontFaceProperties": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning"
},
"wxss.lint.hexColorLength": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "error"
},
"wxss.lint.argumentsInColorFunction": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "error"
},
"wxss.lint.unknownProperties": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning"
},
"wxss.lint.ieHack": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"wxss.lint.unknownVendorSpecificProperties": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"wxss.lint.propertyIgnoredDueToDisplay": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "warning"
},
"wxss.lint.important": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"wxss.lint.float": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
},
"wxss.lint.idSelector": {
"type": "string",
"scope": "resource",
"enum": [
"ignore",
"warning",
"error"
],
"default": "ignore"
}
}
}
},
"author": "chemzqm@gmail.com",
"license": "MIT",
"devDependencies": {
"@types/node": "^14.14.5",
"coc.nvim": "^0.0.79",
"rimraf": "^3.0.2",
"ts-loader": "^8.0.7",
"typescript": "^4.0.5",
"vscode-css-languageservice": "4.3.5",
"vscode-languageserver": "7.0.0-next.3",
"vscode-languageserver-protocol": "^3.15.3",
"vscode-uri": "^2.1.2",
"webpack": "^5.2.0",
"webpack-cli": "^4.1.0"
},
"dependencies": {}
}

View file

@ -1,41 +0,0 @@
const path = require('path')
module.exports = {
entry: {
index: './src/index.ts',
server: './server/node/cssServerMain.ts'
},
target: 'node',
mode: 'none',
resolve: {
mainFields: ['module', 'main'],
extensions: ['.js', '.ts']
},
externals: {
'coc.nvim': 'commonjs coc.nvim'
},
module: {
rules: [{
test: /\.ts$/,
exclude: /node_modules/,
use: [{
loader: 'ts-loader',
options: {
compilerOptions: {
"sourceMap": true,
}
}
}]
}]
},
output: {
path: path.resolve(__dirname, 'lib'),
filename: '[name].js',
libraryTarget: "commonjs",
},
plugins: [
],
node: {
__dirname: false
}
}

View file

@ -1 +0,0 @@
server

View file

@ -1,32 +0,0 @@
# coc-emmet
Emmet completion support for [coc.nvim](https://github.com/neoclide/coc.nvim)
Fork of emmet extension from [VSCode](https://github.com/Microsoft/vscode) with
only completion support.
**Note**: this. extension does completion support for emmet only, you should use
https://github.com/mattn/emmet-vim
## Install
In your vim/neovim, run command:
```vim
:CocInstall coc-emmet
```
## Options
- `emmet.showExpandedAbbreviation`: Shows expanded Emmet abbreviations as suggestions, default `true`.
- `emmet.showAbbreviationSuggestions`: Shows possible Emmet abbreviations as suggestions. Not applicable in stylesheets or when emmet.showExpandedAbbreviation is 'never'.
- `emmet.includeLanguages`: Enable Emmet abbreviations in languages that are not supported by default. Add a mapping here between the language and emmet supported language. E.g.: `{"vue-html": "html", "javascript": "javascriptreact"}`
- `emmet.variables`: Variables to be used in Emmet snippets
- `emmet.syntaxProfiles`: Define profile for specified syntax or use your own profile with specific rules.
- `emmet.excludeLanguages`: An array of languages where Emmet abbreviations should not be expanded, default: `["markdown"]`.
- `emmet.optimizeStylesheetParsing`: When set to `false`, the whole file is parsed to determine if current position is valid for expanding Emmet abbreviations. When set to `true`, only the content around the current position in css/scss/less files is parsed.
- `emmet.preferences`: Preferences used to modify behavior of some actions and resolvers of Emmet.
## LICENSE
MIT

File diff suppressed because it is too large Load diff

View file

@ -1,34 +0,0 @@
{
"name": "coc-emmet",
"version": "1.1.6",
"lockfileVersion": 2,
"requires": true,
"packages": {
"node_modules/@emmetio/extract-abbreviation": {
"version": "0.1.6",
"resolved": "https://registry.npmjs.org/@emmetio/extract-abbreviation/-/extract-abbreviation-0.1.6.tgz",
"integrity": "sha512-Ce3xE2JvTSEbASFbRbA1gAIcMcZWdS2yUYRaQbeM0nbOzaZrUYfa3ePtcriYRZOZmr+CkKA+zbjhvTpIOAYVcw=="
},
"node_modules/vscode-emmet-helper": {
"version": "1.2.17",
"resolved": "https://registry.npmjs.org/vscode-emmet-helper/-/vscode-emmet-helper-1.2.17.tgz",
"integrity": "sha512-X4pzcrJ8dE7M3ArFuySF5fgipKDd/EauXkiJwtjBIVRWpVNq0tF9+lNCyuC7iDUwP3Oq7ow/TGssD3GdG96Jow==",
"deprecated": "This package has been renamed to @vscode/emmet-helper, please update to the new name",
"dependencies": {
"@emmetio/extract-abbreviation": "0.1.6",
"jsonc-parser": "^1.0.0",
"vscode-languageserver-types": "^3.6.0-next.1"
}
},
"node_modules/vscode-emmet-helper/node_modules/jsonc-parser": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-1.0.3.tgz",
"integrity": "sha512-hk/69oAeaIzchq/v3lS50PXuzn5O2ynldopMC+SWBql7J2WtdptfB9dy8Y7+Og5rPkTCpn83zTiO8FMcqlXJ/g=="
},
"node_modules/vscode-languageserver-types": {
"version": "3.16.0",
"resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.16.0.tgz",
"integrity": "sha512-k8luDIWJWyenLc5ToFQQMaSrqCHiLwyKPHKPQZ5zz21vM+vIVUSvsRpcbiECH4WR88K2XZqc4ScRcZ7nk/jbeA=="
}
}
}

View file

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2017 Emmet.io
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -1,2 +0,0 @@
# extract-abbreviation
Extracts Emmet abbreviation from string

View file

@ -1,373 +0,0 @@
'use strict';
/**
* Minimalistic backwards stream reader
*/
class StreamReader {
constructor(string) {
this.string = string;
this.pos = this.string.length;
}
sol() {
return this.pos === 0;
}
peek(offset) {
return this.string.charCodeAt(this.pos - 1 + (offset || 0));
}
prev() {
if (!this.sol()) {
return this.string.charCodeAt(--this.pos);
}
}
eat(match) {
const ok = typeof match === 'function'
? match(this.peek())
: match === this.peek();
if (ok) {
this.pos--;
}
return ok;
}
eatWhile(match) {
const start = this.pos;
while (this.eat(match)) {}
return this.pos < start;
}
}
/**
* Quotes-related utilities
*/
const SINGLE_QUOTE = 39; // '
const DOUBLE_QUOTE = 34; // "
const ESCAPE = 92; // \
/**
* Check if given character code is a quote
* @param {Number} c
* @return {Boolean}
*/
function isQuote(c) {
return c === SINGLE_QUOTE || c === DOUBLE_QUOTE;
}
/**
* Consumes quoted value, if possible
* @param {StreamReader} stream
* @return {Boolean} Returns `true` is value was consumed
*/
function eatQuoted(stream) {
const start = stream.pos;
const quote = stream.prev();
if (isQuote(quote)) {
while (!stream.sol()) {
if (stream.prev() === quote && stream.peek() !== ESCAPE) {
return true;
}
}
}
stream.pos = start;
return false;
}
const TAB = 9;
const SPACE = 32;
const DASH = 45; // -
const SLASH = 47; // /
const COLON = 58; // :
const EQUALS = 61; // =
const ANGLE_LEFT = 60; // <
const ANGLE_RIGHT = 62; // >
/**
* Check if given readers current position points at the end of HTML tag
* @param {StreamReader} stream
* @return {Boolean}
*/
var isAtHTMLTag = function (stream) {
const start = stream.pos;
if (!stream.eat(ANGLE_RIGHT)) {
return false;
}
let ok = false;
stream.eat(SLASH); // possibly self-closed element
while (!stream.sol()) {
stream.eatWhile(isWhiteSpace);
if (eatIdent(stream)) {
// ate identifier: could be a tag name, boolean attribute or unquoted
// attribute value
if (stream.eat(SLASH)) {
// either closing tag or invalid tag
ok = stream.eat(ANGLE_LEFT);
break;
} else if (stream.eat(ANGLE_LEFT)) {
// opening tag
ok = true;
break;
} else if (stream.eat(isWhiteSpace)) {
// boolean attribute
continue;
} else if (stream.eat(EQUALS)) {
// simple unquoted value or invalid attribute
if (eatIdent(stream)) {
continue;
}
break;
} else if (eatAttributeWithUnquotedValue(stream)) {
// identifier was a part of unquoted value
ok = true;
break;
}
// invalid tag
break;
}
if (eatAttribute(stream)) {
continue;
}
break;
}
stream.pos = start;
return ok;
};
/**
* Eats HTML attribute from given string.
* @param {StreamReader} state
* @return {Boolean} `true` if attribute was consumed.
*/
function eatAttribute(stream) {
return eatAttributeWithQuotedValue(stream) || eatAttributeWithUnquotedValue(stream);
}
/**
* @param {StreamReader} stream
* @return {Boolean}
*/
function eatAttributeWithQuotedValue(stream) {
const start = stream.pos;
if (eatQuoted(stream) && stream.eat(EQUALS) && eatIdent(stream)) {
return true;
}
stream.pos = start;
return false;
}
/**
* @param {StreamReader} stream
* @return {Boolean}
*/
function eatAttributeWithUnquotedValue(stream) {
const start = stream.pos;
if (stream.eatWhile(isUnquotedValue) && stream.eat(EQUALS) && eatIdent(stream)) {
return true;
}
stream.pos = start;
return false;
}
/**
* Eats HTML identifier from stream
* @param {StreamReader} stream
* @return {Boolean}
*/
function eatIdent(stream) {
return stream.eatWhile(isIdent);
}
/**
* Check if given character code belongs to HTML identifier
* @param {Number} c
* @return {Boolean}
*/
function isIdent(c) {
return c === COLON || c === DASH || isAlpha(c) || isNumber(c);
}
/**
* Check if given character code is alpha code (letter though A to Z)
* @param {Number} c
* @return {Boolean}
*/
function isAlpha(c) {
c &= ~32; // quick hack to convert any char code to uppercase char code
return c >= 65 && c <= 90; // A-Z
}
/**
* Check if given code is a number
* @param {Number} c
* @return {Boolean}
*/
function isNumber(c) {
return c > 47 && c < 58;
}
/**
* Check if given code is a whitespace
* @param {Number} c
* @return {Boolean}
*/
function isWhiteSpace(c) {
return c === SPACE || c === TAB;
}
/**
* Check if given code may belong to unquoted attribute value
* @param {Number} c
* @return {Boolean}
*/
function isUnquotedValue(c) {
return c && c !== EQUALS && !isWhiteSpace(c) && !isQuote(c);
}
const code = ch => ch.charCodeAt(0);
const SQUARE_BRACE_L = code('[');
const SQUARE_BRACE_R = code(']');
const ROUND_BRACE_L = code('(');
const ROUND_BRACE_R = code(')');
const CURLY_BRACE_L = code('{');
const CURLY_BRACE_R = code('}');
const specialChars = new Set('#.*:$-_!@%^+>/'.split('').map(code));
const bracePairs = new Map()
.set(SQUARE_BRACE_L, SQUARE_BRACE_R)
.set(ROUND_BRACE_L, ROUND_BRACE_R)
.set(CURLY_BRACE_L, CURLY_BRACE_R);
const defaultOptions = {
syntax: 'markup',
lookAhead: null
};
/**
* Extracts Emmet abbreviation from given string.
* The goal of this module is to extract abbreviation from current editors line,
* e.g. like this: `<span>.foo[title=bar|]</span>` -> `.foo[title=bar]`, where
* `|` is a current caret position.
* @param {String} line A text line where abbreviation should be expanded
* @param {Number} [pos] Caret position in line. If not given, uses end-of-line
* @param {Object} [options]
* @param {Boolean} [options.lookAhead] Allow parser to look ahead of `pos` index for
* searching of missing abbreviation parts. Most editors automatically inserts
* closing braces for `[`, `{` and `(`, which will most likely be right after
* current caret position. So in order to properly expand abbreviation, user
* must explicitly move caret right after auto-inserted braces. Whith this option
* enabled, parser will search for closing braces right after `pos`. Default is `true`
* @param {String} [options.syntax] Name of context syntax of expanded abbreviation.
* Either 'markup' (default) or 'stylesheet'. In 'stylesheet' syntax, braces `[]`
* and `{}` are not supported thus not extracted.
* @return {Object} Object with `abbreviation` and its `location` in given line
* if abbreviation can be extracted, `null` otherwise
*/
function extractAbbreviation(line, pos, options) {
// make sure `pos` is within line range
pos = Math.min(line.length, Math.max(0, pos == null ? line.length : pos));
if (typeof options === 'boolean') {
options = Object.assign(defaultOptions, { lookAhead: options });
} else {
options = Object.assign(defaultOptions, options);
}
if (options.lookAhead == null || options.lookAhead === true) {
pos = offsetPastAutoClosed(line, pos, options);
}
let c;
const stream = new StreamReader(line);
stream.pos = pos;
const stack = [];
while (!stream.sol()) {
c = stream.peek();
if (isCloseBrace(c, options.syntax)) {
stack.push(c);
} else if (isOpenBrace(c, options.syntax)) {
if (stack.pop() !== bracePairs.get(c)) {
// unexpected brace
break;
}
} else if (has(stack, SQUARE_BRACE_R) || has(stack, CURLY_BRACE_R)) {
// respect all characters inside attribute sets or text nodes
stream.pos--;
continue;
} else if (isAtHTMLTag(stream) || !isAbbreviation(c)) {
break;
}
stream.pos--;
}
if (!stack.length && stream.pos !== pos) {
// found something, remove some invalid symbols from the
// beginning and return abbreviation
const abbreviation = line.slice(stream.pos, pos).replace(/^[*+>^]+/, '');
return {
abbreviation,
location: pos - abbreviation.length
};
}
}
/**
* Returns new `line` index which is right after characters beyound `pos` that
* edditor will likely automatically close, e.g. }, ], and quotes
* @param {String} line
* @param {Number} pos
* @return {Number}
*/
function offsetPastAutoClosed(line, pos, options) {
// closing quote is allowed only as a next character
if (isQuote(line.charCodeAt(pos))) {
pos++;
}
// offset pointer until non-autoclosed character is found
while (isCloseBrace(line.charCodeAt(pos), options.syntax)) {
pos++;
}
return pos;
}
function has(arr, value) {
return arr.indexOf(value) !== -1;
}
function isAbbreviation(c) {
return (c > 64 && c < 91) // uppercase letter
|| (c > 96 && c < 123) // lowercase letter
|| (c > 47 && c < 58) // number
|| specialChars.has(c); // special character
}
function isOpenBrace(c, syntax) {
return c === ROUND_BRACE_L || (syntax === 'markup' && (c === SQUARE_BRACE_L || c === CURLY_BRACE_L));
}
function isCloseBrace(c, syntax) {
return c === ROUND_BRACE_R || (syntax === 'markup' && (c === SQUARE_BRACE_R || c === CURLY_BRACE_R));
}
module.exports = extractAbbreviation;

View file

@ -1,371 +0,0 @@
/**
* Minimalistic backwards stream reader
*/
class StreamReader {
constructor(string) {
this.string = string;
this.pos = this.string.length;
}
sol() {
return this.pos === 0;
}
peek(offset) {
return this.string.charCodeAt(this.pos - 1 + (offset || 0));
}
prev() {
if (!this.sol()) {
return this.string.charCodeAt(--this.pos);
}
}
eat(match) {
const ok = typeof match === 'function'
? match(this.peek())
: match === this.peek();
if (ok) {
this.pos--;
}
return ok;
}
eatWhile(match) {
const start = this.pos;
while (this.eat(match)) {}
return this.pos < start;
}
}
/**
* Quotes-related utilities
*/
const SINGLE_QUOTE = 39; // '
const DOUBLE_QUOTE = 34; // "
const ESCAPE = 92; // \
/**
* Check if given character code is a quote
* @param {Number} c
* @return {Boolean}
*/
function isQuote(c) {
return c === SINGLE_QUOTE || c === DOUBLE_QUOTE;
}
/**
* Consumes quoted value, if possible
* @param {StreamReader} stream
* @return {Boolean} Returns `true` is value was consumed
*/
function eatQuoted(stream) {
const start = stream.pos;
const quote = stream.prev();
if (isQuote(quote)) {
while (!stream.sol()) {
if (stream.prev() === quote && stream.peek() !== ESCAPE) {
return true;
}
}
}
stream.pos = start;
return false;
}
const TAB = 9;
const SPACE = 32;
const DASH = 45; // -
const SLASH = 47; // /
const COLON = 58; // :
const EQUALS = 61; // =
const ANGLE_LEFT = 60; // <
const ANGLE_RIGHT = 62; // >
/**
* Check if given readers current position points at the end of HTML tag
* @param {StreamReader} stream
* @return {Boolean}
*/
var isAtHTMLTag = function (stream) {
const start = stream.pos;
if (!stream.eat(ANGLE_RIGHT)) {
return false;
}
let ok = false;
stream.eat(SLASH); // possibly self-closed element
while (!stream.sol()) {
stream.eatWhile(isWhiteSpace);
if (eatIdent(stream)) {
// ate identifier: could be a tag name, boolean attribute or unquoted
// attribute value
if (stream.eat(SLASH)) {
// either closing tag or invalid tag
ok = stream.eat(ANGLE_LEFT);
break;
} else if (stream.eat(ANGLE_LEFT)) {
// opening tag
ok = true;
break;
} else if (stream.eat(isWhiteSpace)) {
// boolean attribute
continue;
} else if (stream.eat(EQUALS)) {
// simple unquoted value or invalid attribute
if (eatIdent(stream)) {
continue;
}
break;
} else if (eatAttributeWithUnquotedValue(stream)) {
// identifier was a part of unquoted value
ok = true;
break;
}
// invalid tag
break;
}
if (eatAttribute(stream)) {
continue;
}
break;
}
stream.pos = start;
return ok;
};
/**
* Eats HTML attribute from given string.
* @param {StreamReader} state
* @return {Boolean} `true` if attribute was consumed.
*/
function eatAttribute(stream) {
return eatAttributeWithQuotedValue(stream) || eatAttributeWithUnquotedValue(stream);
}
/**
* @param {StreamReader} stream
* @return {Boolean}
*/
function eatAttributeWithQuotedValue(stream) {
const start = stream.pos;
if (eatQuoted(stream) && stream.eat(EQUALS) && eatIdent(stream)) {
return true;
}
stream.pos = start;
return false;
}
/**
* @param {StreamReader} stream
* @return {Boolean}
*/
function eatAttributeWithUnquotedValue(stream) {
const start = stream.pos;
if (stream.eatWhile(isUnquotedValue) && stream.eat(EQUALS) && eatIdent(stream)) {
return true;
}
stream.pos = start;
return false;
}
/**
* Eats HTML identifier from stream
* @param {StreamReader} stream
* @return {Boolean}
*/
function eatIdent(stream) {
return stream.eatWhile(isIdent);
}
/**
* Check if given character code belongs to HTML identifier
* @param {Number} c
* @return {Boolean}
*/
function isIdent(c) {
return c === COLON || c === DASH || isAlpha(c) || isNumber(c);
}
/**
* Check if given character code is alpha code (letter though A to Z)
* @param {Number} c
* @return {Boolean}
*/
function isAlpha(c) {
c &= ~32; // quick hack to convert any char code to uppercase char code
return c >= 65 && c <= 90; // A-Z
}
/**
* Check if given code is a number
* @param {Number} c
* @return {Boolean}
*/
function isNumber(c) {
return c > 47 && c < 58;
}
/**
* Check if given code is a whitespace
* @param {Number} c
* @return {Boolean}
*/
function isWhiteSpace(c) {
return c === SPACE || c === TAB;
}
/**
* Check if given code may belong to unquoted attribute value
* @param {Number} c
* @return {Boolean}
*/
function isUnquotedValue(c) {
return c && c !== EQUALS && !isWhiteSpace(c) && !isQuote(c);
}
const code = ch => ch.charCodeAt(0);
const SQUARE_BRACE_L = code('[');
const SQUARE_BRACE_R = code(']');
const ROUND_BRACE_L = code('(');
const ROUND_BRACE_R = code(')');
const CURLY_BRACE_L = code('{');
const CURLY_BRACE_R = code('}');
const specialChars = new Set('#.*:$-_!@%^+>/'.split('').map(code));
const bracePairs = new Map()
.set(SQUARE_BRACE_L, SQUARE_BRACE_R)
.set(ROUND_BRACE_L, ROUND_BRACE_R)
.set(CURLY_BRACE_L, CURLY_BRACE_R);
const defaultOptions = {
syntax: 'markup',
lookAhead: null
};
/**
* Extracts Emmet abbreviation from given string.
* The goal of this module is to extract abbreviation from current editors line,
* e.g. like this: `<span>.foo[title=bar|]</span>` -> `.foo[title=bar]`, where
* `|` is a current caret position.
* @param {String} line A text line where abbreviation should be expanded
* @param {Number} [pos] Caret position in line. If not given, uses end-of-line
* @param {Object} [options]
* @param {Boolean} [options.lookAhead] Allow parser to look ahead of `pos` index for
* searching of missing abbreviation parts. Most editors automatically inserts
* closing braces for `[`, `{` and `(`, which will most likely be right after
* current caret position. So in order to properly expand abbreviation, user
* must explicitly move caret right after auto-inserted braces. Whith this option
* enabled, parser will search for closing braces right after `pos`. Default is `true`
* @param {String} [options.syntax] Name of context syntax of expanded abbreviation.
* Either 'markup' (default) or 'stylesheet'. In 'stylesheet' syntax, braces `[]`
* and `{}` are not supported thus not extracted.
* @return {Object} Object with `abbreviation` and its `location` in given line
* if abbreviation can be extracted, `null` otherwise
*/
function extractAbbreviation(line, pos, options) {
// make sure `pos` is within line range
pos = Math.min(line.length, Math.max(0, pos == null ? line.length : pos));
if (typeof options === 'boolean') {
options = Object.assign(defaultOptions, { lookAhead: options });
} else {
options = Object.assign(defaultOptions, options);
}
if (options.lookAhead == null || options.lookAhead === true) {
pos = offsetPastAutoClosed(line, pos, options);
}
let c;
const stream = new StreamReader(line);
stream.pos = pos;
const stack = [];
while (!stream.sol()) {
c = stream.peek();
if (isCloseBrace(c, options.syntax)) {
stack.push(c);
} else if (isOpenBrace(c, options.syntax)) {
if (stack.pop() !== bracePairs.get(c)) {
// unexpected brace
break;
}
} else if (has(stack, SQUARE_BRACE_R) || has(stack, CURLY_BRACE_R)) {
// respect all characters inside attribute sets or text nodes
stream.pos--;
continue;
} else if (isAtHTMLTag(stream) || !isAbbreviation(c)) {
break;
}
stream.pos--;
}
if (!stack.length && stream.pos !== pos) {
// found something, remove some invalid symbols from the
// beginning and return abbreviation
const abbreviation = line.slice(stream.pos, pos).replace(/^[*+>^]+/, '');
return {
abbreviation,
location: pos - abbreviation.length
};
}
}
/**
* Returns new `line` index which is right after characters beyound `pos` that
* edditor will likely automatically close, e.g. }, ], and quotes
* @param {String} line
* @param {Number} pos
* @return {Number}
*/
function offsetPastAutoClosed(line, pos, options) {
// closing quote is allowed only as a next character
if (isQuote(line.charCodeAt(pos))) {
pos++;
}
// offset pointer until non-autoclosed character is found
while (isCloseBrace(line.charCodeAt(pos), options.syntax)) {
pos++;
}
return pos;
}
function has(arr, value) {
return arr.indexOf(value) !== -1;
}
function isAbbreviation(c) {
return (c > 64 && c < 91) // uppercase letter
|| (c > 96 && c < 123) // lowercase letter
|| (c > 47 && c < 58) // number
|| specialChars.has(c); // special character
}
function isOpenBrace(c, syntax) {
return c === ROUND_BRACE_L || (syntax === 'markup' && (c === SQUARE_BRACE_L || c === CURLY_BRACE_L));
}
function isCloseBrace(c, syntax) {
return c === ROUND_BRACE_R || (syntax === 'markup' && (c === SQUARE_BRACE_R || c === CURLY_BRACE_R));
}
export default extractAbbreviation;

View file

@ -1,29 +0,0 @@
{
"name": "@emmetio/extract-abbreviation",
"version": "0.1.6",
"description": "Extracts Emmet abbreviation from string",
"main": "dist/extract-abbreviation.cjs.js",
"module": "dist/extract-abbreviation.es.js",
"scripts": {
"test": "mocha",
"build": "rollup -c",
"prepublish": "npm test && npm run build"
},
"repository": {
"type": "git",
"url": "git+https://github.com/emmetio/extract-abbreviation.git"
},
"keywords": [],
"author": "Sergey Chikuyonok <serge.che@gmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/emmetio/extract-abbreviation/issues"
},
"homepage": "https://github.com/emmetio/extract-abbreviation#readme",
"devDependencies": {
"babel-plugin-transform-es2015-modules-commonjs": "^6.22.0",
"babel-register": "^6.22.0",
"mocha": "^3.2.0",
"rollup": "^0.41.4"
}
}

View file

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) Microsoft
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -1,11 +0,0 @@
# vscode-emmet-helper
A helper module to use emmet modules with Visual Studio Code
Visual Studio Code extensions that provide language service and want to provide emmet abbreviation expansions
in auto-complete can include this module and use the `doComplete` method.
Just pass the one of the emmet supported syntaxes that you would like the completion provider to use along with other parameters that you would generally pass to a completion provider.
If `emmet.includeLanguages` has a mapping for your language, then the builit-in emmet extension will provide
html emmet abbreviations. Ask the user to remove the mapping, if your extension decides to provide
emmet completions using this module

View file

@ -1,4 +0,0 @@
{
perform: true,
assignees: [ aeschli ]
}

View file

@ -1,5 +0,0 @@
language: node_js
sudo: false
node_js:
- "6"

View file

@ -1,35 +0,0 @@
1.0.3 2018-03-07
==================
- provide ems modules
1.0.2 2018-03-05
==================
- added the *visit.onComment* API, reported when comments are allowed.
- added the *ParseErrorCode.InvalidCommentToken* enum value, reported when comments are disallowed.
1.0.1
==================
- added the *format* API: computes edits to format a JSON document.
- added the *modify* API: computes edits to insert, remove or replace a property or value in a JSON document.
- added the *allyEdits* API: applies edits to a document
1.0.0
==================
* remove nls dependency (remove getParseErrorMessage)
0.4.2 / 2017-05-05
==================
* added ParseError.offset & ParseError.length
0.4.1 / 2017-04-02
==================
* added ParseOptions.allowTrailingComma
0.4.0 / 2017-02-23
==================
* fix for `getLocation`. Now `getLocation` inside an object will always return a property from inside that property. Can be empty string if the object has no properties or if the offset is before a actual property `{ "a": { | }} will return location ['a', ' ']`
0.3.0 / 2017-01-17
==================
* Updating to typescript 2.0

View file

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) Microsoft
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -1,291 +0,0 @@
# jsonc-parser
Scanner and parser for JSON with comments.
[![npm Package](https://img.shields.io/npm/v/jsonc-parser.svg?style=flat-square)](https://www.npmjs.org/package/jsonc-parser)
[![NPM Downloads](https://img.shields.io/npm/dm/jsonc-parser.svg)](https://npmjs.org/package/jsonc-parser)
[![Build Status](https://travis-ci.org/Microsoft/node-jsonc-parser.svg?branch=master)](https://travis-ci.org/Microsoft/node-jsonc-parser)
Why?
----
JSONC is JSON with JavaScript style comments. This node module provides a scanner and fault tolerant parser that can process JSONC but is also useful for standard JSON.
- the *scanner* tokenizes the input string into tokens and token offsets
- the *visit* function implements a 'SAX' style parser with callbacks for the encountered properties and values.
- the *parseTree* function computes a hierarchical DOM with offsets representing the encountered properties and values.
- the *parse* function evaluates the JavaScipt object represented by JSON string in a fault tolerant fashion.
- the *getLocation* API returns a location object that describes the property or value located at a given offset in a JSON document.
- ths *findNodeAtLocation* API finds the node at a given location path in a JSON DOM.
- the *format* API computes edits to format a JSON document.
- the *modify* API computes edits to insert, remove or replace a property or value in a JSON document.
- the *applyEdits* API applies edits to a document.
Installation
------------
npm install --save jsonc-parser
API
---
### Scanner:
```typescript
/**
* Creates a JSON scanner on the given text.
* If ignoreTrivia is set, whitespaces or comments are ignored.
*/
export function createScanner(text:string, ignoreTrivia:boolean = false):JSONScanner;
/**
* The scanner object, representing a JSON scanner at a position in the input string.
*/
export interface JSONScanner {
/**
* Sets the scan position to a new offset. A call to 'scan' is needed to get the first token.
*/
setPosition(pos: number): any;
/**
* Read the next token. Returns the tolen code.
*/
scan(): SyntaxKind;
/**
* Returns the current scan position, which is after the last read token.
*/
getPosition(): number;
/**
* Returns the last read token.
*/
getToken(): SyntaxKind;
/**
* Returns the last read token value. The value for strings is the decoded string content. For numbers its of type number, for boolean it's true or false.
*/
getTokenValue(): string;
/**
* The start offset of the last read token.
*/
getTokenOffset(): number;
/**
* The length of the last read token.
*/
getTokenLength(): number;
/**
* An error code of the last scan.
*/
getTokenError(): ScanError;
}
```
### Parser:
```typescript
export interface ParseOptions {
disallowComments?: boolean;
}
/**
* Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault lolerant as possible, but still return a result.
* Therefore always check the errors list to find out if the input was valid.
*/
export declare function parse(text: string, errors?: {error: ParseErrorCode;}[], options?: ParseOptions): any;
/**
* Parses the given text and invokes the visitor functions for each object, array and literal reached.
*/
export declare function visit(text: string, visitor: JSONVisitor, options?: ParseOptions): any;
export interface JSONVisitor {
/**
* Invoked when an open brace is encountered and an object is started. The offset and length represent the location of the open brace.
*/
onObjectBegin?: (offset: number, length: number) => void;
/**
* Invoked when a property is encountered. The offset and length represent the location of the property name.
*/
onObjectProperty?: (property: string, offset: number, length: number) => void;
/**
* Invoked when a closing brace is encountered and an object is completed. The offset and length represent the location of the closing brace.
*/
onObjectEnd?: (offset: number, length: number) => void;
/**
* Invoked when an open bracket is encountered. The offset and length represent the location of the open bracket.
*/
onArrayBegin?: (offset: number, length: number) => void;
/**
* Invoked when a closing bracket is encountered. The offset and length represent the location of the closing bracket.
*/
onArrayEnd?: (offset: number, length: number) => void;
/**
* Invoked when a literal value is encountered. The offset and length represent the location of the literal value.
*/
onLiteralValue?: (value: any, offset: number, length: number) => void;
/**
* Invoked when a comma or colon separator is encountered. The offset and length represent the location of the separator.
*/
onSeparator?: (charcter: string, offset: number, length: number) => void;
/**
* When comments are allowed, invoked when a line or block comment is encountered. The offset and length represent the location of the comment.
*/
onComment?: (offset: number, length: number) => void;
/**
* Invoked on an error.
*/
onError?: (error: ParseErrorCode, offset: number, length: number) => void;
}
/**
* Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
*/
export declare function parseTree(text: string, errors?: ParseError[], options?: ParseOptions): Node;
export declare type NodeType = "object" | "array" | "property" | "string" | "number" | "boolean" | "null";
export interface Node {
type: NodeType;
value?: any;
offset: number;
length: number;
columnOffset?: number;
parent?: Node;
children?: Node[];
}
```
### Utilities:
```typescript
/**
* Takes JSON with JavaScript-style comments and remove
* them. Optionally replaces every none-newline character
* of comments with a replaceCharacter
*/
export declare function stripComments(text: string, replaceCh?: string): string;
/**
* For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.
*/
export declare function getLocation(text: string, position: number): Location;
export declare type Segment = string | number;
export interface Location {
/**
* The previous property key or literal value (string, number, boolean or null) or undefined.
*/
previousNode?: Node;
/**
* The path describing the location in the JSON document. The path consists of a sequence strings
* representing an object property or numbers for array indices.
*/
path: Segment[];
/**
* Matches the locations path against a pattern consisting of strings (for properties) and numbers (for array indices).
* '*' will match a single segment, of any property name or index.
* '**' will match a sequece of segments or no segment, of any property name or index.
*/
matches: (patterns: Segment[]) => boolean;
/**
* If set, the location's offset is at a property key.
*/
isAtPropertyKey: boolean;
}
/**
* Finds the node at the given path in a JSON DOM.
*/
export function findNodeAtLocation(root: Node, path: JSONPath): Node | undefined;
/**
* Evaluates the JavaScript object of the given JSON DOM node
*/
export function getNodeValue(node: Node): any;
/**
* Computes the edits needed to format a JSON document.
*
* @param documentText The input text
* @param range The range to format or `undefined` to format the full content
* @param options The formatting options
* @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
* removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
* text in the original document. However, multiple edits can have
* the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
* To apply edits to an input, you can use `applyEdits`
*/
export function format(documentText: string, range: Range, options: FormattingOptions): Edit[];
/**
* Computes the edits needed to modify a value in the JSON document.
*
* @param documentText The input text
* @param path The path of the value to change. The path represents either to the document root, a property or an array item.
* If the path points to an non-existing property or item, it will be created.
* @param value The new value for the specified property or item. If the value is undefined,
* the property or item will be removed.
* @param options Options
* @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
* removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
* text in the original document. However, multiple edits can have
* the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
* To apply edits to an input, you can use `applyEdits`
*/
export function modify(text: string, path: JSONPath, value: any, options: ModificationOptions): Edit[];
/**
* Applies edits to a input string.
*/
export function applyEdits(text: string, edits: Edit[]): string;
/**
* Represents a text modification
*/
export interface Edit {
/**
* The start offset of the modification.
*/
offset: number;
/**
* The length of the modification. Must not be negative. Empty length represents an *insert*.
*/
length: number;
/**
* The new content. Empty content represents a *remove*.
*/
content: string;
}
/**
* A text range in the document
*/
export interface Range {
/**
* The start offset of the range.
*/
offset: number;
/**
* The length of the range. Must not be negative.
*/
length: number;
}
export interface FormattingOptions {
/**
* If indentation is based on spaces (`insertSpaces` = true), then what is the number of spaces that make an indent?
*/
tabSize: number;
/**
* Is indentation based on spaces?
*/
insertSpaces: boolean;
/**
* The default 'end of line' character
*/
eol: string;
}
```
License
-------
(MIT License)
Copyright 2018, Microsoft

View file

@ -1,5 +0,0 @@
import { Edit, FormattingOptions, JSONPath } from './main';
export declare function removeProperty(text: string, path: JSONPath, formattingOptions: FormattingOptions): Edit[];
export declare function setProperty(text: string, path: JSONPath, value: any, formattingOptions: FormattingOptions, getInsertionIndex?: (properties: string[]) => number): Edit[];
export declare function applyEdit(text: string, edit: Edit): string;
export declare function isWS(text: string, offset: number): boolean;

View file

@ -1,168 +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';
import { parseTree, findNodeAtLocation } from './main';
import { format, isEOL } from './format';
export function removeProperty(text, path, formattingOptions) {
return setProperty(text, path, void 0, formattingOptions);
}
export function setProperty(text, path, value, formattingOptions, getInsertionIndex) {
var errors = [];
var root = parseTree(text, errors);
var parent = void 0;
var lastSegment = void 0;
while (path.length > 0) {
lastSegment = path.pop();
parent = findNodeAtLocation(root, path);
if (parent === void 0 && value !== void 0) {
if (typeof lastSegment === 'string') {
value = (_a = {}, _a[lastSegment] = value, _a);
}
else {
value = [value];
}
}
else {
break;
}
}
if (!parent) {
// empty document
if (value === void 0) {
throw new Error('Can not delete in empty document');
}
return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, formattingOptions);
}
else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) {
var existing = findNodeAtLocation(parent, [lastSegment]);
if (existing !== void 0) {
if (value === void 0) {
if (!existing.parent) {
throw new Error('Malformed AST');
}
var propertyIndex = parent.children.indexOf(existing.parent);
var removeBegin = void 0;
var removeEnd = existing.parent.offset + existing.parent.length;
if (propertyIndex > 0) {
// remove the comma of the previous node
var previous = parent.children[propertyIndex - 1];
removeBegin = previous.offset + previous.length;
}
else {
removeBegin = parent.offset + 1;
if (parent.children.length > 1) {
// remove the comma of the next node
var next = parent.children[1];
removeEnd = next.offset;
}
}
return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, formattingOptions);
}
else {
// set value of existing property
return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, formattingOptions);
}
}
else {
if (value === void 0) {
return []; // property does not exist, nothing to do
}
var newProperty = JSON.stringify(lastSegment) + ": " + JSON.stringify(value);
var index = getInsertionIndex ? getInsertionIndex(parent.children.map(function (p) { return p.children[0].value; })) : parent.children.length;
var edit = void 0;
if (index > 0) {
var previous = parent.children[index - 1];
edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
}
else if (parent.children.length === 0) {
edit = { offset: parent.offset + 1, length: 0, content: newProperty };
}
else {
edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' };
}
return withFormatting(text, edit, formattingOptions);
}
}
else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) {
var insertIndex = lastSegment;
if (insertIndex === -1) {
// Insert
var newProperty = "" + JSON.stringify(value);
var edit = void 0;
if (parent.children.length === 0) {
edit = { offset: parent.offset + 1, length: 0, content: newProperty };
}
else {
var previous = parent.children[parent.children.length - 1];
edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
}
return withFormatting(text, edit, formattingOptions);
}
else {
if (value === void 0 && parent.children.length >= 0) {
//Removal
var removalIndex = lastSegment;
var toRemove = parent.children[removalIndex];
var edit = void 0;
if (parent.children.length === 1) {
// only item
edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' };
}
else if (parent.children.length - 1 === removalIndex) {
// last item
var previous = parent.children[removalIndex - 1];
var offset = previous.offset + previous.length;
var parentEndOffset = parent.offset + parent.length;
edit = { offset: offset, length: parentEndOffset - 2 - offset, content: '' };
}
else {
edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' };
}
return withFormatting(text, edit, formattingOptions);
}
else {
throw new Error('Array modification not supported yet');
}
}
}
else {
throw new Error("Can not add " + (typeof lastSegment !== 'number' ? 'index' : 'property') + " to parent of type " + parent.type);
}
var _a;
}
function withFormatting(text, edit, formattingOptions) {
// apply the edit
var newText = applyEdit(text, edit);
// format the new text
var begin = edit.offset;
var end = edit.offset + edit.content.length;
if (edit.length === 0 || edit.content.length === 0) {
while (begin > 0 && !isEOL(newText, begin - 1)) {
begin--;
}
while (end < newText.length && !isEOL(newText, end)) {
end++;
}
}
var edits = format(newText, { offset: begin, length: end - begin }, formattingOptions);
// apply the formatting edits and track the begin and end offsets of the changes
for (var i = edits.length - 1; i >= 0; i--) {
var edit_1 = edits[i];
newText = applyEdit(newText, edit_1);
begin = Math.min(begin, edit_1.offset);
end = Math.max(end, edit_1.offset + edit_1.length);
end += edit_1.content.length - edit_1.length;
}
// create a single edit with all changes
var editLength = text.length - (newText.length - end) - begin;
return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
}
export function applyEdit(text, edit) {
return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
}
export function isWS(text, offset) {
return '\r\n \t'.indexOf(text.charAt(offset)) !== -1;
}
//# sourceMappingURL=edit.js.map

View file

@ -1,3 +0,0 @@
import * as Json from './main';
export declare function format(documentText: string, range: Json.Range | undefined, options: Json.FormattingOptions): Json.Edit[];
export declare function isEOL(text: string, offset: number): boolean;

View file

@ -1,195 +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';
import * as Json from './main';
export function format(documentText, range, options) {
var initialIndentLevel;
var formatText;
var formatTextStart;
var rangeStart;
var rangeEnd;
if (range) {
rangeStart = range.offset;
rangeEnd = rangeStart + range.length;
formatTextStart = rangeStart;
while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
formatTextStart--;
}
var endOffset = rangeEnd;
while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
endOffset++;
}
formatText = documentText.substring(formatTextStart, endOffset);
initialIndentLevel = computeIndentLevel(formatText, 0, options);
}
else {
formatText = documentText;
initialIndentLevel = 0;
formatTextStart = 0;
rangeStart = 0;
rangeEnd = documentText.length;
}
var eol = getEOL(options, documentText);
var lineBreak = false;
var indentLevel = 0;
var indentValue;
if (options.insertSpaces) {
indentValue = repeat(' ', options.tabSize || 4);
}
else {
indentValue = '\t';
}
var scanner = Json.createScanner(formatText, false);
var hasError = false;
function newLineAndIndent() {
return eol + repeat(indentValue, initialIndentLevel + indentLevel);
}
function scanNext() {
var token = scanner.scan();
lineBreak = false;
while (token === Json.SyntaxKind.Trivia || token === Json.SyntaxKind.LineBreakTrivia) {
lineBreak = lineBreak || (token === Json.SyntaxKind.LineBreakTrivia);
token = scanner.scan();
}
hasError = token === Json.SyntaxKind.Unknown || scanner.getTokenError() !== Json.ScanError.None;
return token;
}
var editOperations = [];
function addEdit(text, startOffset, endOffset) {
if (!hasError && startOffset < rangeEnd && endOffset > rangeStart && documentText.substring(startOffset, endOffset) !== text) {
editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
}
}
var firstToken = scanNext();
if (firstToken !== Json.SyntaxKind.EOF) {
var firstTokenStart = scanner.getTokenOffset() + formatTextStart;
var initialIndent = repeat(indentValue, initialIndentLevel);
addEdit(initialIndent, formatTextStart, firstTokenStart);
}
while (firstToken !== Json.SyntaxKind.EOF) {
var firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
var secondToken = scanNext();
var replaceContent = '';
while (!lineBreak && (secondToken === Json.SyntaxKind.LineCommentTrivia || secondToken === Json.SyntaxKind.BlockCommentTrivia)) {
// comments on the same line: keep them on the same line, but ignore them otherwise
var commentTokenStart = scanner.getTokenOffset() + formatTextStart;
addEdit(' ', firstTokenEnd, commentTokenStart);
firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
replaceContent = secondToken === Json.SyntaxKind.LineCommentTrivia ? newLineAndIndent() : '';
secondToken = scanNext();
}
if (secondToken === Json.SyntaxKind.CloseBraceToken) {
if (firstToken !== Json.SyntaxKind.OpenBraceToken) {
indentLevel--;
replaceContent = newLineAndIndent();
}
}
else if (secondToken === Json.SyntaxKind.CloseBracketToken) {
if (firstToken !== Json.SyntaxKind.OpenBracketToken) {
indentLevel--;
replaceContent = newLineAndIndent();
}
}
else {
switch (firstToken) {
case Json.SyntaxKind.OpenBracketToken:
case Json.SyntaxKind.OpenBraceToken:
indentLevel++;
replaceContent = newLineAndIndent();
break;
case Json.SyntaxKind.CommaToken:
case Json.SyntaxKind.LineCommentTrivia:
replaceContent = newLineAndIndent();
break;
case Json.SyntaxKind.BlockCommentTrivia:
if (lineBreak) {
replaceContent = newLineAndIndent();
}
else {
// symbol following comment on the same line: keep on same line, separate with ' '
replaceContent = ' ';
}
break;
case Json.SyntaxKind.ColonToken:
replaceContent = ' ';
break;
case Json.SyntaxKind.StringLiteral:
if (secondToken === Json.SyntaxKind.ColonToken) {
replaceContent = '';
break;
}
// fall through
case Json.SyntaxKind.NullKeyword:
case Json.SyntaxKind.TrueKeyword:
case Json.SyntaxKind.FalseKeyword:
case Json.SyntaxKind.NumericLiteral:
case Json.SyntaxKind.CloseBraceToken:
case Json.SyntaxKind.CloseBracketToken:
if (secondToken === Json.SyntaxKind.LineCommentTrivia || secondToken === Json.SyntaxKind.BlockCommentTrivia) {
replaceContent = ' ';
}
else if (secondToken !== Json.SyntaxKind.CommaToken && secondToken !== Json.SyntaxKind.EOF) {
hasError = true;
}
break;
case Json.SyntaxKind.Unknown:
hasError = true;
break;
}
if (lineBreak && (secondToken === Json.SyntaxKind.LineCommentTrivia || secondToken === Json.SyntaxKind.BlockCommentTrivia)) {
replaceContent = newLineAndIndent();
}
}
var secondTokenStart = scanner.getTokenOffset() + formatTextStart;
addEdit(replaceContent, firstTokenEnd, secondTokenStart);
firstToken = secondToken;
}
return editOperations;
}
function repeat(s, count) {
var result = '';
for (var i = 0; i < count; i++) {
result += s;
}
return result;
}
function computeIndentLevel(content, offset, options) {
var i = 0;
var nChars = 0;
var tabSize = options.tabSize || 4;
while (i < content.length) {
var ch = content.charAt(i);
if (ch === ' ') {
nChars++;
}
else if (ch === '\t') {
nChars += tabSize;
}
else {
break;
}
i++;
}
return Math.floor(nChars / tabSize);
}
function getEOL(options, text) {
for (var i = 0; i < text.length; i++) {
var ch = text.charAt(i);
if (ch === '\r') {
if (i + 1 < text.length && text.charAt(i + 1) === '\n') {
return '\r\n';
}
return '\r';
}
else if (ch === '\n') {
return '\n';
}
}
return (options && options.eol) || '\n';
}
export function isEOL(text, offset) {
return '\r\n'.indexOf(text.charAt(offset)) !== -1;
}
//# sourceMappingURL=format.js.map

View file

@ -1,289 +0,0 @@
export declare enum ScanError {
None = 0,
UnexpectedEndOfComment = 1,
UnexpectedEndOfString = 2,
UnexpectedEndOfNumber = 3,
InvalidUnicode = 4,
InvalidEscapeCharacter = 5,
InvalidCharacter = 6,
}
export declare enum SyntaxKind {
Unknown = 0,
OpenBraceToken = 1,
CloseBraceToken = 2,
OpenBracketToken = 3,
CloseBracketToken = 4,
CommaToken = 5,
ColonToken = 6,
NullKeyword = 7,
TrueKeyword = 8,
FalseKeyword = 9,
StringLiteral = 10,
NumericLiteral = 11,
LineCommentTrivia = 12,
BlockCommentTrivia = 13,
LineBreakTrivia = 14,
Trivia = 15,
EOF = 16,
}
/**
* The scanner object, representing a JSON scanner at a position in the input string.
*/
export interface JSONScanner {
/**
* Sets the scan position to a new offset. A call to 'scan' is needed to get the first token.
*/
setPosition(pos: number): void;
/**
* Read the next token. Returns the tolen code.
*/
scan(): SyntaxKind;
/**
* Returns the current scan position, which is after the last read token.
*/
getPosition(): number;
/**
* Returns the last read token.
*/
getToken(): SyntaxKind;
/**
* Returns the last read token value. The value for strings is the decoded string content. For numbers its of type number, for boolean it's true or false.
*/
getTokenValue(): string;
/**
* The start offset of the last read token.
*/
getTokenOffset(): number;
/**
* The length of the last read token.
*/
getTokenLength(): number;
/**
* An error code of the last scan.
*/
getTokenError(): ScanError;
}
/**
* Creates a JSON scanner on the given text.
* If ignoreTrivia is set, whitespaces or comments are ignored.
*/
export declare function createScanner(text: string, ignoreTrivia?: boolean): JSONScanner;
/**
* Takes JSON with JavaScript-style comments and remove
* them. Optionally replaces every none-newline character
* of comments with a replaceCharacter
*/
export declare function stripComments(text: string, replaceCh?: string): string;
export interface ParseError {
error: ParseErrorCode;
offset: number;
length: number;
}
export declare enum ParseErrorCode {
InvalidSymbol = 0,
InvalidNumberFormat = 1,
PropertyNameExpected = 2,
ValueExpected = 3,
ColonExpected = 4,
CommaExpected = 5,
CloseBraceExpected = 6,
CloseBracketExpected = 7,
EndOfFileExpected = 8,
InvalidCommentToken = 9,
UnexpectedEndOfComment = 10,
UnexpectedEndOfString = 11,
UnexpectedEndOfNumber = 12,
InvalidUnicode = 13,
InvalidEscapeCharacter = 14,
InvalidCharacter = 15,
}
export declare type NodeType = 'object' | 'array' | 'property' | 'string' | 'number' | 'boolean' | 'null';
export interface Node {
type: NodeType;
value?: any;
offset: number;
length: number;
columnOffset?: number;
parent?: Node;
children?: Node[];
}
export declare type Segment = string | number;
export declare type JSONPath = Segment[];
export interface Location {
/**
* The previous property key or literal value (string, number, boolean or null) or undefined.
*/
previousNode?: Node;
/**
* The path describing the location in the JSON document. The path consists of a sequence strings
* representing an object property or numbers for array indices.
*/
path: JSONPath;
/**
* Matches the locations path against a pattern consisting of strings (for properties) and numbers (for array indices).
* '*' will match a single segment, of any property name or index.
* '**' will match a sequece of segments or no segment, of any property name or index.
*/
matches: (patterns: JSONPath) => boolean;
/**
* If set, the location's offset is at a property key.
*/
isAtPropertyKey: boolean;
}
/**
* For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.
*/
export declare function getLocation(text: string, position: number): Location;
export interface ParseOptions {
disallowComments?: boolean;
allowTrailingComma?: boolean;
}
/**
* Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
* Therefore always check the errors list to find out if the input was valid.
*/
export declare function parse(text: string, errors?: ParseError[], options?: ParseOptions): any;
/**
* Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
*/
export declare function parseTree(text: string, errors?: ParseError[], options?: ParseOptions): Node;
/**
* Finds the node at the given path in a JSON DOM.
*/
export declare function findNodeAtLocation(root: Node, path: JSONPath): Node | undefined;
/**
* Evaluates the JavaScript object of the given JSON DOM node
*/
export declare function getNodeValue(node: Node): any;
/**
* Parses the given text and invokes the visitor functions for each object, array and literal reached.
*/
export declare function visit(text: string, visitor: JSONVisitor, options?: ParseOptions): any;
export interface JSONVisitor {
/**
* Invoked when an open brace is encountered and an object is started. The offset and length represent the location of the open brace.
*/
onObjectBegin?: (offset: number, length: number) => void;
/**
* Invoked when a property is encountered. The offset and length represent the location of the property name.
*/
onObjectProperty?: (property: string, offset: number, length: number) => void;
/**
* Invoked when a closing brace is encountered and an object is completed. The offset and length represent the location of the closing brace.
*/
onObjectEnd?: (offset: number, length: number) => void;
/**
* Invoked when an open bracket is encountered. The offset and length represent the location of the open bracket.
*/
onArrayBegin?: (offset: number, length: number) => void;
/**
* Invoked when a closing bracket is encountered. The offset and length represent the location of the closing bracket.
*/
onArrayEnd?: (offset: number, length: number) => void;
/**
* Invoked when a literal value is encountered. The offset and length represent the location of the literal value.
*/
onLiteralValue?: (value: any, offset: number, length: number) => void;
/**
* Invoked when a comma or colon separator is encountered. The offset and length represent the location of the separator.
*/
onSeparator?: (character: string, offset: number, length: number) => void;
/**
* When comments are allowed, invoked when a line or block comment is encountered. The offset and length represent the location of the comment.
*/
onComment?: (offset: number, length: number) => void;
/**
* Invoked on an error.
*/
onError?: (error: ParseErrorCode, offset: number, length: number) => void;
}
/**
* Represents a text modification
*/
export interface Edit {
/**
* The start offset of the modification.
*/
offset: number;
/**
* The length of the modification. Must not be negative. Empty length represents an *insert*.
*/
length: number;
/**
* The new content. Empty content represents a *remove*.
*/
content: string;
}
/**
* A text range in the document
*/
export interface Range {
/**
* The start offset of the range.
*/
offset: number;
/**
* The length of the range. Must not be negative.
*/
length: number;
}
export interface FormattingOptions {
/**
* If indentation is based on spaces (`insertSpaces` = true), then what is the number of spaces that make an indent?
*/
tabSize?: number;
/**
* Is indentation based on spaces?
*/
insertSpaces?: boolean;
/**
* The default 'end of line' character. If not set, '\n' is used as default.
*/
eol?: string;
}
/**
* Computes the edits needed to format a JSON document.
*
* @param documentText The input text
* @param range The range to format or `undefined` to format the full content
* @param options The formatting options
* @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
* removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
* text in the original document. However, multiple edits can have
* the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
* To apply edits to an input, you can use `applyEdits`
*/
export declare function format(documentText: string, range: Range | undefined, options: FormattingOptions): Edit[];
/**
* Options used when computing the modification edits
*/
export interface ModificationOptions {
/**
* Formatting options
*/
formattingOptions: FormattingOptions;
/**
* Optional fucntion to define the insertion index given an existing list of properties.
*/
getInsertionIndex?: (properties: string[]) => number;
}
/**
* Computes the edits needed to modify a value in the JSON document.
*
* @param documentText The input text
* @param path The path of the value to change. The path represents either to the document root, a property or an array item.
* If the path points to an non-existing property or item, it will be created.
* @param value The new value for the specified property or item. If the value is undefined,
* the property or item will be removed.
* @param options Options
* @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
* removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
* text in the original document. However, multiple edits can have
* the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
* To apply edits to an input, you can use `applyEdits`
*/
export declare function modify(text: string, path: JSONPath, value: any, options: ModificationOptions): Edit[];
/**
* Applies edits to a input string.
*/
export declare function applyEdits(text: string, edits: Edit[]): string;

View file

@ -1,985 +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';
import { format as _format } from './format';
import { setProperty, applyEdit } from './edit';
export var ScanError;
(function (ScanError) {
ScanError[ScanError["None"] = 0] = "None";
ScanError[ScanError["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
ScanError[ScanError["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
ScanError[ScanError["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
ScanError[ScanError["InvalidUnicode"] = 4] = "InvalidUnicode";
ScanError[ScanError["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
ScanError[ScanError["InvalidCharacter"] = 6] = "InvalidCharacter";
})(ScanError || (ScanError = {}));
export var SyntaxKind;
(function (SyntaxKind) {
SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown";
SyntaxKind[SyntaxKind["OpenBraceToken"] = 1] = "OpenBraceToken";
SyntaxKind[SyntaxKind["CloseBraceToken"] = 2] = "CloseBraceToken";
SyntaxKind[SyntaxKind["OpenBracketToken"] = 3] = "OpenBracketToken";
SyntaxKind[SyntaxKind["CloseBracketToken"] = 4] = "CloseBracketToken";
SyntaxKind[SyntaxKind["CommaToken"] = 5] = "CommaToken";
SyntaxKind[SyntaxKind["ColonToken"] = 6] = "ColonToken";
SyntaxKind[SyntaxKind["NullKeyword"] = 7] = "NullKeyword";
SyntaxKind[SyntaxKind["TrueKeyword"] = 8] = "TrueKeyword";
SyntaxKind[SyntaxKind["FalseKeyword"] = 9] = "FalseKeyword";
SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral";
SyntaxKind[SyntaxKind["NumericLiteral"] = 11] = "NumericLiteral";
SyntaxKind[SyntaxKind["LineCommentTrivia"] = 12] = "LineCommentTrivia";
SyntaxKind[SyntaxKind["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
SyntaxKind[SyntaxKind["LineBreakTrivia"] = 14] = "LineBreakTrivia";
SyntaxKind[SyntaxKind["Trivia"] = 15] = "Trivia";
SyntaxKind[SyntaxKind["EOF"] = 16] = "EOF";
})(SyntaxKind || (SyntaxKind = {}));
/**
* Creates a JSON scanner on the given text.
* If ignoreTrivia is set, whitespaces or comments are ignored.
*/
export function createScanner(text, ignoreTrivia) {
if (ignoreTrivia === void 0) { ignoreTrivia = false; }
var pos = 0, len = text.length, value = '', tokenOffset = 0, token = SyntaxKind.Unknown, scanError = ScanError.None;
function scanHexDigits(count, exact) {
var digits = 0;
var value = 0;
while (digits < count || !exact) {
var ch = text.charCodeAt(pos);
if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) {
value = value * 16 + ch - 48 /* _0 */;
}
else if (ch >= 65 /* A */ && ch <= 70 /* F */) {
value = value * 16 + ch - 65 /* A */ + 10;
}
else if (ch >= 97 /* a */ && ch <= 102 /* f */) {
value = value * 16 + ch - 97 /* a */ + 10;
}
else {
break;
}
pos++;
digits++;
}
if (digits < count) {
value = -1;
}
return value;
}
function setPosition(newPosition) {
pos = newPosition;
value = '';
tokenOffset = 0;
token = SyntaxKind.Unknown;
scanError = ScanError.None;
}
function scanNumber() {
var start = pos;
if (text.charCodeAt(pos) === 48 /* _0 */) {
pos++;
}
else {
pos++;
while (pos < text.length && isDigit(text.charCodeAt(pos))) {
pos++;
}
}
if (pos < text.length && text.charCodeAt(pos) === 46 /* dot */) {
pos++;
if (pos < text.length && isDigit(text.charCodeAt(pos))) {
pos++;
while (pos < text.length && isDigit(text.charCodeAt(pos))) {
pos++;
}
}
else {
scanError = ScanError.UnexpectedEndOfNumber;
return text.substring(start, pos);
}
}
var end = pos;
if (pos < text.length && (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */)) {
pos++;
if (pos < text.length && text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) {
pos++;
}
if (pos < text.length && isDigit(text.charCodeAt(pos))) {
pos++;
while (pos < text.length && isDigit(text.charCodeAt(pos))) {
pos++;
}
end = pos;
}
else {
scanError = ScanError.UnexpectedEndOfNumber;
}
}
return text.substring(start, end);
}
function scanString() {
var result = '', start = pos;
while (true) {
if (pos >= len) {
result += text.substring(start, pos);
scanError = ScanError.UnexpectedEndOfString;
break;
}
var ch = text.charCodeAt(pos);
if (ch === 34 /* doubleQuote */) {
result += text.substring(start, pos);
pos++;
break;
}
if (ch === 92 /* backslash */) {
result += text.substring(start, pos);
pos++;
if (pos >= len) {
scanError = ScanError.UnexpectedEndOfString;
break;
}
ch = text.charCodeAt(pos++);
switch (ch) {
case 34 /* doubleQuote */:
result += '\"';
break;
case 92 /* backslash */:
result += '\\';
break;
case 47 /* slash */:
result += '/';
break;
case 98 /* b */:
result += '\b';
break;
case 102 /* f */:
result += '\f';
break;
case 110 /* n */:
result += '\n';
break;
case 114 /* r */:
result += '\r';
break;
case 116 /* t */:
result += '\t';
break;
case 117 /* u */:
var ch_1 = scanHexDigits(4, true);
if (ch_1 >= 0) {
result += String.fromCharCode(ch_1);
}
else {
scanError = ScanError.InvalidUnicode;
}
break;
default:
scanError = ScanError.InvalidEscapeCharacter;
}
start = pos;
continue;
}
if (ch >= 0 && ch <= 0x1f) {
if (isLineBreak(ch)) {
result += text.substring(start, pos);
scanError = ScanError.UnexpectedEndOfString;
break;
}
else {
scanError = ScanError.InvalidCharacter;
// mark as error but continue with string
}
}
pos++;
}
return result;
}
function scanNext() {
value = '';
scanError = ScanError.None;
tokenOffset = pos;
if (pos >= len) {
// at the end
tokenOffset = len;
return token = SyntaxKind.EOF;
}
var code = text.charCodeAt(pos);
// trivia: whitespace
if (isWhiteSpace(code)) {
do {
pos++;
value += String.fromCharCode(code);
code = text.charCodeAt(pos);
} while (isWhiteSpace(code));
return token = SyntaxKind.Trivia;
}
// trivia: newlines
if (isLineBreak(code)) {
pos++;
value += String.fromCharCode(code);
if (code === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
pos++;
value += '\n';
}
return token = SyntaxKind.LineBreakTrivia;
}
switch (code) {
// tokens: []{}:,
case 123 /* openBrace */:
pos++;
return token = SyntaxKind.OpenBraceToken;
case 125 /* closeBrace */:
pos++;
return token = SyntaxKind.CloseBraceToken;
case 91 /* openBracket */:
pos++;
return token = SyntaxKind.OpenBracketToken;
case 93 /* closeBracket */:
pos++;
return token = SyntaxKind.CloseBracketToken;
case 58 /* colon */:
pos++;
return token = SyntaxKind.ColonToken;
case 44 /* comma */:
pos++;
return token = SyntaxKind.CommaToken;
// strings
case 34 /* doubleQuote */:
pos++;
value = scanString();
return token = SyntaxKind.StringLiteral;
// comments
case 47 /* slash */:
var start = pos - 1;
// Single-line comment
if (text.charCodeAt(pos + 1) === 47 /* slash */) {
pos += 2;
while (pos < len) {
if (isLineBreak(text.charCodeAt(pos))) {
break;
}
pos++;
}
value = text.substring(start, pos);
return token = SyntaxKind.LineCommentTrivia;
}
// Multi-line comment
if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
pos += 2;
var commentClosed = false;
while (pos < len) {
var ch = text.charCodeAt(pos);
if (ch === 42 /* asterisk */ && (pos + 1 < len) && text.charCodeAt(pos + 1) === 47 /* slash */) {
pos += 2;
commentClosed = true;
break;
}
pos++;
}
if (!commentClosed) {
pos++;
scanError = ScanError.UnexpectedEndOfComment;
}
value = text.substring(start, pos);
return token = SyntaxKind.BlockCommentTrivia;
}
// just a single slash
value += String.fromCharCode(code);
pos++;
return token = SyntaxKind.Unknown;
// numbers
case 45 /* minus */:
value += String.fromCharCode(code);
pos++;
if (pos === len || !isDigit(text.charCodeAt(pos))) {
return token = SyntaxKind.Unknown;
}
// found a minus, followed by a number so
// we fall through to proceed with scanning
// numbers
case 48 /* _0 */:
case 49 /* _1 */:
case 50 /* _2 */:
case 51 /* _3 */:
case 52 /* _4 */:
case 53 /* _5 */:
case 54 /* _6 */:
case 55 /* _7 */:
case 56 /* _8 */:
case 57 /* _9 */:
value += scanNumber();
return token = SyntaxKind.NumericLiteral;
// literals and unknown symbols
default:
// is a literal? Read the full word.
while (pos < len && isUnknownContentCharacter(code)) {
pos++;
code = text.charCodeAt(pos);
}
if (tokenOffset !== pos) {
value = text.substring(tokenOffset, pos);
// keywords: true, false, null
switch (value) {
case 'true': return token = SyntaxKind.TrueKeyword;
case 'false': return token = SyntaxKind.FalseKeyword;
case 'null': return token = SyntaxKind.NullKeyword;
}
return token = SyntaxKind.Unknown;
}
// some
value += String.fromCharCode(code);
pos++;
return token = SyntaxKind.Unknown;
}
}
function isUnknownContentCharacter(code) {
if (isWhiteSpace(code) || isLineBreak(code)) {
return false;
}
switch (code) {
case 125 /* closeBrace */:
case 93 /* closeBracket */:
case 123 /* openBrace */:
case 91 /* openBracket */:
case 34 /* doubleQuote */:
case 58 /* colon */:
case 44 /* comma */:
return false;
}
return true;
}
function scanNextNonTrivia() {
var result;
do {
result = scanNext();
} while (result >= SyntaxKind.LineCommentTrivia && result <= SyntaxKind.Trivia);
return result;
}
return {
setPosition: setPosition,
getPosition: function () { return pos; },
scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
getToken: function () { return token; },
getTokenValue: function () { return value; },
getTokenOffset: function () { return tokenOffset; },
getTokenLength: function () { return pos - tokenOffset; },
getTokenError: function () { return scanError; }
};
}
function isWhiteSpace(ch) {
return ch === 32 /* space */ || ch === 9 /* tab */ || ch === 11 /* verticalTab */ || ch === 12 /* formFeed */ ||
ch === 160 /* nonBreakingSpace */ || ch === 5760 /* ogham */ || ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
ch === 8239 /* narrowNoBreakSpace */ || ch === 8287 /* mathematicalSpace */ || ch === 12288 /* ideographicSpace */ || ch === 65279 /* byteOrderMark */;
}
function isLineBreak(ch) {
return ch === 10 /* lineFeed */ || ch === 13 /* carriageReturn */ || ch === 8232 /* lineSeparator */ || ch === 8233 /* paragraphSeparator */;
}
function isDigit(ch) {
return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
}
/**
* Takes JSON with JavaScript-style comments and remove
* them. Optionally replaces every none-newline character
* of comments with a replaceCharacter
*/
export function stripComments(text, replaceCh) {
var _scanner = createScanner(text), parts = [], kind, offset = 0, pos;
do {
pos = _scanner.getPosition();
kind = _scanner.scan();
switch (kind) {
case SyntaxKind.LineCommentTrivia:
case SyntaxKind.BlockCommentTrivia:
case SyntaxKind.EOF:
if (offset !== pos) {
parts.push(text.substring(offset, pos));
}
if (replaceCh !== void 0) {
parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh));
}
offset = _scanner.getPosition();
break;
}
} while (kind !== SyntaxKind.EOF);
return parts.join('');
}
export var ParseErrorCode;
(function (ParseErrorCode) {
ParseErrorCode[ParseErrorCode["InvalidSymbol"] = 0] = "InvalidSymbol";
ParseErrorCode[ParseErrorCode["InvalidNumberFormat"] = 1] = "InvalidNumberFormat";
ParseErrorCode[ParseErrorCode["PropertyNameExpected"] = 2] = "PropertyNameExpected";
ParseErrorCode[ParseErrorCode["ValueExpected"] = 3] = "ValueExpected";
ParseErrorCode[ParseErrorCode["ColonExpected"] = 4] = "ColonExpected";
ParseErrorCode[ParseErrorCode["CommaExpected"] = 5] = "CommaExpected";
ParseErrorCode[ParseErrorCode["CloseBraceExpected"] = 6] = "CloseBraceExpected";
ParseErrorCode[ParseErrorCode["CloseBracketExpected"] = 7] = "CloseBracketExpected";
ParseErrorCode[ParseErrorCode["EndOfFileExpected"] = 8] = "EndOfFileExpected";
ParseErrorCode[ParseErrorCode["InvalidCommentToken"] = 9] = "InvalidCommentToken";
ParseErrorCode[ParseErrorCode["UnexpectedEndOfComment"] = 10] = "UnexpectedEndOfComment";
ParseErrorCode[ParseErrorCode["UnexpectedEndOfString"] = 11] = "UnexpectedEndOfString";
ParseErrorCode[ParseErrorCode["UnexpectedEndOfNumber"] = 12] = "UnexpectedEndOfNumber";
ParseErrorCode[ParseErrorCode["InvalidUnicode"] = 13] = "InvalidUnicode";
ParseErrorCode[ParseErrorCode["InvalidEscapeCharacter"] = 14] = "InvalidEscapeCharacter";
ParseErrorCode[ParseErrorCode["InvalidCharacter"] = 15] = "InvalidCharacter";
})(ParseErrorCode || (ParseErrorCode = {}));
function getLiteralNodeType(value) {
switch (typeof value) {
case 'boolean': return 'boolean';
case 'number': return 'number';
case 'string': return 'string';
default: return 'null';
}
}
/**
* For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.
*/
export function getLocation(text, position) {
var segments = []; // strings or numbers
var earlyReturnException = new Object();
var previousNode = void 0;
var previousNodeInst = {
value: {},
offset: 0,
length: 0,
type: 'object'
};
var isAtPropertyKey = false;
function setPreviousNode(value, offset, length, type) {
previousNodeInst.value = value;
previousNodeInst.offset = offset;
previousNodeInst.length = length;
previousNodeInst.type = type;
previousNodeInst.columnOffset = void 0;
previousNode = previousNodeInst;
}
try {
visit(text, {
onObjectBegin: function (offset, length) {
if (position <= offset) {
throw earlyReturnException;
}
previousNode = void 0;
isAtPropertyKey = position > offset;
segments.push(''); // push a placeholder (will be replaced)
},
onObjectProperty: function (name, offset, length) {
if (position < offset) {
throw earlyReturnException;
}
setPreviousNode(name, offset, length, 'property');
segments[segments.length - 1] = name;
if (position <= offset + length) {
throw earlyReturnException;
}
},
onObjectEnd: function (offset, length) {
if (position <= offset) {
throw earlyReturnException;
}
previousNode = void 0;
segments.pop();
},
onArrayBegin: function (offset, length) {
if (position <= offset) {
throw earlyReturnException;
}
previousNode = void 0;
segments.push(0);
},
onArrayEnd: function (offset, length) {
if (position <= offset) {
throw earlyReturnException;
}
previousNode = void 0;
segments.pop();
},
onLiteralValue: function (value, offset, length) {
if (position < offset) {
throw earlyReturnException;
}
setPreviousNode(value, offset, length, getLiteralNodeType(value));
if (position <= offset + length) {
throw earlyReturnException;
}
},
onSeparator: function (sep, offset, length) {
if (position <= offset) {
throw earlyReturnException;
}
if (sep === ':' && previousNode && previousNode.type === 'property') {
previousNode.columnOffset = offset;
isAtPropertyKey = false;
previousNode = void 0;
}
else if (sep === ',') {
var last = segments[segments.length - 1];
if (typeof last === 'number') {
segments[segments.length - 1] = last + 1;
}
else {
isAtPropertyKey = true;
segments[segments.length - 1] = '';
}
previousNode = void 0;
}
}
});
}
catch (e) {
if (e !== earlyReturnException) {
throw e;
}
}
return {
path: segments,
previousNode: previousNode,
isAtPropertyKey: isAtPropertyKey,
matches: function (pattern) {
var k = 0;
for (var i = 0; k < pattern.length && i < segments.length; i++) {
if (pattern[k] === segments[i] || pattern[k] === '*') {
k++;
}
else if (pattern[k] !== '**') {
return false;
}
}
return k === pattern.length;
}
};
}
/**
* Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
* Therefore always check the errors list to find out if the input was valid.
*/
export function parse(text, errors, options) {
if (errors === void 0) { errors = []; }
var currentProperty = null;
var currentParent = [];
var previousParents = [];
function onValue(value) {
if (Array.isArray(currentParent)) {
currentParent.push(value);
}
else if (currentProperty) {
currentParent[currentProperty] = value;
}
}
var visitor = {
onObjectBegin: function () {
var object = {};
onValue(object);
previousParents.push(currentParent);
currentParent = object;
currentProperty = null;
},
onObjectProperty: function (name) {
currentProperty = name;
},
onObjectEnd: function () {
currentParent = previousParents.pop();
},
onArrayBegin: function () {
var array = [];
onValue(array);
previousParents.push(currentParent);
currentParent = array;
currentProperty = null;
},
onArrayEnd: function () {
currentParent = previousParents.pop();
},
onLiteralValue: onValue,
onError: function (error, offset, length) {
errors.push({ error: error, offset: offset, length: length });
}
};
visit(text, visitor, options);
return currentParent[0];
}
/**
* Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
*/
export function parseTree(text, errors, options) {
if (errors === void 0) { errors = []; }
var currentParent = { type: 'array', offset: -1, length: -1, children: [] }; // artificial root
function ensurePropertyComplete(endOffset) {
if (currentParent.type === 'property') {
currentParent.length = endOffset - currentParent.offset;
currentParent = currentParent.parent;
}
}
function onValue(valueNode) {
currentParent.children.push(valueNode);
return valueNode;
}
var visitor = {
onObjectBegin: function (offset) {
currentParent = onValue({ type: 'object', offset: offset, length: -1, parent: currentParent, children: [] });
},
onObjectProperty: function (name, offset, length) {
currentParent = onValue({ type: 'property', offset: offset, length: -1, parent: currentParent, children: [] });
currentParent.children.push({ type: 'string', value: name, offset: offset, length: length, parent: currentParent });
},
onObjectEnd: function (offset, length) {
currentParent.length = offset + length - currentParent.offset;
currentParent = currentParent.parent;
ensurePropertyComplete(offset + length);
},
onArrayBegin: function (offset, length) {
currentParent = onValue({ type: 'array', offset: offset, length: -1, parent: currentParent, children: [] });
},
onArrayEnd: function (offset, length) {
currentParent.length = offset + length - currentParent.offset;
currentParent = currentParent.parent;
ensurePropertyComplete(offset + length);
},
onLiteralValue: function (value, offset, length) {
onValue({ type: getLiteralNodeType(value), offset: offset, length: length, parent: currentParent, value: value });
ensurePropertyComplete(offset + length);
},
onSeparator: function (sep, offset, length) {
if (currentParent.type === 'property') {
if (sep === ':') {
currentParent.columnOffset = offset;
}
else if (sep === ',') {
ensurePropertyComplete(offset);
}
}
},
onError: function (error, offset, length) {
errors.push({ error: error, offset: offset, length: length });
}
};
visit(text, visitor, options);
var result = currentParent.children[0];
if (result) {
delete result.parent;
}
return result;
}
/**
* Finds the node at the given path in a JSON DOM.
*/
export function findNodeAtLocation(root, path) {
if (!root) {
return void 0;
}
var node = root;
for (var _i = 0, path_1 = path; _i < path_1.length; _i++) {
var segment = path_1[_i];
if (typeof segment === 'string') {
if (node.type !== 'object' || !Array.isArray(node.children)) {
return void 0;
}
var found = false;
for (var _a = 0, _b = node.children; _a < _b.length; _a++) {
var propertyNode = _b[_a];
if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment) {
node = propertyNode.children[1];
found = true;
break;
}
}
if (!found) {
return void 0;
}
}
else {
var index = segment;
if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {
return void 0;
}
node = node.children[index];
}
}
return node;
}
/**
* Evaluates the JavaScript object of the given JSON DOM node
*/
export function getNodeValue(node) {
if (node.type === 'array') {
return node.children.map(getNodeValue);
}
else if (node.type === 'object') {
var obj = Object.create(null);
for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
var prop = _a[_i];
obj[prop.children[0].value] = getNodeValue(prop.children[1]);
}
return obj;
}
return node.value;
}
/**
* Parses the given text and invokes the visitor functions for each object, array and literal reached.
*/
export function visit(text, visitor, options) {
var _scanner = createScanner(text, false);
function toNoArgVisit(visitFunction) {
return visitFunction ? function () { return visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength()); } : function () { return true; };
}
function toOneArgVisit(visitFunction) {
return visitFunction ? function (arg) { return visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength()); } : function () { return true; };
}
var onObjectBegin = toNoArgVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisit(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisit(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisit(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
var disallowComments = options && options.disallowComments;
var allowTrailingComma = options && options.allowTrailingComma;
function scanNext() {
while (true) {
var token = _scanner.scan();
switch (_scanner.getTokenError()) {
case ScanError.InvalidUnicode:
handleError(ParseErrorCode.InvalidUnicode);
break;
case ScanError.InvalidEscapeCharacter:
handleError(ParseErrorCode.InvalidEscapeCharacter);
break;
case ScanError.UnexpectedEndOfNumber:
handleError(ParseErrorCode.UnexpectedEndOfNumber);
break;
case ScanError.UnexpectedEndOfComment:
if (!disallowComments) {
handleError(ParseErrorCode.UnexpectedEndOfComment);
}
break;
case ScanError.UnexpectedEndOfString:
handleError(ParseErrorCode.UnexpectedEndOfString);
break;
case ScanError.InvalidCharacter:
handleError(ParseErrorCode.InvalidCharacter);
break;
}
switch (token) {
case SyntaxKind.LineCommentTrivia:
case SyntaxKind.BlockCommentTrivia:
if (disallowComments) {
handleError(ParseErrorCode.InvalidCommentToken);
}
else {
onComment();
}
break;
case SyntaxKind.Unknown:
handleError(ParseErrorCode.InvalidSymbol);
break;
case SyntaxKind.Trivia:
case SyntaxKind.LineBreakTrivia:
break;
default:
return token;
}
}
}
function handleError(error, skipUntilAfter, skipUntil) {
if (skipUntilAfter === void 0) { skipUntilAfter = []; }
if (skipUntil === void 0) { skipUntil = []; }
onError(error);
if (skipUntilAfter.length + skipUntil.length > 0) {
var token = _scanner.getToken();
while (token !== SyntaxKind.EOF) {
if (skipUntilAfter.indexOf(token) !== -1) {
scanNext();
break;
}
else if (skipUntil.indexOf(token) !== -1) {
break;
}
token = scanNext();
}
}
}
function parseString(isValue) {
var value = _scanner.getTokenValue();
if (isValue) {
onLiteralValue(value);
}
else {
onObjectProperty(value);
}
scanNext();
return true;
}
function parseLiteral() {
switch (_scanner.getToken()) {
case SyntaxKind.NumericLiteral:
var value = 0;
try {
value = JSON.parse(_scanner.getTokenValue());
if (typeof value !== 'number') {
handleError(ParseErrorCode.InvalidNumberFormat);
value = 0;
}
}
catch (e) {
handleError(ParseErrorCode.InvalidNumberFormat);
}
onLiteralValue(value);
break;
case SyntaxKind.NullKeyword:
onLiteralValue(null);
break;
case SyntaxKind.TrueKeyword:
onLiteralValue(true);
break;
case SyntaxKind.FalseKeyword:
onLiteralValue(false);
break;
default:
return false;
}
scanNext();
return true;
}
function parseProperty() {
if (_scanner.getToken() !== SyntaxKind.StringLiteral) {
handleError(ParseErrorCode.PropertyNameExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);
return false;
}
parseString(false);
if (_scanner.getToken() === SyntaxKind.ColonToken) {
onSeparator(':');
scanNext(); // consume colon
if (!parseValue()) {
handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);
}
}
else {
handleError(ParseErrorCode.ColonExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);
}
return true;
}
function parseObject() {
onObjectBegin();
scanNext(); // consume open brace
var needsComma = false;
while (_scanner.getToken() !== SyntaxKind.CloseBraceToken && _scanner.getToken() !== SyntaxKind.EOF) {
if (_scanner.getToken() === SyntaxKind.CommaToken) {
if (!needsComma) {
handleError(ParseErrorCode.ValueExpected, [], []);
}
onSeparator(',');
scanNext(); // consume comma
if (_scanner.getToken() === SyntaxKind.CloseBraceToken && allowTrailingComma) {
break;
}
}
else if (needsComma) {
handleError(ParseErrorCode.CommaExpected, [], []);
}
if (!parseProperty()) {
handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);
}
needsComma = true;
}
onObjectEnd();
if (_scanner.getToken() !== SyntaxKind.CloseBraceToken) {
handleError(ParseErrorCode.CloseBraceExpected, [SyntaxKind.CloseBraceToken], []);
}
else {
scanNext(); // consume close brace
}
return true;
}
function parseArray() {
onArrayBegin();
scanNext(); // consume open bracket
var needsComma = false;
while (_scanner.getToken() !== SyntaxKind.CloseBracketToken && _scanner.getToken() !== SyntaxKind.EOF) {
if (_scanner.getToken() === SyntaxKind.CommaToken) {
if (!needsComma) {
handleError(ParseErrorCode.ValueExpected, [], []);
}
onSeparator(',');
scanNext(); // consume comma
if (_scanner.getToken() === SyntaxKind.CloseBracketToken && allowTrailingComma) {
break;
}
}
else if (needsComma) {
handleError(ParseErrorCode.CommaExpected, [], []);
}
if (!parseValue()) {
handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBracketToken, SyntaxKind.CommaToken]);
}
needsComma = true;
}
onArrayEnd();
if (_scanner.getToken() !== SyntaxKind.CloseBracketToken) {
handleError(ParseErrorCode.CloseBracketExpected, [SyntaxKind.CloseBracketToken], []);
}
else {
scanNext(); // consume close bracket
}
return true;
}
function parseValue() {
switch (_scanner.getToken()) {
case SyntaxKind.OpenBracketToken:
return parseArray();
case SyntaxKind.OpenBraceToken:
return parseObject();
case SyntaxKind.StringLiteral:
return parseString(true);
default:
return parseLiteral();
}
}
scanNext();
if (_scanner.getToken() === SyntaxKind.EOF) {
return true;
}
if (!parseValue()) {
handleError(ParseErrorCode.ValueExpected, [], []);
return false;
}
if (_scanner.getToken() !== SyntaxKind.EOF) {
handleError(ParseErrorCode.EndOfFileExpected, [], []);
}
return true;
}
/**
* Computes the edits needed to format a JSON document.
*
* @param documentText The input text
* @param range The range to format or `undefined` to format the full content
* @param options The formatting options
* @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
* removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
* text in the original document. However, multiple edits can have
* the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
* To apply edits to an input, you can use `applyEdits`
*/
export function format(documentText, range, options) {
return _format(documentText, range, options);
}
/**
* Computes the edits needed to modify a value in the JSON document.
*
* @param documentText The input text
* @param path The path of the value to change. The path represents either to the document root, a property or an array item.
* If the path points to an non-existing property or item, it will be created.
* @param value The new value for the specified property or item. If the value is undefined,
* the property or item will be removed.
* @param options Options
* @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
* removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
* text in the original document. However, multiple edits can have
* the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
* To apply edits to an input, you can use `applyEdits`
*/
export function modify(text, path, value, options) {
return setProperty(text, path, value, options.formattingOptions, options.getInsertionIndex);
}
/**
* Applies edits to a input string.
*/
export function applyEdits(text, edits) {
for (var i = edits.length - 1; i >= 0; i--) {
text = applyEdit(text, edits[i]);
}
return text;
}
//# sourceMappingURL=main.js.map

View file

@ -1,5 +0,0 @@
import { Edit, FormattingOptions, JSONPath } from './main';
export declare function removeProperty(text: string, path: JSONPath, formattingOptions: FormattingOptions): Edit[];
export declare function setProperty(text: string, path: JSONPath, value: any, formattingOptions: FormattingOptions, getInsertionIndex?: (properties: string[]) => number): Edit[];
export declare function applyEdit(text: string, edit: Edit): string;
export declare function isWS(text: string, offset: number): boolean;

View file

@ -1,183 +0,0 @@
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports", "./main", "./format"], factory);
}
})(function (require, exports) {
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
var main_1 = require("./main");
var format_1 = require("./format");
function removeProperty(text, path, formattingOptions) {
return setProperty(text, path, void 0, formattingOptions);
}
exports.removeProperty = removeProperty;
function setProperty(text, path, value, formattingOptions, getInsertionIndex) {
var errors = [];
var root = main_1.parseTree(text, errors);
var parent = void 0;
var lastSegment = void 0;
while (path.length > 0) {
lastSegment = path.pop();
parent = main_1.findNodeAtLocation(root, path);
if (parent === void 0 && value !== void 0) {
if (typeof lastSegment === 'string') {
value = (_a = {}, _a[lastSegment] = value, _a);
}
else {
value = [value];
}
}
else {
break;
}
}
if (!parent) {
// empty document
if (value === void 0) {
throw new Error('Can not delete in empty document');
}
return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, formattingOptions);
}
else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) {
var existing = main_1.findNodeAtLocation(parent, [lastSegment]);
if (existing !== void 0) {
if (value === void 0) {
if (!existing.parent) {
throw new Error('Malformed AST');
}
var propertyIndex = parent.children.indexOf(existing.parent);
var removeBegin = void 0;
var removeEnd = existing.parent.offset + existing.parent.length;
if (propertyIndex > 0) {
// remove the comma of the previous node
var previous = parent.children[propertyIndex - 1];
removeBegin = previous.offset + previous.length;
}
else {
removeBegin = parent.offset + 1;
if (parent.children.length > 1) {
// remove the comma of the next node
var next = parent.children[1];
removeEnd = next.offset;
}
}
return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, formattingOptions);
}
else {
// set value of existing property
return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, formattingOptions);
}
}
else {
if (value === void 0) {
return []; // property does not exist, nothing to do
}
var newProperty = JSON.stringify(lastSegment) + ": " + JSON.stringify(value);
var index = getInsertionIndex ? getInsertionIndex(parent.children.map(function (p) { return p.children[0].value; })) : parent.children.length;
var edit = void 0;
if (index > 0) {
var previous = parent.children[index - 1];
edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
}
else if (parent.children.length === 0) {
edit = { offset: parent.offset + 1, length: 0, content: newProperty };
}
else {
edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' };
}
return withFormatting(text, edit, formattingOptions);
}
}
else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) {
var insertIndex = lastSegment;
if (insertIndex === -1) {
// Insert
var newProperty = "" + JSON.stringify(value);
var edit = void 0;
if (parent.children.length === 0) {
edit = { offset: parent.offset + 1, length: 0, content: newProperty };
}
else {
var previous = parent.children[parent.children.length - 1];
edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
}
return withFormatting(text, edit, formattingOptions);
}
else {
if (value === void 0 && parent.children.length >= 0) {
//Removal
var removalIndex = lastSegment;
var toRemove = parent.children[removalIndex];
var edit = void 0;
if (parent.children.length === 1) {
// only item
edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' };
}
else if (parent.children.length - 1 === removalIndex) {
// last item
var previous = parent.children[removalIndex - 1];
var offset = previous.offset + previous.length;
var parentEndOffset = parent.offset + parent.length;
edit = { offset: offset, length: parentEndOffset - 2 - offset, content: '' };
}
else {
edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' };
}
return withFormatting(text, edit, formattingOptions);
}
else {
throw new Error('Array modification not supported yet');
}
}
}
else {
throw new Error("Can not add " + (typeof lastSegment !== 'number' ? 'index' : 'property') + " to parent of type " + parent.type);
}
var _a;
}
exports.setProperty = setProperty;
function withFormatting(text, edit, formattingOptions) {
// apply the edit
var newText = applyEdit(text, edit);
// format the new text
var begin = edit.offset;
var end = edit.offset + edit.content.length;
if (edit.length === 0 || edit.content.length === 0) {
while (begin > 0 && !format_1.isEOL(newText, begin - 1)) {
begin--;
}
while (end < newText.length && !format_1.isEOL(newText, end)) {
end++;
}
}
var edits = format_1.format(newText, { offset: begin, length: end - begin }, formattingOptions);
// apply the formatting edits and track the begin and end offsets of the changes
for (var i = edits.length - 1; i >= 0; i--) {
var edit_1 = edits[i];
newText = applyEdit(newText, edit_1);
begin = Math.min(begin, edit_1.offset);
end = Math.max(end, edit_1.offset + edit_1.length);
end += edit_1.content.length - edit_1.length;
}
// create a single edit with all changes
var editLength = text.length - (newText.length - end) - begin;
return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
}
function applyEdit(text, edit) {
return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
}
exports.applyEdit = applyEdit;
function isWS(text, offset) {
return '\r\n \t'.indexOf(text.charAt(offset)) !== -1;
}
exports.isWS = isWS;
});
//# sourceMappingURL=edit.js.map

View file

@ -1,3 +0,0 @@
import * as Json from './main';
export declare function format(documentText: string, range: Json.Range | undefined, options: Json.FormattingOptions): Json.Edit[];
export declare function isEOL(text: string, offset: number): boolean;

View file

@ -1,208 +0,0 @@
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports", "./main"], factory);
}
})(function (require, exports) {
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
var Json = require("./main");
function format(documentText, range, options) {
var initialIndentLevel;
var formatText;
var formatTextStart;
var rangeStart;
var rangeEnd;
if (range) {
rangeStart = range.offset;
rangeEnd = rangeStart + range.length;
formatTextStart = rangeStart;
while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
formatTextStart--;
}
var endOffset = rangeEnd;
while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
endOffset++;
}
formatText = documentText.substring(formatTextStart, endOffset);
initialIndentLevel = computeIndentLevel(formatText, 0, options);
}
else {
formatText = documentText;
initialIndentLevel = 0;
formatTextStart = 0;
rangeStart = 0;
rangeEnd = documentText.length;
}
var eol = getEOL(options, documentText);
var lineBreak = false;
var indentLevel = 0;
var indentValue;
if (options.insertSpaces) {
indentValue = repeat(' ', options.tabSize || 4);
}
else {
indentValue = '\t';
}
var scanner = Json.createScanner(formatText, false);
var hasError = false;
function newLineAndIndent() {
return eol + repeat(indentValue, initialIndentLevel + indentLevel);
}
function scanNext() {
var token = scanner.scan();
lineBreak = false;
while (token === Json.SyntaxKind.Trivia || token === Json.SyntaxKind.LineBreakTrivia) {
lineBreak = lineBreak || (token === Json.SyntaxKind.LineBreakTrivia);
token = scanner.scan();
}
hasError = token === Json.SyntaxKind.Unknown || scanner.getTokenError() !== Json.ScanError.None;
return token;
}
var editOperations = [];
function addEdit(text, startOffset, endOffset) {
if (!hasError && startOffset < rangeEnd && endOffset > rangeStart && documentText.substring(startOffset, endOffset) !== text) {
editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
}
}
var firstToken = scanNext();
if (firstToken !== Json.SyntaxKind.EOF) {
var firstTokenStart = scanner.getTokenOffset() + formatTextStart;
var initialIndent = repeat(indentValue, initialIndentLevel);
addEdit(initialIndent, formatTextStart, firstTokenStart);
}
while (firstToken !== Json.SyntaxKind.EOF) {
var firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
var secondToken = scanNext();
var replaceContent = '';
while (!lineBreak && (secondToken === Json.SyntaxKind.LineCommentTrivia || secondToken === Json.SyntaxKind.BlockCommentTrivia)) {
// comments on the same line: keep them on the same line, but ignore them otherwise
var commentTokenStart = scanner.getTokenOffset() + formatTextStart;
addEdit(' ', firstTokenEnd, commentTokenStart);
firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
replaceContent = secondToken === Json.SyntaxKind.LineCommentTrivia ? newLineAndIndent() : '';
secondToken = scanNext();
}
if (secondToken === Json.SyntaxKind.CloseBraceToken) {
if (firstToken !== Json.SyntaxKind.OpenBraceToken) {
indentLevel--;
replaceContent = newLineAndIndent();
}
}
else if (secondToken === Json.SyntaxKind.CloseBracketToken) {
if (firstToken !== Json.SyntaxKind.OpenBracketToken) {
indentLevel--;
replaceContent = newLineAndIndent();
}
}
else {
switch (firstToken) {
case Json.SyntaxKind.OpenBracketToken:
case Json.SyntaxKind.OpenBraceToken:
indentLevel++;
replaceContent = newLineAndIndent();
break;
case Json.SyntaxKind.CommaToken:
case Json.SyntaxKind.LineCommentTrivia:
replaceContent = newLineAndIndent();
break;
case Json.SyntaxKind.BlockCommentTrivia:
if (lineBreak) {
replaceContent = newLineAndIndent();
}
else {
// symbol following comment on the same line: keep on same line, separate with ' '
replaceContent = ' ';
}
break;
case Json.SyntaxKind.ColonToken:
replaceContent = ' ';
break;
case Json.SyntaxKind.StringLiteral:
if (secondToken === Json.SyntaxKind.ColonToken) {
replaceContent = '';
break;
}
// fall through
case Json.SyntaxKind.NullKeyword:
case Json.SyntaxKind.TrueKeyword:
case Json.SyntaxKind.FalseKeyword:
case Json.SyntaxKind.NumericLiteral:
case Json.SyntaxKind.CloseBraceToken:
case Json.SyntaxKind.CloseBracketToken:
if (secondToken === Json.SyntaxKind.LineCommentTrivia || secondToken === Json.SyntaxKind.BlockCommentTrivia) {
replaceContent = ' ';
}
else if (secondToken !== Json.SyntaxKind.CommaToken && secondToken !== Json.SyntaxKind.EOF) {
hasError = true;
}
break;
case Json.SyntaxKind.Unknown:
hasError = true;
break;
}
if (lineBreak && (secondToken === Json.SyntaxKind.LineCommentTrivia || secondToken === Json.SyntaxKind.BlockCommentTrivia)) {
replaceContent = newLineAndIndent();
}
}
var secondTokenStart = scanner.getTokenOffset() + formatTextStart;
addEdit(replaceContent, firstTokenEnd, secondTokenStart);
firstToken = secondToken;
}
return editOperations;
}
exports.format = format;
function repeat(s, count) {
var result = '';
for (var i = 0; i < count; i++) {
result += s;
}
return result;
}
function computeIndentLevel(content, offset, options) {
var i = 0;
var nChars = 0;
var tabSize = options.tabSize || 4;
while (i < content.length) {
var ch = content.charAt(i);
if (ch === ' ') {
nChars++;
}
else if (ch === '\t') {
nChars += tabSize;
}
else {
break;
}
i++;
}
return Math.floor(nChars / tabSize);
}
function getEOL(options, text) {
for (var i = 0; i < text.length; i++) {
var ch = text.charAt(i);
if (ch === '\r') {
if (i + 1 < text.length && text.charAt(i + 1) === '\n') {
return '\r\n';
}
return '\r';
}
else if (ch === '\n') {
return '\n';
}
}
return (options && options.eol) || '\n';
}
function isEOL(text, offset) {
return '\r\n'.indexOf(text.charAt(offset)) !== -1;
}
exports.isEOL = isEOL;
});
//# sourceMappingURL=format.js.map

View file

@ -1,289 +0,0 @@
export declare enum ScanError {
None = 0,
UnexpectedEndOfComment = 1,
UnexpectedEndOfString = 2,
UnexpectedEndOfNumber = 3,
InvalidUnicode = 4,
InvalidEscapeCharacter = 5,
InvalidCharacter = 6,
}
export declare enum SyntaxKind {
Unknown = 0,
OpenBraceToken = 1,
CloseBraceToken = 2,
OpenBracketToken = 3,
CloseBracketToken = 4,
CommaToken = 5,
ColonToken = 6,
NullKeyword = 7,
TrueKeyword = 8,
FalseKeyword = 9,
StringLiteral = 10,
NumericLiteral = 11,
LineCommentTrivia = 12,
BlockCommentTrivia = 13,
LineBreakTrivia = 14,
Trivia = 15,
EOF = 16,
}
/**
* The scanner object, representing a JSON scanner at a position in the input string.
*/
export interface JSONScanner {
/**
* Sets the scan position to a new offset. A call to 'scan' is needed to get the first token.
*/
setPosition(pos: number): void;
/**
* Read the next token. Returns the tolen code.
*/
scan(): SyntaxKind;
/**
* Returns the current scan position, which is after the last read token.
*/
getPosition(): number;
/**
* Returns the last read token.
*/
getToken(): SyntaxKind;
/**
* Returns the last read token value. The value for strings is the decoded string content. For numbers its of type number, for boolean it's true or false.
*/
getTokenValue(): string;
/**
* The start offset of the last read token.
*/
getTokenOffset(): number;
/**
* The length of the last read token.
*/
getTokenLength(): number;
/**
* An error code of the last scan.
*/
getTokenError(): ScanError;
}
/**
* Creates a JSON scanner on the given text.
* If ignoreTrivia is set, whitespaces or comments are ignored.
*/
export declare function createScanner(text: string, ignoreTrivia?: boolean): JSONScanner;
/**
* Takes JSON with JavaScript-style comments and remove
* them. Optionally replaces every none-newline character
* of comments with a replaceCharacter
*/
export declare function stripComments(text: string, replaceCh?: string): string;
export interface ParseError {
error: ParseErrorCode;
offset: number;
length: number;
}
export declare enum ParseErrorCode {
InvalidSymbol = 0,
InvalidNumberFormat = 1,
PropertyNameExpected = 2,
ValueExpected = 3,
ColonExpected = 4,
CommaExpected = 5,
CloseBraceExpected = 6,
CloseBracketExpected = 7,
EndOfFileExpected = 8,
InvalidCommentToken = 9,
UnexpectedEndOfComment = 10,
UnexpectedEndOfString = 11,
UnexpectedEndOfNumber = 12,
InvalidUnicode = 13,
InvalidEscapeCharacter = 14,
InvalidCharacter = 15,
}
export declare type NodeType = 'object' | 'array' | 'property' | 'string' | 'number' | 'boolean' | 'null';
export interface Node {
type: NodeType;
value?: any;
offset: number;
length: number;
columnOffset?: number;
parent?: Node;
children?: Node[];
}
export declare type Segment = string | number;
export declare type JSONPath = Segment[];
export interface Location {
/**
* The previous property key or literal value (string, number, boolean or null) or undefined.
*/
previousNode?: Node;
/**
* The path describing the location in the JSON document. The path consists of a sequence strings
* representing an object property or numbers for array indices.
*/
path: JSONPath;
/**
* Matches the locations path against a pattern consisting of strings (for properties) and numbers (for array indices).
* '*' will match a single segment, of any property name or index.
* '**' will match a sequece of segments or no segment, of any property name or index.
*/
matches: (patterns: JSONPath) => boolean;
/**
* If set, the location's offset is at a property key.
*/
isAtPropertyKey: boolean;
}
/**
* For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.
*/
export declare function getLocation(text: string, position: number): Location;
export interface ParseOptions {
disallowComments?: boolean;
allowTrailingComma?: boolean;
}
/**
* Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
* Therefore always check the errors list to find out if the input was valid.
*/
export declare function parse(text: string, errors?: ParseError[], options?: ParseOptions): any;
/**
* Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
*/
export declare function parseTree(text: string, errors?: ParseError[], options?: ParseOptions): Node;
/**
* Finds the node at the given path in a JSON DOM.
*/
export declare function findNodeAtLocation(root: Node, path: JSONPath): Node | undefined;
/**
* Evaluates the JavaScript object of the given JSON DOM node
*/
export declare function getNodeValue(node: Node): any;
/**
* Parses the given text and invokes the visitor functions for each object, array and literal reached.
*/
export declare function visit(text: string, visitor: JSONVisitor, options?: ParseOptions): any;
export interface JSONVisitor {
/**
* Invoked when an open brace is encountered and an object is started. The offset and length represent the location of the open brace.
*/
onObjectBegin?: (offset: number, length: number) => void;
/**
* Invoked when a property is encountered. The offset and length represent the location of the property name.
*/
onObjectProperty?: (property: string, offset: number, length: number) => void;
/**
* Invoked when a closing brace is encountered and an object is completed. The offset and length represent the location of the closing brace.
*/
onObjectEnd?: (offset: number, length: number) => void;
/**
* Invoked when an open bracket is encountered. The offset and length represent the location of the open bracket.
*/
onArrayBegin?: (offset: number, length: number) => void;
/**
* Invoked when a closing bracket is encountered. The offset and length represent the location of the closing bracket.
*/
onArrayEnd?: (offset: number, length: number) => void;
/**
* Invoked when a literal value is encountered. The offset and length represent the location of the literal value.
*/
onLiteralValue?: (value: any, offset: number, length: number) => void;
/**
* Invoked when a comma or colon separator is encountered. The offset and length represent the location of the separator.
*/
onSeparator?: (character: string, offset: number, length: number) => void;
/**
* When comments are allowed, invoked when a line or block comment is encountered. The offset and length represent the location of the comment.
*/
onComment?: (offset: number, length: number) => void;
/**
* Invoked on an error.
*/
onError?: (error: ParseErrorCode, offset: number, length: number) => void;
}
/**
* Represents a text modification
*/
export interface Edit {
/**
* The start offset of the modification.
*/
offset: number;
/**
* The length of the modification. Must not be negative. Empty length represents an *insert*.
*/
length: number;
/**
* The new content. Empty content represents a *remove*.
*/
content: string;
}
/**
* A text range in the document
*/
export interface Range {
/**
* The start offset of the range.
*/
offset: number;
/**
* The length of the range. Must not be negative.
*/
length: number;
}
export interface FormattingOptions {
/**
* If indentation is based on spaces (`insertSpaces` = true), then what is the number of spaces that make an indent?
*/
tabSize?: number;
/**
* Is indentation based on spaces?
*/
insertSpaces?: boolean;
/**
* The default 'end of line' character. If not set, '\n' is used as default.
*/
eol?: string;
}
/**
* Computes the edits needed to format a JSON document.
*
* @param documentText The input text
* @param range The range to format or `undefined` to format the full content
* @param options The formatting options
* @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
* removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
* text in the original document. However, multiple edits can have
* the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
* To apply edits to an input, you can use `applyEdits`
*/
export declare function format(documentText: string, range: Range | undefined, options: FormattingOptions): Edit[];
/**
* Options used when computing the modification edits
*/
export interface ModificationOptions {
/**
* Formatting options
*/
formattingOptions: FormattingOptions;
/**
* Optional fucntion to define the insertion index given an existing list of properties.
*/
getInsertionIndex?: (properties: string[]) => number;
}
/**
* Computes the edits needed to modify a value in the JSON document.
*
* @param documentText The input text
* @param path The path of the value to change. The path represents either to the document root, a property or an array item.
* If the path points to an non-existing property or item, it will be created.
* @param value The new value for the specified property or item. If the value is undefined,
* the property or item will be removed.
* @param options Options
* @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
* removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
* text in the original document. However, multiple edits can have
* the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
* To apply edits to an input, you can use `applyEdits`
*/
export declare function modify(text: string, path: JSONPath, value: any, options: ModificationOptions): Edit[];
/**
* Applies edits to a input string.
*/
export declare function applyEdits(text: string, edits: Edit[]): string;

View file

@ -1,32 +0,0 @@
{
"name": "jsonc-parser",
"version": "1.0.3",
"description": "Scanner and parser for JSON with comments.",
"main": "./lib/umd/main.js",
"typings": "./lib/umd/main",
"module": "./lib/esm/main.js",
"author": "Microsoft Corporation",
"repository": {
"type": "git",
"url": "https://github.com/Microsoft/node-jsonc-parser"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/Microsoft/node-jsonc-parser/issues"
},
"devDependencies": {
"mocha": "^2.4.5",
"typescript": "^2.7.2",
"@types/node": "^7.0.43",
"@types/mocha": "^2.2.32",
"tslint": "^5.9.1"
},
"scripts": {
"prepare": "npm run compile",
"compile": "tsc -p ./src && tsc -p ./src/tsconfig.esm.json",
"watch": "tsc -w -p ./src",
"test": "npm run compile && mocha",
"preversion": "npm test",
"postversion": "git push && git push --tags"
}
}

View file

@ -1,31 +0,0 @@
THIRD-PARTY SOFTWARE NOTICES AND INFORMATION
For Microsoft vscode-languageserver
This project incorporates material from the project(s) listed below (collectively, “Third Party Code”).
Microsoft is not the original author of the Third Party Code. The original copyright notice and license
under which Microsoft received such Third Party Code are set out below. This Third Party Code is licensed
to you under their original license terms set forth below. Microsoft reserves all other rights not expressly
granted, whether by implication, estoppel or otherwise.
1. DefinitelyTyped version 0.0.1 (https://github.com/borisyankov/DefinitelyTyped)
This project is licensed under the MIT license.
Copyrights are respective of each contributor listed at the beginning of each definition file.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -1,98 +0,0 @@
import { TextDocument, Position, Range, CompletionList } from 'vscode-languageserver-types';
export interface EmmetConfiguration {
showExpandedAbbreviation?: string;
showAbbreviationSuggestions?: boolean;
syntaxProfiles?: object;
variables?: object;
preferences?: object;
excludeLanguages?: string[];
showSuggestionsAsSnippets?: boolean;
}
export interface ExpandOptions {
field: (index: any, placeholder: any) => string;
syntax: string;
profile: any;
addons: any;
variables: any;
snippets: any;
format: any;
preferences: any;
}
export declare function doComplete(document: TextDocument, position: Position, syntax: string, emmetConfig: EmmetConfiguration): CompletionList;
export declare const emmetSnippetField: (index: any, placeholder: any) => string;
export declare function isStyleSheet(syntax: any): boolean;
/**
* * Extracts abbreviation from the given position in the given document
* @param document The TextDocument from which abbreviation needs to be extracted
* @param position The Position in the given document from where abbreviation needs to be extracted
* @param options The options to pass to the @emmetio/extract-abbreviation module
*/
export declare function extractAbbreviation(document: TextDocument, position: Position, options?: boolean | {
lookAhead?: boolean;
syntax?: string;
}): {
abbreviation: string;
abbreviationRange: Range;
filter: string;
};
/**
* Extracts abbreviation from the given text
* @param text Text from which abbreviation needs to be extracted
* @param syntax Syntax used to extract the abbreviation from the given text
*/
export declare function extractAbbreviationFromText(text: string, syntax?: string): {
abbreviation: string;
filter: string;
};
/**
* Returns a boolean denoting validity of given abbreviation in the context of given syntax
* Not needed once https://github.com/emmetio/atom-plugin/issues/22 is fixed
* @param syntax string
* @param abbreviation string
*/
export declare function isAbbreviationValid(syntax: string, abbreviation: string): boolean;
/**
* Returns options to be used by the @emmetio/expand-abbreviation module
* @param syntax
* @param textToReplace
*/
export declare function getExpandOptions(syntax: string, emmetConfig?: object, filter?: string): ExpandOptions;
/**
* Parses given abbreviation using given options and returns a tree
* @param abbreviation string
* @param options options used by the @emmetio/expand-abbreviation module to parse given abbreviation
*/
export declare function parseAbbreviation(abbreviation: string, options: ExpandOptions): any;
/**
* Expands given abbreviation using given options
* @param abbreviation string or parsed abbreviation
* @param options options used by the @emmetio/expand-abbreviation module to expand given abbreviation
*/
export declare function expandAbbreviation(abbreviation: any, options: ExpandOptions): string;
/**
* Updates customizations from snippets.json and syntaxProfiles.json files in the directory configured in emmet.extensionsPath setting
*/
export declare function updateExtensionsPath(emmetExtensionsPath: string, workspaceFolderPath?: string): Promise<void>;
/**
* Get the corresponding emmet mode for given vscode language mode
* Eg: jsx for typescriptreact/javascriptreact or pug for jade
* If the language is not supported by emmet or has been exlcuded via `exlcudeLanguages` setting,
* then nothing is returned
*
* @param language
* @param exlcudedLanguages Array of language ids that user has chosen to exlcude for emmet
*/
export declare function getEmmetMode(language: string, excludedLanguages?: string[]): string;
/**
* Returns a completion participant for Emmet of the form {
* onCssProperty: () => void
* onCssPropertyValue: () => void
* onHtmlContent: () => void
* }
* @param document The TextDocument for which completions are being provided
* @param position The Position in the given document where completions are being provided
* @param syntax The Emmet syntax to use when providing Emmet completions
* @param emmetSettings The Emmet settings to use when providing Emmet completions
* @param result The Completion List object that needs to be updated with Emmet completions
*/
export declare function getEmmetCompletionParticipants(document: TextDocument, position: Position, syntax: string, emmetSettings: EmmetConfiguration, result: CompletionList): any;

View file

@ -1,952 +0,0 @@
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const vscode_languageserver_types_1 = require("vscode-languageserver-types");
const expand_full_1 = require("./expand/expand-full");
const extract = require("@emmetio/extract-abbreviation");
const path = require("path");
const fs = require("fs");
const JSONC = require("jsonc-parser");
const os_1 = require("os");
const data_1 = require("./data");
const snippetKeyCache = new Map();
let markupSnippetKeys;
let markupSnippetKeysRegex;
const stylesheetCustomSnippetsKeyCache = new Map();
const htmlAbbreviationStartRegex = /^[a-z,A-Z,!,(,[,#,\.]/;
const cssAbbreviationRegex = /^-?[a-z,A-Z,!,@,#]/;
const htmlAbbreviationRegex = /[a-z,A-Z\.]/;
const emmetModes = ['html', 'pug', 'slim', 'haml', 'xml', 'xsl', 'jsx', 'css', 'scss', 'sass', 'less', 'stylus'];
const commonlyUsedTags = [...data_1.htmlData.tags, 'lorem'];
const bemFilterSuffix = 'bem';
const filterDelimitor = '|';
const trimFilterSuffix = 't';
const commentFilterSuffix = 'c';
const maxFilters = 3;
const vendorPrefixes = { 'w': "webkit", 'm': "moz", 's': "ms", 'o': "o" };
const defaultVendorProperties = {
'w': "animation, animation-delay, animation-direction, animation-duration, animation-fill-mode, animation-iteration-count, animation-name, animation-play-state, animation-timing-function, appearance, backface-visibility, background-clip, background-composite, background-origin, background-size, border-fit, border-horizontal-spacing, border-image, border-vertical-spacing, box-align, box-direction, box-flex, box-flex-group, box-lines, box-ordinal-group, box-orient, box-pack, box-reflect, box-shadow, color-correction, column-break-after, column-break-before, column-break-inside, column-count, column-gap, column-rule-color, column-rule-style, column-rule-width, column-span, column-width, dashboard-region, font-smoothing, highlight, hyphenate-character, hyphenate-limit-after, hyphenate-limit-before, hyphens, line-box-contain, line-break, line-clamp, locale, margin-before-collapse, margin-after-collapse, marquee-direction, marquee-increment, marquee-repetition, marquee-style, mask-attachment, mask-box-image, mask-box-image-outset, mask-box-image-repeat, mask-box-image-slice, mask-box-image-source, mask-box-image-width, mask-clip, mask-composite, mask-image, mask-origin, mask-position, mask-repeat, mask-size, nbsp-mode, perspective, perspective-origin, rtl-ordering, text-combine, text-decorations-in-effect, text-emphasis-color, text-emphasis-position, text-emphasis-style, text-fill-color, text-orientation, text-security, text-stroke-color, text-stroke-width, transform, transition, transform-origin, transform-style, transition-delay, transition-duration, transition-property, transition-timing-function, user-drag, user-modify, user-select, writing-mode, svg-shadow, box-sizing, border-radius",
'm': "animation-delay, animation-direction, animation-duration, animation-fill-mode, animation-iteration-count, animation-name, animation-play-state, animation-timing-function, appearance, backface-visibility, background-inline-policy, binding, border-bottom-colors, border-image, border-left-colors, border-right-colors, border-top-colors, box-align, box-direction, box-flex, box-ordinal-group, box-orient, box-pack, box-shadow, box-sizing, column-count, column-gap, column-rule-color, column-rule-style, column-rule-width, column-width, float-edge, font-feature-settings, font-language-override, force-broken-image-icon, hyphens, image-region, orient, outline-radius-bottomleft, outline-radius-bottomright, outline-radius-topleft, outline-radius-topright, perspective, perspective-origin, stack-sizing, tab-size, text-blink, text-decoration-color, text-decoration-line, text-decoration-style, text-size-adjust, transform, transform-origin, transform-style, transition, transition-delay, transition-duration, transition-property, transition-timing-function, user-focus, user-input, user-modify, user-select, window-shadow, background-clip, border-radius",
's': "accelerator, backface-visibility, background-position-x, background-position-y, behavior, block-progression, box-align, box-direction, box-flex, box-line-progression, box-lines, box-ordinal-group, box-orient, box-pack, content-zoom-boundary, content-zoom-boundary-max, content-zoom-boundary-min, content-zoom-chaining, content-zoom-snap, content-zoom-snap-points, content-zoom-snap-type, content-zooming, filter, flow-from, flow-into, font-feature-settings, grid-column, grid-column-align, grid-column-span, grid-columns, grid-layer, grid-row, grid-row-align, grid-row-span, grid-rows, high-contrast-adjust, hyphenate-limit-chars, hyphenate-limit-lines, hyphenate-limit-zone, hyphens, ime-mode, interpolation-mode, layout-flow, layout-grid, layout-grid-char, layout-grid-line, layout-grid-mode, layout-grid-type, line-break, overflow-style, perspective, perspective-origin, perspective-origin-x, perspective-origin-y, scroll-boundary, scroll-boundary-bottom, scroll-boundary-left, scroll-boundary-right, scroll-boundary-top, scroll-chaining, scroll-rails, scroll-snap-points-x, scroll-snap-points-y, scroll-snap-type, scroll-snap-x, scroll-snap-y, scrollbar-arrow-color, scrollbar-base-color, scrollbar-darkshadow-color, scrollbar-face-color, scrollbar-highlight-color, scrollbar-shadow-color, scrollbar-track-color, text-align-last, text-autospace, text-justify, text-kashida-space, text-overflow, text-size-adjust, text-underline-position, touch-action, transform, transform-origin, transform-origin-x, transform-origin-y, transform-origin-z, transform-style, transition, transition-delay, transition-duration, transition-property, transition-timing-function, user-select, word-break, wrap-flow, wrap-margin, wrap-through, writing-mode",
'o': "dashboard-region, animation, animation-delay, animation-direction, animation-duration, animation-fill-mode, animation-iteration-count, animation-name, animation-play-state, animation-timing-function, border-image, link, link-source, object-fit, object-position, tab-size, table-baseline, transform, transform-origin, transition, transition-delay, transition-duration, transition-property, transition-timing-function, accesskey, input-format, input-required, marquee-dir, marquee-loop, marquee-speed, marquee-style"
};
/**
* Returns all applicable emmet expansions for abbreviation at given position in a CompletionList
* @param document TextDocument in which completions are requested
* @param position Position in the document at which completions are requested
* @param syntax Emmet supported language
* @param emmetConfig Emmet Configurations as derived from VS Code
*/
function doComplete(document, position, syntax, emmetConfig) {
if (emmetConfig.showExpandedAbbreviation === 'never' || !getEmmetMode(syntax, emmetConfig.excludeLanguages)) {
return;
}
// Fetch markupSnippets so that we can provide possible abbreviation completions
// For example, when text at position is `a`, completions should return `a:blank`, `a:link`, `acr` etc.
if (!isStyleSheet(syntax)) {
if (!snippetKeyCache.has(syntax) || !markupSnippetKeysRegex || markupSnippetKeysRegex.length === 0) {
let registry = customSnippetRegistry[syntax] ? customSnippetRegistry[syntax] : expand_full_1.createSnippetsRegistry(syntax);
if (!snippetKeyCache.has(syntax)) {
snippetKeyCache.set(syntax, registry.all({ type: 'string' }).map(snippet => {
return snippet.key;
}));
}
markupSnippetKeysRegex = registry.all({ type: 'regexp' }).map(snippet => {
return snippet.key;
});
}
markupSnippetKeys = snippetKeyCache.get(syntax);
}
let extractedValue = extractAbbreviation(document, position, { syntax, lookAhead: !isStyleSheet(syntax) });
if (!extractedValue) {
return;
}
let { abbreviationRange, abbreviation, filter } = extractedValue;
let currentLineTillPosition = getCurrentLine(document, position).substr(0, position.character);
let currentWord = getCurrentWord(currentLineTillPosition);
// Dont attempt to expand open tags
if (currentWord === abbreviation
&& currentLineTillPosition.endsWith(`<${abbreviation}`)
&& (syntax === 'html' || syntax === 'xml' || syntax === 'xsl' || syntax === 'jsx')) {
return;
}
// `preferences` is supported in Emmet config to allow backward compatibility
// `getExpandOptions` converts it into a format understandable by new modules
// We retain a copy here to be used by the vendor prefixing feature
let expandOptions = getExpandOptions(syntax, emmetConfig, filter);
let preferences = expandOptions['preferences'];
delete expandOptions['preferences'];
let expandedText;
let expandedAbbr;
let completionItems = [];
// Create completion item after expanding given abbreviation
// if abbreviation is valid and expanded value is not noise
const createExpandedAbbr = (syntax, abbr) => {
if (!isAbbreviationValid(syntax, abbreviation)) {
return;
}
try {
expandedText = expand_full_1.expand(abbr, expandOptions);
}
catch (e) {
}
if (!expandedText || isExpandedTextNoise(syntax, abbr, expandedText)) {
return;
}
expandedAbbr = vscode_languageserver_types_1.CompletionItem.create(abbr);
expandedAbbr.textEdit = vscode_languageserver_types_1.TextEdit.replace(abbreviationRange, escapeNonTabStopDollar(addFinalTabStop(expandedText)));
expandedAbbr.documentation = replaceTabStopsWithCursors(expandedText);
expandedAbbr.insertTextFormat = vscode_languageserver_types_1.InsertTextFormat.Snippet;
expandedAbbr.detail = 'Emmet Abbreviation';
expandedAbbr.label = abbreviation;
expandedAbbr.label += filter ? '|' + filter.replace(',', '|') : "";
completionItems = [expandedAbbr];
};
if (isStyleSheet(syntax)) {
let { prefixOptions, abbreviationWithoutPrefix } = splitVendorPrefix(abbreviation);
createExpandedAbbr(syntax, abbreviationWithoutPrefix);
// When abbr is longer than usual emmet snippets and matches better with existing css property, then no emmet
if (abbreviationWithoutPrefix.length > 4
&& data_1.cssData.properties.find(x => x.startsWith(abbreviationWithoutPrefix))) {
return vscode_languageserver_types_1.CompletionList.create([], true);
}
if (expandedAbbr) {
let prefixedExpandedText = applyVendorPrefixes(expandedText, prefixOptions, preferences);
expandedAbbr.textEdit = vscode_languageserver_types_1.TextEdit.replace(abbreviationRange, escapeNonTabStopDollar(addFinalTabStop(prefixedExpandedText)));
expandedAbbr.documentation = replaceTabStopsWithCursors(prefixedExpandedText);
expandedAbbr.label = removeTabStops(expandedText);
expandedAbbr.filterText = abbreviation;
// Custom snippets should show up in completions if abbreviation is a prefix
const stylesheetCustomSnippetsKeys = stylesheetCustomSnippetsKeyCache.has(syntax) ? stylesheetCustomSnippetsKeyCache.get(syntax) : stylesheetCustomSnippetsKeyCache.get('css');
completionItems = makeSnippetSuggestion(stylesheetCustomSnippetsKeys, abbreviation, abbreviation, abbreviationRange, expandOptions, 'Emmet Custom Snippet', false);
if (!completionItems.find(x => x.textEdit.newText === expandedAbbr.textEdit.newText)) {
// Fix for https://github.com/Microsoft/vscode/issues/28933#issuecomment-309236902
// When user types in propertyname, emmet uses it to match with snippet names, resulting in width -> widows or font-family -> font: family
// Filter out those cases here.
const abbrRegex = new RegExp('.*' + abbreviationWithoutPrefix.split('').map(x => (x === '$' || x === '+') ? '\\' + x : x).join('.*') + '.*', 'i');
if (/\d/.test(abbreviation) || abbrRegex.test(expandedAbbr.label)) {
completionItems.push(expandedAbbr);
}
}
}
// Incomplete abbreviations that use vendor prefix
if (!completionItems.length && (abbreviation === '-' || /^-[wmso]{1,4}-?$/.test(abbreviation))) {
return vscode_languageserver_types_1.CompletionList.create([], true);
}
}
else {
createExpandedAbbr(syntax, abbreviation);
let tagToFindMoreSuggestionsFor = abbreviation;
let newTagMatches = abbreviation.match(/(>|\+)([\w:-]+)$/);
if (newTagMatches && newTagMatches.length === 3) {
tagToFindMoreSuggestionsFor = newTagMatches[2];
}
let commonlyUsedTagSuggestions = makeSnippetSuggestion(commonlyUsedTags, tagToFindMoreSuggestionsFor, abbreviation, abbreviationRange, expandOptions, 'Emmet Abbreviation');
completionItems = completionItems.concat(commonlyUsedTagSuggestions);
if (emmetConfig.showAbbreviationSuggestions === true) {
let abbreviationSuggestions = makeSnippetSuggestion(markupSnippetKeys.filter(x => !commonlyUsedTags.includes(x)), tagToFindMoreSuggestionsFor, abbreviation, abbreviationRange, expandOptions, 'Emmet Abbreviation');
// Workaround for the main expanded abbr not appearing before the snippet suggestions
if (expandedAbbr && abbreviationSuggestions.length > 0 && tagToFindMoreSuggestionsFor !== abbreviation) {
expandedAbbr.sortText = '0' + expandedAbbr.label;
abbreviationSuggestions.forEach(item => {
// Workaround for snippet suggestions items getting filtered out as the complete abbr does not start with snippetKey
item.filterText = abbreviation;
// Workaround for the main expanded abbr not appearing before the snippet suggestions
item.sortText = '9' + abbreviation;
});
}
completionItems = completionItems.concat(abbreviationSuggestions);
}
}
if (emmetConfig.showSuggestionsAsSnippets === true) {
completionItems.forEach(x => x.kind = vscode_languageserver_types_1.CompletionItemKind.Snippet);
}
return completionItems.length ? vscode_languageserver_types_1.CompletionList.create(completionItems, true) : undefined;
}
exports.doComplete = doComplete;
/**
* Create & return snippets for snippet keys that start with given prefix
*/
function makeSnippetSuggestion(snippetKeys, prefix, abbreviation, abbreviationRange, expandOptions, snippetDetail, skipFullMatch = true) {
if (!prefix || !snippetKeys) {
return [];
}
let snippetCompletions = [];
snippetKeys.forEach(snippetKey => {
if (!snippetKey.startsWith(prefix.toLowerCase()) || (skipFullMatch && snippetKey === prefix.toLowerCase())) {
return;
}
let currentAbbr = abbreviation + snippetKey.substr(prefix.length);
let expandedAbbr;
try {
expandedAbbr = expand_full_1.expand(currentAbbr, expandOptions);
}
catch (e) {
}
if (!expandedAbbr) {
return;
}
let item = vscode_languageserver_types_1.CompletionItem.create(prefix + snippetKey.substr(prefix.length));
item.documentation = replaceTabStopsWithCursors(expandedAbbr);
item.detail = snippetDetail;
item.textEdit = vscode_languageserver_types_1.TextEdit.replace(abbreviationRange, escapeNonTabStopDollar(addFinalTabStop(expandedAbbr)));
item.insertTextFormat = vscode_languageserver_types_1.InsertTextFormat.Snippet;
snippetCompletions.push(item);
});
return snippetCompletions;
}
function getCurrentWord(currentLineTillPosition) {
if (currentLineTillPosition) {
let matches = currentLineTillPosition.match(/[\w,:,-,\.]*$/);
if (matches) {
return matches[0];
}
}
}
function replaceTabStopsWithCursors(expandedWord) {
return expandedWord.replace(/([^\\])\$\{\d+\}/g, '$1|').replace(/\$\{\d+:([^\}]+)\}/g, '$1');
}
function removeTabStops(expandedWord) {
return expandedWord.replace(/([^\\])\$\{\d+\}/g, '$1').replace(/\$\{\d+:([^\}]+)\}/g, '$1');
}
function escapeNonTabStopDollar(text) {
return text ? text.replace(/([^\\])(\$)([^\{])/g, '$1\\$2$3') : text;
}
function addFinalTabStop(text) {
if (!text || !text.trim()) {
return text;
}
let maxTabStop = -1;
let maxTabStopRanges = [];
let foundLastStop = false;
let replaceWithLastStop = false;
let i = 0;
let n = text.length;
try {
while (i < n && !foundLastStop) {
// Look for ${
if (text[i++] != '$' || text[i++] != '{') {
continue;
}
// Find tabstop
let numberStart = -1;
let numberEnd = -1;
while (i < n && /\d/.test(text[i])) {
numberStart = numberStart < 0 ? i : numberStart;
numberEnd = i + 1;
i++;
}
// If ${ was not followed by a number and either } or :, then its not a tabstop
if (numberStart === -1 || numberEnd === -1 || i >= n || (text[i] != '}' && text[i] != ':')) {
continue;
}
// If ${0} was found, then break
const currentTabStop = text.substring(numberStart, numberEnd);
foundLastStop = currentTabStop === '0';
if (foundLastStop) {
break;
}
let foundPlaceholder = false;
if (text[i++] == ':') {
// TODO: Nested placeholders may break here
while (i < n) {
if (text[i] == '}') {
foundPlaceholder = true;
break;
}
i++;
}
}
// Decide to replace currentTabStop with ${0} only if its the max among all tabstops and is not a placeholder
if (Number(currentTabStop) > Number(maxTabStop)) {
maxTabStop = currentTabStop;
maxTabStopRanges = [{ numberStart, numberEnd }];
replaceWithLastStop = !foundPlaceholder;
}
else if (currentTabStop == maxTabStop) {
maxTabStopRanges.push({ numberStart, numberEnd });
}
}
}
catch (e) {
}
if (replaceWithLastStop && !foundLastStop) {
for (let i = 0; i < maxTabStopRanges.length; i++) {
let rangeStart = maxTabStopRanges[i].numberStart;
let rangeEnd = maxTabStopRanges[i].numberEnd;
text = text.substr(0, rangeStart) + '0' + text.substr(rangeEnd);
}
}
return text;
}
function getCurrentLine(document, position) {
let offset = document.offsetAt(position);
let text = document.getText();
let start = 0;
let end = text.length;
for (let i = offset - 1; i >= 0; i--) {
if (text[i] === '\n') {
start = i + 1;
break;
}
}
for (let i = offset; i < text.length; i++) {
if (text[i] === '\n') {
end = i;
break;
}
}
return text.substring(start, end);
}
let customSnippetRegistry = {};
let variablesFromFile = {};
let profilesFromFile = {};
exports.emmetSnippetField = (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`;
function isStyleSheet(syntax) {
let stylesheetSyntaxes = ['css', 'scss', 'sass', 'less', 'stylus'];
return (stylesheetSyntaxes.indexOf(syntax) > -1);
}
exports.isStyleSheet = isStyleSheet;
function getFilters(text, pos) {
let filter;
for (let i = 0; i < maxFilters; i++) {
if (text.endsWith(`${filterDelimitor}${bemFilterSuffix}`, pos)) {
pos -= bemFilterSuffix.length + 1;
filter = filter ? bemFilterSuffix + ',' + filter : bemFilterSuffix;
}
else if (text.endsWith(`${filterDelimitor}${commentFilterSuffix}`, pos)) {
pos -= commentFilterSuffix.length + 1;
filter = filter ? commentFilterSuffix + ',' + filter : commentFilterSuffix;
}
else if (text.endsWith(`${filterDelimitor}${trimFilterSuffix}`, pos)) {
pos -= trimFilterSuffix.length + 1;
filter = filter ? trimFilterSuffix + ',' + filter : trimFilterSuffix;
}
else {
break;
}
}
return {
pos: pos,
filter: filter
};
}
/**
* * Extracts abbreviation from the given position in the given document
* @param document The TextDocument from which abbreviation needs to be extracted
* @param position The Position in the given document from where abbreviation needs to be extracted
* @param options The options to pass to the @emmetio/extract-abbreviation module
*/
function extractAbbreviation(document, position, options) {
const currentLine = getCurrentLine(document, position);
const currentLineTillPosition = currentLine.substr(0, position.character);
const { pos, filter } = getFilters(currentLineTillPosition, position.character);
const lengthOccupiedByFilter = filter ? filter.length + 1 : 0;
try {
let extractOptions = options;
if (typeof extractOptions !== 'boolean') {
extractOptions = extractOptions || {};
extractOptions = {
syntax: (isStyleSheet(extractOptions.syntax) || extractOptions.syntax === 'stylesheet') ? 'stylesheet' : 'markup',
lookAhead: extractOptions.lookAhead
};
}
const result = extract(currentLine, pos, extractOptions);
const rangeToReplace = vscode_languageserver_types_1.Range.create(position.line, result.location, position.line, result.location + result.abbreviation.length + lengthOccupiedByFilter);
return {
abbreviationRange: rangeToReplace,
abbreviation: result.abbreviation,
filter
};
}
catch (e) {
}
}
exports.extractAbbreviation = extractAbbreviation;
/**
* Extracts abbreviation from the given text
* @param text Text from which abbreviation needs to be extracted
* @param syntax Syntax used to extract the abbreviation from the given text
*/
function extractAbbreviationFromText(text, syntax) {
if (!text) {
return;
}
const { pos, filter } = getFilters(text, text.length);
try {
let extractOptions = (isStyleSheet(syntax) || syntax === 'stylesheet') ? { syntax: 'stylesheet', lookAhead: false } : true;
const result = extract(text, pos, extractOptions);
return {
abbreviation: result.abbreviation,
filter
};
}
catch (e) {
}
}
exports.extractAbbreviationFromText = extractAbbreviationFromText;
/**
* Returns a boolean denoting validity of given abbreviation in the context of given syntax
* Not needed once https://github.com/emmetio/atom-plugin/issues/22 is fixed
* @param syntax string
* @param abbreviation string
*/
function isAbbreviationValid(syntax, abbreviation) {
if (!abbreviation) {
return false;
}
if (isStyleSheet(syntax)) {
// Fix for https://github.com/Microsoft/vscode/issues/1623 in new emmet
if (abbreviation.endsWith(':')) {
return false;
}
if (abbreviation.indexOf('#') > -1) {
return hexColorRegex.test(abbreviation) || propertyHexColorRegex.test(abbreviation);
}
return cssAbbreviationRegex.test(abbreviation);
}
if (abbreviation.startsWith('!')) {
return !/[^!]/.test(abbreviation);
}
const multipleMatch = abbreviation.match(/\*(\d+)$/);
if (multipleMatch) {
return parseInt(multipleMatch[1], 10) <= 100;
}
// Its common for users to type (sometextinsidebrackets), this should not be treated as an abbreviation
// Grouping in abbreviation is valid only if it's inside a text node or preceeded/succeeded with one of the symbols for nesting, sibling, repeater or climb up
if ((/\(/.test(abbreviation) || /\)/.test(abbreviation)) && !/\{[^\}\{]*[\(\)]+[^\}\{]*\}(?:[>\+\*\^]|$)/.test(abbreviation) && !/\(.*\)[>\+\*\^]/.test(abbreviation) && !/[>\+\*\^]\(.*\)/.test(abbreviation)) {
return false;
}
return (htmlAbbreviationStartRegex.test(abbreviation) && htmlAbbreviationRegex.test(abbreviation));
}
exports.isAbbreviationValid = isAbbreviationValid;
function isExpandedTextNoise(syntax, abbreviation, expandedText) {
// Unresolved css abbreviations get expanded to a blank property value
// Eg: abc -> abc: ; or abc:d -> abc: d; which is noise if it gets suggested for every word typed
if (isStyleSheet(syntax)) {
let after = (syntax === 'sass' || syntax === 'stylus') ? '' : ';';
return expandedText === `${abbreviation}: \${1}${after}` || expandedText.replace(/\s/g, '') === abbreviation.replace(/\s/g, '') + after;
}
if (commonlyUsedTags.indexOf(abbreviation.toLowerCase()) > -1 || markupSnippetKeys.indexOf(abbreviation) > -1) {
return false;
}
// Custom tags can have - or :
if (/[-,:]/.test(abbreviation) && !/--|::/.test(abbreviation) && !abbreviation.endsWith(':')) {
return false;
}
// Its common for users to type some text and end it with period, this should not be treated as an abbreviation
// Else it becomes noise.
// When user just types '.', return the expansion
// Otherwise emmet loses change to participate later
// For example in `.foo`. See https://github.com/Microsoft/vscode/issues/66013
if (abbreviation === '.') {
return false;
}
const dotMatches = abbreviation.match(/^([a-z,A-Z,\d]*)\.$/);
if (dotMatches) {
// Valid html tags such as `div.`
if (dotMatches[1] && data_1.htmlData.tags.includes(dotMatches[1])) {
return false;
}
return true;
}
// Unresolved html abbreviations get expanded as if it were a tag
// Eg: abc -> <abc></abc> which is noise if it gets suggested for every word typed
return (expandedText.toLowerCase() === `<${abbreviation.toLowerCase()}>\${1}</${abbreviation.toLowerCase()}>`);
}
/**
* Returns options to be used by the @emmetio/expand-abbreviation module
* @param syntax
* @param textToReplace
*/
function getExpandOptions(syntax, emmetConfig, filter) {
emmetConfig = emmetConfig || {};
emmetConfig['preferences'] = emmetConfig['preferences'] || {};
// Fetch snippet registry
let baseSyntax = isStyleSheet(syntax) ? 'css' : 'html';
if (!customSnippetRegistry[syntax] && customSnippetRegistry[baseSyntax]) {
customSnippetRegistry[syntax] = customSnippetRegistry[baseSyntax];
}
// Fetch Profile
let profile = getProfile(syntax, emmetConfig['syntaxProfiles']);
let filtersFromProfile = (profile && profile['filters']) ? profile['filters'].split(',') : [];
filtersFromProfile = filtersFromProfile.map(filterFromProfile => filterFromProfile.trim());
// Update profile based on preferences
if (emmetConfig['preferences']['format.noIndentTags']) {
if (Array.isArray(emmetConfig['preferences']['format.noIndentTags'])) {
profile['formatSkip'] = emmetConfig['preferences']['format.noIndentTags'];
}
else if (typeof emmetConfig['preferences']['format.noIndentTags'] === 'string') {
profile['formatSkip'] = emmetConfig['preferences']['format.noIndentTags'].split(',');
}
}
if (emmetConfig['preferences']['format.forceIndentationForTags']) {
if (Array.isArray(emmetConfig['preferences']['format.forceIndentationForTags'])) {
profile['formatForce'] = emmetConfig['preferences']['format.forceIndentationForTags'];
}
else if (typeof emmetConfig['preferences']['format.forceIndentationForTags'] === 'string') {
profile['formatForce'] = emmetConfig['preferences']['format.forceIndentationForTags'].split(',');
}
}
if (emmetConfig['preferences']['profile.allowCompactBoolean'] && typeof emmetConfig['preferences']['profile.allowCompactBoolean'] === 'boolean') {
profile['compactBooleanAttributes'] = emmetConfig['preferences']['profile.allowCompactBoolean'];
}
// Fetch Add Ons
let addons = {};
if (filter && filter.split(',').find(x => x.trim() === 'bem') || filtersFromProfile.indexOf('bem') > -1) {
addons['bem'] = { element: '__' };
if (emmetConfig['preferences']['bem.elementSeparator']) {
addons['bem']['element'] = emmetConfig['preferences']['bem.elementSeparator'];
}
if (emmetConfig['preferences']['bem.modifierSeparator']) {
addons['bem']['modifier'] = emmetConfig['preferences']['bem.modifierSeparator'];
}
}
if (syntax === 'jsx') {
addons['jsx'] = true;
}
// Fetch Formatters
let formatters = getFormatters(syntax, emmetConfig['preferences']);
if (filter && filter.split(',').find(x => x.trim() === 'c') || filtersFromProfile.indexOf('c') > -1) {
if (!formatters['comment']) {
formatters['comment'] = {
enabled: true
};
}
else {
formatters['comment']['enabled'] = true;
}
}
// If the user doesn't provide specific properties for a vendor, use the default values
let preferences = emmetConfig['preferences'];
for (const v in vendorPrefixes) {
let vendorProperties = preferences['css.' + vendorPrefixes[v] + 'Properties'];
if (vendorProperties == null) {
preferences['css.' + vendorPrefixes[v] + 'Properties'] = defaultVendorProperties[v];
}
}
return {
field: exports.emmetSnippetField,
syntax: syntax,
profile: profile,
addons: addons,
variables: getVariables(emmetConfig['variables']),
snippets: customSnippetRegistry[syntax],
format: formatters,
preferences: preferences
};
}
exports.getExpandOptions = getExpandOptions;
function splitVendorPrefix(abbreviation) {
abbreviation = abbreviation || "";
if (abbreviation[0] != '-') {
return {
prefixOptions: "",
abbreviationWithoutPrefix: abbreviation
};
}
else {
abbreviation = abbreviation.substr(1);
let pref = "-";
if (/^[wmso]*-./.test(abbreviation)) {
let index = abbreviation.indexOf("-");
if (index > -1) {
pref += abbreviation.substr(0, index + 1);
abbreviation = abbreviation.substr(index + 1);
}
}
return {
prefixOptions: pref,
abbreviationWithoutPrefix: abbreviation
};
}
}
function applyVendorPrefixes(expandedProperty, vendors, preferences) {
preferences = preferences || {};
expandedProperty = expandedProperty || "";
vendors = vendors || "";
if (vendors[0] !== '-') {
return expandedProperty;
}
if (vendors == "-") {
let defaultVendors = "-";
let property = expandedProperty.substr(0, expandedProperty.indexOf(':'));
if (!property) {
return expandedProperty;
}
for (const v in vendorPrefixes) {
let vendorProperties = preferences['css.' + vendorPrefixes[v] + 'Properties'];
if (vendorProperties && vendorProperties.split(',').find(x => x.trim() === property))
defaultVendors += v;
}
// If no vendors specified, add all
vendors = defaultVendors == "-" ? "-wmso" : defaultVendors;
vendors += '-';
}
vendors = vendors.substr(1);
let prefixedProperty = "";
for (let index = 0; index < vendors.length - 1; index++) {
prefixedProperty += '-' + vendorPrefixes[vendors[index]] + '-' + expandedProperty + "\n";
}
return prefixedProperty + expandedProperty;
}
/**
* Parses given abbreviation using given options and returns a tree
* @param abbreviation string
* @param options options used by the @emmetio/expand-abbreviation module to parse given abbreviation
*/
function parseAbbreviation(abbreviation, options) {
return expand_full_1.parse(abbreviation, options);
}
exports.parseAbbreviation = parseAbbreviation;
/**
* Expands given abbreviation using given options
* @param abbreviation string or parsed abbreviation
* @param options options used by the @emmetio/expand-abbreviation module to expand given abbreviation
*/
function expandAbbreviation(abbreviation, options) {
let expandedText;
let preferences = options['preferences'];
delete options['preferences'];
if (isStyleSheet(options['syntax']) && typeof abbreviation === 'string') {
let { prefixOptions, abbreviationWithoutPrefix } = splitVendorPrefix(abbreviation);
expandedText = expand_full_1.expand(abbreviationWithoutPrefix, options);
expandedText = applyVendorPrefixes(expandedText, prefixOptions, preferences);
}
else {
expandedText = expand_full_1.expand(abbreviation, options);
}
return escapeNonTabStopDollar(addFinalTabStop(expandedText));
}
exports.expandAbbreviation = expandAbbreviation;
/**
* Maps and returns syntaxProfiles of previous format to ones compatible with new emmet modules
* @param syntax
*/
function getProfile(syntax, profilesFromSettings) {
if (!profilesFromSettings) {
profilesFromSettings = {};
}
let profilesConfig = Object.assign({}, profilesFromFile, profilesFromSettings);
let options = profilesConfig[syntax];
if (!options || typeof options === 'string') {
if (options === 'xhtml') {
return {
selfClosingStyle: 'xhtml'
};
}
return {};
}
let newOptions = {};
for (let key in options) {
switch (key) {
case 'tag_case':
newOptions['tagCase'] = (options[key] === 'lower' || options[key] === 'upper') ? options[key] : '';
break;
case 'attr_case':
newOptions['attributeCase'] = (options[key] === 'lower' || options[key] === 'upper') ? options[key] : '';
break;
case 'attr_quotes':
newOptions['attributeQuotes'] = options[key];
break;
case 'tag_nl':
newOptions['format'] = (options[key] === true || options[key] === false) ? options[key] : true;
break;
case 'inline_break':
newOptions['inlineBreak'] = options[key];
break;
case 'self_closing_tag':
if (options[key] === true) {
newOptions['selfClosingStyle'] = 'xml';
break;
}
if (options[key] === false) {
newOptions['selfClosingStyle'] = 'html';
break;
}
newOptions['selfClosingStyle'] = options[key];
break;
case 'compact_bool':
newOptions['compactBooleanAttributes'] = options[key];
break;
default:
newOptions[key] = options[key];
break;
}
}
return newOptions;
}
/**
* Returns variables to be used while expanding snippets
*/
function getVariables(variablesFromSettings) {
if (!variablesFromSettings) {
return variablesFromFile;
}
return Object.assign({}, variablesFromFile, variablesFromSettings);
}
function getFormatters(syntax, preferences) {
if (!preferences) {
return {};
}
if (!isStyleSheet(syntax)) {
let commentFormatter = {};
for (let key in preferences) {
switch (key) {
case 'filter.commentAfter':
commentFormatter['after'] = preferences[key];
break;
case 'filter.commentBefore':
commentFormatter['before'] = preferences[key];
break;
case 'filter.commentTrigger':
commentFormatter['trigger'] = preferences[key];
break;
default:
break;
}
}
return {
comment: commentFormatter
};
}
let fuzzySearchMinScore = typeof preferences['css.fuzzySearchMinScore'] === 'number' ? preferences['css.fuzzySearchMinScore'] : 0.3;
if (fuzzySearchMinScore > 1) {
fuzzySearchMinScore = 1;
}
else if (fuzzySearchMinScore < 0) {
fuzzySearchMinScore = 0;
}
let stylesheetFormatter = {
'fuzzySearchMinScore': fuzzySearchMinScore
};
for (let key in preferences) {
switch (key) {
case 'css.floatUnit':
stylesheetFormatter['floatUnit'] = preferences[key];
break;
case 'css.intUnit':
stylesheetFormatter['intUnit'] = preferences[key];
break;
case 'css.unitAliases':
let unitAliases = {};
preferences[key].split(',').forEach(alias => {
if (!alias || !alias.trim() || alias.indexOf(':') === -1) {
return;
}
let aliasName = alias.substr(0, alias.indexOf(':'));
let aliasValue = alias.substr(aliasName.length + 1);
if (!aliasName.trim() || !aliasValue) {
return;
}
unitAliases[aliasName.trim()] = aliasValue;
});
stylesheetFormatter['unitAliases'] = unitAliases;
break;
case `${syntax}.valueSeparator`:
stylesheetFormatter['between'] = preferences[key];
break;
case `${syntax}.propertyEnd`:
stylesheetFormatter['after'] = preferences[key];
break;
default:
break;
}
}
return {
stylesheet: stylesheetFormatter
};
}
/**
* Updates customizations from snippets.json and syntaxProfiles.json files in the directory configured in emmet.extensionsPath setting
*/
function updateExtensionsPath(emmetExtensionsPath, workspaceFolderPath) {
if (!emmetExtensionsPath || !emmetExtensionsPath.trim()) {
resetSettingsFromFile();
return Promise.resolve();
}
emmetExtensionsPath = emmetExtensionsPath.trim();
workspaceFolderPath = workspaceFolderPath ? workspaceFolderPath.trim() : '';
if (emmetExtensionsPath[0] === '~') {
emmetExtensionsPath = path.join(os_1.homedir(), emmetExtensionsPath.substr(1));
}
else if (!path.isAbsolute(emmetExtensionsPath) && workspaceFolderPath) {
emmetExtensionsPath = path.join(workspaceFolderPath, emmetExtensionsPath);
}
if (!path.isAbsolute(emmetExtensionsPath)) {
resetSettingsFromFile();
return Promise.reject('The path provided in emmet.extensionsPath setting should be absoulte path');
}
if (!dirExists(emmetExtensionsPath)) {
resetSettingsFromFile();
return Promise.reject(`The directory ${emmetExtensionsPath} doesnt exist. Update emmet.extensionsPath setting`);
}
let dirPath = emmetExtensionsPath;
let snippetsPath = path.join(dirPath, 'snippets.json');
let profilesPath = path.join(dirPath, 'syntaxProfiles.json');
let snippetsPromise = new Promise((resolve, reject) => {
fs.readFile(snippetsPath, (err, snippetsData) => {
if (err) {
return reject(`Error while fetching the file ${snippetsPath}`);
}
try {
let errors = [];
let snippetsJson = JSONC.parse(snippetsData.toString(), errors);
if (errors.length > 0) {
return reject(`Found error ${JSONC.ScanError[errors[0].error]} while parsing the file ${snippetsPath} at offset ${errors[0].offset}`);
}
variablesFromFile = snippetsJson['variables'];
customSnippetRegistry = {};
snippetKeyCache.clear();
Object.keys(snippetsJson).forEach(syntax => {
if (!snippetsJson[syntax]['snippets']) {
return;
}
let baseSyntax = isStyleSheet(syntax) ? 'css' : 'html';
let customSnippets = snippetsJson[syntax]['snippets'];
if (snippetsJson[baseSyntax] && snippetsJson[baseSyntax]['snippets'] && baseSyntax !== syntax) {
customSnippets = Object.assign({}, snippetsJson[baseSyntax]['snippets'], snippetsJson[syntax]['snippets']);
}
if (!isStyleSheet(syntax)) {
// In Emmet 2.0 all snippets should be valid abbreviations
// Convert old snippets that do not follow this format to new format
for (let snippetKey in customSnippets) {
if (customSnippets.hasOwnProperty(snippetKey)
&& customSnippets[snippetKey].startsWith('<')
&& customSnippets[snippetKey].endsWith('>')) {
customSnippets[snippetKey] = `{${customSnippets[snippetKey]}}`;
}
}
}
else {
stylesheetCustomSnippetsKeyCache.set(syntax, Object.keys(customSnippets));
}
customSnippetRegistry[syntax] = expand_full_1.createSnippetsRegistry(syntax, customSnippets);
let snippetKeys = customSnippetRegistry[syntax].all({ type: 'string' }).map(snippet => {
return snippet.key;
});
snippetKeyCache.set(syntax, snippetKeys);
});
}
catch (e) {
return reject(`Error while parsing the file ${snippetsPath}`);
}
return resolve();
});
});
let variablesPromise = new Promise((resolve, reject) => {
fs.readFile(profilesPath, (err, profilesData) => {
try {
if (!err) {
profilesFromFile = JSON.parse(profilesData.toString());
}
}
catch (e) {
}
return resolve();
});
});
return Promise.all([snippetsPromise, variablesFromFile]).then(() => Promise.resolve());
}
exports.updateExtensionsPath = updateExtensionsPath;
function dirExists(dirPath) {
try {
return fs.statSync(dirPath).isDirectory();
}
catch (e) {
return false;
}
}
function resetSettingsFromFile() {
customSnippetRegistry = {};
snippetKeyCache.clear();
stylesheetCustomSnippetsKeyCache.clear();
profilesFromFile = {};
variablesFromFile = {};
}
/**
* Get the corresponding emmet mode for given vscode language mode
* Eg: jsx for typescriptreact/javascriptreact or pug for jade
* If the language is not supported by emmet or has been exlcuded via `exlcudeLanguages` setting,
* then nothing is returned
*
* @param language
* @param exlcudedLanguages Array of language ids that user has chosen to exlcude for emmet
*/
function getEmmetMode(language, excludedLanguages = []) {
if (!language || excludedLanguages.indexOf(language) > -1) {
return;
}
if (/\b(typescriptreact|javascriptreact|jsx-tags)\b/.test(language)) { // treat tsx like jsx
return 'jsx';
}
if (language === 'sass-indented') { // map sass-indented to sass
return 'sass';
}
if (language === 'jade') {
return 'pug';
}
if (emmetModes.indexOf(language) > -1) {
return language;
}
}
exports.getEmmetMode = getEmmetMode;
const propertyHexColorRegex = /^[a-zA-Z]+:?#[\d.a-fA-F]{0,6}$/;
const hexColorRegex = /^#[\d,a-f,A-F]{1,6}$/;
const onlyLetters = /^[a-z,A-Z]+$/;
/**
* Returns a completion participant for Emmet of the form {
* onCssProperty: () => void
* onCssPropertyValue: () => void
* onHtmlContent: () => void
* }
* @param document The TextDocument for which completions are being provided
* @param position The Position in the given document where completions are being provided
* @param syntax The Emmet syntax to use when providing Emmet completions
* @param emmetSettings The Emmet settings to use when providing Emmet completions
* @param result The Completion List object that needs to be updated with Emmet completions
*/
function getEmmetCompletionParticipants(document, position, syntax, emmetSettings, result) {
return {
getId: () => 'emmet',
onCssProperty: (context) => {
if (context && context.propertyName) {
const currentresult = doComplete(document, position, syntax, emmetSettings);
if (result && currentresult) {
result.items = currentresult.items;
result.isIncomplete = true;
}
}
},
onCssPropertyValue: (context) => {
if (context && context.propertyValue) {
const extractedResults = extractAbbreviation(document, position, { syntax: 'css', lookAhead: false });
if (!extractedResults) {
return;
}
const validAbbreviationWithColon = extractedResults.abbreviation === `${context.propertyName}:${context.propertyValue}` && onlyLetters.test(context.propertyValue);
if (validAbbreviationWithColon // Allows abbreviations like pos:f
|| hexColorRegex.test(extractedResults.abbreviation)
|| extractedResults.abbreviation === '!') {
const currentresult = doComplete(document, position, syntax, emmetSettings);
if (result && currentresult) {
result.items = currentresult.items;
result.isIncomplete = true;
}
}
}
},
onHtmlContent: () => {
const currentresult = doComplete(document, position, syntax, emmetSettings);
if (result && currentresult) {
result.items = currentresult.items;
result.isIncomplete = true;
}
}
};
}
exports.getEmmetCompletionParticipants = getEmmetCompletionParticipants;
//# sourceMappingURL=emmetHelper.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -1,33 +0,0 @@
{
"name": "vscode-emmet-helper",
"version": "1.2.17",
"description": "Helper to use emmet modules in Visual Studio Code",
"main": "./out/emmetHelper.js",
"types": "./out/emmetHelper.d.ts",
"author": "Microsoft Corporation",
"repository": {
"type": "git",
"url": "https://github.com/Microsoft/vscode-emmet-helper"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/Microsoft/vscode-emmet-helper"
},
"devDependencies": {
"@types/node": "^6.0.46",
"cpy-cli": "^1.0.1",
"mocha": "3.4.2",
"typescript": "^2.1.5"
},
"dependencies": {
"@emmetio/extract-abbreviation": "0.1.6",
"jsonc-parser": "^1.0.0",
"vscode-languageserver-types": "^3.6.0-next.1"
},
"scripts": {
"prepublish": "npm run compile && npm run test",
"watch": "tsc -watch -p ./",
"compile": "tsc -p ./ && cpy ./src/expand/*.js ./out/expand && cpy ./src/typings/emmetHelper.d.ts ./out",
"test": "mocha out/test"
}
}

View file

@ -1,53 +0,0 @@
THIRD-PARTY SOFTWARE NOTICES AND INFORMATION
vscode-emmet-helper incorporates third party material from the projects listed below. The original copyright
notice and the license under which Microsoft received such third party material are set forth below. Microsoft
reserves all other rights not expressly granted, whether by implication, estoppel or otherwise.
1. expand-abbreivation (https://github.com/emmetio/expand-abbreivation)
MIT License
Copyright (c) 2017 Emmet.io
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2. extract-abbreivation (https://github.com/emmetio/extract-abbreivation)
MIT License
Copyright (c) 2017 Emmet.io
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -1,11 +0,0 @@
{
"compilerOptions": {
"target": "es6",
"lib": ["es2016"],
"module": "commonjs",
"outDir": "out",
"sourceMap": true,
"allowJs": true
},
"exclude": ["node_modules", "out"]
}

View file

@ -1,11 +0,0 @@
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -1,17 +0,0 @@
# VSCode Language Server Types
[![NPM Version](https://img.shields.io/npm/v/vscode-languageserver-types.svg)](https://npmjs.org/package/vscode-languageserver-types)
[![NPM Downloads](https://img.shields.io/npm/dm/vscode-languageserver-types.svg)](https://npmjs.org/package/vscode-languageserver-types)
[![Build Status](https://travis-ci.org/Microsoft/vscode-languageserver-types-node.svg?branch=master)](https://travis-ci.org/Microsoft/vscode-languageserver-types-node)
Npm module containing the types used by the VSCode language client and [Node.js](https://nodejs.org/) language server
Click [here](https://code.visualstudio.com/docs/extensions/example-language-server) for a detailed document on how
to implement language servers for [VSCode](https://code.visualstudio.com/).
## History
For the history please see the [main repository](https://github.com/Microsoft/vscode-languageserver-node/blob/master/README.md)
## License
[MIT](https://github.com/Microsoft/vscode-languageserver-node/blob/master/License.txt)

View file

@ -1,28 +0,0 @@
{
"name": "vscode-languageserver-types",
"description": "Types used by the Language server for node",
"version": "3.16.0",
"author": "Microsoft Corporation",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/Microsoft/vscode-languageserver-node.git",
"directory": "types"
},
"bugs": {
"url": "https://github.com/Microsoft/vscode-languageserver-node/issues"
},
"main": "./lib/umd/main.js",
"typings": "./lib/umd/main",
"module": "./lib/esm/main.js",
"scripts": {
"prepublishOnly": "git clean -xfd . && npm install && npm run clean && npm run compile:esm && npm run compile && npm run test",
"postpublish": "node ../build/npm/post-publish.js",
"compile": "node ../build/bin/tsc -b ./tsconfig.json",
"compile:esm": "node ../build/bin/tsc -b ./tsconfig.esm.json",
"clean": "node ../node_modules/rimraf/bin.js lib",
"watch": "node ../build/bin/tsc -b ./tsconfig-watch.json -w",
"test": "node ../node_modules/mocha/bin/_mocha",
"preversion": "npm test"
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,204 +0,0 @@
{
"name": "coc-emmet",
"version": "1.1.6",
"description": "emmet extension for coc",
"main": "lib/index.js",
"publisher": "chemzqm",
"keywords": [
"coc.nvim",
"emmet",
"html",
"css"
],
"engines": {
"coc": "^0.0.29"
},
"scripts": {
"clean": "rimraf lib",
"build": "webpack",
"prepare": "npx npm-run-all clean build"
},
"activationEvents": [
"*"
],
"contributes": {
"configuration": {
"type": "object",
"title": "Emmet",
"properties": {
"emmet.showExpandedAbbreviation": {
"type": [
"string"
],
"enum": [
"never",
"always",
"inMarkupAndStylesheetFilesOnly"
],
"default": "always",
"markdownDescription": "Shows expanded Emmet abbreviations as suggestions."
},
"emmet.showAbbreviationSuggestions": {
"type": "boolean",
"default": true,
"markdownDescription": "Shows possible Emmet abbreviations as suggestions. Not applicable in stylesheets or when emmet.showExpandedAbbreviation is 'never'."
},
"emmet.includeLanguages": {
"type": "object",
"default": {},
"markdownDescription": "Enable Emmet abbreviations in languages that are not supported by default. Add a mapping here between the language and emmet supported language. E.g.: `{\"vue-html\": \"html\", \"javascript\": \"javascriptreact\"}`"
},
"emmet.variables": {
"type": "object",
"properties": {
"lang": {
"type": "string",
"default": "en"
},
"charset": {
"type": "string",
"default": "UTF-8"
}
},
"default": {},
"description": "Variables to be used in Emmet snippets"
},
"emmet.syntaxProfiles": {
"type": "object",
"default": {},
"description": "Define profile for specified syntax or use your own profile with specific rules."
},
"emmet.excludeLanguages": {
"type": "array",
"default": [
"markdown"
],
"description": "An array of languages where Emmet abbreviations should not be expanded."
},
"emmet.extensionsPath": {
"type": "string",
"default": null,
"description": "Path to a folder containing Emmet profiles and snippets."
},
"emmet.showSuggestionsAsSnippets": {
"type": "boolean",
"default": true,
"markdownDescription": "Show emmet completion items as snippet kind."
},
"emmet.preferences": {
"type": "object",
"default": {},
"description": "Preferences used to modify behavior of some actions and resolvers of Emmet.",
"properties": {
"css.intUnit": {
"type": "string",
"default": "px"
},
"css.floatUnit": {
"type": "string",
"default": "em"
},
"css.propertyEnd": {
"type": "string",
"default": ";"
},
"sass.propertyEnd": {
"type": "string",
"default": ""
},
"stylus.propertyEnd": {
"type": "string",
"default": ""
},
"css.valueSeparator": {
"type": "string",
"default": ": "
},
"sass.valueSeparator": {
"type": "string",
"default": ": "
},
"stylus.valueSeparator": {
"type": "string",
"default": " "
},
"bem.elementSeparator": {
"type": "string",
"default": "__"
},
"bem.modifierSeparator": {
"type": "string",
"default": "_"
},
"filter.commentBefore": {
"type": "string",
"default": ""
},
"filter.commentAfter": {
"type": "string",
"default": "\n<!-- /[#ID][.CLASS] -->"
},
"filter.commentTrigger": {
"type": "array",
"default": [
"id",
"class"
]
},
"format.noIndentTags": {
"type": "array",
"default": [
"html"
]
},
"format.forceIndentationForTags": {
"type": "array",
"default": [
"body"
]
},
"profile.allowCompactBoolean": {
"type": "boolean",
"default": false
},
"css.fuzzySearchMinScore": {
"type": "number",
"default": 0.3
}
}
},
"emmet.optimizeStylesheetParsing": {
"type": "boolean",
"default": true,
"markdownDescription": "When set to `false`, the whole file is parsed to determine if current position is valid for expanding Emmet abbreviations. When set to `true`, only the content around the current position in css/scss/less files is parsed."
},
"emmet.priority": {
"type": "integer",
"default": 3
}
}
}
},
"author": "chemzqm@gmail.com",
"license": "MIT",
"devDependencies": {
"@chemzqm/tsconfig": "^0.0.3",
"@chemzqm/tslint-config": "^1.0.18",
"@types/node": "^10.14.7",
"coc.nvim": "^0.0.67",
"rimraf": "^2.6.3",
"ts-loader": "^6.0.3",
"tslint": "^5.16.0",
"typescript": "^3.4.4",
"webpack": "^4.34.0",
"webpack-cli": "^3.3.4",
"@emmetio/css-parser": "ramya-rao-a/css-parser#vscode",
"@emmetio/html-matcher": "^0.3.3",
"@emmetio/math-expression": "^0.1.1",
"vscode-languageserver-protocol": "^3.15.0-next.5",
"vscode-uri": "^1.0.6"
},
"dependencies": {
"vscode-emmet-helper": "^1.2.15"
}
}

View file

@ -1,40 +0,0 @@
const path = require('path')
module.exports = {
entry: './src/index.ts',
target: 'node',
mode: 'none',
resolve: {
mainFields: ['module', 'main'],
extensions: ['.js', '.ts']
},
externals: {
'coc.nvim': 'commonjs coc.nvim',
'vscode-emmet-helper': 'commonjs vscode-emmet-helper',
},
module: {
rules: [{
test: /\.ts$/,
exclude: /node_modules/,
use: [{
loader: 'ts-loader',
options: {
compilerOptions: {
"sourceMap": true,
}
}
}]
}]
},
output: {
path: path.join(__dirname, 'lib'),
filename: 'index.js',
libraryTarget: "commonjs",
},
plugins: [
],
node: {
__dirname: false,
__filename: false
}
}

View file

@ -1,4 +0,0 @@
# These are supported funding model platforms
patreon: chemzqm
custom: https://www.paypal.com/paypalme/chezqm

View file

@ -1,79 +0,0 @@
# coc-eslint
Eslint language server extension for [coc.nvim](https://github.com/neoclide/coc.nvim).
Forked from [vscode-eslint](https://github.com/Microsoft/vscode-eslint).
**Note** invoke `eslint.showOutputChannel` to invoke command of current eslint statusline.
## Supporting
If you like my extension, consider supporting me on Patreon or PayPal:
<a href="https://www.patreon.com/chemzqm"><img src="https://c5.patreon.com/external/logo/become_a_patron_button.png" alt="Patreon donate button" /> </a>
<a href="https://www.paypal.com/paypalme/chezqm"><img src="https://werwolv.net/assets/paypal_banner.png" alt="PayPal donate button" /> </a>
## Install
In your vim/neovim run the following command:
```sh
:CocInstall coc-eslint
```
## Features
- Lint `javascript` files using eslint.
- Provide `codeActions` for fixing lint issues.
- Provide eslint commands:
- `eslint.executeAutofix` Fix all auto-fixable Problems.
- `eslint.createConfig` Create ESLint configuration.
- `eslint.showOutputChannel` Show Output Channel.
- `eslint.resetLibraryExecution` Reset Library Execution Decisions.
- `eslint.manageLibraryExecution` Manage Library Execution.
- `eslint.lintProject` Run eslint for current project, add errors to quickfix list.
## Configuration options
**Notice** these configuration settings allow you to configure the behaviour of the coc-eslint extension. They should be set in your `coc-settings.json` file, which can be opened with the `:CocConfig` command.
- `eslint.enable`: Controls whether eslint is enabled or not. default: `true`
- `eslint.execArgv`: Arguments of node used on language server start. default: `[]`
- `eslint.packageManager`: The package manager you use to install node modules. default: `"npm"`
Valid options: ["npm","yarn","pnpm"]
- `eslint.alwaysShowStatus`: Always show the ESlint status bar item. default: `false`
- `eslint.nodeEnv`: The value of `NODE_ENV` to use when running eslint tasks. default: `null`
- `eslint.nodePath`: A path added to `NODE_PATH` when resolving the eslint module. default: `null`
- `eslint.options`: The eslint options object to provide args normally passed to eslint when executed from a command line (see http://eslint.org/docs/developer-guide/nodejs-api#cliengine). default: `{}`
- `eslint.trace.server`: Traces the communication between VSCode and the eslint linter service. default: `"off"`
- `eslint.run`: Run the linter on save (onSave) or on type (onType) default: `"onType"`
Valid options: ["onSave","onType"]
- `eslint.autoFixOnSave`: Turns auto fix on save on or off. default: `false`
- `eslint.quiet`: Turns on quiet mode, which ignores warnings. default: `false`
- `eslint.onIgnoredFiles`: Whether ESLint should issue a warning on ignored files. default: `"off"`
Valid options: ["warn","off"]
- `eslint.workingDirectories`: Working directories for files in different folders.
- `eslint.validate`: An array of language ids which should be validated by ESLint. If not installed ESLint will show an error.
- `eslint.probe`: An array of language ids for which the extension should probe if support is installed. default: `["javascript","javascriptreact","typescript","typescriptreact","html","vue","markdown"]`
- `eslint.runtime`: The location of the node binary to run ESLint under. default: `null`
- `eslint.debug`: Enables ESLint debug mode (same as --debug on the command line) default: `false`
- `eslint.codeAction.disableRuleComment`: default: `{"enable":true,"location":"separateLine"}`
- `eslint.codeAction.showDocumentation`: default: `{"enable":true}`
- `eslint.codeActionsOnSave.mode`: Specifies the code action mode. Possible values are 'all' and 'problems'. default: `"all"`
Valid options: ["all","problems"]
- `eslint.format.enable`: Enables ESLint as a formatter. default: `false`
- `eslint.lintTask.options`: Command line options applied when running the task for linting the whole workspace (see https://eslint.org/docs/user-guide/command-line-interface). default: `["."]`
## Auto-fixing
The extension supports automatic fixing of warnings to the extent that it is supported by eslint.
For warnings which support an auto-fix. You can apply the quick fix by either:
- Set `eslint.autoFixOnSave` to `true` and save your file (recommended).
- Trigger `<Plug>(coc-codeaction)` with mapped keys, and select a fix action in the input list.
- Run command `:CocCommand eslint.executeAutofix`.
- Trigger command `eslint.executeAutofix` from `:CocCommand`.
## License
MIT

View file

@ -1,51 +0,0 @@
const path = require('path')
const isProduction = process.env.NODE_ENV == 'production'
let entryPlugin = {
name: 'entry',
setup(build) {
build.onResolve({filter: /^(index|server)\.ts$/}, args => {
return {
path: args.path,
namespace: 'entry-ns'
}
})
build.onLoad({filter: /.*/, namespace: 'entry-ns'}, args => {
let contents = ''
if (args.path == 'index.ts') {
contents = `
import {activate, deactivate} from './src/index'
export {activate, deactivate}
`
} else if (args.path == 'server.ts') {
contents = `require('./server/eslintServer')`
} else {
throw new Error('Bad path')
}
return {
contents,
resolveDir: __dirname
}
})
}
}
async function start() {
await require('esbuild').build({
entryPoints: ['index.ts', 'server.ts'],
define: {'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')},
bundle: true,
platform: 'node',
target: 'node12.16',
mainFields: ['module', 'main'],
minify: isProduction,
sourcemap: !isProduction,
external: ['coc.nvim'],
outdir: path.resolve(__dirname, 'lib'),
plugins: [entryPlugin]
})
}
start().catch(e => {
console.error(e)
})

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,394 +0,0 @@
{
"name": "coc-eslint",
"version": "1.4.5",
"description": "Eslint extension for coc.nvim",
"main": "lib/index.js",
"publisher": "chemzqm",
"repository": {
"type": "git",
"url": "https://github.com/neoclide/coc-eslint.git"
},
"keywords": [
"coc.nvim",
"eslint"
],
"engines": {
"coc": "^0.0.80"
},
"scripts": {
"clean": "rimraf lib",
"build": "node esbuild.js",
"prepare": "node esbuild.js"
},
"activationEvents": [
"*"
],
"contributes": {
"commands": [
{
"title": "Fix all auto-fixable Problems",
"category": "ESLint",
"command": "eslint.executeAutofix"
},
{
"title": "Create ESLint configuration",
"category": "ESLint",
"command": "eslint.createConfig"
},
{
"title": "Show Output Channel",
"category": "ESLint",
"command": "eslint.showOutputChannel"
},
{
"title": "Reset Library Execution Decisions",
"category": "ESLint",
"command": "eslint.resetLibraryExecution"
},
{
"title": "Manage Library Execution",
"category": "ESLint",
"command": "eslint.manageLibraryExecution"
},
{
"title": "Run eslint for current project",
"category": "ESLint",
"command": "eslint.lintProject"
}
],
"configuration": {
"type": "object",
"title": "Eslint",
"properties": {
"eslint.enable": {
"scope": "resource",
"type": "boolean",
"default": true,
"description": "Controls whether eslint is enabled or not.",
"deprecationMessage": "This setting is deprecated. Disable ESLint using the extensions list."
},
"eslint.packageManager": {
"scope": "resource",
"type": "string",
"enum": [
"npm",
"yarn",
"pnpm"
],
"default": "npm",
"description": "The package manager you use to install node modules."
},
"eslint.alwaysShowStatus": {
"type": "boolean",
"default": false,
"description": "Always show the ESlint status bar item.",
"scope": "window"
},
"eslint.nodeEnv": {
"scope": "resource",
"type": [
"string",
"null"
],
"default": null,
"description": "The value of NODE_ENV to use when running eslint tasks."
},
"eslint.nodePath": {
"scope": "machine-overridable",
"type": [
"string",
"null"
],
"default": null,
"description": "A path added to NODE_PATH when resolving the eslint module."
},
"eslint.options": {
"scope": "resource",
"type": "object",
"default": {},
"description": "The eslint options object to provide args normally passed to eslint when executed from a command line (see http://eslint.org/docs/developer-guide/nodejs-api#cliengine)."
},
"eslint.trace.server": {
"scope": "window",
"anyOf": [
{
"type": "string",
"enum": [
"off",
"messages",
"verbose"
],
"default": "off"
},
{
"type": "object",
"properties": {
"verbosity": {
"type": "string",
"enum": [
"off",
"messages",
"verbose"
],
"default": "off"
},
"format": {
"type": "string",
"enum": [
"text",
"json"
],
"default": "text"
}
}
}
],
"default": "off",
"description": "Traces the communication between VSCode and the eslint linter service."
},
"eslint.run": {
"scope": "resource",
"type": "string",
"enum": [
"onSave",
"onType"
],
"default": "onType",
"description": "Run the linter on save (onSave) or on type (onType)"
},
"eslint.autoFixOnSave": {
"scope": "resource",
"type": "boolean",
"default": false,
"description": "Turns auto fix on save on or off."
},
"eslint.quiet": {
"scope": "resource",
"type": "boolean",
"default": false,
"description": "Turns on quiet mode, which ignores warnings."
},
"eslint.onIgnoredFiles": {
"scope": "resource",
"type": "string",
"enum": [
"warn",
"off"
],
"default": "off",
"description": "Whether ESLint should issue a warning on ignored files."
},
"eslint.workingDirectories": {
"scope": "resource",
"type": "array",
"description": "Working directories for files in different folders.",
"items": {
"anyOf": [
{
"type": "string"
},
{
"type": "object",
"properties": {
"mode": {
"type": "string",
"enum": [
"auto",
"location"
]
},
"default": "location"
},
"required": [
"mode"
]
},
{
"type": "object",
"properties": {
"directory": {
"type": "string",
"description": "The working directory to use if a file's path starts with this directory."
},
"!cwd": {
"type": "boolean",
"description": "Set to true if ESLint shouldn't change the working directory."
}
},
"required": [
"directory"
]
},
{
"type": "object",
"properties": {
"pattern": {
"type": "string",
"description": "A glob pattern to match a working directory."
},
"!cwd": {
"type": "boolean",
"description": "Set to true if ESLint shouldn't change the working directory."
}
},
"required": [
"pattern"
]
}
]
}
},
"eslint.validate": {
"scope": "resource",
"type": "array",
"items": {
"anyOf": [
{
"type": "string"
},
{
"type": "object",
"properties": {
"language": {
"type": "string",
"description": "The language id to be validated by ESLint."
},
"autoFix": {
"type": "boolean",
"description": "Whether auto fixes are provided for the language."
}
},
"deprecationMessage": "Auto Fix is enabled by default. Use the single string form."
}
]
},
"description": "An array of language ids which should be validated by ESLint. If not installed ESLint will show an error."
},
"eslint.probe": {
"scope": "resource",
"type": "array",
"items": {
"type": "string"
},
"default": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact",
"html",
"vue",
"markdown"
],
"description": "An array of language ids for which the extension should probe if support is installed."
},
"eslint.runtime": {
"scope": "machine-overridable",
"type": [
"string",
"null"
],
"default": null,
"description": "The location of the node binary to run ESLint under."
},
"eslint.debug": {
"scope": "window",
"type": "boolean",
"default": false,
"description": "Enables ESLint debug mode (same as --debug on the command line)"
},
"eslint.execArgv": {
"type": "array",
"default": [],
"description": "Arguments of node used on language server start.",
"items": {
"type": "string"
}
},
"eslint.codeAction.disableRuleComment": {
"scope": "resource",
"type": "object",
"default": {
"enable": true,
"location": "separateLine"
},
"properties": {
"enable": {
"type": "boolean",
"default": true,
"description": "Show the disable code actions."
},
"location": {
"type": "string",
"enum": [
"separateLine",
"sameLine"
],
"default": "separateLine",
"description": "Configure the disable rule code action to insert the comment on the same line or a new line."
}
}
},
"eslint.codeAction.showDocumentation": {
"scope": "resource",
"type": "object",
"default": {
"enable": true
},
"properties": {
"enable": {
"type": "boolean",
"default": true,
"description": "Show the documentation code actions."
}
}
},
"eslint.codeActionsOnSave.mode": {
"scope": "resource",
"type": "string",
"enum": [
"all",
"problems"
],
"enumDescriptions": [
"Fixes all possible problems in the file. This option might take some time.",
"Only fixes reported problems that have non overlapping textual edits. This options runs a lot faster."
],
"default": "all",
"description": "Specifies the code action mode. Possible values are 'all' and 'problems'."
},
"eslint.format.enable": {
"scope": "resource",
"type": "boolean",
"default": false,
"description": "Enables ESLint as a formatter."
},
"eslint.lintTask.options": {
"scope": "resource",
"type": "array",
"default": [
"."
],
"description": "Command line options applied when running the task for linting the whole workspace (see https://eslint.org/docs/user-guide/command-line-interface).",
"items": {
"type": "string"
}
}
}
}
},
"author": "chemzqm@gmail.com",
"license": "MIT",
"devDependencies": {
"@types/node": "^10.12.0",
"coc.nvim": "^0.0.80",
"esbuild": "^0.8.29",
"eslint": "^7.15.0",
"rimraf": "^3.0.0",
"typescript": "^4.1.2",
"vscode-languageserver": "7.0.0",
"vscode-languageserver-protocol": "3.15.3",
"vscode-languageserver-textdocument": "^1.0.1",
"vscode-uri": "^2.1.1"
},
"dependencies": {}
}

View file

@ -1,4 +0,0 @@
# These are supported funding model platforms
patreon: chemzqm
custom: https://www.paypal.com/paypalme/chezqm

View file

@ -1,3 +0,0 @@
{
"coc.preferences.formatOnSaveFiletypes": []
}

View file

@ -1,137 +0,0 @@
# coc-html
Html language server extension for [coc.nvim](https://github.com/neoclide/coc.nvim).
Code changed from html extension of [VSCode](https://github.com/Microsoft/vscode/tree/master/extensions/html-language-features)
## Supporting
If you like this extension, consider supporting me on Patreon or PayPal:
<a href="https://www.patreon.com/chemzqm"><img src="https://c5.patreon.com/external/logo/become_a_patron_button.png" alt="Patreon donate button" /> </a>
<a href="https://www.paypal.com/paypalme/chezqm"><img src="https://werwolv.net/assets/paypal_banner.png" alt="PayPal donate button" /> </a>
## Install
In your vim/neovim, run command:
```
:CocInstall coc-html
```
## Features
- Completion provider
- Formatting
- Document Symbols & Highlights
- Document Links
- CSS mode
- Javascript mode
## Configuration options
- *html.experimental.custom.tags*:
A list of JSON file paths that define custom tags.
- *html.experimental.custom.attributes*:
A list of JSON file paths that define custom attributes.
- *html.enable*:
default: `true`
- *html.execArgv*:
default: `[]`
- *html.trace.server*:
default: `"off"`
Valid options: ["off","messages","verbose"]
- *html.filetypes*:
default: `["html","handlebars","htmldjango","blade"]`
- *html.format.enable*:
Enable/disable default HTML formatter, default: `true`
- *html.format.wrapLineLength*:
Maximum amount of characters per line (0 = disable)., default: `120`
- *html.format.unformatted*:
List of tags, comma separated, that shouldn't be reformatted. 'null' defaults to all tags listed at https://www.w3.org/TR/html5/dom.html#phrasing-content., default: `"wbr"`
- *html.format.contentUnformatted*:
List of tags, comma separated, where the content shouldn't be reformatted. 'null' defaults to the 'pre' tag., default: `"pre,code,textarea"`
- *html.format.indentInnerHtml*:
default: `false`
- *html.format.preserveNewLines*:
default: `true`
- *html.format.maxPreserveNewLines*:
List of tags, comma separated, that should have an extra newline before them. 'null', default: `null`
- *html.format.indentHandlebars*:
default: `false`
- *html.format.endWithNewline*:
default: `false`
- *html.format.extraLiners*:
List of tags, comma separated, that should have an extra newline before them., default: `"head, body, /html"`
- *html.format.wrapAttributes*:
default: `"auto"`
Valid options: ["auto","force","force-aligned","force-expand-multiline"]
- *html.suggest.angular1*:
Configures if the built-in HTML language support suggests Angular V1 tags and properties., default: `true`
- *html.suggest.ionic*:
Configures if the built-in HTML language support suggests Ionic tags, properties and values., default: `true`
- *html.suggest.html5*:
Configures if the built-in HTML language support suggests HTML5 tags, properties and values., default: `true`
- *html.validate.scripts*:
Configures if the built-in HTML language support validates embedded scripts., default: `true`
- *html.validate.styles*:
Configures if the built-in HTML language support validates embedded styles., default: `true`
- *html.validate.html*:
Configures if the built-in HTML language support validates HTML., default: `true`
- *html.autoClosingTags*:
Enable/disable autoClosing of HTML tags., default: `false`
Trigger completion in `coc-settings.json` for complete list.
## License
MIT

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -1 +0,0 @@
../typescript/bin/tsc

View file

@ -1 +0,0 @@
../typescript/bin/tsserver

View file

@ -1,20 +0,0 @@
{
"name": "coc-html",
"version": "1.4.1",
"lockfileVersion": 2,
"requires": true,
"packages": {
"node_modules/typescript": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.4.3.tgz",
"integrity": "sha512-4xfscpisVgqqDfPaJo5vkd+Qd/ItkoagnHpufr+i2QCHBsNYp+G7UAoyFl8aPtx879u38wPV65rZ8qbGZijalA==",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=4.2.0"
}
}
}
}

View file

@ -1,480 +0,0 @@
TypeScript is authored by:
- 0verk1ll
- Abubaker Bashir
- Adam Freidin
- Adam Postma
- Adi Dahiya
- Aditya Daflapurkar
- Adnan Chowdhury
- Adrian Leonhard
- Adrien Gibrat
- Ahmad Farid
- Ajay Poshak
- Alan Agius
- Alan Pierce
- Alessandro Vergani
- Alex Chugaev
- Alex Eagle
- Alex Khomchenko
- Alex Ryan
- Alexander
- Alexander Kuvaev
- Alexander Rusakov
- Alexander Tarasyuk
- Ali Sabzevari
- Aluan Haddad
- amaksimovich2
- Anatoly Ressin
- Anders Hejlsberg
- Anders Kaseorg
- Andre Sutherland
- Andreas Martin
- Andrej Baran
- Andrew
- Andrew Branch
- Andrew Casey
- Andrew Faulkner
- Andrew Ochsner
- Andrew Stegmaier
- Andrew Z Allen
- Andrey Roenko
- Andrii Dieiev
- András Parditka
- Andy Hanson
- Anil Anar
- Anix
- Anton Khlynovskiy
- Anton Tolmachev
- Anubha Mathur
- AnyhowStep
- Armando Aguirre
- Arnaud Tournier
- Arnav Singh
- Arpad Borsos
- Artem Tyurin
- Arthur Ozga
- Asad Saeeduddin
- Austin Cummings
- Avery Morin
- Aziz Khambati
- Basarat Ali Syed
- @begincalendar
- Ben Duffield
- Ben Lichtman
- Ben Mosher
- Benedikt Meurer
- Benjamin Bock
- Benjamin Lichtman
- Benny Neugebauer
- BigAru
- Bill Ticehurst
- Blaine Bublitz
- Blake Embrey
- @bluelovers
- @bootstraponline
- Bowden Kelly
- Bowden Kenny
- Brad Zacher
- Brandon Banks
- Brandon Bloom
- Brandon Slade
- Brendan Kenny
- Brett Mayen
- Brian Terlson
- Bryan Forbes
- Caitlin Potter
- Caleb Sander
- Cameron Taggart
- @cedvdb
- Charles
- Charles Pierce
- Charly POLY
- Chris Bubernak
- Chris Patterson
- christian
- Christophe Vidal
- Chuck Jazdzewski
- Clay Miller
- Colby Russell
- Colin Snover
- Collins Abitekaniza
- Connor Clark
- Cotton Hou
- csigs
- Cyrus Najmabadi
- Dafrok Zhang
- Dahan Gong
- Daiki Nishikawa
- Dan Corder
- Dan Freeman
- Dan Quirk
- Dan Rollo
- Daniel Gooss
- Daniel Imms
- Daniel Krom
- Daniel Król
- Daniel Lehenbauer
- Daniel Rosenwasser
- David Li
- David Sheldrick
- David Sherret
- David Souther
- David Staheli
- Denis Nedelyaev
- Derek P Sifford
- Dhruv Rajvanshi
- Dick van den Brink
- Diogo Franco (Kovensky)
- Dirk Bäumer
- Dirk Holtwick
- Dmitrijs Minajevs
- Dom Chen
- Donald Pipowitch
- Doug Ilijev
- dreamran43@gmail.com
- @e-cloud
- Ecole Keine
- Eddie Jaoude
- Edward Thomson
- EECOLOR
- Eli Barzilay
- Elizabeth Dinella
- Ely Alamillo
- Eric Grube
- Eric Tsang
- Erik Edrosa
- Erik McClenney
- Esakki Raj
- Ethan Resnick
- Ethan Rubio
- Eugene Timokhov
- Evan Cahill
- Evan Martin
- Evan Sebastian
- ExE Boss
- Eyas Sharaiha
- Fabian Cook
- @falsandtru
- Filipe Silva
- @flowmemo
- Forbes Lindesay
- Francois Hendriks
- Francois Wouts
- Frank Wallis
- František Žiacik
- Frederico Bittencourt
- fullheightcoding
- Gabe Moothart
- Gabriel Isenberg
- Gabriela Araujo Britto
- Gabriela Britto
- gb714us
- Gilad Peleg
- Godfrey Chan
- Gorka Hernández Estomba
- Graeme Wicksted
- Guillaume Salles
- Guy Bedford
- hafiz
- Halasi Tamás
- Hendrik Liebau
- Henry Mercer
- Herrington Darkholme
- Hoang Pham
- Holger Jeromin
- Homa Wong
- Hye Sung Jung
- Iain Monro
- @IdeaHunter
- Igor Novozhilov
- Igor Oleinikov
- Ika
- iliashkolyar
- IllusionMH
- Ingvar Stepanyan
- Ingvar Stepanyan
- Isiah Meadows
- ispedals
- Ivan Enderlin
- Ivo Gabe de Wolff
- Iwata Hidetaka
- Jack Bates
- Jack Williams
- Jake Boone
- Jakub Korzeniowski
- Jakub Młokosiewicz
- James Henry
- James Keane
- James Whitney
- Jan Melcher
- Jason Freeman
- Jason Jarrett
- Jason Killian
- Jason Ramsay
- JBerger
- Jean Pierre
- Jed Mao
- Jeff Wilcox
- Jeffrey Morlan
- Jesse Schalken
- Jesse Trinity
- Jing Ma
- Jiri Tobisek
- Joe Calzaretta
- Joe Chung
- Joel Day
- Joey Watts
- Johannes Rieken
- John Doe
- John Vilk
- Jonathan Bond-Caron
- Jonathan Park
- Jonathan Toland
- Jordan Harband
- Jordi Oliveras Rovira
- Joscha Feth
- Joseph Wunderlich
- Josh Abernathy
- Josh Goldberg
- Josh Kalderimis
- Josh Soref
- Juan Luis Boya García
- Julian Williams
- Justin Bay
- Justin Johansson
- jwbay
- K. Preißer
- Kagami Sascha Rosylight
- Kanchalai Tanglertsampan
- karthikkp
- Kate Miháliková
- Keen Yee Liau
- Keith Mashinter
- Ken Howard
- Kenji Imamula
- Kerem Kat
- Kevin Donnelly
- Kevin Gibbons
- Kevin Lang
- Khải
- Kitson Kelly
- Klaus Meinhardt
- Kris Zyp
- Kyle Kelley
- Kārlis Gaņģis
- laoxiong
- Leon Aves
- Limon Monte
- Lorant Pinter
- Lucien Greathouse
- Luka Hartwig
- Lukas Elmer
- M.Yoshimura
- Maarten Sijm
- Magnus Hiie
- Magnus Kulke
- Manish Bansal
- Manish Giri
- Marcus Noble
- Marin Marinov
- Marius Schulz
- Markus Johnsson
- Markus Wolf
- Martin
- Martin Hiller
- Martin Johns
- Martin Probst
- Martin Vseticka
- Martyn Janes
- Masahiro Wakame
- Mateusz Burzyński
- Matt Bierner
- Matt McCutchen
- Matt Mitchell
- Matthew Aynalem
- Matthew Miller
- Mattias Buelens
- Max Heiber
- Maxwell Paul Brickner
- @meyer
- Micah Zoltu
- @micbou
- Michael
- Michael Crane
- Michael Henderson
- Michael Tamm
- Michael Tang
- Michal Przybys
- Mike Busyrev
- Mike Morearty
- Milosz Piechocki
- Mine Starks
- Minh Nguyen
- Mohamed Hegazy
- Mohsen Azimi
- Mukesh Prasad
- Myles Megyesi
- Nathan Day
- Nathan Fenner
- Nathan Shively-Sanders
- Nathan Yee
- ncoley
- Nicholas Yang
- Nicu Micleușanu
- @nieltg
- Nima Zahedi
- Noah Chen
- Noel Varanda
- Noel Yoo
- Noj Vek
- nrcoley
- Nuno Arruda
- Oleg Mihailik
- Oleksandr Chekhovskyi
- Omer Sheikh
- Orta Therox
- Orta Therox
- Oskar Grunning
- Oskar Segersva¨rd
- Oussama Ben Brahim
- Ozair Patel
- Patrick McCartney
- Patrick Zhong
- Paul Koerbitz
- Paul van Brenk
- @pcbro
- Pedro Maltez
- Pete Bacon Darwin
- Peter Burns
- Peter Šándor
- Philip Pesca
- Philippe Voinov
- Pi Lanningham
- Piero Cangianiello
- Pierre-Antoine Mills
- @piloopin
- Pranav Senthilnathan
- Prateek Goel
- Prateek Nayak
- Prayag Verma
- Priyantha Lankapura
- @progre
- Punya Biswal
- r7kamura
- Rado Kirov
- Raj Dosanjh
- rChaser53
- Reiner Dolp
- Remo H. Jansen
- @rflorian
- Rhys van der Waerden
- @rhysd
- Ricardo N Feliciano
- Richard Karmazín
- Richard Knoll
- Roger Spratley
- Ron Buckton
- Rostislav Galimsky
- Rowan Wyborn
- rpgeeganage
- Ruwan Pradeep Geeganage
- Ryan Cavanaugh
- Ryan Clarke
- Ryohei Ikegami
- Salisbury, Tom
- Sam Bostock
- Sam Drugan
- Sam El-Husseini
- Sam Lanning
- Sangmin Lee
- Sanket Mishra
- Sarangan Rajamanickam
- Sasha Joseph
- Sean Barag
- Sergey Rubanov
- Sergey Shandar
- Sergey Tychinin
- Sergii Bezliudnyi
- Sergio Baidon
- Sharon Rolel
- Sheetal Nandi
- Shengping Zhong
- Sheon Han
- Shyyko Serhiy
- Siddharth Singh
- sisisin
- Slawomir Sadziak
- Solal Pirelli
- Soo Jae Hwang
- Stan Thomas
- Stanislav Iliev
- Stanislav Sysoev
- Stas Vilchik
- Stephan Ginthör
- Steve Lucco
- @styfle
- Sudheesh Singanamalla
- Suhas
- Suhas Deshpande
- superkd37
- Sébastien Arod
- @T18970237136
- @t_
- Tan Li Hau
- Tapan Prakash
- Taras Mankovski
- Tarik Ozket
- Tetsuharu Ohzeki
- The Gitter Badger
- Thomas den Hollander
- Thorsten Ball
- Tien Hoanhtien
- Tim Lancina
- Tim Perry
- Tim Schaub
- Tim Suchanek
- Tim Viiding-Spader
- Tingan Ho
- Titian Cernicova-Dragomir
- tkondo
- Todd Thomson
- togru
- Tom J
- Torben Fitschen
- Toxyxer
- @TravCav
- Troy Tae
- TruongSinh Tran-Nguyen
- Tycho Grouwstra
- uhyo
- Vadi Taslim
- Vakhurin Sergey
- Valera Rozuvan
- Vilic Vane
- Vimal Raghubir
- Vladimir Kurchatkin
- Vladimir Matveev
- Vyacheslav Pukhanov
- Wenlu Wang
- Wes Souza
- Wesley Wigham
- William Orr
- Wilson Hobbs
- xiaofa
- xl1
- Yacine Hmito
- Yang Cao
- York Yao
- @yortus
- Yoshiki Shibukawa
- Yuichi Nukiyama
- Yuval Greenfield
- Yuya Tanaka
- Z
- Zeeshan Ahmed
- Zev Spitz
- Zhengbo Li
- Zixiang Li
- @Zzzen
- 阿卡琳

View file

@ -1 +0,0 @@
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.

View file

@ -1,15 +0,0 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */

View file

@ -1,55 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View file

@ -1,104 +0,0 @@
# TypeScript
[![GitHub Actions CI](https://github.com/microsoft/TypeScript/workflows/CI/badge.svg)](https://github.com/microsoft/TypeScript/actions?query=workflow%3ACI)
[![Devops Build Status](https://dev.azure.com/typescript/TypeScript/_apis/build/status/Typescript/node10)](https://dev.azure.com/typescript/TypeScript/_build?definitionId=7)
[![npm version](https://badge.fury.io/js/typescript.svg)](https://www.npmjs.com/package/typescript)
[![Downloads](https://img.shields.io/npm/dm/typescript.svg)](https://www.npmjs.com/package/typescript)
[TypeScript](https://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types to JavaScript that support tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](https://www.typescriptlang.org/play/), and stay up to date via [our blog](https://blogs.msdn.microsoft.com/typescript) and [Twitter account](https://twitter.com/typescript).
Find others who are using TypeScript at [our community page](https://www.typescriptlang.org/community/).
## Installing
For the latest stable version:
```bash
npm install -g typescript
```
For our nightly builds:
```bash
npm install -g typescript@next
```
## Contribute
There are many ways to [contribute](https://github.com/microsoft/TypeScript/blob/main/CONTRIBUTING.md) to TypeScript.
* [Submit bugs](https://github.com/microsoft/TypeScript/issues) and help us verify fixes as they are checked in.
* Review the [source code changes](https://github.com/microsoft/TypeScript/pulls).
* Engage with other TypeScript users and developers on [StackOverflow](https://stackoverflow.com/questions/tagged/typescript).
* Help each other in the [TypeScript Community Discord](https://discord.gg/typescript).
* Join the [#typescript](https://twitter.com/search?q=%23TypeScript) discussion on Twitter.
* [Contribute bug fixes](https://github.com/microsoft/TypeScript/blob/main/CONTRIBUTING.md).
* Read the archived language specification ([docx](https://github.com/microsoft/TypeScript/blob/main/doc/TypeScript%20Language%20Specification%20-%20ARCHIVED.docx?raw=true),
[pdf](https://github.com/microsoft/TypeScript/blob/main/doc/TypeScript%20Language%20Specification%20-%20ARCHIVED.pdf?raw=true), [md](https://github.com/microsoft/TypeScript/blob/main/doc/spec-ARCHIVED.md)).
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see
the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com)
with any additional questions or comments.
## Documentation
* [TypeScript in 5 minutes](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html)
* [Programming handbook](https://www.typescriptlang.org/docs/handbook/intro.html)
* [Homepage](https://www.typescriptlang.org/)
## Building
In order to build the TypeScript compiler, ensure that you have [Git](https://git-scm.com/downloads) and [Node.js](https://nodejs.org/) installed.
Clone a copy of the repo:
```bash
git clone https://github.com/microsoft/TypeScript.git
```
Change to the TypeScript directory:
```bash
cd TypeScript
```
Install [Gulp](https://gulpjs.com/) tools and dev dependencies:
```bash
npm install -g gulp
npm ci
```
Use one of the following to build and test:
```
gulp local # Build the compiler into built/local.
gulp clean # Delete the built compiler.
gulp LKG # Replace the last known good with the built one.
# Bootstrapping step to be executed when the built compiler reaches a stable state.
gulp tests # Build the test infrastructure using the built compiler.
gulp runtests # Run tests using the built compiler and test infrastructure.
# You can override the specific suite runner used or specify a test for this command.
# Use --tests=<testPath> for a specific test and/or --runner=<runnerName> for a specific suite.
# Valid runners include conformance, compiler, fourslash, project, user, and docker
# The user and docker runners are extended test suite runners - the user runner
# works on disk in the tests/cases/user directory, while the docker runner works in containers.
# You'll need to have the docker executable in your system path for the docker runner to work.
gulp runtests-parallel # Like runtests, but split across multiple threads. Uses a number of threads equal to the system
# core count by default. Use --workers=<number> to adjust this.
gulp baseline-accept # This replaces the baseline test results with the results obtained from gulp runtests.
gulp lint # Runs eslint on the TypeScript source.
gulp help # List the above commands.
```
## Usage
```bash
node built/local/tsc.js hello.ts
```
## Roadmap
For details on our planned features and future direction please refer to our [roadmap](https://github.com/microsoft/TypeScript/wiki/Roadmap).

File diff suppressed because one or more lines are too long

View file

@ -1,2 +0,0 @@
#!/usr/bin/env node
require('../lib/tsc.js')

View file

@ -1,2 +0,0 @@
#!/usr/bin/env node
require('../lib/tsserver.js')

View file

@ -1,5 +0,0 @@
# Read This!
**These files are not meant to be edited by hand.**
If you need to make modifications, the respective files should be changed within the repository's top-level `src` directory.
Running `gulp LKG` will then appropriately update the files in this directory.

View file

@ -1,67 +0,0 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
"use strict";
var fs = require("fs");
function pipeExists(name) {
return fs.existsSync(name);
}
function createCancellationToken(args) {
var cancellationPipeName;
for (var i = 0; i < args.length - 1; i++) {
if (args[i] === "--cancellationPipeName") {
cancellationPipeName = args[i + 1];
break;
}
}
if (!cancellationPipeName) {
return {
isCancellationRequested: function () { return false; },
setRequest: function (_requestId) { return void 0; },
resetRequest: function (_requestId) { return void 0; }
};
}
if (cancellationPipeName.charAt(cancellationPipeName.length - 1) === "*") {
var namePrefix_1 = cancellationPipeName.slice(0, -1);
if (namePrefix_1.length === 0 || namePrefix_1.indexOf("*") >= 0) {
throw new Error("Invalid name for template cancellation pipe: it should have length greater than 2 characters and contain only one '*'.");
}
var perRequestPipeName_1;
var currentRequestId_1;
return {
isCancellationRequested: function () { return perRequestPipeName_1 !== undefined && pipeExists(perRequestPipeName_1); },
setRequest: function (requestId) {
currentRequestId_1 = requestId;
perRequestPipeName_1 = namePrefix_1 + requestId;
},
resetRequest: function (requestId) {
if (currentRequestId_1 !== requestId) {
throw new Error("Mismatched request id, expected " + currentRequestId_1 + ", actual " + requestId);
}
perRequestPipeName_1 = undefined;
}
};
}
else {
return {
isCancellationRequested: function () { return pipeExists(cancellationPipeName); },
setRequest: function (_requestId) { return void 0; },
resetRequest: function (_requestId) { return void 0; }
};
}
}
module.exports = createCancellationToken;
//# sourceMappingURL=cancellationToken.js.map

View file

@ -1,24 +0,0 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es5" />
/// <reference lib="dom" />
/// <reference lib="webworker.importscripts" />
/// <reference lib="scripthost" />

File diff suppressed because it is too large Load diff

View file

@ -1,361 +0,0 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/////////////////////////////
/// Window Iterable APIs
/////////////////////////////
interface AudioParam {
setValueCurveAtTime(values: Iterable<number>, startTime: number, duration: number): AudioParam;
}
interface AudioParamMap extends ReadonlyMap<string, AudioParam> {
}
interface BaseAudioContext {
createIIRFilter(feedforward: Iterable<number>, feedback: Iterable<number>): IIRFilterNode;
createPeriodicWave(real: Iterable<number>, imag: Iterable<number>, constraints?: PeriodicWaveConstraints): PeriodicWave;
}
interface CSSRuleList {
[Symbol.iterator](): IterableIterator<CSSRule>;
}
interface CSSStyleDeclaration {
[Symbol.iterator](): IterableIterator<string>;
}
interface Cache {
addAll(requests: Iterable<RequestInfo>): Promise<void>;
}
interface CanvasPathDrawingStyles {
setLineDash(segments: Iterable<number>): void;
}
interface DOMRectList {
[Symbol.iterator](): IterableIterator<DOMRect>;
}
interface DOMStringList {
[Symbol.iterator](): IterableIterator<string>;
}
interface DOMTokenList {
[Symbol.iterator](): IterableIterator<string>;
entries(): IterableIterator<[number, string]>;
keys(): IterableIterator<number>;
values(): IterableIterator<string>;
}
interface DataTransferItemList {
[Symbol.iterator](): IterableIterator<DataTransferItem>;
}
interface FileList {
[Symbol.iterator](): IterableIterator<File>;
}
interface FontFaceSet extends Set<FontFace> {
}
interface FormData {
[Symbol.iterator](): IterableIterator<[string, FormDataEntryValue]>;
/**
* Returns an array of key, value pairs for every entry in the list.
*/
entries(): IterableIterator<[string, FormDataEntryValue]>;
/**
* Returns a list of keys in the list.
*/
keys(): IterableIterator<string>;
/**
* Returns a list of values in the list.
*/
values(): IterableIterator<FormDataEntryValue>;
}
interface HTMLAllCollection {
[Symbol.iterator](): IterableIterator<Element>;
}
interface HTMLCollectionBase {
[Symbol.iterator](): IterableIterator<Element>;
}
interface HTMLCollectionOf<T extends Element> {
[Symbol.iterator](): IterableIterator<T>;
}
interface HTMLFormElement {
[Symbol.iterator](): IterableIterator<Element>;
}
interface HTMLSelectElement {
[Symbol.iterator](): IterableIterator<HTMLOptionElement>;
}
interface Headers {
[Symbol.iterator](): IterableIterator<[string, string]>;
/**
* Returns an iterator allowing to go through all key/value pairs contained in this object.
*/
entries(): IterableIterator<[string, string]>;
/**
* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object.
*/
keys(): IterableIterator<string>;
/**
* Returns an iterator allowing to go through all values of the key/value pairs contained in this object.
*/
values(): IterableIterator<string>;
}
interface IDBDatabase {
/**
* Returns a new transaction with the given mode ("readonly" or "readwrite") and scope which can be a single object store name or an array of names.
*/
transaction(storeNames: string | Iterable<string>, mode?: IDBTransactionMode): IDBTransaction;
}
interface IDBObjectStore {
/**
* Creates a new index in store with the given name, keyPath and options and returns a new IDBIndex. If the keyPath and options define constraints that cannot be satisfied with the data already in store the upgrade transaction will abort with a "ConstraintError" DOMException.
*
* Throws an "InvalidStateError" DOMException if not called within an upgrade transaction.
*/
createIndex(name: string, keyPath: string | Iterable<string>, options?: IDBIndexParameters): IDBIndex;
}
interface MediaKeyStatusMap {
[Symbol.iterator](): IterableIterator<[BufferSource, MediaKeyStatus]>;
entries(): IterableIterator<[BufferSource, MediaKeyStatus]>;
keys(): IterableIterator<BufferSource>;
values(): IterableIterator<MediaKeyStatus>;
}
interface MediaList {
[Symbol.iterator](): IterableIterator<string>;
}
interface MessageEvent<T = any> {
/** @deprecated */
initMessageEvent(type: string, bubbles?: boolean, cancelable?: boolean, data?: any, origin?: string, lastEventId?: string, source?: MessageEventSource | null, ports?: Iterable<MessagePort>): void;
}
interface MimeTypeArray {
[Symbol.iterator](): IterableIterator<MimeType>;
}
interface NamedNodeMap {
[Symbol.iterator](): IterableIterator<Attr>;
}
interface Navigator {
requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: Iterable<MediaKeySystemConfiguration>): Promise<MediaKeySystemAccess>;
vibrate(pattern: Iterable<number>): boolean;
}
interface NodeList {
[Symbol.iterator](): IterableIterator<Node>;
/**
* Returns an array of key, value pairs for every entry in the list.
*/
entries(): IterableIterator<[number, Node]>;
/**
* Returns an list of keys in the list.
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the list.
*/
values(): IterableIterator<Node>;
}
interface NodeListOf<TNode extends Node> {
[Symbol.iterator](): IterableIterator<TNode>;
/**
* Returns an array of key, value pairs for every entry in the list.
*/
entries(): IterableIterator<[number, TNode]>;
/**
* Returns an list of keys in the list.
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the list.
*/
values(): IterableIterator<TNode>;
}
interface Plugin {
[Symbol.iterator](): IterableIterator<MimeType>;
}
interface PluginArray {
[Symbol.iterator](): IterableIterator<Plugin>;
}
interface RTCStatsReport extends ReadonlyMap<string, any> {
}
interface ReadableStream<R = any> {
[Symbol.iterator](): IterableIterator<any>;
entries(): IterableIterator<[number, any]>;
keys(): IterableIterator<number>;
values(): IterableIterator<any>;
}
interface SVGLengthList {
[Symbol.iterator](): IterableIterator<SVGLength>;
}
interface SVGNumberList {
[Symbol.iterator](): IterableIterator<SVGNumber>;
}
interface SVGPointList {
[Symbol.iterator](): IterableIterator<DOMPoint>;
}
interface SVGStringList {
[Symbol.iterator](): IterableIterator<string>;
}
interface SVGTransformList {
[Symbol.iterator](): IterableIterator<SVGTransform>;
}
interface SourceBufferList {
[Symbol.iterator](): IterableIterator<SourceBuffer>;
}
interface SpeechRecognitionResult {
[Symbol.iterator](): IterableIterator<SpeechRecognitionAlternative>;
}
interface SpeechRecognitionResultList {
[Symbol.iterator](): IterableIterator<SpeechRecognitionResult>;
}
interface StyleSheetList {
[Symbol.iterator](): IterableIterator<CSSStyleSheet>;
}
interface SubtleCrypto {
deriveKey(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | HkdfParams | Pbkdf2Params, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKey>;
generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKeyPair>;
generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
generateKey(algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKeyPair | CryptoKey>;
importKey(format: "jwk", keyData: JsonWebKey, algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
importKey(format: Exclude<KeyFormat, "jwk">, keyData: BufferSource, algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKey>;
unwrapKey(format: KeyFormat, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, unwrappedKeyAlgorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKey>;
}
interface TextTrackCueList {
[Symbol.iterator](): IterableIterator<TextTrackCue>;
}
interface TextTrackList {
[Symbol.iterator](): IterableIterator<TextTrack>;
}
interface TouchList {
[Symbol.iterator](): IterableIterator<Touch>;
}
interface URLSearchParams {
[Symbol.iterator](): IterableIterator<[string, string]>;
/**
* Returns an array of key, value pairs for every entry in the search params.
*/
entries(): IterableIterator<[string, string]>;
/**
* Returns a list of keys in the search params.
*/
keys(): IterableIterator<string>;
/**
* Returns a list of values in the search params.
*/
values(): IterableIterator<string>;
}
interface WEBGL_draw_buffers {
drawBuffersWEBGL(buffers: Iterable<GLenum>): void;
}
interface WebGL2RenderingContextBase {
clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Iterable<GLfloat>, srcOffset?: GLuint): void;
clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Iterable<GLint>, srcOffset?: GLuint): void;
clearBufferuiv(buffer: GLenum, drawbuffer: GLint, values: Iterable<GLuint>, srcOffset?: GLuint): void;
drawBuffers(buffers: Iterable<GLenum>): void;
getActiveUniforms(program: WebGLProgram, uniformIndices: Iterable<GLuint>, pname: GLenum): any;
getUniformIndices(program: WebGLProgram, uniformNames: Iterable<string>): Iterable<GLuint> | null;
invalidateFramebuffer(target: GLenum, attachments: Iterable<GLenum>): void;
invalidateSubFramebuffer(target: GLenum, attachments: Iterable<GLenum>, x: GLint, y: GLint, width: GLsizei, height: GLsizei): void;
transformFeedbackVaryings(program: WebGLProgram, varyings: Iterable<string>, bufferMode: GLenum): void;
uniform1uiv(location: WebGLUniformLocation | null, data: Iterable<GLuint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform2uiv(location: WebGLUniformLocation | null, data: Iterable<GLuint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform3uiv(location: WebGLUniformLocation | null, data: Iterable<GLuint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform4uiv(location: WebGLUniformLocation | null, data: Iterable<GLuint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix2x3fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix2x4fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix3x2fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix3x4fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix4x2fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix4x3fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
vertexAttribI4iv(index: GLuint, values: Iterable<GLint>): void;
vertexAttribI4uiv(index: GLuint, values: Iterable<GLuint>): void;
}
interface WebGL2RenderingContextOverloads {
uniform1fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform1iv(location: WebGLUniformLocation | null, data: Iterable<GLint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform2fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform2iv(location: WebGLUniformLocation | null, data: Iterable<GLint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform3fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform3iv(location: WebGLUniformLocation | null, data: Iterable<GLint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform4fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform4iv(location: WebGLUniformLocation | null, data: Iterable<GLint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix2fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix3fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix4fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
}
interface WebGLRenderingContextBase {
vertexAttrib1fv(index: GLuint, values: Iterable<GLfloat>): void;
vertexAttrib2fv(index: GLuint, values: Iterable<GLfloat>): void;
vertexAttrib3fv(index: GLuint, values: Iterable<GLfloat>): void;
vertexAttrib4fv(index: GLuint, values: Iterable<GLfloat>): void;
}
interface WebGLRenderingContextOverloads {
uniform1fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
uniform1iv(location: WebGLUniformLocation | null, v: Iterable<GLint>): void;
uniform2fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
uniform2iv(location: WebGLUniformLocation | null, v: Iterable<GLint>): void;
uniform3fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
uniform3iv(location: WebGLUniformLocation | null, v: Iterable<GLint>): void;
uniform4fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
uniform4iv(location: WebGLUniformLocation | null, v: Iterable<GLint>): void;
uniformMatrix2fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Iterable<GLfloat>): void;
uniformMatrix3fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Iterable<GLfloat>): void;
uniformMatrix4fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Iterable<GLfloat>): void;
}

View file

@ -1,89 +0,0 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Map<K, V> {
clear(): void;
delete(key: K): boolean;
forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value: V): this;
readonly size: number;
}
interface MapConstructor {
new(): Map<any, any>;
new<K, V>(entries?: readonly (readonly [K, V])[] | null): Map<K, V>;
readonly prototype: Map<any, any>;
}
declare var Map: MapConstructor;
interface ReadonlyMap<K, V> {
forEach(callbackfn: (value: V, key: K, map: ReadonlyMap<K, V>) => void, thisArg?: any): void;
get(key: K): V | undefined;
has(key: K): boolean;
readonly size: number;
}
interface WeakMap<K extends object, V> {
delete(key: K): boolean;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value: V): this;
}
interface WeakMapConstructor {
new <K extends object = object, V = any>(entries?: readonly [K, V][] | null): WeakMap<K, V>;
readonly prototype: WeakMap<object, any>;
}
declare var WeakMap: WeakMapConstructor;
interface Set<T> {
add(value: T): this;
clear(): void;
delete(value: T): boolean;
forEach(callbackfn: (value: T, value2: T, set: Set<T>) => void, thisArg?: any): void;
has(value: T): boolean;
readonly size: number;
}
interface SetConstructor {
new <T = any>(values?: readonly T[] | null): Set<T>;
readonly prototype: Set<any>;
}
declare var Set: SetConstructor;
interface ReadonlySet<T> {
forEach(callbackfn: (value: T, value2: T, set: ReadonlySet<T>) => void, thisArg?: any): void;
has(value: T): boolean;
readonly size: number;
}
interface WeakSet<T extends object> {
add(value: T): this;
delete(value: T): boolean;
has(value: T): boolean;
}
interface WeakSetConstructor {
new <T extends object = object>(values?: readonly T[] | null): WeakSet<T>;
readonly prototype: WeakSet<object>;
}
declare var WeakSet: WeakSetConstructor;

View file

@ -1,519 +0,0 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Array<T> {
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find<S extends T>(predicate: (this: void, value: T, index: number, obj: T[]) => value is S, thisArg?: any): S | undefined;
find(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): number;
/**
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: T, start?: number, end?: number): this;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
}
interface ArrayConstructor {
/**
* Creates an array from an array-like object.
* @param arrayLike An array-like object to convert to an array.
*/
from<T>(arrayLike: ArrayLike<T>): T[];
/**
* Creates an array from an iterable object.
* @param arrayLike An array-like object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): U[];
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of<T>(...items: T[]): T[];
}
interface DateConstructor {
new (value: number | string | Date): Date;
}
interface Function {
/**
* Returns the name of the function. Function names are read-only and can not be changed.
*/
readonly name: string;
}
interface Math {
/**
* Returns the number of leading zero bits in the 32-bit binary representation of a number.
* @param x A numeric expression.
*/
clz32(x: number): number;
/**
* Returns the result of 32-bit multiplication of two numbers.
* @param x First number
* @param y Second number
*/
imul(x: number, y: number): number;
/**
* Returns the sign of the x, indicating whether x is positive, negative or zero.
* @param x The numeric expression to test
*/
sign(x: number): number;
/**
* Returns the base 10 logarithm of a number.
* @param x A numeric expression.
*/
log10(x: number): number;
/**
* Returns the base 2 logarithm of a number.
* @param x A numeric expression.
*/
log2(x: number): number;
/**
* Returns the natural logarithm of 1 + x.
* @param x A numeric expression.
*/
log1p(x: number): number;
/**
* Returns the result of (e^x - 1), which is an implementation-dependent approximation to
* subtracting 1 from the exponential function of x (e raised to the power of x, where e
* is the base of the natural logarithms).
* @param x A numeric expression.
*/
expm1(x: number): number;
/**
* Returns the hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
cosh(x: number): number;
/**
* Returns the hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
sinh(x: number): number;
/**
* Returns the hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
tanh(x: number): number;
/**
* Returns the inverse hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
acosh(x: number): number;
/**
* Returns the inverse hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
asinh(x: number): number;
/**
* Returns the inverse hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
atanh(x: number): number;
/**
* Returns the square root of the sum of squares of its arguments.
* @param values Values to compute the square root for.
* If no arguments are passed, the result is +0.
* If there is only one argument, the result is the absolute value.
* If any argument is +Infinity or -Infinity, the result is +Infinity.
* If any argument is NaN, the result is NaN.
* If all arguments are either +0 or 0, the result is +0.
*/
hypot(...values: number[]): number;
/**
* Returns the integral part of the a numeric expression, x, removing any fractional digits.
* If x is already an integer, the result is x.
* @param x A numeric expression.
*/
trunc(x: number): number;
/**
* Returns the nearest single precision float representation of a number.
* @param x A numeric expression.
*/
fround(x: number): number;
/**
* Returns an implementation-dependent approximation to the cube root of number.
* @param x A numeric expression.
*/
cbrt(x: number): number;
}
interface NumberConstructor {
/**
* The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1
* that is representable as a Number value, which is approximately:
* 2.2204460492503130808472633361816 x 1016.
*/
readonly EPSILON: number;
/**
* Returns true if passed value is finite.
* Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
isFinite(number: unknown): boolean;
/**
* Returns true if the value passed is an integer, false otherwise.
* @param number A numeric value.
*/
isInteger(number: unknown): boolean;
/**
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
* number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter
* to a number. Only values of the type number, that are also NaN, result in true.
* @param number A numeric value.
*/
isNaN(number: unknown): boolean;
/**
* Returns true if the value passed is a safe integer.
* @param number A numeric value.
*/
isSafeInteger(number: unknown): boolean;
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as
* a Number value.
* The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 1.
*/
readonly MAX_SAFE_INTEGER: number;
/**
* The value of the smallest integer n such that n and n 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 ((2^53 1)).
*/
readonly MIN_SAFE_INTEGER: number;
/**
* Converts a string to a floating-point number.
* @param string A string that contains a floating-point number.
*/
parseFloat(string: string): number;
/**
* Converts A string to an integer.
* @param string A string to convert into a number.
* @param radix A value between 2 and 36 that specifies the base of the number in `string`.
* If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.
* All other strings are considered decimal.
*/
parseInt(string: string, radix?: number): number;
}
interface ObjectConstructor {
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source The source object from which to copy properties.
*/
assign<T, U>(target: T, source: U): T & U;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
*/
assign<T, U, V>(target: T, source1: U, source2: V): T & U & V;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
* @param source3 The third source object from which to copy properties.
*/
assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param sources One or more source objects from which to copy properties
*/
assign(target: object, ...sources: any[]): any;
/**
* Returns an array of all symbol properties found directly on object o.
* @param o Object to retrieve the symbols from.
*/
getOwnPropertySymbols(o: any): symbol[];
/**
* Returns the names of the enumerable string properties and methods of an object.
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
keys(o: {}): string[];
/**
* Returns true if the values are the same value, false otherwise.
* @param value1 The first value.
* @param value2 The second value.
*/
is(value1: any, value2: any): boolean;
/**
* Sets the prototype of a specified object o to object proto or null. Returns the object o.
* @param o The object to change its prototype.
* @param proto The value of the new prototype or null.
*/
setPrototypeOf(o: any, proto: object | null): any;
}
interface ReadonlyArray<T> {
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find<S extends T>(predicate: (this: void, value: T, index: number, obj: readonly T[]) => value is S, thisArg?: any): S | undefined;
find(predicate: (value: T, index: number, obj: readonly T[]) => unknown, thisArg?: any): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: T, index: number, obj: readonly T[]) => unknown, thisArg?: any): number;
}
interface RegExp {
/**
* Returns a string indicating the flags of the regular expression in question. This field is read-only.
* The characters in this string are sequenced and concatenated in the following order:
*
* - "g" for global
* - "i" for ignoreCase
* - "m" for multiline
* - "u" for unicode
* - "y" for sticky
*
* If no flags are set, the value is the empty string.
*/
readonly flags: string;
/**
* Returns a Boolean value indicating the state of the sticky flag (y) used with a regular
* expression. Default is false. Read-only.
*/
readonly sticky: boolean;
/**
* Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular
* expression. Default is false. Read-only.
*/
readonly unicode: boolean;
}
interface RegExpConstructor {
new (pattern: RegExp | string, flags?: string): RegExp;
(pattern: RegExp | string, flags?: string): RegExp;
}
interface String {
/**
* Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point
* value of the UTF-16 encoded code point starting at the string element at position pos in
* the String resulting from converting this object to a String.
* If there is no element at that position, the result is undefined.
* If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.
*/
codePointAt(pos: number): number | undefined;
/**
* Returns true if searchString appears as a substring of the result of converting this
* object to a String, at one or more positions that are
* greater than or equal to position; otherwise, returns false.
* @param searchString search string
* @param position If position is undefined, 0 is assumed, so as to search all of the String.
*/
includes(searchString: string, position?: number): boolean;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* endPosition length(this). Otherwise returns false.
*/
endsWith(searchString: string, endPosition?: number): boolean;
/**
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
*/
normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string;
/**
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
*/
normalize(form?: string): string;
/**
* Returns a String value that is made from count copies appended together. If count is 0,
* the empty string is returned.
* @param count number of copies to append
*/
repeat(count: number): string;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* position. Otherwise returns false.
*/
startsWith(searchString: string, position?: number): boolean;
/**
* Returns an `<a>` HTML anchor element and sets the name attribute to the text value
* @param name
*/
anchor(name: string): string;
/** Returns a `<big>` HTML element */
big(): string;
/** Returns a `<blink>` HTML element */
blink(): string;
/** Returns a `<b>` HTML element */
bold(): string;
/** Returns a `<tt>` HTML element */
fixed(): string;
/** Returns a `<font>` HTML element and sets the color attribute value */
fontcolor(color: string): string;
/** Returns a `<font>` HTML element and sets the size attribute value */
fontsize(size: number): string;
/** Returns a `<font>` HTML element and sets the size attribute value */
fontsize(size: string): string;
/** Returns an `<i>` HTML element */
italics(): string;
/** Returns an `<a>` HTML element and sets the href attribute value */
link(url: string): string;
/** Returns a `<small>` HTML element */
small(): string;
/** Returns a `<strike>` HTML element */
strike(): string;
/** Returns a `<sub>` HTML element */
sub(): string;
/** Returns a `<sup>` HTML element */
sup(): string;
}
interface StringConstructor {
/**
* Return the String value whose elements are, in order, the elements in the List elements.
* If length is 0, the empty string is returned.
*/
fromCodePoint(...codePoints: number[]): string;
/**
* String.raw is usually used as a tag function of a Tagged Template String. When called as
* such, the first argument will be a well formed template call site object and the rest
* parameter will contain the substitution values. It can also be called directly, for example,
* to interleave strings and values from your own tag function, and in this case the only thing
* it needs from the first argument is the raw property.
* @param template A well-formed template string call site representation.
* @param substitutions A set of substitution values.
*/
raw(template: { raw: readonly string[] | ArrayLike<string>}, ...substitutions: any[]): string;
}

View file

@ -1,30 +0,0 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es5" />
/// <reference lib="es2015.core" />
/// <reference lib="es2015.collection" />
/// <reference lib="es2015.iterable" />
/// <reference lib="es2015.generator" />
/// <reference lib="es2015.promise" />
/// <reference lib="es2015.proxy" />
/// <reference lib="es2015.reflect" />
/// <reference lib="es2015.symbol" />
/// <reference lib="es2015.symbol.wellknown" />

View file

@ -1,79 +0,0 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2015.iterable" />
interface Generator<T = unknown, TReturn = any, TNext = unknown> extends Iterator<T, TReturn, TNext> {
// NOTE: 'next' is defined using a tuple to ensure we report the correct assignability errors in all places.
next(...args: [] | [TNext]): IteratorResult<T, TReturn>;
return(value: TReturn): IteratorResult<T, TReturn>;
throw(e: any): IteratorResult<T, TReturn>;
[Symbol.iterator](): Generator<T, TReturn, TNext>;
}
interface GeneratorFunction {
/**
* Creates a new Generator object.
* @param args A list of arguments the function accepts.
*/
new (...args: any[]): Generator;
/**
* Creates a new Generator object.
* @param args A list of arguments the function accepts.
*/
(...args: any[]): Generator;
/**
* The length of the arguments.
*/
readonly length: number;
/**
* Returns the name of the function.
*/
readonly name: string;
/**
* A reference to the prototype.
*/
readonly prototype: Generator;
}
interface GeneratorFunctionConstructor {
/**
* Creates a new Generator function.
* @param args A list of arguments the function accepts.
*/
new (...args: string[]): GeneratorFunction;
/**
* Creates a new Generator function.
* @param args A list of arguments the function accepts.
*/
(...args: string[]): GeneratorFunction;
/**
* The length of the arguments.
*/
readonly length: number;
/**
* Returns the name of the function.
*/
readonly name: string;
/**
* A reference to the prototype.
*/
readonly prototype: GeneratorFunction;
}

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