This guide shows how to use ast-grep with Pug template files using custom language support.
-
Built the Pug Parser: We've compiled the tree-sitter-pug parser as a dynamic library (
pug.so
) -
Configuration: Created
sgconfig.yml
with:
customLanguages:
pug:
libraryPath: pug.so
extensions: [pug]
expandoChar: _
# Find all h1 elements
ast-grep --lang pug -p 'h1' test.pug
# Find divs with attributes
ast-grep --lang pug -p 'div($ATTRS)' test.pug
# Find list items with content
ast-grep --lang pug -p 'li $CONTENT' test.pug
# Change h1 to h2
ast-grep --lang pug -p 'h1 $TITLE' -r 'h2 $TITLE' test.pug
# Update class attributes
ast-grep --lang pug -p 'div(class="$CLASS")' -r 'div(class="new-$CLASS")' test.pug
Created test.pug
with sample Pug content to verify functionality.
- ✅ Full AST-based parsing of Pug templates
- ✅ Pattern matching with meta-variables ($VAR)
- ✅ Rewrite capabilities for refactoring
- ✅ No modifications needed to ast-grep core
- ✅ Uses experimental custom language feature
This approach is much cleaner than modifying the core ast-grep codebase and can be easily distributed to other users.%