Skip to content

Instantly share code, notes, and snippets.

@vgrichina
Last active June 27, 2025 22:37
Show Gist options
  • Save vgrichina/3ea1ae2912cdd2f2a5e8bd10610c26eb to your computer and use it in GitHub Desktop.
Save vgrichina/3ea1ae2912cdd2f2a5e8bd10610c26eb to your computer and use it in GitHub Desktop.
Pug Language Support for ast-grep

Pug Language Support for ast-grep

This guide shows how to use ast-grep with Pug template files using custom language support.

Setup

  1. Built the Pug Parser: We've compiled the tree-sitter-pug parser as a dynamic library (pug.so)

  2. Configuration: Created sgconfig.yml with:

customLanguages:
  pug:
    libraryPath: pug.so
    extensions: [pug]
    expandoChar: _

Usage Examples

Search for elements

# 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

Rewrite patterns

# 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

Test File

Created test.pug with sample Pug content to verify functionality.

Benefits

  • ✅ 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.%

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment