Tree-sitter CSS Grammar
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
- breaking The `tree_sitter.Language.build_library` static method, used for compiling grammars from source, was removed in `tree-sitter` versions 0.22.0 and newer. Attempting to use this method will result in an `AttributeError`.
- gotcha The `tree-sitter-css` package provides the *grammar* but not the *parser* itself. You must always import `Language` and `Parser` from the `tree_sitter` core library. Direct imports like `from tree_sitter_css import Parser` will fail.
- gotcha The core `tree-sitter` library (version 0.25.0+) introduced significant internal ABI bumps and changes to how parsing/querying cancellation is handled. While `tree-sitter-css` at version 0.25.0 should be compatible, older versions of `tree-sitter` (e.g., <0.25.0) might lead to ABI mismatches or require adjusting code using deprecated cancellation patterns.
Install
-
pip install tree-sitter tree-sitter-css
Imports
- language
import tree_sitter_css; from tree_sitter import Language, Parser
Quickstart
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')}")