I have setup web-mode and lsp mode for PHP programming in my config file. It is very minimal and flymake works perfectly.

I am struggling to find a way to get code formatting to work. I was told that I could install PHP_beautifier from Pear (which i did) and use it in emacs. But I am not sure how exactly?

There is no such package in emacs either.

My question is what is the best way to auto-format code on save with PHP?

(use-package lsp-mode
  :ensure t
  (setq lsp-headerline-breadcrumb-enable nil) ;; works
  (setq lsp-enable-symbol-highlighting nil) ;; works
  (setq lsp-signature-render-documentation nil)
  (setq lsp-completion-provider :none) ;; works
  (setq lsp-diagnostics-provider :flymake) ;; underline error

(use-package web-mode
  :ensure t
  (setq web-mode-code-indent-offset 4)
  (setq web-mode-markup-indent-offset 4)
  (setq web-mode-enable-sql-detection t)


1 Answer 1


Check whether web-mode-enable-auto-indentation is enabled. It should be so for GUI Emacs (not in terminal) by default. With this option enabled, buffer contents should be re-indented automatically.

Optionally, call M-x web-mode-buffer-indent (C-c TAB or C-c C-i and available from menu). For example, this way:

(defun my-web-mode-hook ()
  (add-hook 'after-save-hook #'web-mode-buffer-indent))

(add-hook 'web-mode-hook 'my-web-mode-hook)

The following part of the answer addresses the question(s) more generally.

It's quite typical to install php-mode for PHP programming language syntax highlighting and indentation. Whilst web-mode is more suitable for the scripts containing a mix of languages. If your case is the former, I'd suggest to use php-mode and install one of the PHP language servers for the mentioned lsp-mode to direct requests to.

Note, that since Emacs 29 built-in LSP client Eglot is provided, which also would still require installation of a language server.

Another thing to note, you might find tree-sitter usage useful (support for which is also built-in since Emacs 29).

  • Most of the time, my PHP code has PHP and HTML in the same file. Hence why I use web-mode. Unlike PPHP mode, it doesn't have a formatter.
    – Vinn
    Aug 21, 2023 at 15:22
  • 1
    I added some ideas for web-mode usage to the answer.
    – Y. E.
    Aug 21, 2023 at 16:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.