提交 cf6b4b56 编写于 作者: A Alex Dima

Remove the rest of vs/languages

上级 d7397bca
......@@ -47,9 +47,6 @@ const indentationFilter = [
'!**/package.json',
'!**/npm-shrinkwrap.json',
'!**/octicons/**',
'!**/vs/languages/sass/test/common/example.scss',
'!**/vs/languages/less/common/parser/less.grammar.txt',
'!**/vs/languages/css/common/buildscripts/css-schema.xml',
'!**/vs/base/common/marked/raw.marked.js',
'!**/vs/base/common/winjs.base.raw.js',
'!**/vs/base/node/terminateProcess.sh',
......@@ -89,7 +86,6 @@ const tslintFilter = [
'!src/vs/base/**/*.test.ts',
'!extensions/typescript/test/colorize-fixtures/**',
'!extensions/vscode-api-tests/testWorkspace/**',
'!src/vs/languages/**/*.test.ts',
'!src/vs/workbench/**/*.test.ts',
'!extensions/**/*.test.ts'
];
......
......@@ -5,7 +5,7 @@
exports.base = require('./vs/base/buildfile').collectModules();
exports.editor = require('./vs/editor/buildfile').collectModules();
exports.languages = require('./vs/languages/buildfile').collectModules();
exports.languages = [];
exports.workbench = require('./vs/workbench/buildfile').collectModules(['vs/workbench/workbench.main']);
exports.code = require('./vs/code/buildfile').collectModules();
......
/*---------------------------------------------------------------------------------------------
* 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 'vs/languages/html/common/html.contribution';
import { TestInstantiationService } from 'vs/test/utils/instantiationTestUtils';
import * as assert from 'assert';
import { ModeServiceImpl } from 'vs/editor/common/services/modeServiceImpl';
import {IExtensionService} from 'vs/platform/extensions/common/extensions';
suite('Editor Modes - Modes Registry', () => {
let instantiationService: TestInstantiationService;
setup(() => {
instantiationService= new TestInstantiationService();
instantiationService.stub(IExtensionService);
});
test('Bug 12104: [f12] createModel not successfully handling mime type list?', () => {
let modeService = instantiationService.createInstance(ModeServiceImpl);
assert.equal(modeService.getModeId('text/html,text/plain'), 'html');
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
var EntryPoint = (function() {
function toArray(param) {
if (!param) {
return [];
}
if (!Array.isArray(param)) {
return [param];
}
return param;
}
function EntryPoint(result, modules) {
this.result = result;
this.modules = toArray(modules);
}
EntryPoint.prototype.define = function(moduleId, excludes) {
excludes = toArray(excludes);
this.result.push({
name: moduleId,
exclude: ['vs/css', 'vs/nls'].concat(this.modules).concat(excludes)
});
return new EntryPoint(this.result, this.modules.concat([moduleId].concat(excludes)));
};
EntryPoint.prototype.combine = function(other) {
return new EntryPoint(this.result, this.modules.concat(other.modules));
};
return EntryPoint;
})();
exports.collectModules = function(args) {
var result = [];
// var common = new EntryPoint(result, 'vs/editor/common/languages.common');
// var worker = new EntryPoint(result, ['vs/editor/common/languages.common', 'vs/base/common/worker/workerServer', 'vs/editor/common/worker/editorWorkerServer']);
// ---- beautify-html (shared btw html and xml) -----------------------------
// worker.define('vs/languages/lib/common/beautify-html');
// // ---- html ----------------------------------
// common.define('vs/languages/html/common/html')
// .combine(worker)
// .define('vs/languages/html/common/htmlWorker', ['vs/languages/lib/common/beautify-html']);
return result;
};
\ No newline at end of file
// ATTENTION - THIS DIRECTORY CONTAINS THIRD PARTY OPEN SOURCE MATERIALS:
[{
"name": "HTML 5.1 W3C Working Draft",
"version": "08 October 2015",
"license": "W3C Document License",
"repositoryURL": "http://www.w3.org/TR/2015/WD-html51-20151008/",
"licenseDetail": [
"Copyright © 2015 W3C® (MIT, ERCIM, Keio, Beihang). This software or document includes material copied ",
"from or derived from HTML 5.1 W3C Working Draft (http://www.w3.org/TR/2015/WD-html51-20151008/.)",
"",
"THIS DOCUMENT IS PROVIDED \"AS IS,\" AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT ",
"NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, OR TITLE; THAT THE CONTENTS OF ",
"THE DOCUMENT ARE SUITABLE FOR ANY PURPOSE; NOR THAT THE IMPLEMENTATION OF SUCH CONTENTS WILL NOT INFRINGE ANY THIRD PARTY ",
"PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.",
"",
"COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE ",
"DOCUMENT OR THE PERFORMANCE OR IMPLEMENTATION OF THE CONTENTS THEREOF.",
"",
"The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to this document or its contents",
"without specific, written prior permission. Title to copyright in this document will at all times remain with copyright holders."
]
},
{
"name": "Ionic documentation",
"version": "1.2.4",
"license": "Apache2",
"repositoryURL": "https://github.com/driftyco/ionic-site",
"licenseDetail": [
"Copyright Drifty Co. http://drifty.com/.",
"",
"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"
]
}
]
/*---------------------------------------------------------------------------------------------
* 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 {ModesRegistry} from 'vs/editor/common/modes/modesRegistry';
import nls = require('vs/nls');
import platform = require('vs/platform/platform');
import ConfigurationRegistry = require('vs/platform/configuration/common/configurationRegistry');
ModesRegistry.registerCompatMode({
id: 'html',
extensions: ['.html', '.htm', '.shtml', '.xhtml', '.mdoc', '.jsp', '.asp', '.aspx', '.jshtm'],
aliases: ['HTML', 'htm', 'html', 'xhtml'],
mimetypes: ['text/html', 'text/x-jshtm', 'text/template', 'text/ng-template'],
moduleId: 'vs/languages/html/common/html',
ctorName: 'HTMLMode',
deps: ['text/css', 'text/javascript']
});
var configurationRegistry = <ConfigurationRegistry.IConfigurationRegistry>platform.Registry.as(ConfigurationRegistry.Extensions.Configuration);
export interface IHTMLFormatConfiguration {
wrapLineLength: number;
unformatted: string;
indentInnerHtml: boolean;
preserveNewLines: boolean;
maxPreserveNewLines: number;
indentHandlebars: boolean;
endWithNewline: boolean;
extraLiners: string;
}
export interface IHTMLConfiguration {
format: IHTMLFormatConfiguration;
suggest: {[providerId:string]:boolean};
}
configurationRegistry.registerConfiguration({
'id': 'html',
'order': 20,
'type': 'object',
'title': nls.localize('htmlConfigurationTitle', "HTML"),
'properties': {
'html.format.wrapLineLength': {
'type': 'integer',
'default': 120,
'description': nls.localize('format.wrapLineLength', "Maximum amount of characters per line (0 = disable)."),
},
'html.format.unformatted': {
'type': ['string', 'null'],
'default': 'a, abbr, acronym, b, bdo, big, br, button, cite, code, dfn, em, i, img, input, kbd, label, map, object, q, samp, script, select, small, span, strong, sub, sup, textarea, tt, var',
'description': nls.localize('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."),
},
'html.format.indentInnerHtml': {
'type': 'boolean',
'default': false,
'description': nls.localize('format.indentInnerHtml', "Indent <head> and <body> sections."),
},
'html.format.preserveNewLines': {
'type': 'boolean',
'default': true,
'description': nls.localize('format.preserveNewLines', "Whether existing line breaks before elements should be preserved. Only works before elements, not inside tags or for text."),
},
'html.format.maxPreserveNewLines': {
'type': ['number', 'null'],
'default': null,
'description': nls.localize('format.maxPreserveNewLines', "Maximum number of line breaks to be preserved in one chunk. Use 'null' for unlimited."),
},
'html.format.indentHandlebars': {
'type': 'boolean',
'default': false,
'description': nls.localize('format.indentHandlebars', "Format and indent {{#foo}} and {{/foo}}."),
},
'html.format.endWithNewline': {
'type': 'boolean',
'default': false,
'description': nls.localize('format.endWithNewline', "End with a newline."),
},
'html.format.extraLiners': {
'type': ['string', 'null'],
'default': 'head, body, /html',
'description': nls.localize('format.extraLiners', "List of tags, comma separated, that should have an extra newline before them. 'null' defaults to \"head, body, /html\"."),
},
'html.suggest.angular1': {
'type': ['boolean'],
'default': true,
'description': nls.localize('suggest.angular1', "Configures if the built-in HTML language support suggests Angular V1 tags and properties."),
},
'html.suggest.ionic': {
'type': ['boolean'],
'default': true,
'description': nls.localize('suggest.ionic', "Configures if the built-in HTML language support suggests Ionic tags, properties and values."),
},
'html.suggest.html5': {
'type': ['boolean'],
'default': true,
'description': nls.localize('suggest.html5', "Configures if the built-in HTML language support suggests HTML5 tags, properties and values."),
},
}
});
/*---------------------------------------------------------------------------------------------
* 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 URI from 'vs/base/common/uri';
import winjs = require('vs/base/common/winjs.base');
import editorCommon = require('vs/editor/common/editorCommon');
import modes = require('vs/editor/common/modes');
import htmlWorker = require('vs/languages/html/common/htmlWorker');
import { CompatMode, createWordRegExp, ModeWorkerManager } from 'vs/editor/common/modes/abstractMode';
import { AbstractState } from 'vs/editor/common/modes/abstractState';
import {IModeService} from 'vs/editor/common/services/modeService';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import * as htmlTokenTypes from 'vs/languages/html/common/htmlTokenTypes';
import {EMPTY_ELEMENTS} from 'vs/languages/html/common/htmlEmptyTagsShared';
import {LanguageConfigurationRegistry, LanguageConfiguration} from 'vs/editor/common/modes/languageConfigurationRegistry';
import {TokenizationSupport, IModeLocator, ILeavingNestedModeData, ITokenizationCustomization} from 'vs/editor/common/modes/supports/tokenizationSupport';
import {wireCancellationToken} from 'vs/base/common/async';
import {ICompatWorkerService, CompatWorkerAttr} from 'vs/editor/common/services/compatWorkerService';
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import {IConfigurationService} from 'vs/platform/configuration/common/configuration';
import {IHTMLConfiguration} from 'vs/languages/html/common/html.contribution';
import {CharCode} from 'vs/base/common/charCode';
export { htmlTokenTypes }; // export to be used by Razor. We are the main module, so Razor should get it from us.
export { EMPTY_ELEMENTS }; // export to be used by Razor. We are the main module, so Razor should get it from us.
export enum States {
Content,
OpeningStartTag,
OpeningEndTag,
WithinDoctype,
WithinTag,
WithinComment,
WithinEmbeddedContent,
AttributeName,
AttributeValue
}
// list of elements that embed other content
var tagsEmbeddingContent:string[] = ['script', 'style'];
export class State extends AbstractState {
public kind:States;
public lastTagName:string;
public lastAttributeName:string;
public embeddedContentType:string;
public attributeValueQuote:string;
public attributeValueLength:number;
constructor(modeId:string, kind:States, lastTagName:string, lastAttributeName:string, embeddedContentType:string, attributeValueQuote:string, attributeValueLength:number) {
super(modeId);
this.kind = kind;
this.lastTagName = lastTagName;
this.lastAttributeName = lastAttributeName;
this.embeddedContentType = embeddedContentType;
this.attributeValueQuote = attributeValueQuote;
this.attributeValueLength = attributeValueLength;
}
static escapeTagName(s:string):string {
return htmlTokenTypes.getTag(s.replace(/[:_.]/g, '-'));
}
public makeClone():State {
return new State(this.getModeId(), this.kind, this.lastTagName, this.lastAttributeName, this.embeddedContentType, this.attributeValueQuote, this.attributeValueLength);
}
public equals(other:modes.IState):boolean {
if (other instanceof State) {
return (
super.equals(other) &&
this.kind === other.kind &&
this.lastTagName === other.lastTagName &&
this.lastAttributeName === other.lastAttributeName &&
this.embeddedContentType === other.embeddedContentType &&
this.attributeValueQuote === other.attributeValueQuote &&
this.attributeValueLength === other.attributeValueLength
);
}
return false;
}
private nextElementName(stream:modes.IStream):string {
return stream.advanceIfRegExp(/^[_:\w][_:\w-.\d]*/).toLowerCase();
}
private nextAttributeName(stream:modes.IStream):string {
return stream.advanceIfRegExp(/^[^\s"'>/=\x00-\x0F\x7F\x80-\x9F]*/).toLowerCase();
}
public tokenize(stream:modes.IStream) : modes.ITokenizationResult {
switch(this.kind){
case States.WithinComment:
if (stream.advanceUntilString2('-->', false)) {
return { type: htmlTokenTypes.COMMENT};
} else if(stream.advanceIfString2('-->')) {
this.kind = States.Content;
return { type: htmlTokenTypes.DELIM_COMMENT, dontMergeWithPrev: true };
}
break;
case States.WithinDoctype:
if (stream.advanceUntilString2('>', false)) {
return { type: htmlTokenTypes.DOCTYPE};
} else if(stream.advanceIfString2('>')) {
this.kind = States.Content;
return { type: htmlTokenTypes.DELIM_DOCTYPE, dontMergeWithPrev: true };
}
break;
case States.Content:
if (stream.advanceIfCharCode2(CharCode.LessThan)) {
if (!stream.eos() && stream.peek() === '!') {
if (stream.advanceIfString2('!--')) {
this.kind = States.WithinComment;
return { type: htmlTokenTypes.DELIM_COMMENT, dontMergeWithPrev: true };
}
if (stream.advanceIfStringCaseInsensitive2('!DOCTYPE')) {
this.kind = States.WithinDoctype;
return { type: htmlTokenTypes.DELIM_DOCTYPE, dontMergeWithPrev: true };
}
}
if (stream.advanceIfCharCode2(CharCode.Slash)) {
this.kind = States.OpeningEndTag;
return { type: htmlTokenTypes.DELIM_END, dontMergeWithPrev: true };
}
this.kind = States.OpeningStartTag;
return { type: htmlTokenTypes.DELIM_START, dontMergeWithPrev: true };
}
break;
case States.OpeningEndTag:
var tagName = this.nextElementName(stream);
if (tagName.length > 0){
return {
type: State.escapeTagName(tagName),
};
} else if (stream.advanceIfString2('>')) {
this.kind = States.Content;
return { type: htmlTokenTypes.DELIM_END, dontMergeWithPrev: true };
} else {
stream.advanceUntilString2('>', false);
return { type: '' };
}
case States.OpeningStartTag:
this.lastTagName = this.nextElementName(stream);
if (this.lastTagName.length > 0) {
this.lastAttributeName = null;
if ('script' === this.lastTagName || 'style' === this.lastTagName) {
this.lastAttributeName = null;
this.embeddedContentType = null;
}
this.kind = States.WithinTag;
return {
type: State.escapeTagName(this.lastTagName),
};
}
break;
case States.WithinTag:
if (stream.skipWhitespace2() || stream.eos()) {
this.lastAttributeName = ''; // remember that we have seen a whitespace
return { type: '' };
} else {
if (this.lastAttributeName === '') {
var name = this.nextAttributeName(stream);
if (name.length > 0) {
this.lastAttributeName = name;
this.kind = States.AttributeName;
return { type: htmlTokenTypes.ATTRIB_NAME };
}
}
if (stream.advanceIfString2('/>')) {
this.kind = States.Content;
return { type: htmlTokenTypes.DELIM_START, dontMergeWithPrev: true };
}
if (stream.advanceIfCharCode2(CharCode.GreaterThan)) {
if (tagsEmbeddingContent.indexOf(this.lastTagName) !== -1) {
this.kind = States.WithinEmbeddedContent;
return { type: htmlTokenTypes.DELIM_START, dontMergeWithPrev: true };
} else {
this.kind = States.Content;
return { type: htmlTokenTypes.DELIM_START, dontMergeWithPrev: true };
}
} else {
stream.next2();
return { type: '' };
}
}
case States.AttributeName:
if (stream.skipWhitespace2() || stream.eos()){
return { type: '' };
}
if (stream.advanceIfCharCode2(CharCode.Equals)) {
this.kind = States.AttributeValue;
return { type: htmlTokenTypes.DELIM_ASSIGN };
} else {
this.kind = States.WithinTag;
this.lastAttributeName = '';
return this.tokenize(stream); // no advance yet - jump to WithinTag
}
case States.AttributeValue:
if (stream.eos()) {
return { type: '' };
}
if(stream.skipWhitespace2()) {
if (this.attributeValueQuote === '"' || this.attributeValueQuote === '\'') {
// We are inside the quotes of an attribute value
return { type: htmlTokenTypes.ATTRIB_VALUE };
}
return { type: '' };
}
// We are in a attribute value
if (this.attributeValueQuote === '"' || this.attributeValueQuote === '\'') {
if (this.attributeValueLength === 1 && ('script' === this.lastTagName || 'style' === this.lastTagName) && 'type' === this.lastAttributeName) {
let attributeValue = stream.advanceUntilString(this.attributeValueQuote, true);
if (attributeValue.length > 0) {
this.embeddedContentType = this.unquote(attributeValue);
this.kind = States.WithinTag;
this.attributeValueLength = 0;
this.attributeValueQuote = '';
return { type: htmlTokenTypes.ATTRIB_VALUE };
}
} else {
if (stream.advanceIfCharCode2(this.attributeValueQuote.charCodeAt(0))) {
this.kind = States.WithinTag;
this.attributeValueLength = 0;
this.attributeValueQuote = '';
this.lastAttributeName = null;
} else {
stream.next();
this.attributeValueLength++;
}
return { type: htmlTokenTypes.ATTRIB_VALUE };
}
} else {
let attributeValue = stream.advanceIfRegExp(/^[^\s"'`=<>]+/);
if (attributeValue.length > 0) {
this.kind = States.WithinTag;
this.lastAttributeName = null;
return { type: htmlTokenTypes.ATTRIB_VALUE };
}
var ch = stream.peek();
if (ch === '\'' || ch === '"') {
this.attributeValueQuote = ch;
this.attributeValueLength = 1;
stream.next2();
return { type: htmlTokenTypes.ATTRIB_VALUE };
} else {
this.kind = States.WithinTag;
this.lastAttributeName = null;
return this.tokenize(stream); // no advance yet - jump to WithinTag
}
}
}
stream.next2();
this.kind = States.Content;
return { type: '' };
}
private unquote(value:string):string {
var start = 0;
var end = value.length;
if ('"' === value[0]) {
start++;
}
if ('"' === value[end - 1]) {
end--;
}
return value.substring(start, end);
}
}
export class HTMLMode<W extends htmlWorker.HTMLWorker> extends CompatMode implements ITokenizationCustomization {
public static LANG_CONFIG:LanguageConfiguration = {
wordPattern: createWordRegExp('#-?%'),
comments: {
blockComment: ['<!--', '-->']
},
brackets: [
['<!--', '-->'],
['<', '>'],
],
__electricCharacterSupport: {
embeddedElectricCharacters: ['*', '}', ']', ')']
},
autoClosingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' },
{ open: '\'', close: '\'' }
],
surroundingPairs: [
{ open: '"', close: '"' },
{ open: '\'', close: '\'' }
],
onEnterRules: [
{
beforeText: new RegExp(`<(?!(?:${EMPTY_ELEMENTS.join('|')}))([_:\\w][_:\\w-.\\d]*)([^/>]*(?!/)>)[^<]*$`, 'i'),
afterText: /^<\/([_:\w][_:\w-.\d]*)\s*>$/i,
action: { indentAction: modes.IndentAction.IndentOutdent }
},
{
beforeText: new RegExp(`<(?!(?:${EMPTY_ELEMENTS.join('|')}))(\\w[\\w\\d]*)([^/>]*(?!/)>)[^<]*$`, 'i'),
action: { indentAction: modes.IndentAction.Indent }
}
],
};
protected _modeService:IModeService;
private _modeWorkerManager: ModeWorkerManager<W>;
constructor(
descriptor:modes.IModeDescriptor,
@IInstantiationService instantiationService: IInstantiationService,
@IModeService modeService: IModeService,
@ICompatWorkerService compatWorkerService: ICompatWorkerService,
@IWorkspaceContextService private workspaceContextService: IWorkspaceContextService,
@IConfigurationService private configurationService: IConfigurationService
) {
super(descriptor.id, compatWorkerService);
this._modeWorkerManager = this._createModeWorkerManager(descriptor, instantiationService);
this._modeService = modeService;
if (this.compatWorkerService && this.compatWorkerService.isInMainThread) {
let updateConfiguration = () => {
let opts = configurationService.getConfiguration<IHTMLConfiguration>('html');
this._configureWorker(opts);
};
configurationService.onDidUpdateConfiguration((e) => updateConfiguration());
updateConfiguration();
}
this._registerSupports();
}
protected _registerSupports(): void {
if (this.getId() !== 'html') {
throw new Error('This method must be overwritten!');
}
modes.SuggestRegistry.register(this.getId(), {
triggerCharacters: ['.', ':', '<', '"', '=', '/'],
provideCompletionItems: (model, position, token): Thenable<modes.ISuggestResult> => {
return wireCancellationToken(token, this._provideCompletionItems(model.uri, position));
}
}, true);
modes.DocumentHighlightProviderRegistry.register(this.getId(), {
provideDocumentHighlights: (model, position, token): Thenable<modes.DocumentHighlight[]> => {
return wireCancellationToken(token, this._provideDocumentHighlights(model.uri, position));
}
}, true);
modes.DocumentRangeFormattingEditProviderRegistry.register(this.getId(), {
provideDocumentRangeFormattingEdits: (model, range, options, token): Thenable<editorCommon.ISingleEditOperation[]> => {
return wireCancellationToken(token, this._provideDocumentRangeFormattingEdits(model.uri, range, options));
}
}, true);
modes.LinkProviderRegistry.register(this.getId(), {
provideLinks: (model, token): Thenable<modes.ILink[]> => {
return wireCancellationToken(token, this.provideLinks(model.uri));
}
}, true);
LanguageConfigurationRegistry.register(this.getId(), HTMLMode.LANG_CONFIG);
modes.TokenizationRegistry.register(this.getId(), new TokenizationSupport(this._modeService, this.getId(), this, true));
}
protected _createModeWorkerManager(descriptor:modes.IModeDescriptor, instantiationService: IInstantiationService): ModeWorkerManager<W> {
return new ModeWorkerManager<W>(descriptor, 'vs/languages/html/common/htmlWorker', 'HTMLWorker', null, instantiationService);
}
private _worker<T>(runner:(worker:W)=>winjs.TPromise<T>): winjs.TPromise<T> {
return this._modeWorkerManager.worker(runner);
}
// TokenizationSupport
public getInitialState():modes.IState {
return new State(this.getId(), States.Content, '', '', '', '', 0);
}
public enterNestedMode(state:modes.IState):boolean {
return state instanceof State && (<State>state).kind === States.WithinEmbeddedContent;
}
public getNestedMode(state:modes.IState, locator:IModeLocator): modes.IMode {
let htmlState:State = <State>state;
if (htmlState.embeddedContentType !== null) {
return locator.getMode(htmlState.embeddedContentType);
}
if ('script' === htmlState.lastTagName) {
return locator.getMode('text/javascript');
}
if ('style' === htmlState.lastTagName) {
return locator.getMode('text/css');
}
return null;
}
public getLeavingNestedModeData(line:string, state:modes.IState):ILeavingNestedModeData {
var tagName = (<State>state).lastTagName;
var regexp = new RegExp('<\\/' + tagName + '\\s*>', 'i');
var match:any = regexp.exec(line);
if (match !== null) {
return {
nestedModeBuffer: line.substring(0, match.index),
bufferAfterNestedMode: line.substring(match.index),
stateAfterNestedMode: new State(this.getId(), States.Content, '', '', '', '', 0)
};
}
return null;
}
static $_configureWorker = CompatWorkerAttr(HTMLMode, HTMLMode.prototype._configureWorker);
private _configureWorker(options:any): winjs.TPromise<void> {
return this._worker((w) => w._doConfigure(options));
}
protected provideLinks(resource:URI):winjs.TPromise<modes.ILink[]> {
let workspace = this.workspaceContextService.getWorkspace();
let workspaceResource = workspace ? workspace.resource : null;
return this._provideLinks(resource, workspaceResource);
}
static $_provideLinks = CompatWorkerAttr(HTMLMode, HTMLMode.prototype._provideLinks);
private _provideLinks(resource:URI, workspaceResource:URI):winjs.TPromise<modes.ILink[]> {
return this._worker((w) => w.provideLinks(resource, workspaceResource));
}
static $_provideDocumentRangeFormattingEdits = CompatWorkerAttr(HTMLMode, HTMLMode.prototype._provideDocumentRangeFormattingEdits);
private _provideDocumentRangeFormattingEdits(resource:URI, range:editorCommon.IRange, options:modes.FormattingOptions):winjs.TPromise<editorCommon.ISingleEditOperation[]> {
return this._worker((w) => w.provideDocumentRangeFormattingEdits(resource, range, options));
}
static $_provideDocumentHighlights = CompatWorkerAttr(HTMLMode, HTMLMode.prototype._provideDocumentHighlights);
protected _provideDocumentHighlights(resource:URI, position:editorCommon.IPosition, strict:boolean = false): winjs.TPromise<modes.DocumentHighlight[]> {
return this._worker((w) => w.provideDocumentHighlights(resource, position, strict));
}
static $_provideCompletionItems = CompatWorkerAttr(HTMLMode, HTMLMode.prototype._provideCompletionItems);
protected _provideCompletionItems(resource:URI, position:editorCommon.IPosition):winjs.TPromise<modes.ISuggestResult> {
return this._worker((w) => w.provideCompletionItems(resource, position));
}
}
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import arrays = require('vs/base/common/arrays');
export const EMPTY_ELEMENTS:string[] = ['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr'];
export function isEmptyElement(e: string) : boolean {
return arrays.binarySearch(EMPTY_ELEMENTS, e,(s1: string, s2: string) => s1.localeCompare(s2)) >= 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 {isTag, DELIM_END, DELIM_START, DELIM_ASSIGN, ATTRIB_NAME, ATTRIB_VALUE} from 'vs/languages/html/common/htmlTokenTypes';
import EditorCommon = require('vs/editor/common/editorCommon');
export interface IHTMLScanner {
getTokenType(): string;
isOpenBrace(): boolean;
isAtTokenStart(): boolean;
isAtTokenEnd(): boolean;
getTokenContent(): string;
scanBack() : boolean;
scanForward() : boolean;
getTokenPosition(): EditorCommon.IPosition;
getTokenRange(): EditorCommon.IRange;
getModel(): EditorCommon.ITokenizedModel;
}
function isDelimiter(tokenType: string) {
switch (tokenType) {
case DELIM_START:
case DELIM_END:
case DELIM_ASSIGN:
return true;
}
return false;
}
function isInterestingToken(tokenType: string) {
switch (tokenType) {
case DELIM_START:
case DELIM_END:
case DELIM_ASSIGN:
case ATTRIB_NAME:
case ATTRIB_VALUE:
return true;
}
return isTag(tokenType);
}
export function getScanner(model: EditorCommon.ITokenizedModel, position:EditorCommon.IPosition) : IHTMLScanner {
var lineOffset = position.column - 1;
var currentLine = position.lineNumber;
var tokens = model.getLineTokens(currentLine);
var lineContent = model.getLineContent(currentLine);
var tokenIndex = tokens.findTokenIndexAtOffset(lineOffset);
var tokensOnLine = tokens.getTokenCount();
var tokenType = tokens.getTokenType(tokenIndex);
var tokenStart = tokens.getTokenStartOffset(tokenIndex);
var tokenEnd = tokens.getTokenEndOffset(tokenIndex);
if ((tokenType === '' || isDelimiter(tokenType)) && tokenStart === lineOffset) {
tokenIndex--;
if (tokenIndex >= 0) {
// we are at the end of a different token
tokenType = tokens.getTokenType(tokenIndex);
tokenStart = tokens.getTokenStartOffset(tokenIndex);
tokenEnd = tokens.getTokenEndOffset(tokenIndex);
} else {
tokenType = '';
tokenStart = tokenEnd = 0;
}
}
return {
getTokenType: () => tokenType,
isAtTokenEnd: () => lineOffset === tokenEnd,
isAtTokenStart: () => lineOffset === tokenStart,
getTokenContent: () => lineContent.substring(tokenStart, tokenEnd),
isOpenBrace: () => tokenStart < tokenEnd && lineContent.charAt(tokenStart) === '<',
getTokenPosition: () => <EditorCommon.IPosition> { lineNumber: currentLine, column: tokenStart + 1 },
getTokenRange: () => <EditorCommon.IRange> { startLineNumber: currentLine, startColumn: tokenStart + 1, endLineNumber: currentLine, endColumn: tokenEnd + 1 },
getModel: () => model,
scanBack: () => {
if (currentLine <= 0) {
return false;
}
tokenIndex--;
do {
while (tokenIndex >= 0) {
tokenType = tokens.getTokenType(tokenIndex);
tokenStart = tokens.getTokenStartOffset(tokenIndex);
tokenEnd = tokens.getTokenEndOffset(tokenIndex);
if (isInterestingToken(tokenType)) {
return true;
}
tokenIndex--;
}
currentLine--;
if (currentLine > 0) {
tokens = model.getLineTokens(currentLine);
lineContent = model.getLineContent(currentLine);
tokensOnLine = tokens.getTokenCount();
tokenIndex = tokensOnLine - 1;
}
} while (currentLine > 0);
tokens = null;
tokenType = lineContent = '';
tokenStart = tokenEnd = tokensOnLine = 0;
return false;
},
scanForward: () => {
if (currentLine > model.getLineCount()) {
return false;
}
tokenIndex++;
do {
while (tokenIndex < tokensOnLine) {
tokenType = tokens.getTokenType(tokenIndex);
tokenStart = tokens.getTokenStartOffset(tokenIndex);
tokenEnd = tokens.getTokenEndOffset(tokenIndex);
if (isInterestingToken(tokenType)) {
return true;
}
tokenIndex++;
}
currentLine++;
tokenIndex = 0;
if (currentLine <= model.getLineCount()) {
tokens = model.getLineTokens(currentLine);
lineContent = model.getLineContent(currentLine);
tokensOnLine = tokens.getTokenCount();
}
} while (currentLine <= model.getLineCount());
tokenType = lineContent = '';
tokenStart = tokenEnd = tokensOnLine = 0;
return false;
}
};
}
\ No newline at end of file
此差异已折叠。
/*---------------------------------------------------------------------------------------------
* 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 strings = require('vs/base/common/strings');
export const DELIM_END = 'punctuation.definition.meta.tag.end.html';
export const DELIM_START = 'punctuation.definition.meta.tag.begin.html';
export const DELIM_ASSIGN = 'meta.tag.assign.html';
export const ATTRIB_NAME = 'entity.other.attribute-name.html';
export const ATTRIB_VALUE = 'string.html';
export const COMMENT = 'comment.html.content';
export const DELIM_COMMENT = 'comment.html';
export const DOCTYPE = 'entity.other.attribute-name.html';
export const DELIM_DOCTYPE = 'entity.name.tag.html';
const TAG_PREFIX = 'entity.name.tag.tag-';
export function isTag(tokenType: string) {
return strings.startsWith(tokenType, TAG_PREFIX);
}
export function getTag(name: string) {
return TAG_PREFIX + name;
}
\ No newline at end of file
此差异已折叠。
// June 2012
// ATTENTION - THIS DIRECTORY CONTAINS THIRD PARTY OPEN SOURCE MATERIALS: THEY ARE CLEARED ONLY FOR LIMITED USE BY MONACO FOR THE MONACO PRODUCT. DO NOT USE OR SHARE THIS CODE WITHOUT APPROVAL PURSUANT TO THE MICROSOFT OPEN SOURCE SOFTWARE APPROVAL POLICY.APPROVAL
[{
"name": "js-beautify",
"version": "1.6.2",
"license": "MIT",
"repositoryURL": "https://github.com/beautify-web/js-beautify"
}]
\ No newline at end of file
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export interface IBeautifyCSSOptions {
indent_size?: number; // (4) — indentation size,
indent_char?: string; // (space) — character to indent with,
selector_separator_newline?: boolean; // (true) - separate selectors with newline or not (e.g. "a,\nbr" or "a, br")
end_with_newline?: boolean; // (false) - end with a newline
newline_between_rules?: boolean; // (true) - add a new line after every css rule
}
export interface IBeautifyCSS {
(value:string, options:IBeautifyCSSOptions): string;
}
export declare var css_beautify:IBeautifyCSS;
\ No newline at end of file
// copied https://raw.githubusercontent.com/beautify-web/js-beautify/master/js/lib/beautify-css.js
/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */
/*
The MIT License (MIT)
Copyright (c) 2007-2013 Einar Lielmanis and contributors.
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.
CSS Beautifier
---------------
Written by Harutyun Amirjanyan, (amirjanyan@gmail.com)
Based on code initially developed by: Einar Lielmanis, <einar@jsbeautifier.org>
http://jsbeautifier.org/
Usage:
css_beautify(source_text);
css_beautify(source_text, options);
The options are (default in brackets):
indent_size (4) — indentation size,
indent_char (space) — character to indent with,
selector_separator_newline (true) - separate selectors with newline or
not (e.g. "a,\nbr" or "a, br")
end_with_newline (false) - end with a newline
newline_between_rules (true) - add a new line after every css rule
e.g
css_beautify(css_source_text, {
'indent_size': 1,
'indent_char': '\t',
'selector_separator': ' ',
'end_with_newline': false,
'newline_between_rules': true
});
*/
// http://www.w3.org/TR/CSS21/syndata.html#tokenization
// http://www.w3.org/TR/css3-syntax/
(function() {
function css_beautify(source_text, options) {
options = options || {};
source_text = source_text || '';
// HACK: newline parsing inconsistent. This brute force normalizes the input.
source_text = source_text.replace(/\r\n|[\r\u2028\u2029]/g, '\n')
var indentSize = options.indent_size || 4;
var indentCharacter = options.indent_char || ' ';
var selectorSeparatorNewline = (options.selector_separator_newline === undefined) ? true : options.selector_separator_newline;
var end_with_newline = (options.end_with_newline === undefined) ? false : options.end_with_newline;
var newline_between_rules = (options.newline_between_rules === undefined) ? true : options.newline_between_rules;
var eol = options.eol ? options.eol : '\n';
// compatibility
if (typeof indentSize === "string") {
indentSize = parseInt(indentSize, 10);
}
if(options.indent_with_tabs){
indentCharacter = '\t';
indentSize = 1;
}
eol = eol.replace(/\\r/, '\r').replace(/\\n/, '\n')
// tokenizer
var whiteRe = /^\s+$/;
var wordRe = /[\w$\-_]/;
var pos = -1,
ch;
var parenLevel = 0;
function next() {
ch = source_text.charAt(++pos);
return ch || '';
}
function peek(skipWhitespace) {
var result = '';
var prev_pos = pos;
if (skipWhitespace) {
eatWhitespace();
}
result = source_text.charAt(pos + 1) || '';
pos = prev_pos - 1;
next();
return result;
}
function eatString(endChars) {
var start = pos;
while (next()) {
if (ch === "\\") {
next();
} else if (endChars.indexOf(ch) !== -1) {
break;
} else if (ch === "\n") {
break;
}
}
return source_text.substring(start, pos + 1);
}
function peekString(endChar) {
var prev_pos = pos;
var str = eatString(endChar);
pos = prev_pos - 1;
next();
return str;
}
function eatWhitespace() {
var result = '';
while (whiteRe.test(peek())) {
next();
result += ch;
}
return result;
}
function skipWhitespace() {
var result = '';
if (ch && whiteRe.test(ch)) {
result = ch;
}
while (whiteRe.test(next())) {
result += ch;
}
return result;
}
function eatComment(singleLine) {
var start = pos;
singleLine = peek() === "/";
next();
while (next()) {
if (!singleLine && ch === "*" && peek() === "/") {
next();
break;
} else if (singleLine && ch === "\n") {
return source_text.substring(start, pos);
}
}
return source_text.substring(start, pos) + ch;
}
function lookBack(str) {
return source_text.substring(pos - str.length, pos).toLowerCase() ===
str;
}
// Nested pseudo-class if we are insideRule
// and the next special character found opens
// a new block
function foundNestedPseudoClass() {
var openParen = 0;
for (var i = pos + 1; i < source_text.length; i++) {
var ch = source_text.charAt(i);
if (ch === "{") {
return true;
} else if (ch === '(') {
// pseudoclasses can contain ()
openParen += 1;
} else if (ch === ')') {
if (openParen == 0) {
return false;
}
openParen -= 1;
} else if (ch === ";" || ch === "}") {
return false;
}
}
return false;
}
// printer
var basebaseIndentString = source_text.match(/^[\t ]*/)[0];
var singleIndent = new Array(indentSize + 1).join(indentCharacter);
var indentLevel = 0;
var nestedLevel = 0;
function indent() {
indentLevel++;
basebaseIndentString += singleIndent;
}
function outdent() {
indentLevel--;
basebaseIndentString = basebaseIndentString.slice(0, -indentSize);
}
var print = {};
print["{"] = function(ch) {
print.singleSpace();
output.push(ch);
print.newLine();
};
print["}"] = function(ch) {
print.newLine();
output.push(ch);
print.newLine();
};
print._lastCharWhitespace = function() {
return whiteRe.test(output[output.length - 1]);
};
print.newLine = function(keepWhitespace) {
if (output.length) {
if (!keepWhitespace && output[output.length - 1] !== '\n') {
print.trim();
}
output.push('\n');
if (basebaseIndentString) {
output.push(basebaseIndentString);
}
}
};
print.singleSpace = function() {
if (output.length && !print._lastCharWhitespace()) {
output.push(' ');
}
};
print.preserveSingleSpace = function() {
if (isAfterSpace) {
print.singleSpace();
}
};
print.trim = function() {
while (print._lastCharWhitespace()) {
output.pop();
}
};
var output = [];
/*_____________________--------------------_____________________*/
var insideRule = false;
var insidePropertyValue = false;
var enteringConditionalGroup = false;
var top_ch = '';
var last_top_ch = '';
while (true) {
var whitespace = skipWhitespace();
var isAfterSpace = whitespace !== '';
var isAfterNewline = whitespace.indexOf('\n') !== -1;
last_top_ch = top_ch;
top_ch = ch;
if (!ch) {
break;
} else if (ch === '/' && peek() === '*') { /* css comment */
var header = indentLevel === 0;
if (isAfterNewline || header) {
print.newLine();
}
output.push(eatComment());
print.newLine();
if (header) {
print.newLine(true);
}
} else if (ch === '/' && peek() === '/') { // single line comment
if (!isAfterNewline && last_top_ch !== '{' ) {
print.trim();
}
print.singleSpace();
output.push(eatComment());
print.newLine();
} else if (ch === '@') {
print.preserveSingleSpace();
output.push(ch);
// strip trailing space, if present, for hash property checks
var variableOrRule = peekString(": ,;{}()[]/='\"");
if (variableOrRule.match(/[ :]$/)) {
// we have a variable or pseudo-class, add it and insert one space before continuing
next();
variableOrRule = eatString(": ").replace(/\s$/, '');
output.push(variableOrRule);
print.singleSpace();
}
variableOrRule = variableOrRule.replace(/\s$/, '')
// might be a nesting at-rule
if (variableOrRule in css_beautify.NESTED_AT_RULE) {
nestedLevel += 1;
if (variableOrRule in css_beautify.CONDITIONAL_GROUP_RULE) {
enteringConditionalGroup = true;
}
}
} else if (ch === '#' && peek() === '{') {
print.preserveSingleSpace();
output.push(eatString('}'));
} else if (ch === '{') {
if (peek(true) === '}') {
eatWhitespace();
next();
print.singleSpace();
output.push("{}");
print.newLine();
if (newline_between_rules && indentLevel === 0) {
print.newLine(true);
}
} else {
indent();
print["{"](ch);
// when entering conditional groups, only rulesets are allowed
if (enteringConditionalGroup) {
enteringConditionalGroup = false;
insideRule = (indentLevel > nestedLevel);
} else {
// otherwise, declarations are also allowed
insideRule = (indentLevel >= nestedLevel);
}
}
} else if (ch === '}') {
outdent();
print["}"](ch);
insideRule = false;
insidePropertyValue = false;
if (nestedLevel) {
nestedLevel--;
}
if (newline_between_rules && indentLevel === 0) {
print.newLine(true);
}
} else if (ch === ":") {
eatWhitespace();
if ((insideRule || enteringConditionalGroup) &&
!(lookBack("&") || foundNestedPseudoClass())) {
// 'property: value' delimiter
// which could be in a conditional group query
insidePropertyValue = true;
output.push(':');
print.singleSpace();
} else {
// sass/less parent reference don't use a space
// sass nested pseudo-class don't use a space
if (peek() === ":") {
// pseudo-element
next();
output.push("::");
} else {
// pseudo-class
output.push(':');
}
}
} else if (ch === '"' || ch === '\'') {
print.preserveSingleSpace();
output.push(eatString(ch));
} else if (ch === ';') {
insidePropertyValue = false;
output.push(ch);
print.newLine();
} else if (ch === '(') { // may be a url
if (lookBack("url")) {
output.push(ch);
eatWhitespace();
if (next()) {
if (ch !== ')' && ch !== '"' && ch !== '\'') {
output.push(eatString(')'));
} else {
pos--;
}
}
} else {
parenLevel++;
print.preserveSingleSpace();
output.push(ch);
eatWhitespace();
}
} else if (ch === ')') {
output.push(ch);
parenLevel--;
} else if (ch === ',') {
output.push(ch);
eatWhitespace();
if (selectorSeparatorNewline && !insidePropertyValue && parenLevel < 1) {
print.newLine();
} else {
print.singleSpace();
}
} else if (ch === ']') {
output.push(ch);
} else if (ch === '[') {
print.preserveSingleSpace();
output.push(ch);
} else if (ch === '=') { // no whitespace before or after
eatWhitespace()
ch = '=';
output.push(ch);
} else {
print.preserveSingleSpace();
output.push(ch);
}
}
var sweetCode = '';
if (basebaseIndentString) {
sweetCode += basebaseIndentString;
}
sweetCode += output.join('').replace(/[\r\n\t ]+$/, '');
// establish end_with_newline
if (end_with_newline) {
sweetCode += '\n';
}
if (eol != '\n') {
sweetCode = sweetCode.replace(/[\n]/g, eol);
}
return sweetCode;
}
// https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule
css_beautify.NESTED_AT_RULE = {
"@page": true,
"@font-face": true,
"@keyframes": true,
// also in CONDITIONAL_GROUP_RULE below
"@media": true,
"@supports": true,
"@document": true
};
css_beautify.CONDITIONAL_GROUP_RULE = {
"@media": true,
"@supports": true,
"@document": true
};
/*global define */
if (typeof define === "function" && define.amd) {
// Add support for AMD ( https://github.com/amdjs/amdjs-api/wiki/AMD#defineamd-property- )
define([], function() {
return {
css_beautify: css_beautify
};
});
} else if (typeof exports !== "undefined") {
// Add support for CommonJS. Just put this file somewhere on your require.paths
// and you will be able to `var html_beautify = require("beautify").html_beautify`.
exports.css_beautify = css_beautify;
} else if (typeof window !== "undefined") {
// If we're running a web page and don't have either of the above, add our one global
window.css_beautify = css_beautify;
} else if (typeof global !== "undefined") {
// If we don't even have window, try global.
global.css_beautify = css_beautify;
}
}());
\ No newline at end of file
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export interface IBeautifyHTMLOptions {
/**
* indent <head> and <body> sections
* default false
*/
indent_inner_html?: boolean;
/**
* indentation size
* default 4
*/
indent_size?: number; // indentation size,
/**
* character to indent with
* default space
*/
indent_char?: string; // character to indent with,
/**
* maximum amount of characters per line (0 = disable)
* default 250
*/
wrap_line_length?: number;
/**
* put braces on the same line as control statements (default), or put braces on own line (Allman / ANSI style), or just put end braces on own line, or attempt to keep them where they are.
* "collapse" | "expand" | "end-expand" | "none"
* default "collapse"
*/
brace_style?: string;
/**
* list of tags, that shouldn't be reformatted
* defaults to inline tags
*/
unformatted?: string[];
/**
* "keep"|"separate"|"normal"
* default normal
*/
indent_scripts?: string;
/**
* whether existing line breaks before elements should be preserved. Only works before elements, not inside tags or for text.
* default true
*/
preserve_newlines?: boolean;
/**
* maximum number of line breaks to be preserved in one chunk
* default unlimited
*/
max_preserve_newlines?: number;
/**
* format and indent {{#foo}} and {{/foo}}
* default false
*/
indent_handlebars?: boolean;
/**
* end with a newline
* default false
*/
end_with_newline?: boolean;
/**
* List of tags that should have an extra newline before them.
* default [head,body,/html]
*/
extra_liners?: string[];
}
export interface IBeautifyHTML {
(value:string, options:IBeautifyHTMLOptions): string;
}
export declare var html_beautify:IBeautifyHTML;
\ No newline at end of file
此差异已折叠。
The MIT License (MIT)
Copyright (c) 2007-2013 Einar Lielmanis and contributors.
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.
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
* Mock for the JS formatter. Ignore formatting of JS content in HTML.
*/
export function js_beautify(js_source_text: string, options: any) {
// no formatting
return js_source_text;
}
\ No newline at end of file
/*---------------------------------------------------------------------------------------------
* 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 stream = require('stream');
var DefaultSize:number = 8192;
var ContentLength:string = 'Content-Length: ';
var ContentLengthSize:number = Buffer.byteLength(ContentLength, 'utf8');
var Blank:number = new Buffer(' ', 'utf8')[0];
var BackslashR:number = new Buffer('\r', 'utf8')[0];
var BackslashN:number = new Buffer('\n', 'utf8')[0];
class ProtocolBuffer {
private index:number;
private buffer:Buffer;
constructor() {
this.index = 0;
this.buffer = new Buffer(DefaultSize);
}
public append(data:string | Buffer):void {
var toAppend:Buffer = null;
if (Buffer.isBuffer(data)) {
toAppend = <Buffer>data;
} else {
toAppend = new Buffer(<string>data, 'utf8');
}
if (this.buffer.length - this.index >= toAppend.length) {
toAppend.copy(this.buffer, this.index, 0, toAppend.length);
} else {
var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;
if (this.index === 0) {
this.buffer = new Buffer(newSize);
toAppend.copy(this.buffer, 0, 0, toAppend.length);
} else {
this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
}
}
this.index+= toAppend.length;
}
public tryReadContentLength():number {
var result = -1;
var current = 0;
// we are utf8 encoding...
while (current < this.index && (this.buffer[current] === Blank || this.buffer[current] === BackslashR || this.buffer[current] === BackslashN)) {
current++;
}
if (this.index < current + ContentLengthSize) {
return result;
}
current += ContentLengthSize;
var start = current;
while(current < this.index && this.buffer[current] !== BackslashR) {
current++;
}
if (current + 3 >= this.index || this.buffer[current + 1] !== BackslashN || this.buffer[current + 2] !== BackslashR || this.buffer[current + 3] !== BackslashN) {
return result;
}
var data = this.buffer.toString('utf8', start, current);
result = parseInt(data);
this.buffer = this.buffer.slice(current + 4);
this.index = this.index - (current + 4);
return result;
}
public tryReadContent(length:number):string {
if (this.index < length) {
return null;
}
var result = this.buffer.toString('utf8', 0, length);
var sourceStart = length;
while(sourceStart < this.index && (this.buffer[sourceStart] === BackslashR || this.buffer[sourceStart] === BackslashN)) {
sourceStart++;
}
this.buffer.copy(this.buffer, 0, sourceStart);
this.index = this.index - sourceStart;
return result;
}
public tryReadLine():string {
var end:number = 0;
while (end < this.index && this.buffer[end] !== BackslashR && this.buffer[end] !== BackslashN) {
end++;
}
if (end >= this.index) {
return null;
}
var result = this.buffer.toString('utf8', 0, end);
while (end < this.index && (this.buffer[end] === BackslashR || this.buffer[end] === BackslashN)) {
end++;
}
if (this.index === end) {
this.index = 0;
} else {
this.buffer.copy(this.buffer, 0, end);
this.index = this.index - end;
}
return result;
}
public get numberOfBytes():number {
return this.index;
}
}
export enum ReaderType {
Length = 0,
Line = 1
}
export interface ICallback<T> {
(data:T):void;
}
export class Reader<T> {
private readable:stream.Readable;
private callback:ICallback<T>;
private buffer:ProtocolBuffer;
private nextMessageLength:number;
public constructor(readable:stream.Readable, callback:ICallback<T>, type:ReaderType = ReaderType.Length) {
this.readable = readable;
this.buffer = new ProtocolBuffer();
this.callback = callback;
this.nextMessageLength = -1;
if (type === ReaderType.Length) {
this.readable.on('data', (data:Buffer) => {
this.onLengthData(data);
});
} else if (type === ReaderType.Line) {
this.readable.on('data', (data:Buffer) => {
this.onLineData(data);
});
}
}
private onLengthData(data:Buffer):void {
this.buffer.append(data);
while(true) {
if (this.nextMessageLength === -1) {
this.nextMessageLength = this.buffer.tryReadContentLength();
if (this.nextMessageLength === -1) {
return;
}
}
var msg = this.buffer.tryReadContent(this.nextMessageLength);
if (msg === null) {
return;
}
this.nextMessageLength = -1;
var json = JSON.parse(msg);
this.callback(json);
}
}
private onLineData(data:Buffer):void {
this.buffer.append(data);
while(true) {
var msg = this.buffer.tryReadLine();
if (msg === null) {
return;
}
this.callback(JSON.parse(msg));
}
}
}
export class Writer<T> {
private writable:stream.Writable;
public constructor(writable:stream.Writable) {
this.writable = writable;
}
public write(msg:T):void {
var json = JSON.stringify(msg);
var buffer:string[] = [
ContentLength,
Buffer.byteLength(json, 'utf8').toString(),
'\r\n\r\n',
json,
'\r\n'
];
this.writable.write(buffer.join(''), 'utf8');
}
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册