Git Product home page Git Product logo

vscode-css-languageservice's Introduction

vscode-css-languageservice

Language services for CSS, LESS and SCSS

npm Package NPM Downloads Build Status License: MIT

Why?

The vscode-css-languageservice contains the language smarts behind the CSS, LESS and SCSS editing experience of Visual Studio Code and the Monaco editor.

  • doValidation analyses an input string and returns syntax and lint errors.
  • doComplete provides completion proposals for a given location.
  • doHover provides a hover text for a given location.
  • findDefinition finds the definition of the symbol at the given location.
  • findReferences finds all references to the symbol at the given location.
  • findDocumentHighlights finds all symbols connected to the given location.
  • findDocumentSymbols provides all symbols in the given document
  • doCodeActions evaluates code actions for the given location, typically to fix a problem.
  • findDocumentColors evaluates all color symbols in the given document
  • doRename renames all symbols connected to the given location.
  • prepareRename the range of the node that can be renamed
  • getFoldingRanges returns folding ranges in the given document.

Installation

npm install --save vscode-css-languageservice

API

For the complete API see cssLanguageService.ts and cssLanguageTypes.ts

Development

  • clone this repo, run `npm install``
  • npm test to compile and run tests

How can I run and debug the service?

  • open the folder in VSCode.
  • set breakpoints, e.g. in cssCompletion.ts
  • run the Unit tests from the run viewlet and wait until a breakpoint is hit: image

How can I run and debug the service inside an instance of VSCode?

  • run VSCode out of sources setup as described here: https://github.com/Microsoft/vscode/wiki/How-to-Contribute
  • run npm link in the folder of vscode-css-languageservice
  • use npm link vscode-css-languageservice in vscode/extensions/css-language-features/server to run VSCode with the latest changes from vscode-css-languageservice
  • run VSCode out of source (vscode/scripts/code.sh|bat) and open a .css file
  • in VSCode window that is open on the vscode-css-languageservice sources, run command Debug: Attach to Node process and pick the code-oss process with the css-language-features path image
  • set breakpoints, e.g. in cssCompletion.ts
  • in the instance run from sources, invoke code completion in the .css file

Note: All CSS entities (properties, at-rules, etc) are sourced from https://github.com/microsoft/vscode-custom-data/tree/master/web-data and transpiled here. For adding new property or fixing existing properties' completion/hover description, please open PR there).

License

(MIT License)

Copyright 2016, 20 Microsoft

With the exceptions of build/mdn-documentation.js, which is built upon content from Mozilla Developer Network and distributed under CC BY-SA 2.5.

vscode-css-languageservice's People

Contributors

aeschli avatar avigoldman avatar avivahl avatar brettjurgens avatar dependabot[bot] avatar fyangstudio avatar joaomoreno avatar johnsoncodehk avatar kiricon avatar kumarharsh avatar marknn3 avatar matthew-dean avatar mrmlnc avatar msftgits avatar octref avatar oldstarchy avatar parzhitsky avatar praveenpuglia avatar ragnoroct avatar ramya-rao-a avatar rebornix avatar romainmenke avatar shpelles avatar sstranks avatar svipas avatar tlent avatar tylerleonhardt avatar tyriar avatar wongjn avatar yume-chan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vscode-css-languageservice's Issues

less validation error

.px2rem(@name, @px) {
@{name}: @px / @basesize;
}
提示:
less } expected
less at-rule or selector expected

请支持less的这种写法,谢谢

Gracefully Handle Unknown At-Rules

Currently, the parser just gives up when it encounters an at-rule it does not understand. This puts the parser into "recovery mode" and can cause some very wonky syntax highlighting until it successfully recovers.

It should be possible to build a generic unknown at-rule parser that will mark the error and gracefully handle any valid at-rule syntax if all other at-rule parsers fail.

Add support for CSS next

According to this comment one should create separate issues for individual features, so here it is :)

It would be great if cssnext nesting was supported. Currently, such syntax causes VS Code to report it as an error, e.g.

vs-code-css-next-syntax-error

Are cssnext features in scope of this CSS language service or should they be implemented as an extension instead?

Published target compatibility with webpack/rollup

The current publishing flow uses a tsconfig.json file (the one in src) and transpiles the module imports/exports to UMD.

When trying to bundle the vscode-css-languageservice npm package alongside monaco-editor-core, webpack errors about require being used in a way that cannot be staticly parsed.

Would you consider publishing to es2015 modules as well, and linking to that entry-point from the package.json's "module" field?

To match with other solutions online, dist folder could be something in the form:
dist/umd/...
dist/esm/...
etc.

The "module" field is being automatically picked by webpack, rollup, and other bundlers, and does not collide with the "main" field. It is only used during bundling.

Css el > el and el + el hover are the same

vscode: v1.9.0

It seems that the hover text for both el > el and el + el are the same:
image
image

In particular I think that the hoover for el > el is the wrong one, since the <p> in this case should be indented.

I'm not sure if this is the right place, or if it's better to move it to the vscode repo.

Maintaining browser support data

Code 1.15 just released. At the time of adding support for display: flow-root to languageservice, I didn't have information about Opera 45 supporting it.

Today I went back to MDN to see it is now supported in Opera 45. This means the property now has to be manually told to support this info in css-schema.xml file.

And not just this but anything that needs change. Currently there are some problems.

  1. It's a tedious manual work.
  2. Mobile support data ins't even present.
  3. MDN's browser support tables aren't 100% reliable.

Can we build a system in the languageservice that automatically pulls in data from cainuse or any other service and then we don't need to painstakingly look for changes in browser support and manually update it?

Disable ignoreComment option

Hello,

I'm working on improving vscode-less extension and want to disable autocompletion in the comments.

How to I can disable ignoreComment option for parseStylesheet?

Support for -webkit-font-smoothing

font-smoothing is not part of the standard, but its prefixed version well supported by webkit / Blink based browsers for a while.
capture d ecran 2017-08-18 a 21 57 04

Any plan to add it?

Completion for Mixins after @include

Failed test:

testCompletionFor('@mixin mixin($a: 1, $b) { content: $a + $b; } @include m|', {
	items: [
		{ label: 'mixin' }
	]
}),

I'll create PR for this case 😈

Support for Sass syntax?

Are there any plans to include support for sass:sass syntax in addition to scss already supported?
We use sass because it's generally accepted in our team that sass is easier to write.
I appreciate there might be a fair amount involved.

Question: extend/ integrate custom rules or remove diagnostics

Not sure if this is a question for vs code itself or this language server, but I am wondering if it is possible to write code to disable diagnostic rules provided by the CSS language service or if I can hook into the CSS language service some way to tell it to allow customized CSS.

I want to be able to allow users to use ${foo} inside files with a .CSS extension but to archive that I think I need to ask users to disable the regular CSS diagnostics by using "css.validate": true, in their settings and clone/ implement the CSS diagnostics with the customized rule/ diagnostics.

Do you know if there is a different/ better way to do this?

The syntax ${foo} is used by Aurelia UX (aurelia/vscode-extension#23)

Thanks in advance,

Erik

Auto complete suggestions project wide

This is a feature request, I'd like to auto-complete to work project wide.

I think it should not try to be overtly clever, e.g. following import statements such as @import "../library.scss"; instead it could just parse all *.scss *.less or *.css files for definitions and show those in auto-completion.

Currently this is extremly painful since I have React app where each component has own scss file, and it basically can't auto-complete anything.

I found the base function, which on each completion uses doComplete(document: TextDocument, position: Position, styleSheet: nodes.Stylesheet)

I think one needs to cache the results of one textdocument, and keep tree of files parsed somewhere so that it doesn't need to parse all documents each time doComplete occurs.

[scss] nested selectors not highlighting

Nested selectors in .scss files do not seem to be highlighting correctly (see the nested ul in screenshot below).
macOS Sierra 10.12.6
VSCode Version 1.18.0 (1.18.0)

screen shot 2017-11-16 at 8 02 47 am

replace "Berber" in css-schema.xml and browsers.js

Please replace the string "Berber" with "Tamazight" in these files:
vscode-css-languageservice-master\build\css-schema.xml
vscode-css-languageservice-master\src\data\browsers.js

Note, there are more specific language names, such as "Central Atlas Tamazight" and "Standard Moroccan Tamazight", but from context it appears the above is correct.

Remove 'Go to definition' result when it's the same as request location

I'm writing a LS for a CSS preprocessor, and when implementing the 'Go to Definition' functionality, I see that whenever a textDocument/definition request is sent, I get back a definition with the same exact location as the original request.
When just working with CSS this means 'Go to Definition' has no visible effect in these cases, but when using our preprocessor it means there are 2 definitions instead of one, so ctrl+click, for example, opens a definition menu instead of jumping straight to the proper place.
For more details see: microsoft/vscode#37526

Can these definition location be removed when, e.g., they are the exact same as the request location?

Project infrastructure: code type safety

Currently, tsconfig does not use the "strict" option, and types inside many files are way too loose.

There are also places that use any implicitly not caught due to this, and cases of null safety ignored by the code and tooling.

I suggest turning on strict checks and fixing the types to reflect exactly each interface.

html

vscode 中package.json所有配置,因为我的html无法识别(view in browser已安装)

Provide support for non standard CSS properties and restrictions in VSCode

Hi, I've been using VSCode a bunch for Dota 2 Custom Games, and it does the job great, except when it comes to how Valve have altered CSS to suit their needs.

A list of their properties can be found here, and having the ability to enhance / replace the current CSS Schema with a new properties and restrictions, such as hue-rotation and hex based color inputs accepting 8 hexadecimal characters for color (#333333b0), as opposed to the normal 6 (#FF0000).

Note I'm not asking to have Valves CSS properties being a part of VSCode, rather providing the infrastructure to allow users to enhance the existing language service with new properties or features.

[less] identifier expected when using @media (@var) syntax

  • VSCode Version: Version 1.19.0-insider
  • OS Version: 10.11.6

Steps to Reproduce:

  1. Declare a less breakpoint variable like @m: ~'min-width: 750px';
  2. Use it in a less file with
    @media (@m) { // rules }

Get a [less] identifier expected error on the @m part.

[feature request] Support @apply

The @apply rule is a proposed spec for implementing native mixins in CSS on top of CSS Custom Properties.

It allows declarations like the following:

body {
  @apply --my-theme;
}

This sees real world usage today, primarily from users of the Polymer library, which ships a polyfill. As of VSCode 1.7.1, this is a syntax error.

Test language aware folding

Refs: #44441

[x] anyOS: JSON
[x] anyOS: HTML
[x] anyOS: TypeScript
Complexity: 3

A new provider API has been added that lets language extensions provide syntax-driven folding ranges:
https://github.com/Microsoft/vscode/blob/20b5c3a9b5c2352ab45d58287225c5ed061c18f8/src/vs/vscode.proposed.d.ts#L419

Adapters for JSON, HTML and TypeScript have been added, but they are still work in progress and not really tested. Please create a single issue per language with the findings.

  • enable the feature by settings

    • JSON: "json.experimental.syntaxFolding": true
    • HTML: "html.experimental.syntaxFolding": true
    • TypeScript: typescript.enableExperimentalFolding": true
  • play around with various file contents:

    • open, verify that fold regions appear. Don't get tricked by the indentation based regions. To make sure that the ranges are syntax-driven (not indentation driven), mess up the indentation.
      • JSON:
        • ranges for objects ({...}) and arrays ([...]) that span over more than 2 lines
        • block comments
        • regions (// #region // #endregion)
      • HTML:
        • ranges for html elements that span over more than 2 lines
        • comments that span over more than 2 lines
        • regions (<!-- #region --> <!-- #endregion -->)
        • no support yet inside embedded content (css/javascript)
      • TypeScript
        • ranges for blocks
        • regions (<!-- #region --> <!-- #endregion -->)
      • verify the behaviour while editing. Folded regions should stay closd
      • try the folding commands:
        - fold/unfold regions
        - fold block comments

parseStylesheet doesn't include the right end property of the stylesheet node

Take this content

.bar {
  op0.1
}

At the end of op0.1, the offset is 14
But the cssParser parses the stylesheet and sets the end of the stylesheet node with 12 instead of 14

screen shot 2018-02-25 at 10 38 45 pm

The context here is that op0.1 is a valid emmet abbreviation and emmet completions fails at this point as the offset is greater than the node(stylesheet)'s end property

Cannot read property 'offset' of null

When using the LESSLanguageService on the following sample less file:

.a(@gutter: @gutter-width) {
  &:extend(.b);
}

trying to call the method findDocumentSymbols triggers the error: TypeError: Cannot read property 'offset' of null.

testing.js

const fs = require('fs');
const path = require('path')
const fileUrl = require('file-url');

const { getLESSLanguageService, LanguageService } = require('vscode-css-languageservice');
const { TextDocument } = require('vscode-languageserver');

const lessLangService = getLESSLanguageService()
const gridLessPath = path.join(__dirname, 'grid.less');

const languageId = gridLessPath.split('.').slice(-1)[0];
const text = fs.readFileSync(gridLessPath, 'utf8');
const document = TextDocument.create(fileUrl(gridLessPath), languageId, 1, text);
const stylesheet = lessLangService.parseStylesheet(document);

lessLangService.findDocumentSymbols(document, stylesheet);
.a(@gutter: @gutter-width) {
  &:extend(.b);
}

Stack trace when running node testing.js

TypeError: Cannot read property 'offset' of null
    at getRange (/Users/pranaygp/github/hq-trivia-assistant/css-peek-crash-example/node_modules/vscode-css-languageservice/lib/umd/services/cssNavigation.js:182:84)
    at /Users/pranaygp/github/hq-trivia-assistant/css-peek-crash-example/node_modules/vscode-css-languageservice/lib/umd/services/cssNavigation.js:115:98
    at Selector.Node.accept (/Users/pranaygp/github/hq-trivia-assistant/css-peek-crash-example/node_modules/vscode-css-languageservice/lib/umd/parser/cssNodes.js:204:17)
    at Nodelist.Node.accept (/Users/pranaygp/github/hq-trivia-assistant/css-peek-crash-example/node_modules/vscode-css-languageservice/lib/umd/parser/cssNodes.js:207:27)
    at ExtendsReference.Node.accept (/Users/pranaygp/github/hq-trivia-assistant/css-peek-crash-example/node_modules/vscode-css-languageservice/lib/umd/parser/cssNodes.js:207:27)
    at Declarations.Node.accept (/Users/pranaygp/github/hq-trivia-assistant/css-peek-crash-example/node_modules/vscode-css-languageservice/lib/umd/parser/cssNodes.js:207:27)
    at MixinDeclaration.Node.accept (/Users/pranaygp/github/hq-trivia-assistant/css-peek-crash-example/node_modules/vscode-css-languageservice/lib/umd/parser/cssNodes.js:207:27)
    at Stylesheet.Node.accept (/Users/pranaygp/github/hq-trivia-assistant/css-peek-crash-example/node_modules/vscode-css-languageservice/lib/umd/parser/cssNodes.js:207:27)
    at CSSNavigation.findDocumentSymbols (/Users/pranaygp/github/hq-trivia-assistant/css-peek-crash-example/node_modules/vscode-css-languageservice/lib/umd/services/cssNavigation.js:83:24)
    at Object.<anonymous> (/Users/pranaygp/github/hq-trivia-assistant/css-peek-crash-example/testing.js:16:29)

[folding] limit number of ranges created

The LSP folding API provides a number of max ranges the that the server should create.
We should pass that limit to the service and limit the number of ranges

CSS Format support

CSS Language Server is consumed inside Eclipse with https://github.com/mickaelistria/eclipse-bluesky It works well but CSS format is not available.

VSCode provides an extension at https://github.com/aeschli/vscode-css-formatter which uses jsbeautify. I understand that you don't want have dependencies to jsbeautify, but it should be fanatstic if you could provide a settings to choose the CSS formatter.

You could provide a CSS formatter interface that a project could implement with jsbeautify, and the CSS client will have the capability to register the CSS formatter to use. In this case any Editor, IDE which supports language server could benefit with CSS format.

Thanks!

Build no longer working due to dependency update.

The build seems to be failing due to the dependency vscode-languageserver-types containing the typing for WorkspaceEdit having been changed recently, making the version index no longer compatible.

No completions after nested selectors

Given the following piece of SCSS code

div {
  &:hover {
    /* ... */
  }
  [CURSOR HERE]
}

when you invoke doComplete from SCSS language service at the denoted place, it returns no completions.

[folding] improve region regex

We want to stay compatible with the css region regexes used for indentation based folding:
https://github.com/Microsoft/vscode/blob/master/extensions/css/language-configuration.json#L26

  • no spaces required before and after #region and #endregion
  • allow freestyle text after #region
	test('Simple region without spaces', () => {
		const input = [
			/*0*/'/*#region*/',
			/*1*/'& .bar {',
			/*2*/'  color: red;',
			/*3*/'}',
			/*4*/'/*#endregion*/'
		];
		assertRanges(input, [r(0, 4, 'region'), r(1, 2)]);
	});

	test('Simple region with description', () => {
		const input = [
			/*0*/'/* #region Header page */',
			/*1*/'.bar {',
			/*2*/'  color: red;',
			/*3*/'}',
			/*4*/'/* #endregion */'
		];
		assertRanges(input, [r(0, 4, 'region'), r(1, 2)]);
	});

[folding] handle intersecting folding regions

Folding ranges must not intersect. Region range should be given precedence.

The tests describe the expected bahaviour:

	test('region intersecting with declaration', () => {
		const input = [
			/*0*/'/* #region */',
			/*1*/'.bar {',
			/*2*/'  color: red;',
			/*3*/'/* #endregion */',
			/*4*/'  display: block;',
			/*5*/'}',
		];
		assertRanges(input, [r(0, 3, 'region')]);
	});	

	test('region intersecting with declaration 2', () => {
		const input = [
			/*0*/'.bar {',
			/*1*/'/* #region */',
			/*2*/'  color: red;',
			/*3*/'}',			
			/*4*/'/* #endregion */',
		];
		assertRanges(input, [r(1, 4, 'region')]);
	});

[SCSS] Syntax Error when `!important` as arguments of Method

VSCode underlines error at !important syntax when it's argument of method if:

@function get-mixin-important-var($important) {
  @return if($important, !important, null);
//                      ~~~ Error: expression expected
}
@mixin heading($important: false) {
  $i: get-mixin-important-var($important);
  font-family: "arial" $i;
}

.heading {
  @include heading(true);
}

However this snippet is valid when pasted to SASS Online Editor (https://www.sassmeister.com/) with option

  • Sass compiler: v3.3.14
  • Syntax: SCSS

And it's compiled to valid CSS:

.heading {
  font-family: "arial" !important;
}

[feature request] Support CSS Custom Properties

CSS Custom Properties are a relatively new standard. Work is in progress to support them in Edge, and they're shipping today in Chrome, Safari, and Firefox.

Custom property usage is fairly straightforward, just an expression like var(--prop-name) or var(--prop-name, exprAsFallbackValue). The main tricky bit is that the allowed syntax for custom property values is extremely permissive, allowing stuff like:

body {
  --js-might-read-this: if(x > 5) this.width = 10;

  --my-theme: {
    color: red;
    background: white;
  };
}

The latter style does see real world usage today to implement mixins, and is reported as a syntax error in vscode as of v1.7.1.

Themes not respecting new @apply support

It looks like themes are not respecting the new @apply rules, at least in regards to color-coding.

Using 1.8.0 stable

screen shot 2016-12-16 at 9 58 51 am

edit: This is the default dark theme, but I see the issue in Dracula, Light+, Monokai, and others

Feature request: setting to disable features like jump to definition/find references

I'm implementing a language service that includes features for jumping to definition / find references with CSS Custom Properties, and I'm finding that the built in CSS Languageservice clashes with the results.

e.g. jump to definition will give two results for the same location with slightly different ranges, turning an instant jump into an interaction with a menu.

(Our language service understands HTML Imports, which is very useful for our users, otherwise I'd just turn off our CSS features in our VSCode plugin and defer to the vscode css languageservice.)

Add a guide to setup development workflow.

Hi,

It isn't mentioned anywhere as to how someone can develop a version locally and test it against a local vscode version.

Here are the things needed.

  1. How to use the local instance of the extension.
  2. How to make sure when you update your extension vscode's watch picks up that change and rebuilds.
  3. How to use debuggers.

I only know about 1. which is,

  • Make sure your extension directory and vscode code directory reside side by side.
somewhere-on-your-pc/
    -vscode-css-languageservice
    -vscode

and then in /vscode/extensions/css/server and run npm run install-service-local.

I can't figure out 2 and 3 however. Help required.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.