Tree-sitter CSS Grammar

0.25.0 · active · verified Sun Apr 12

tree-sitter-css is a Python package that provides the pre-compiled Tree-sitter grammar for CSS. It enables the `tree-sitter` Python library to parse CSS code into concrete syntax trees for various applications like syntax highlighting, code analysis, and refactoring tools. The library is actively maintained, with regular updates often aligning with the core `tree-sitter` project.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to install the `tree-sitter` core library and `tree-sitter-css` grammar, load the CSS language object, parse a simple CSS string, and access basic properties of the generated syntax tree's root node. For advanced tree traversal and querying using Tree-sitter's pattern matching capabilities, refer to the `tree-sitter` library's official documentation.

import tree_sitter_css
from tree_sitter import Language, Parser

# Load the CSS language grammar
CSS_LANGUAGE = Language(tree_sitter_css.language())

# Create a parser and set its language
parser = Parser()
parser.set_language(CSS_LANGUAGE)

# Parse some CSS code
css_code = b"""
body {
    font-family: Arial, sans-serif;
    margin: 0;
}
.container {
    padding: 20px;
    display: flex;
}
"""
tree = parser.parse(css_code)

# Access the root node of the syntax tree
root_node = tree.root_node
print(f"Root node type: {root_node.type}")
print(f"Root node children count: {len(root_node.children)}")

# Example: Find a class selector (basic node access for quickstart)
# More advanced usage typically involves tree-sitter Query objects.
for child in root_node.children:
    if child.type == 'rule_set':
        # In Tree-sitter, fields can be accessed by name if defined in grammar
        selector = child.child_by_field_name('selectors')
        if selector:
            print(f"Selector found: {selector.text.decode('utf8')}")

view raw JSON →