Search code examples
emacsansi-escape

How do I display ANSI color codes in emacs for any mode?


I have a log file that uses ANSI escape color codes to format the text. The mode is fundamental. There are other answered questions that address this issue but I'm not sure how to apply it to this mode or any other mode. I know the solution has something to do with configuring ansi-color in some way.


Solution

  • You could use code below

    (require 'ansi-color)
    (defun display-ansi-colors ()
      (interactive)
      (ansi-color-apply-on-region (point-min) (point-max)))
    

    Then you can execute display-ansi-colors via M-x, via a key-binding of your choosing, or via some programmatic condition (maybe your log files have a extension or name that matches some regexp)

    If you want to do this with read-only buffers (log files, grep results), you may use inhibit-read-only, so the function will be:

    (defun display-ansi-colors ()
      (interactive)
      (let ((inhibit-read-only t))
        (ansi-color-apply-on-region (point-min) (point-max))))