Emacs Text Colorization – How to Guide

colorsemacs

I want to view (and/or edit) colorized text in emacs, such as is output by ls -l --color=always, tree..., or whatever.

The text I refer to exists in a file. When I open that file in emacs, I want to be able to see it colorized, or toggle it to show ANSI (SGR) escape sequences.

ansi-color.el seems be be what I need, but I haven't been able to get it to do any colorizing of the ANSi escape sequences, but I do see blue-bold for individual contol bytes (eg. ^A and ^[)… I'm not sure if that is a feature of ansi-color, but I think it is.

According to the ansi-color.el comments, it can work with strings and regions, but even that doesn't seem to work.. For example the function ansi-color-apply-on-region is not recognized by M-x. It says, "No match"

I've added (require 'ansi-color) to my .emacs file and even (add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on). I get no error or warning when emacs starts, so I'm stuck.

How can I get the standard functions to work, and can it be made to automatically apply when opening a file whose name is suffixed with .col?

Best Answer

I think the piece you're missing is the interactive form. It's how Emacs distinguishes between a function designed to be called by other functions, and a function designed to be called directly by the user. See the Emacs Lisp Intro node

Now if you read the definition of ansi-color-apply-on-region, you'll see that it's not designed for interactive use. "ansi-color" is designed to filter comint output. However it's easy to make an interactive wrapper for it.

(defun ansi-color-apply-on-region-int (beg end)
  "interactive version of func"
  (interactive "r")
  (ansi-color-apply-on-region beg end))

The next bit is you want to turn on ansi colors for the .col extension. You can add a hook function to whatever major-mode you want use to edit those files. The function would be run whenever you turn on the major-mode, so you will have to add a check for the proper file suffix.

Alternatively you can hack a quick derived mode based on "fundamental" mode.

(define-derived-mode fundamental-ansi-mode fundamental-mode "fundamental ansi"
  "Fundamental mode that understands ansi colors."
  (require 'ansi-color)
  (ansi-color-apply-on-region (point-min) (point-max)))

and associate it with that extension.

(setq auto-mode-alist
      (cons '("\\.col\\'" . fundamental-ansi-mode) auto-mode-alist))
Related Question