Subject: bug#49609: [PATCH] Add option for handling SGR control sequences in compilation-mode

From: Ivan Sokolov <[email-masked]>
Date: Sat, 17 Jul 2021 22:48:43 +0300

I don't have much to say about the patch -- it's a well known solution,
I don't know why we don't have it yet.

>From e41f7bfa24c0fac575ebd7513ea5c527aa4c38ac Mon Sep 17 00:00:00 2001
From: Ivan Sokolov <[email-masked]>
Date: Sat, 17 Jul 2021 21:56:37 +0300
Subject: [PATCH] Add option for handling SGR control sequences in
 compilation-mode

---
 lisp/ansi-color.el | 32 ++++++++++++++++++++++++++++++++
 1 file changed, 32 insertions(+)

diff --git a/lisp/ansi-color.el b/lisp/ansi-color.el
index 44dc0351d4..013f2a8c5d 100644
--- a/lisp/ansi-color.el
+++ b/lisp/ansi-color.el
@@ -75,6 +75,7 @@
 ;;; Code:
 
 (defvar comint-last-output-start)
+(defvar compilation-filter-start)
 
 ;; Customization
 
@@ -181,6 +182,21 @@ ansi-color-for-comint-mode
   :group 'ansi-colors
   :version "23.2")
 
+(defcustom ansi-color-for-compilation-mode t
+  "Determines what to do with compilation output.
+If nil, do nothing.
+If the symbol `filter', then filter all SGR control sequences.
+If anything else (such as t), then translate SGR control sequences
+into text properties.
+
+In order for this to have any effect, `ansi-color-compilation-filter'
+must be in `compilation-filter-hook'."
+  :type '(choice (const :tag "Do nothing" nil)
+                 (const :tag "Filter" filter)
+                 (other :tag "Translate" t))
+  :group 'ansi-colors
+  :version "28.1")
+
 (defvar ansi-color-apply-face-function #'ansi-color-apply-overlay-face
   "Function for applying an Ansi Color face to text in a buffer.
 This function should accept three arguments: BEG, END, and FACE,
@@ -228,6 +244,22 @@ ansi-color-process-output
 	  (t
 	   (ansi-color-apply-on-region start-marker end-marker)))))
 
+;;;###autoload
+(defun ansi-color-compilation-filter ()
+  "Maybe translate SGR control sequences into text properties.
+Depending on variable `ansi-color-for-compilation-mode' the
+compilation output is either nor processed, SGR control sequences
+are filtered using `ansi-color-filter-region', or SGR control
+sequences are translated into text properties using
+`ansi-color-apply-on-region'."
+  (let ((inhibit-read-only t))
+    (pcase ansi-color-for-compilation-mode
+      ('nil nil)
+      ('filter
+       (ansi-color-filter-region compilation-filter-start (point)))
+      (_
+       (ansi-color-apply-on-region compilation-filter-start (point))))))
+
 (define-obsolete-function-alias 'ansi-color-unfontify-region
   'font-lock-default-unfontify-region "24.1")
 
-- 
2.32.0