Cucumber's ANSI colors messing up emacs compilation buffer

I use this to turn on ansi color interpretation in my compilation buffer:

(require 'ansi-color)
(defun colorize-compilation-buffer ()
  (let ((inhibit-read-only t))
    (ansi-color-apply-on-region (point-min) (point-max))))
(add-hook 'compilation-filter-hook 'colorize-compilation-buffer)

I improve code so it doesn't pollute M-x grep like commands and more efficient:

(ignore-errors
  (require 'ansi-color)
  (defun my-colorize-compilation-buffer ()
    (when (eq major-mode 'compilation-mode)
      (ansi-color-apply-on-region compilation-filter-start (point-max))))
  (add-hook 'compilation-filter-hook 'my-colorize-compilation-buffer))

As of 2020, the most modern way appears to be the xterm-color Emacs package.

  1. Execute M-x package-install with xterm-color.

  2. Add the following lines to your ~/.emacs or ~/.emacs.d/init.el:

(require 'xterm-color)
(setq compilation-environment '("TERM=xterm-256color"))
(defun my/advice-compilation-filter (f proc string)
  (funcall f proc (xterm-color-filter string)))
(advice-add 'compilation-filter :around #'my/advice-compilation-filter)

(See xterm-color documentation.)

Note that this will provide an error message if xterm-color was not installed properly. This is strongly advised, because on an incomplete Emacs installation it will clearly explain to you what's wrong, instead of leaving you wondering why the colors don't work.

However, if you really prefer to not being informed if xterm-color is missing, use instead:

(when (require 'ansi-color nil t)
  (setq compilation-environment '("TERM=xterm-256color"))
  (defun my/advice-compilation-filter (f proc string)
    (funcall f proc (xterm-color-filter string)))
  (advice-add 'compilation-filter :around #'my/advice-compilation-filter))

Tags:

Emacs

Cucumber