How to colorize text in emacs?

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))

The following solution allow to read (and not save) files containing ANSI color sequences. The filenames must have a .txt extension.

Put the library tty-format in ~/.emacs.d/site-lisp/, then add these lines to your ~/.emacs init file.

(add-to-list 'load-path "~/.emacs.d/site-lisp/")              
(require 'tty-format)
(add-hook 'find-file-hooks 'tty-format-guess)

Tags:

Colors

Emacs