mirror of
https://github.com/microsoft/vscode.git
synced 2026-04-25 02:58:56 +01:00
[css] split extension (for #45900)
This commit is contained in:
33
extensions/css-language-features/server/.vscode/launch.json
vendored
Normal file
33
extensions/css-language-features/server/.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"version": "0.1.0",
|
||||
// List of configurations. Add new configurations or edit existing ones.
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Attach",
|
||||
"type": "node",
|
||||
"request": "attach",
|
||||
"port": 6044,
|
||||
"protocol": "inspector",
|
||||
"sourceMaps": true,
|
||||
"outFiles": ["${workspaceFolder}/out/**/*.js"]
|
||||
},
|
||||
{
|
||||
"name": "Unit Tests",
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"program": "${workspaceFolder}/../../../node_modules/mocha/bin/_mocha",
|
||||
"stopOnEntry": false,
|
||||
"args": [
|
||||
"--timeout",
|
||||
"999999",
|
||||
"--colors"
|
||||
],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"runtimeExecutable": null,
|
||||
"runtimeArgs": [],
|
||||
"env": {},
|
||||
"sourceMaps": true,
|
||||
"outFiles": ["${workspaceFolder}/out/**/*.js"]
|
||||
}
|
||||
]
|
||||
}
|
||||
9
extensions/css-language-features/server/.vscode/tasks.json
vendored
Normal file
9
extensions/css-language-features/server/.vscode/tasks.json
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"version": "0.1.0",
|
||||
"command": "npm",
|
||||
"isShellCommand": true,
|
||||
"showOutput": "silent",
|
||||
"args": ["run", "watch"],
|
||||
"isWatching": true,
|
||||
"problemMatcher": "$tsc-watch"
|
||||
}
|
||||
28
extensions/css-language-features/server/package.json
Normal file
28
extensions/css-language-features/server/package.json
Normal file
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "vscode-css-languageserver",
|
||||
"description": "CSS/LESS/SCSS language server",
|
||||
"version": "1.0.0",
|
||||
"author": "Microsoft Corporation",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "*"
|
||||
},
|
||||
"dependencies": {
|
||||
"vscode-css-languageservice": "^3.0.9-next.1",
|
||||
"vscode-emmet-helper": "^1.2.0",
|
||||
"vscode-languageserver": "^4.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/mocha": "2.2.33",
|
||||
"@types/node": "7.0.43"
|
||||
},
|
||||
"scripts": {
|
||||
"compile": "gulp compile-extension:css-server",
|
||||
"watch": "gulp watch-extension:css-server",
|
||||
"install-service-next": "yarn add vscode-css-languageservice@next",
|
||||
"install-service-local": "npm install ../../../../vscode-css-languageservice -f",
|
||||
"install-server-next": "yarn add vscode-languageserver@next",
|
||||
"install-server-local": "npm install ../../../../vscode-languageserver-node/server -f",
|
||||
"test": "../../../node_modules/.bin/mocha"
|
||||
}
|
||||
}
|
||||
278
extensions/css-language-features/server/src/cssServerMain.ts
Normal file
278
extensions/css-language-features/server/src/cssServerMain.ts
Normal file
@@ -0,0 +1,278 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* 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 {
|
||||
createConnection, IConnection, TextDocuments, InitializeParams, InitializeResult, ServerCapabilities,
|
||||
ConfigurationRequest, WorkspaceFolder, DocumentColorRequest, ColorPresentationRequest
|
||||
} from 'vscode-languageserver';
|
||||
|
||||
import { TextDocument, CompletionList } from 'vscode-languageserver-types';
|
||||
|
||||
import { getCSSLanguageService, getSCSSLanguageService, getLESSLanguageService, LanguageSettings, LanguageService, Stylesheet } from 'vscode-css-languageservice';
|
||||
import { getLanguageModelCache } from './languageModelCache';
|
||||
import { formatError, runSafe } from './utils/errors';
|
||||
import URI from 'vscode-uri';
|
||||
import { getPathCompletionParticipant } from './pathCompletion';
|
||||
|
||||
export interface Settings {
|
||||
css: LanguageSettings;
|
||||
less: LanguageSettings;
|
||||
scss: LanguageSettings;
|
||||
}
|
||||
|
||||
// Create a connection for the server.
|
||||
let connection: IConnection = createConnection();
|
||||
|
||||
console.log = connection.console.log.bind(connection.console);
|
||||
console.error = connection.console.error.bind(connection.console);
|
||||
|
||||
process.on('unhandledRejection', (e: any) => {
|
||||
connection.console.error(formatError(`Unhandled exception`, e));
|
||||
});
|
||||
|
||||
// Create a simple text document manager. The text document manager
|
||||
// supports full document sync only
|
||||
let documents: TextDocuments = new TextDocuments();
|
||||
// Make the text document manager listen on the connection
|
||||
// for open, change and close text document events
|
||||
documents.listen(connection);
|
||||
|
||||
let stylesheets = getLanguageModelCache<Stylesheet>(10, 60, document => getLanguageService(document).parseStylesheet(document));
|
||||
documents.onDidClose(e => {
|
||||
stylesheets.onDocumentRemoved(e.document);
|
||||
});
|
||||
connection.onShutdown(() => {
|
||||
stylesheets.dispose();
|
||||
});
|
||||
|
||||
let scopedSettingsSupport = false;
|
||||
let workspaceFolders: WorkspaceFolder[] | undefined;
|
||||
|
||||
// After the server has started the client sends an initilize request. The server receives
|
||||
// in the passed params the rootPath of the workspace plus the client capabilities.
|
||||
connection.onInitialize((params: InitializeParams): InitializeResult => {
|
||||
workspaceFolders = (<any>params).workspaceFolders;
|
||||
if (!Array.isArray(workspaceFolders)) {
|
||||
workspaceFolders = [];
|
||||
if (params.rootPath) {
|
||||
workspaceFolders.push({ name: '', uri: URI.file(params.rootPath).toString() });
|
||||
}
|
||||
}
|
||||
|
||||
function hasClientCapability(name: string) {
|
||||
let keys = name.split('.');
|
||||
let c: any = params.capabilities;
|
||||
for (let i = 0; c && i < keys.length; i++) {
|
||||
c = c[keys[i]];
|
||||
}
|
||||
return !!c;
|
||||
}
|
||||
let snippetSupport = hasClientCapability('textDocument.completion.completionItem.snippetSupport');
|
||||
scopedSettingsSupport = hasClientCapability('workspace.configuration');
|
||||
let capabilities: ServerCapabilities = {
|
||||
// Tell the client that the server works in FULL text document sync mode
|
||||
textDocumentSync: documents.syncKind,
|
||||
completionProvider: snippetSupport ? { resolveProvider: false } : undefined,
|
||||
hoverProvider: true,
|
||||
documentSymbolProvider: true,
|
||||
referencesProvider: true,
|
||||
definitionProvider: true,
|
||||
documentHighlightProvider: true,
|
||||
codeActionProvider: true,
|
||||
renameProvider: true,
|
||||
colorProvider: true
|
||||
};
|
||||
return { capabilities };
|
||||
});
|
||||
|
||||
let languageServices: { [id: string]: LanguageService } = {
|
||||
css: getCSSLanguageService(),
|
||||
scss: getSCSSLanguageService(),
|
||||
less: getLESSLanguageService()
|
||||
};
|
||||
|
||||
function getLanguageService(document: TextDocument) {
|
||||
let service = languageServices[document.languageId];
|
||||
if (!service) {
|
||||
connection.console.log('Document type is ' + document.languageId + ', using css instead.');
|
||||
service = languageServices['css'];
|
||||
}
|
||||
return service;
|
||||
}
|
||||
|
||||
let documentSettings: { [key: string]: Thenable<LanguageSettings | undefined> } = {};
|
||||
// remove document settings on close
|
||||
documents.onDidClose(e => {
|
||||
delete documentSettings[e.document.uri];
|
||||
});
|
||||
function getDocumentSettings(textDocument: TextDocument): Thenable<LanguageSettings | undefined> {
|
||||
if (scopedSettingsSupport) {
|
||||
let promise = documentSettings[textDocument.uri];
|
||||
if (!promise) {
|
||||
let configRequestParam = { items: [{ scopeUri: textDocument.uri, section: textDocument.languageId }] };
|
||||
promise = connection.sendRequest(ConfigurationRequest.type, configRequestParam).then(s => s[0]);
|
||||
documentSettings[textDocument.uri] = promise;
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
return Promise.resolve(void 0);
|
||||
}
|
||||
|
||||
// The settings have changed. Is send on server activation as well.
|
||||
connection.onDidChangeConfiguration(change => {
|
||||
updateConfiguration(<Settings>change.settings);
|
||||
});
|
||||
|
||||
function updateConfiguration(settings: Settings) {
|
||||
for (let languageId in languageServices) {
|
||||
languageServices[languageId].configure((settings as any)[languageId]);
|
||||
}
|
||||
// reset all document settings
|
||||
documentSettings = {};
|
||||
// Revalidate any open text documents
|
||||
documents.all().forEach(triggerValidation);
|
||||
}
|
||||
|
||||
let pendingValidationRequests: { [uri: string]: NodeJS.Timer } = {};
|
||||
const validationDelayMs = 500;
|
||||
|
||||
// The content of a text document has changed. This event is emitted
|
||||
// when the text document first opened or when its content has changed.
|
||||
documents.onDidChangeContent(change => {
|
||||
triggerValidation(change.document);
|
||||
});
|
||||
|
||||
// a document has closed: clear all diagnostics
|
||||
documents.onDidClose(event => {
|
||||
cleanPendingValidation(event.document);
|
||||
connection.sendDiagnostics({ uri: event.document.uri, diagnostics: [] });
|
||||
});
|
||||
|
||||
function cleanPendingValidation(textDocument: TextDocument): void {
|
||||
let request = pendingValidationRequests[textDocument.uri];
|
||||
if (request) {
|
||||
clearTimeout(request);
|
||||
delete pendingValidationRequests[textDocument.uri];
|
||||
}
|
||||
}
|
||||
|
||||
function triggerValidation(textDocument: TextDocument): void {
|
||||
cleanPendingValidation(textDocument);
|
||||
pendingValidationRequests[textDocument.uri] = setTimeout(() => {
|
||||
delete pendingValidationRequests[textDocument.uri];
|
||||
validateTextDocument(textDocument);
|
||||
}, validationDelayMs);
|
||||
}
|
||||
|
||||
function validateTextDocument(textDocument: TextDocument): void {
|
||||
let settingsPromise = getDocumentSettings(textDocument);
|
||||
settingsPromise.then(settings => {
|
||||
let stylesheet = stylesheets.get(textDocument);
|
||||
let diagnostics = getLanguageService(textDocument).doValidation(textDocument, stylesheet, settings);
|
||||
// Send the computed diagnostics to VSCode.
|
||||
connection.sendDiagnostics({ uri: textDocument.uri, diagnostics });
|
||||
}, e => {
|
||||
connection.console.error(formatError(`Error while validating ${textDocument.uri}`, e));
|
||||
});
|
||||
}
|
||||
|
||||
connection.onCompletion(textDocumentPosition => {
|
||||
return runSafe(() => {
|
||||
let document = documents.get(textDocumentPosition.textDocument.uri);
|
||||
const cssLS = getLanguageService(document);
|
||||
const pathCompletionList: CompletionList = {
|
||||
isIncomplete: false,
|
||||
items: []
|
||||
};
|
||||
cssLS.setCompletionParticipants([getPathCompletionParticipant(document, workspaceFolders, pathCompletionList)]);
|
||||
const result = cssLS.doComplete(document, textDocumentPosition.position, stylesheets.get(document))!; /* TODO: remove ! once LS has null annotations */
|
||||
return {
|
||||
isIncomplete: result.isIncomplete,
|
||||
items: [...pathCompletionList.items, ...result.items]
|
||||
};
|
||||
}, null, `Error while computing completions for ${textDocumentPosition.textDocument.uri}`);
|
||||
});
|
||||
|
||||
connection.onHover(textDocumentPosition => {
|
||||
return runSafe(() => {
|
||||
let document = documents.get(textDocumentPosition.textDocument.uri);
|
||||
let styleSheet = stylesheets.get(document);
|
||||
return getLanguageService(document).doHover(document, textDocumentPosition.position, styleSheet)!; /* TODO: remove ! once LS has null annotations */
|
||||
}, null, `Error while computing hover for ${textDocumentPosition.textDocument.uri}`);
|
||||
});
|
||||
|
||||
connection.onDocumentSymbol(documentSymbolParams => {
|
||||
return runSafe(() => {
|
||||
let document = documents.get(documentSymbolParams.textDocument.uri);
|
||||
let stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).findDocumentSymbols(document, stylesheet);
|
||||
}, [], `Error while computing document symbols for ${documentSymbolParams.textDocument.uri}`);
|
||||
});
|
||||
|
||||
connection.onDefinition(documentSymbolParams => {
|
||||
return runSafe(() => {
|
||||
let document = documents.get(documentSymbolParams.textDocument.uri);
|
||||
let stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).findDefinition(document, documentSymbolParams.position, stylesheet);
|
||||
}, null, `Error while computing definitions for ${documentSymbolParams.textDocument.uri}`);
|
||||
});
|
||||
|
||||
connection.onDocumentHighlight(documentSymbolParams => {
|
||||
return runSafe(() => {
|
||||
let document = documents.get(documentSymbolParams.textDocument.uri);
|
||||
let stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).findDocumentHighlights(document, documentSymbolParams.position, stylesheet);
|
||||
}, [], `Error while computing document highlights for ${documentSymbolParams.textDocument.uri}`);
|
||||
});
|
||||
|
||||
connection.onReferences(referenceParams => {
|
||||
return runSafe(() => {
|
||||
let document = documents.get(referenceParams.textDocument.uri);
|
||||
let stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).findReferences(document, referenceParams.position, stylesheet);
|
||||
}, [], `Error while computing references for ${referenceParams.textDocument.uri}`);
|
||||
});
|
||||
|
||||
connection.onCodeAction(codeActionParams => {
|
||||
return runSafe(() => {
|
||||
let document = documents.get(codeActionParams.textDocument.uri);
|
||||
let stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).doCodeActions(document, codeActionParams.range, codeActionParams.context, stylesheet);
|
||||
}, [], `Error while computing code actions for ${codeActionParams.textDocument.uri}`);
|
||||
});
|
||||
|
||||
connection.onRequest(DocumentColorRequest.type, params => {
|
||||
return runSafe(() => {
|
||||
let document = documents.get(params.textDocument.uri);
|
||||
if (document) {
|
||||
let stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).findDocumentColors(document, stylesheet);
|
||||
}
|
||||
return [];
|
||||
}, [], `Error while computing document colors for ${params.textDocument.uri}`);
|
||||
});
|
||||
|
||||
connection.onRequest(ColorPresentationRequest.type, params => {
|
||||
return runSafe(() => {
|
||||
let document = documents.get(params.textDocument.uri);
|
||||
if (document) {
|
||||
let stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).getColorPresentations(document, stylesheet, params.color, params.range);
|
||||
}
|
||||
return [];
|
||||
}, [], `Error while computing color presentations for ${params.textDocument.uri}`);
|
||||
});
|
||||
|
||||
connection.onRenameRequest(renameParameters => {
|
||||
return runSafe(() => {
|
||||
let document = documents.get(renameParameters.textDocument.uri);
|
||||
let stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).doRename(document, renameParameters.position, renameParameters.newName, stylesheet);
|
||||
}, null, `Error while computing renames for ${renameParameters.textDocument.uri}`);
|
||||
});
|
||||
|
||||
// Listen on the connection
|
||||
connection.listen();
|
||||
@@ -0,0 +1,83 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* 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 { TextDocument } from 'vscode-languageserver';
|
||||
|
||||
export interface LanguageModelCache<T> {
|
||||
get(document: TextDocument): T;
|
||||
onDocumentRemoved(document: TextDocument): void;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export function getLanguageModelCache<T>(maxEntries: number, cleanupIntervalTimeInSec: number, parse: (document: TextDocument) => T): LanguageModelCache<T> {
|
||||
let languageModels: { [uri: string]: { version: number, languageId: string, cTime: number, languageModel: T } } = {};
|
||||
let nModels = 0;
|
||||
|
||||
let cleanupInterval: NodeJS.Timer | undefined = void 0;
|
||||
if (cleanupIntervalTimeInSec > 0) {
|
||||
cleanupInterval = setInterval(() => {
|
||||
let cutoffTime = Date.now() - cleanupIntervalTimeInSec * 1000;
|
||||
let uris = Object.keys(languageModels);
|
||||
for (let uri of uris) {
|
||||
let languageModelInfo = languageModels[uri];
|
||||
if (languageModelInfo.cTime < cutoffTime) {
|
||||
delete languageModels[uri];
|
||||
nModels--;
|
||||
}
|
||||
}
|
||||
}, cleanupIntervalTimeInSec * 1000);
|
||||
}
|
||||
|
||||
return {
|
||||
get(document: TextDocument): T {
|
||||
let version = document.version;
|
||||
let languageId = document.languageId;
|
||||
let languageModelInfo = languageModels[document.uri];
|
||||
if (languageModelInfo && languageModelInfo.version === version && languageModelInfo.languageId === languageId) {
|
||||
languageModelInfo.cTime = Date.now();
|
||||
return languageModelInfo.languageModel;
|
||||
}
|
||||
let languageModel = parse(document);
|
||||
languageModels[document.uri] = { languageModel, version, languageId, cTime: Date.now() };
|
||||
if (!languageModelInfo) {
|
||||
nModels++;
|
||||
}
|
||||
|
||||
if (nModels === maxEntries) {
|
||||
let oldestTime = Number.MAX_VALUE;
|
||||
let oldestUri = null;
|
||||
for (let uri in languageModels) {
|
||||
let languageModelInfo = languageModels[uri];
|
||||
if (languageModelInfo.cTime < oldestTime) {
|
||||
oldestUri = uri;
|
||||
oldestTime = languageModelInfo.cTime;
|
||||
}
|
||||
}
|
||||
if (oldestUri) {
|
||||
delete languageModels[oldestUri];
|
||||
nModels--;
|
||||
}
|
||||
}
|
||||
return languageModel;
|
||||
|
||||
},
|
||||
onDocumentRemoved(document: TextDocument) {
|
||||
let uri = document.uri;
|
||||
if (languageModels[uri]) {
|
||||
delete languageModels[uri];
|
||||
nModels--;
|
||||
}
|
||||
},
|
||||
dispose() {
|
||||
if (typeof cleanupInterval !== 'undefined') {
|
||||
clearInterval(cleanupInterval);
|
||||
cleanupInterval = void 0;
|
||||
languageModels = {};
|
||||
nModels = 0;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
119
extensions/css-language-features/server/src/pathCompletion.ts
Normal file
119
extensions/css-language-features/server/src/pathCompletion.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* 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 path from 'path';
|
||||
import * as fs from 'fs';
|
||||
import URI from 'vscode-uri';
|
||||
|
||||
import { TextDocument, CompletionList, CompletionItemKind, CompletionItem, TextEdit, Range, Position } from 'vscode-languageserver-types';
|
||||
import { WorkspaceFolder } from 'vscode-languageserver';
|
||||
import { ICompletionParticipant } from 'vscode-css-languageservice';
|
||||
|
||||
import { startsWith } from './utils/strings';
|
||||
|
||||
export function getPathCompletionParticipant(
|
||||
document: TextDocument,
|
||||
workspaceFolders: WorkspaceFolder[] | undefined,
|
||||
result: CompletionList
|
||||
): ICompletionParticipant {
|
||||
return {
|
||||
onURILiteralValue: (context: { uriValue: string, position: Position, range: Range; }) => {
|
||||
if (!workspaceFolders || workspaceFolders.length === 0) {
|
||||
return;
|
||||
}
|
||||
const workspaceRoot = resolveWorkspaceRoot(document, workspaceFolders);
|
||||
|
||||
// Handle quoted values
|
||||
let uriValue = context.uriValue;
|
||||
let range = context.range;
|
||||
if (startsWith(uriValue, `'`) || startsWith(uriValue, `"`)) {
|
||||
uriValue = uriValue.slice(1, -1);
|
||||
range = getRangeWithoutQuotes(range);
|
||||
}
|
||||
|
||||
const suggestions = providePathSuggestions(uriValue, range, URI.parse(document.uri).fsPath, workspaceRoot);
|
||||
result.items = [...suggestions, ...result.items];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function providePathSuggestions(value: string, range: Range, activeDocFsPath: string, root?: string): CompletionItem[] {
|
||||
if (startsWith(value, '/') && !root) {
|
||||
return [];
|
||||
}
|
||||
|
||||
let replaceRange: Range;
|
||||
const lastIndexOfSlash = value.lastIndexOf('/');
|
||||
if (lastIndexOfSlash === -1) {
|
||||
replaceRange = getFullReplaceRange(range);
|
||||
} else {
|
||||
const valueAfterLastSlash = value.slice(lastIndexOfSlash + 1);
|
||||
replaceRange = getReplaceRange(range, valueAfterLastSlash);
|
||||
}
|
||||
|
||||
let parentDir: string;
|
||||
if (lastIndexOfSlash === -1) {
|
||||
parentDir = path.resolve(root);
|
||||
} else {
|
||||
const valueBeforeLastSlash = value.slice(0, lastIndexOfSlash + 1);
|
||||
|
||||
parentDir = startsWith(value, '/')
|
||||
? path.resolve(root, '.' + valueBeforeLastSlash)
|
||||
: path.resolve(activeDocFsPath, '..', valueBeforeLastSlash);
|
||||
}
|
||||
|
||||
try {
|
||||
return fs.readdirSync(parentDir).map(f => {
|
||||
if (isDir(path.resolve(parentDir, f))) {
|
||||
return {
|
||||
label: f + '/',
|
||||
kind: CompletionItemKind.Folder,
|
||||
textEdit: TextEdit.replace(replaceRange, f + '/'),
|
||||
command: {
|
||||
title: 'Suggest',
|
||||
command: 'editor.action.triggerSuggest'
|
||||
}
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
label: f,
|
||||
kind: CompletionItemKind.File,
|
||||
textEdit: TextEdit.replace(replaceRange, f)
|
||||
};
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
const isDir = (p: string) => {
|
||||
return fs.statSync(p).isDirectory();
|
||||
};
|
||||
|
||||
function resolveWorkspaceRoot(activeDoc: TextDocument, workspaceFolders: WorkspaceFolder[]): string | undefined {
|
||||
for (let i = 0; i < workspaceFolders.length; i++) {
|
||||
if (startsWith(activeDoc.uri, workspaceFolders[i].uri)) {
|
||||
return path.resolve(URI.parse(workspaceFolders[i].uri).fsPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getFullReplaceRange(valueRange: Range) {
|
||||
const start = Position.create(valueRange.end.line, valueRange.start.character);
|
||||
const end = Position.create(valueRange.end.line, valueRange.end.character);
|
||||
return Range.create(start, end);
|
||||
}
|
||||
function getReplaceRange(valueRange: Range, valueAfterLastSlash: string) {
|
||||
const start = Position.create(valueRange.end.line, valueRange.end.character - valueAfterLastSlash.length);
|
||||
const end = Position.create(valueRange.end.line, valueRange.end.character);
|
||||
return Range.create(start, end);
|
||||
}
|
||||
function getRangeWithoutQuotes(range: Range) {
|
||||
const start = Position.create(range.start.line, range.start.character + 1);
|
||||
const end = Position.create(range.end.line, range.end.character - 1);
|
||||
return Range.create(start, end);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* 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 'mocha';
|
||||
import * as assert from 'assert';
|
||||
import * as path from 'path';
|
||||
import Uri from 'vscode-uri';
|
||||
import { TextDocument, CompletionList } from 'vscode-languageserver-types';
|
||||
import { WorkspaceFolder } from 'vscode-languageserver-protocol';
|
||||
import { getPathCompletionParticipant } from '../pathCompletion';
|
||||
import { getCSSLanguageService } from 'vscode-css-languageservice';
|
||||
|
||||
export interface ItemDescription {
|
||||
label: string;
|
||||
resultText?: string;
|
||||
}
|
||||
|
||||
suite('Completions', () => {
|
||||
const cssLanguageService = getCSSLanguageService();
|
||||
|
||||
let assertCompletion = function (completions: CompletionList, expected: ItemDescription, document: TextDocument, offset: number) {
|
||||
let matches = completions.items.filter(completion => {
|
||||
return completion.label === expected.label;
|
||||
});
|
||||
|
||||
assert.equal(matches.length, 1, `${expected.label} should only existing once: Actual: ${completions.items.map(c => c.label).join(', ')}`);
|
||||
let match = matches[0];
|
||||
if (expected.resultText && match.textEdit) {
|
||||
assert.equal(TextDocument.applyEdits(document, [match.textEdit]), expected.resultText);
|
||||
}
|
||||
};
|
||||
|
||||
function assertCompletions(value: string, expected: { count?: number, items?: ItemDescription[] }, testUri: string, workspaceFolders?: WorkspaceFolder[]): void {
|
||||
const offset = value.indexOf('|');
|
||||
value = value.substr(0, offset) + value.substr(offset + 1);
|
||||
|
||||
const document = TextDocument.create(testUri, 'css', 0, value);
|
||||
const position = document.positionAt(offset);
|
||||
|
||||
if (!workspaceFolders) {
|
||||
workspaceFolders = [{ name: 'x', uri: path.dirname(testUri) }];
|
||||
}
|
||||
|
||||
let participantResult = CompletionList.create([]);
|
||||
cssLanguageService.setCompletionParticipants([getPathCompletionParticipant(document, workspaceFolders, participantResult)]);
|
||||
|
||||
const stylesheet = cssLanguageService.parseStylesheet(document);
|
||||
let list = cssLanguageService.doComplete!(document, position, stylesheet);
|
||||
list.items = list.items.concat(participantResult.items);
|
||||
|
||||
if (expected.count) {
|
||||
assert.equal(list.items.length, expected.count);
|
||||
}
|
||||
if (expected.items) {
|
||||
for (let item of expected.items) {
|
||||
assertCompletion(list, item, document, offset);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test('CSS Path completion', function () {
|
||||
let testUri = Uri.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).fsPath;
|
||||
|
||||
assertCompletions('html { background-image: url("./|")', {
|
||||
items: [
|
||||
{ label: 'about.html', resultText: 'html { background-image: url("./about.html")' }
|
||||
]
|
||||
}, testUri);
|
||||
|
||||
assertCompletions(`html { background-image: url('../|')`, {
|
||||
items: [
|
||||
{ label: 'about/', resultText: `html { background-image: url('../about/')` },
|
||||
{ label: 'index.html', resultText: `html { background-image: url('../index.html')` },
|
||||
{ label: 'src/', resultText: `html { background-image: url('../src/')` }
|
||||
]
|
||||
}, testUri);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* 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 'mocha';
|
||||
import * as assert from 'assert';
|
||||
import { getCSSLanguageService, getSCSSLanguageService } from 'vscode-css-languageservice/lib/umd/cssLanguageService';
|
||||
import { TextDocument, CompletionList } from 'vscode-languageserver-types';
|
||||
import { getEmmetCompletionParticipants } from 'vscode-emmet-helper';
|
||||
|
||||
suite('CSS Emmet Support', () => {
|
||||
|
||||
const cssLanguageService = getCSSLanguageService();
|
||||
const scssLanguageService = getSCSSLanguageService();
|
||||
|
||||
function assertCompletions(syntax: string, value: string, expectedProposal: string, expectedProposalDoc: string): void {
|
||||
const offset = value.indexOf('|');
|
||||
value = value.substr(0, offset) + value.substr(offset + 1);
|
||||
|
||||
const document = TextDocument.create('test://test/test.' + syntax, syntax, 0, value);
|
||||
const position = document.positionAt(offset);
|
||||
const emmetCompletionList: CompletionList = {
|
||||
isIncomplete: true,
|
||||
items: undefined
|
||||
};
|
||||
const languageService = syntax === 'scss' ? scssLanguageService : cssLanguageService;
|
||||
languageService.setCompletionParticipants([getEmmetCompletionParticipants(document, position, document.languageId, {}, emmetCompletionList)]);
|
||||
const stylesheet = languageService.parseStylesheet(document);
|
||||
const list = languageService.doComplete!(document, position, stylesheet);
|
||||
|
||||
assert.ok(list);
|
||||
assert.ok(emmetCompletionList);
|
||||
|
||||
if (expectedProposal && expectedProposalDoc) {
|
||||
let actualLabels = (emmetCompletionList!.items || []).map(c => c.label).sort();
|
||||
let actualDocs = (emmetCompletionList!.items || []).map(c => c.documentation).sort();
|
||||
assert.ok(actualLabels.indexOf(expectedProposal) !== -1, 'Not found:' + expectedProposal + ' is ' + actualLabels.join(', '));
|
||||
assert.ok(actualDocs.indexOf(expectedProposalDoc) !== -1, 'Not found:' + expectedProposalDoc + ' is ' + actualDocs.join(', '));
|
||||
} else {
|
||||
assert.ok(!emmetCompletionList || !emmetCompletionList.items);
|
||||
}
|
||||
}
|
||||
|
||||
test('Css Emmet Completions', function (): any {
|
||||
this.skip(); // disabled again (see #29113)
|
||||
|
||||
assertCompletions('css', '.foo { display: none; m10| }', 'margin: 10px;', 'margin: 10px;');
|
||||
assertCompletions('css', 'foo { display: none; pos:f| }', 'position: fixed;', 'position: fixed;');
|
||||
assertCompletions('css', 'foo { display: none; margin: a| }', null, null);
|
||||
assertCompletions('css', 'foo| { display: none; }', null, null);
|
||||
assertCompletions('css', 'foo {| display: none; }', null, null);
|
||||
assertCompletions('css', 'foo { display: none;| }', null, null);
|
||||
assertCompletions('css', 'foo { display: none|; }', null, null);
|
||||
assertCompletions('css', '.foo { display: none; -m-m10| }', 'margin: 10px;', '-moz-margin: 10px;\nmargin: 10px;');
|
||||
});
|
||||
|
||||
test('Scss Emmet Completions', function (): any {
|
||||
this.skip(); // disabled again (see #29113)
|
||||
|
||||
assertCompletions('scss', '.foo { display: none; .bar { m10| } }', 'margin: 10px;', 'margin: 10px;');
|
||||
assertCompletions('scss', 'foo { display: none; .bar { pos:f| } }', 'position: fixed;', 'position: fixed;');
|
||||
assertCompletions('scss', 'foo { display: none; margin: a| .bar {}}', null, null);
|
||||
assertCompletions('scss', 'foo| { display: none; }', null, null);
|
||||
assertCompletions('scss', 'foo {| display: none; }', null, null);
|
||||
assertCompletions('scss', 'foo { display: none;| }', null, null);
|
||||
assertCompletions('scss', 'foo { display: none|; }', null, null);
|
||||
assertCompletions('scss', '.foo { display: none; -m-m10| }', 'margin: 10px;', '-moz-margin: 10px;\nmargin: 10px;');
|
||||
});
|
||||
});
|
||||
33
extensions/css-language-features/server/src/utils/errors.ts
Normal file
33
extensions/css-language-features/server/src/utils/errors.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
'use strict';
|
||||
|
||||
export function formatError(message: string, err: any): string {
|
||||
if (err instanceof Error) {
|
||||
let error = <Error>err;
|
||||
return `${message}: ${error.message}\n${error.stack}`;
|
||||
} else if (typeof err === 'string') {
|
||||
return `${message}: ${err}`;
|
||||
} else if (err) {
|
||||
return `${message}: ${err.toString()}`;
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
export function runSafe<T>(func: () => Thenable<T> | T, errorVal: T, errorMessage: string): Thenable<T> | T {
|
||||
try {
|
||||
let t = func();
|
||||
if (t instanceof Promise) {
|
||||
return t.then(void 0, e => {
|
||||
console.error(formatError(errorMessage, e));
|
||||
return errorVal;
|
||||
});
|
||||
}
|
||||
return t;
|
||||
} catch (e) {
|
||||
console.error(formatError(errorMessage, e));
|
||||
return errorVal;
|
||||
}
|
||||
}
|
||||
19
extensions/css-language-features/server/src/utils/strings.ts
Normal file
19
extensions/css-language-features/server/src/utils/strings.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
'use strict';
|
||||
|
||||
export function startsWith(haystack: string, needle: string): boolean {
|
||||
if (haystack.length < needle.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (let i = 0; i < needle.length; i++) {
|
||||
if (haystack[i] !== needle[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
3
extensions/css-language-features/server/test/mocha.opts
Normal file
3
extensions/css-language-features/server/test/mocha.opts
Normal file
@@ -0,0 +1,3 @@
|
||||
--ui tdd
|
||||
--useColors true
|
||||
./out/test
|
||||
@@ -0,0 +1,4 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
@@ -0,0 +1,4 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
@@ -0,0 +1,4 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
14
extensions/css-language-features/server/tsconfig.json
Normal file
14
extensions/css-language-features/server/tsconfig.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"module": "commonjs",
|
||||
"outDir": "./out",
|
||||
"noUnusedLocals": true,
|
||||
"lib": [
|
||||
"es5", "es2015.promise"
|
||||
]
|
||||
},
|
||||
"include": [
|
||||
"src/**/*"
|
||||
]
|
||||
}
|
||||
68
extensions/css-language-features/server/yarn.lock
Normal file
68
extensions/css-language-features/server/yarn.lock
Normal file
@@ -0,0 +1,68 @@
|
||||
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
|
||||
# yarn lockfile v1
|
||||
|
||||
|
||||
"@emmetio/extract-abbreviation@0.1.6":
|
||||
version "0.1.6"
|
||||
resolved "https://registry.yarnpkg.com/@emmetio/extract-abbreviation/-/extract-abbreviation-0.1.6.tgz#e4a9856c1057f0aff7d443b8536477c243abe28c"
|
||||
|
||||
"@types/mocha@2.2.33":
|
||||
version "2.2.33"
|
||||
resolved "https://registry.yarnpkg.com/@types/mocha/-/mocha-2.2.33.tgz#d79a0061ec270379f4d9e225f4096fb436669def"
|
||||
|
||||
"@types/node@7.0.43":
|
||||
version "7.0.43"
|
||||
resolved "https://registry.yarnpkg.com/@types/node/-/node-7.0.43.tgz#a187e08495a075f200ca946079c914e1a5fe962c"
|
||||
|
||||
jsonc-parser@^1.0.0:
|
||||
version "1.0.0"
|
||||
resolved "https://registry.yarnpkg.com/jsonc-parser/-/jsonc-parser-1.0.0.tgz#ddcc864ae708e60a7a6dd36daea00172fa8d9272"
|
||||
|
||||
vscode-css-languageservice@^3.0.9-next.1:
|
||||
version "3.0.9-next.1"
|
||||
resolved "https://registry.yarnpkg.com/vscode-css-languageservice/-/vscode-css-languageservice-3.0.9-next.1.tgz#92319b641a7624e84950aef2c55e5b4db001ff9a"
|
||||
dependencies:
|
||||
vscode-languageserver-types "^3.6.1"
|
||||
vscode-nls "^3.2.1"
|
||||
|
||||
vscode-emmet-helper@^1.2.0:
|
||||
version "1.2.0"
|
||||
resolved "https://registry.yarnpkg.com/vscode-emmet-helper/-/vscode-emmet-helper-1.2.0.tgz#6b9311be065c9c99d5de2dae18ea0730d9cfb734"
|
||||
dependencies:
|
||||
"@emmetio/extract-abbreviation" "0.1.6"
|
||||
jsonc-parser "^1.0.0"
|
||||
vscode-languageserver-types "^3.6.0-next.1"
|
||||
|
||||
vscode-jsonrpc@^3.6.0:
|
||||
version "3.6.0"
|
||||
resolved "https://registry.yarnpkg.com/vscode-jsonrpc/-/vscode-jsonrpc-3.6.0.tgz#848d56995d5168950d84feb5d9c237ae5c6a02d4"
|
||||
|
||||
vscode-languageserver-protocol@^3.6.0:
|
||||
version "3.6.0"
|
||||
resolved "https://registry.yarnpkg.com/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.6.0.tgz#579642cdcccf74b0cd771c33daa3239acb40d040"
|
||||
dependencies:
|
||||
vscode-jsonrpc "^3.6.0"
|
||||
vscode-languageserver-types "^3.6.0"
|
||||
|
||||
vscode-languageserver-types@^3.6.0, vscode-languageserver-types@^3.6.1:
|
||||
version "3.6.1"
|
||||
resolved "https://registry.yarnpkg.com/vscode-languageserver-types/-/vscode-languageserver-types-3.6.1.tgz#4bc06a48dff653495f12f94b8b1e228988a1748d"
|
||||
|
||||
vscode-languageserver-types@^3.6.0-next.1:
|
||||
version "3.6.0-next.1"
|
||||
resolved "https://registry.yarnpkg.com/vscode-languageserver-types/-/vscode-languageserver-types-3.6.0-next.1.tgz#98e488d3f87b666b4ee1a3d89f0023e246d358f3"
|
||||
|
||||
vscode-languageserver@^4.0.0:
|
||||
version "4.0.0"
|
||||
resolved "https://registry.yarnpkg.com/vscode-languageserver/-/vscode-languageserver-4.0.0.tgz#8b792f0d6d10acfe363d02371ed4ce53d08af88a"
|
||||
dependencies:
|
||||
vscode-languageserver-protocol "^3.6.0"
|
||||
vscode-uri "^1.0.1"
|
||||
|
||||
vscode-nls@^3.2.1:
|
||||
version "3.2.2"
|
||||
resolved "https://registry.yarnpkg.com/vscode-nls/-/vscode-nls-3.2.2.tgz#3817eca5b985c2393de325197cf4e15eb2aa5350"
|
||||
|
||||
vscode-uri@^1.0.1:
|
||||
version "1.0.1"
|
||||
resolved "https://registry.yarnpkg.com/vscode-uri/-/vscode-uri-1.0.1.tgz#11a86befeac3c4aa3ec08623651a3c81a6d0bbc8"
|
||||
Reference in New Issue
Block a user