如何在emacs中为任何模式显示ANSI颜色代码?

Ave*_*ery 24 emacs ansi

我有一个日志文件,使用ANSI转义颜色代码格式化文本.模式是fundamental.还有其他已回答的问题可以解决此问题,但我不确定如何将其应用于此模式或任何其他模式.我知道解决方案与ansi-color某些方面的配置有关.

jua*_*eon 44

你可以使用下面的代码

(require 'ansi-color)
(defun display-ansi-colors ()
  (interactive)
  (ansi-color-apply-on-region (point-min) (point-max)))
Run Code Online (Sandbox Code Playgroud)

然后你可以display-ansi-colors通过Mx,你选择的键绑定,或通过一些程序条件执行(也许你的日志文件有一个扩展或名称,匹配一些正则表达式)

如果你想用只读缓冲区(日志文件,grep结果)来做这个,你可以使用inhibit-read-only,所以函数将是:

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

  • @Avery,是的。Also, if anyone else is wondering how to do it, adding this to your .emacs will turn on ansi-color display for all `.log` files (choose your file extension appropriately):`(add-to-list 'auto-模式列表 '("\\.log\\'" .display-ansi-colors))` (2认同)
  • ansi-color-apply-on-region效果很好,但似乎太慢了(处理13,000行区域需要30秒)。 (2认同)

gav*_*koa 8

用户定义函数:

(defun my-ansi-color (&optional beg end)
  "Interpret ANSI color esacape sequence by colorifying cotent.
Operate on selected region on whole buffer."
  (interactive
   (if (use-region-p)
       (list (region-beginning) (region-end))
     (list (point-min) (point-max))))
  (ansi-color-apply-on-region beg end))
Run Code Online (Sandbox Code Playgroud)

对于使用 comint/compilation 的缓冲区,请使用过滤器:

(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))
Run Code Online (Sandbox Code Playgroud)


deb*_*0ch 6

Gavenkoa和Juanleon的解决方案对我有用,但不满意,因为他们正在修改我正在阅读的文件的内容.

要在不修改文件内容的情况下着色,请下载tty-format.el并将以下内容添加到.emacs中:

(add-to-list 'load-path "path/to/your/tty-format.el/")

(require 'tty-format)

;; M-x display-ansi-colors to explicitly decode ANSI color escape sequences                                                                                                                                        
(defun display-ansi-colors ()
  (interactive)
  (format-decode-buffer 'ansi-colors))

;; decode ANSI color escape sequences for *.txt or README files                                                                                                                                                    
(add-hook 'find-file-hooks 'tty-format-guess)

;; decode ANSI color escape sequences for .log files                                                                                                                                                               
(add-to-list 'auto-mode-alist '("\\.log\\'" . display-ansi-colors))
Run Code Online (Sandbox Code Playgroud)

tty-format基于ansi-color.el,它仅与最新版本的emacs一起本地发送.