Setting up Emacs for Stan in 2026

It is easier than ever to set up Emacs for Stan development. Here’s a screen shot of the kind of thing you can expect:

The entire init.el needed to get this behavior is below (excluding the theme, which is zenburn).

Simply:

  • ensure Emacs is at least version 29 (released July 2023) and it was compiled with tree-sitter support
  • Download the Stan Language Sever and put it in a place you’ll remember.
  • Include the following in your init.el. Where it says PATH/TO/stan-language-server, replace PATH/TO/ with the actual location (if anyone is an elisp wizard and wants to help me write a function that downloads the language server for you, feel free to reach out!)
(require 'package)
;; elgot is built in to emacs 29+, but some features work better if you use the
;; latest version from GNU ELPA
(add-to-list 'package-archives '("gnu" . "https://elpa.gnu.org/packages/") t)

;; for stan-ts-mode
(add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t)
;; can also pull from MELPA stable, if desired:
;; (add-to-list 'package-archives '("melpa-stable" . "https://stable.melpa.org/packages/") t)
(package-initialize)

(use-package treesit
  :if (treesit-available-p))

(use-package stan-ts-mode
  :requires treesit
  :mode "\\.stan\\'"
  :defer t
  :init
  (add-to-list 'treesit-language-source-alist '(stan . ("https://github.com/WardBrian/tree-sitter-stan" "v0.2.9")))
  (unless (treesit-language-available-p 'stan)
    (treesit-install-language-grammar 'stan)))

(use-package eglot
  :ensure t
  :demand t
  :pin gnu
  :hook (stan-ts-mode . eglot-ensure)
  :config
  (add-to-list 'eglot-server-programs 
    '(stan-ts-mode . ("PATH/TO/stan-language-server" "--stdio"))))

This also serves as an announcement that stan-ts-mode is now on MELPA. Thanks to @avehtari for encouraging me to finish polishing the mode and for implementing some nice features like better auto-indentation.

2 Likes

Awesome!

Should there be

:mode ("\\.stan\\'" "\\.stanfunctions\\'")

So that the stan-ts-mode is loaded if you open a .stanfunctions file before opening any .stan -files? (Probably a rare case, but…)

1 Like

If you’re a big user of .stanfunctions files that is probably a better default config. Note that the stan-language-server support for .stanfunctions is more complete than the tree-sitter-stan support (which does its best, but is not actually aware of the functions-only syntax, see Grammar for `.stanfunctions` · Issue #10 · WardBrian/tree-sitter-stan · GitHub)