Save Ukraine

Emacs 29: Install Tree-Sitter parser modules with an Emacs package

Christian Kruse,

Sadly installing grammars has to be done manually, and it is not trivial: you need to compile a grammar and copy the resulting .so or .dylib file to the right directory. To make handling a bit easier I wrote a small Emacs package for that: treesit-parser-manager.

You define a list of parsers and treesit-parser-manager takes care of the rest. For example my list looks like this:

(setq treesit-parser-manager-grammars
      '(
        ("https://github.com/tree-sitter/tree-sitter-rust"
         ("tree-sitter-rust"))

        ("https://github.com/ikatyang/tree-sitter-toml"
         ("tree-sitter-toml"))

        ("https://github.com/elixir-lang/tree-sitter-elixir"
         ("tree-sitter-elixir"))

        ("https://github.com/tree-sitter/tree-sitter-typescript"
         ("tree-sitter-typescript/tsx" "tree-sitter-typescript/typescript"))

        ("https://github.com/tree-sitter/tree-sitter-javascript"
         ("tree-sitter-javascript"))

        ("https://github.com/tree-sitter/tree-sitter-css"
         ("tree-sitter-css"))

        ("https://github.com/serenadeai/tree-sitter-scss"
         ("tree-sitter-scss"))

        ("https://github.com/tree-sitter/tree-sitter-json"
         ("tree-sitter-json"))))

This defines a list with the grammars for Rust, TOML files, Elixir, TypeScript and TSX, JavaScript, CSS, SCSS and JSON. Now I can call treesit-parser-manager-compile-or-update and my little Emacs mode installs (or updates) the desired grammars.

A complete setup using straight could look like this:

(use-package treesit-parser-manager
  :straight (treesit-parser-manager :host codeberg :repo "ckruse/treesit-parser-manager" :files ("*.el"))
  :commands (treesit-parser-manager-install-grammars
             treesit-parser-manager-update-grammars
             treesit-parser-manager-install-or-update-grammars
             treesit-parser-manager-remove-grammar)
  :custom
  (treesit-parser-manager-grammars
   '(("https://github.com/tree-sitter/tree-sitter-rust"
      ("tree-sitter-rust"))

     ("https://github.com/ikatyang/tree-sitter-toml"
      ("tree-sitter-toml"))

     ("https://github.com/elixir-lang/tree-sitter-elixir"
      ("tree-sitter-elixir"))

     ("https://github.com/tree-sitter/tree-sitter-typescript"
      ("tree-sitter-typescript/tsx" "tree-sitter-typescript/typescript"))

     ("https://github.com/tree-sitter/tree-sitter-javascript"
      ("tree-sitter-javascript"))

     ("https://github.com/tree-sitter/tree-sitter-css"
      ("tree-sitter-css"))

     ("https://github.com/serenadeai/tree-sitter-scss"
      ("tree-sitter-scss"))

     ("https://github.com/tree-sitter/tree-sitter-json"
      ("tree-sitter-json"))))
  :config
  (setq treesit-extra-load-path (list (expand-file-name "tree-sit" user-emacs-directory)))
  :hook (emacs-startup . treesit-parser-manager-install-grammars))

I hope this helps some fellow Emacs users!