1 ;;; ansi-color.el --- translate ANSI escape sequences into faces
3 ;; Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc.
5 ;; Author: Alex Schroeder <alex@gnu.org>
6 ;; Maintainer: Alex Schroeder <alex@gnu.org>
8 ;; Keywords: comm processes terminals services
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify it
13 ;; under the terms of the GNU General Public License as published by the
14 ;; Free Software Foundation; either version 2, or (at your option) any
17 ;; GNU Emacs is distributed in the hope that it will be useful, but
18 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 ;; General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
29 ;; This file provides a function that takes a string or a region
30 ;; containing Select Graphic Rendition (SGR) control sequences (formerly
31 ;; known as ANSI escape sequences) and tries to translate these into
34 ;; This allows you to run ls --color=yes in shell-mode. In order to
35 ;; test this, proceed as follows:
37 ;; 1. start a shell: M-x shell
38 ;; 2. load this file: M-x load-library RET ansi-color RET
39 ;; 3. activate ansi-color: M-x ansi-color-for-comint-mode-on
40 ;; 4. test ls --color=yes in the *shell* buffer
42 ;; Note that starting your shell from within Emacs might set the TERM
43 ;; environment variable. The new setting might disable the output of
44 ;; SGR control sequences. Using ls --color=yes forces ls to produce
47 ;; If you decide you like this, add the following to your .emacs file:
49 ;; (add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)
51 ;; SGR control sequences are defined in section 3.8.117 of the ECMA-48
52 ;; standard (identical to ISO/IEC 6429), which is freely available as a
53 ;; PDF file <URL:http://www.ecma.ch/ecma1/STAND/ECMA-048.HTM>. The
54 ;; "Graphic Rendition Combination Mode (GRCM)" implemented is
55 ;; "cumulative mode" as defined in section 7.2.8. Cumulative mode means
56 ;; that whenever possible, SGR control sequences are combined (ie. blue
59 ;; The basic functions are:
61 ;; `ansi-color-apply' to colorize a string containing SGR control
64 ;; `ansi-color-filter-apply' to filter SGR control sequences from a
67 ;; `ansi-color-apply-on-region' to colorize a region containing SGR
70 ;; `ansi-color-filter-region' to filter SGR control sequences from a
75 ;; Georges Brun-Cottan <gbruncot@emc.com> for improving ansi-color.el
76 ;; substantially by adding the code needed to cope with arbitrary chunks
77 ;; of output and the filter functions.
79 ;; Markus Kuhn <Markus.Kuhn@cl.cam.ac.uk> for pointing me to ECMA-48.
81 ;; Stefan Monnier <foo@acm.com> explaing obscure font-lock stuff and
90 (defgroup ansi-colors nil
91 "Translating SGR control sequences to faces.
92 This translation effectively colorizes strings and regions based upon
93 SGR control sequences embedded in the text. SGR (Select Graphic
94 Rendition) control sequences are defined in section 3.8.117 of the
95 ECMA-48 standard \(identical to ISO/IEC 6429), which is freely available
96 as a PDF file <URL:http://www.ecma.ch/ecma1/STAND/ECMA-048.HTM>."
100 (defcustom ansi-color-faces-vector
101 [default bold default italic underline bold bold-italic modeline
]
102 "Faces used for SGR control sequences determining a face.
103 This vector holds the faces used for SGR control sequence parameters 0
106 Parameter Description Face used by default
111 4 underlined underline
112 5 slowly blinking bold
113 6 rapidly blinking bold-italic
114 7 negative image modeline
116 Note that the symbol `default' is special: It will not be combined
117 with the current face.
119 This vector is used by `ansi-color-make-color-map' to create a color
120 map. This color map is stored in the variable `ansi-color-map'."
121 :type
'(vector face face face face face face face face
)
122 :set
'ansi-color-map-update
123 :initialize
'custom-initialize-default
126 (defcustom ansi-color-names-vector
127 ["black" "red" "green" "yellow" "blue" "magenta" "cyan" "white"]
128 "Colors used for SGR control sequences determining a color.
129 This vector holds the colors used for SGR control sequences parameters
130 30 to 37 \(foreground colors) and 40 to 47 (background colors).
142 This vector is used by `ansi-color-make-color-map' to create a color
143 map. This color map is stored in the variable `ansi-color-map'."
144 :type
'(vector string string string string string string string string
)
145 :set
'ansi-color-map-update
146 :initialize
'custom-initialize-default
149 (defconst ansi-color-regexp
"\033\\[\\([0-9;]*\\)m"
150 "Regexp that matches SGR control sequences.")
152 (defconst ansi-color-parameter-regexp
"\\([0-9]*\\)[m;]"
153 "Regexp that matches SGR control sequence parameters.")
156 ;; Convenience functions for comint modes (eg. shell-mode)
159 (defcustom ansi-color-for-comint-mode nil
160 "Determines what to do with comint output.
162 If the symbol `filter', then filter all SGR control sequences.
163 If anything else (such as t), then translate SGR control sequences
164 into text-properties.
166 In order for this to have any effect, `ansi-color-process-output' must
167 be in `comint-output-filter-functions'.
169 This can be used to enable colorized ls --color=yes output
170 in shell buffers. You set this variable by calling one of:
171 \\[ansi-color-for-comint-mode-on]
172 \\[ansi-color-for-comint-mode-off]
173 \\[ansi-color-for-comint-mode-filter]"
174 :type
'(choice (const :tag
"Do nothing" nil
)
175 (const :tag
"Filter" filter
)
176 (const :tag
"Translate" t
))
180 (defun ansi-color-for-comint-mode-on ()
181 "Set `ansi-color-for-comint-mode' to t."
183 (setq ansi-color-for-comint-mode t
))
185 (defun ansi-color-for-comint-mode-off ()
186 "Set `ansi-color-for-comint-mode' to nil."
188 (setq ansi-color-for-comint-mode nil
))
190 (defun ansi-color-for-comint-mode-filter ()
191 "Set `ansi-color-for-comint-mode' to symbol `filter'."
193 (setq ansi-color-for-comint-mode
'filter
))
196 (defun ansi-color-process-output (string)
197 "Maybe translate SGR control sequences of comint output into text-properties.
199 Depending on variable `ansi-color-for-comint-mode' the comint output is
200 either not processed, SGR control sequences are filtered using
201 `ansi-color-filter-region', or SGR control sequences are translated into
202 text-properties using `ansi-color-apply-on-region'.
204 The comint output is assumed to lie between the marker
205 `comint-last-output-start' and the process-mark.
207 This is a good function to put in `comint-output-filter-functions'."
208 (let ((start-marker (or comint-last-output-start
210 (end-marker (process-mark (get-buffer-process (current-buffer)))))
211 (cond ((eq ansi-color-for-comint-mode nil
))
212 ((eq ansi-color-for-comint-mode
'filter
)
213 (ansi-color-filter-region start-marker end-marker
))
215 (ansi-color-apply-on-region start-marker end-marker
)))))
217 (add-hook 'comint-output-filter-functions
218 'ansi-color-process-output
)
221 ;; Alternative font-lock-unfontify-region-function for Emacs only
223 (defun ansi-color-unfontify-region (beg end
&rest xemacs-stuff
)
224 "Replacement function for `font-lock-default-unfontify-region'.
226 As text-properties are implemented using extents in XEmacs, this
227 function is probably not needed. In Emacs, however, things are a bit
228 different: When font-lock is active in a buffer, you cannot simply add
229 face text-properties to the buffer. Font-lock will remove the face
230 text-property using `font-lock-unfontify-region-function'. If you want
231 to insert the strings returned by `ansi-color-apply' into such buffers,
232 you must set `font-lock-unfontify-region-function' to
233 `ansi-color-unfontify-region'. This function will not remove all face
234 text-properties unconditionally. It will keep the face text-properties
235 if the property `ansi-color' is set.
237 The region from BEG to END is unfontified. XEMACS-STUFF is ignored.
239 A possible way to install this would be:
241 \(add-hook 'font-lock-mode-hook
242 \(function (lambda ()
243 \(setq font-lock-unfontify-region-function
244 'ansi-color-unfontify-region))))"
245 ;; Simplified now that font-lock-unfontify-region uses save-buffer-state.
246 (when (boundp 'font-lock-syntactic-keywords
)
247 (remove-text-properties beg end
'(syntax-table nil
)))
248 ;; instead of just using (remove-text-properties beg end '(face
249 ;; nil)), we find regions with a non-nil face test-property, skip
250 ;; positions with the ansi-color property set, and remove the
251 ;; remaining face test-properties.
252 (while (setq beg
(text-property-not-all beg end
'face nil
))
253 (setq beg
(or (text-property-not-all beg end
'ansi-color t
) end
))
254 (when (get-text-property beg
'face
)
255 (let ((end-face (or (text-property-any beg end
'face nil
)
257 (remove-text-properties beg end-face
'(face nil
))
258 (setq beg end-face
)))))
260 ;; Working with strings
262 (defvar ansi-color-context nil
263 "Context saved between two calls to `ansi-color-apply'.
264 This is a list of the form (FACES FRAGMENT) or nil. FACES is a list of
265 faces the last call to `ansi-color-apply' ended with, and FRAGMENT is a
266 string starting with an escape sequence, possibly the start of a new
268 (make-variable-buffer-local 'ansi-color-context
)
270 (defun ansi-color-filter-apply (string)
271 "Filter out all SGR control sequences from STRING.
273 Every call to this function will set and use the buffer-local variable
274 `ansi-color-context' to save partial escape sequences. This information
275 will be used for the next call to `ansi-color-apply'. Set
276 `ansi-color-context' to nil if you don't want this.
278 This function can be added to `comint-preoutput-filter-functions'."
279 (let ((start 0) end result
)
280 ;; if context was saved and is a string, prepend it
281 (if (cadr ansi-color-context
)
282 (setq string
(concat (cadr ansi-color-context
) string
)
283 ansi-color-context nil
))
284 ;; find the next escape sequence
285 (while (setq end
(string-match ansi-color-regexp string start
))
286 (setq result
(concat result
(substring string start end
))
287 start
(match-end 0)))
288 ;; save context, add the remainder of the string to the result
290 (if (string-match "\033" string start
)
291 (let ((pos (match-beginning 0)))
292 (setq fragment
(substring string pos
)
293 result
(concat result
(substring string start pos
))))
294 (setq result
(concat result
(substring string start
))))
296 (setq ansi-color-context
(list nil fragment
))
297 (setq ansi-color-context nil
)))
300 (defun ansi-color-apply (string)
301 "Translates SGR control sequences into text-properties.
303 Applies SGR control sequences setting foreground and background colors
304 to STRING using text-properties and returns the result. The colors used
305 are given in `ansi-color-faces-vector' and `ansi-color-names-vector'.
306 See function `ansi-color-apply-sequence' for details.
308 Every call to this function will set and use the buffer-local variable
309 `ansi-color-context' to save partial escape sequences and current face.
310 This information will be used for the next call to `ansi-color-apply'.
311 Set `ansi-color-context' to nil if you don't want this.
313 This function can be added to `comint-preoutput-filter-functions'.
315 You cannot insert the strings returned into buffers using font-lock.
316 See `ansi-color-unfontify-region' for a way around this."
317 (let ((face (car ansi-color-context
))
318 (start 0) end escape-sequence result
)
319 ;; if context was saved and is a string, prepend it
320 (if (cadr ansi-color-context
)
321 (setq string
(concat (cadr ansi-color-context
) string
)
322 ansi-color-context nil
))
323 ;; find the next escape sequence
324 (while (setq end
(string-match ansi-color-regexp string start
))
325 ;; store escape sequence
326 (setq escape-sequence
(match-string 1 string
))
327 ;; colorize the old block from start to end using old face
329 (put-text-property start end
'ansi-color t string
)
330 (put-text-property start end
'face face string
))
331 (setq result
(concat result
(substring string start end
))
333 ;; create new face by applying all the parameters in the escape
335 (setq face
(ansi-color-apply-sequence escape-sequence face
)))
336 ;; if the rest of the string should have a face, put it there
338 (put-text-property start
(length string
) 'ansi-color t string
)
339 (put-text-property start
(length string
) 'face face string
))
340 ;; save context, add the remainder of the string to the result
342 (if (string-match "\033" string start
)
343 (let ((pos (match-beginning 0)))
344 (setq fragment
(substring string pos
)
345 result
(concat result
(substring string start pos
))))
346 (setq result
(concat result
(substring string start
))))
347 (if (or face fragment
)
348 (setq ansi-color-context
(list face fragment
))
349 (setq ansi-color-context nil
)))
352 ;; Working with regions
354 (defvar ansi-color-context-region nil
355 "Context saved between two calls to `ansi-color-apply-on-region'.
356 This is a list of the form (FACES MARKER) or nil. FACES is a list of
357 faces the last call to `ansi-color-apply-on-region' ended with, and
358 MARKER is a buffer position within an escape sequence or the last
359 position processed.")
360 (make-variable-buffer-local 'ansi-color-context-region
)
362 (defun ansi-color-filter-region (begin end
)
363 "Filter out all SGR control sequences from region BEGIN to END.
365 Every call to this function will set and use the buffer-local variable
366 `ansi-color-context-region' to save position. This information will be
367 used for the next call to `ansi-color-apply-on-region'. Specifically,
368 it will override BEGIN, the start of the region. Set
369 `ansi-color-context-region' to nil if you don't want this."
370 (let ((end-marker (copy-marker end
))
371 (start (or (cadr ansi-color-context-region
) begin
)))
374 ;; find the next escape sequence
375 (while (re-search-forward ansi-color-regexp end-marker t
)
376 ;; delete the escape sequence
378 ;; save context, add the remainder of the string to the result
379 (if (re-search-forward "\033" end-marker t
)
380 (setq ansi-color-context-region
(list nil
(match-beginning 0)))
381 (setq ansi-color-context-region nil
)))))
383 (defun ansi-color-apply-on-region (begin end
)
384 "Translates SGR control sequences into overlays or extents.
386 Applies SGR control sequences setting foreground and background colors
387 to text in region between BEGIN and END using extents or overlays.
388 Emacs will use overlays, XEmacs will use extents. The colors used are
389 given in `ansi-color-faces-vector' and `ansi-color-names-vector'. See
390 function `ansi-color-apply-sequence' for details.
392 Every call to this function will set and use the buffer-local variable
393 `ansi-color-context-region' to save position and current face. This
394 information will be used for the next call to
395 `ansi-color-apply-on-region'. Specifically, it will override BEGIN, the
396 start of the region and set the face with which to start. Set
397 `ansi-color-context-region' to nil if you don't want this."
398 (let ((face (car ansi-color-context-region
))
399 (start-marker (or (cadr ansi-color-context-region
)
400 (copy-marker begin
)))
401 (end-marker (copy-marker end
))
404 (goto-char start-marker
)
405 ;; find the next escape sequence
406 (while (re-search-forward ansi-color-regexp end-marker t
)
407 ;; colorize the old block from start to end using old face
409 (ansi-color-set-extent-face
410 (ansi-color-make-extent start-marker
(match-beginning 0))
412 ;; store escape sequence and new start position
413 (setq escape-sequence
(match-string 1)
414 start-marker
(copy-marker (match-end 0)))
415 ;; delete the escape sequence
417 ;; create new face by applying all the parameters in the escape
419 (setq face
(ansi-color-apply-sequence escape-sequence face
)))
420 ;; search for the possible start of a new escape sequence
421 (if (re-search-forward "\033" end-marker t
)
423 ;; if the rest of the region should have a face, put it there
425 (ansi-color-set-extent-face
426 (ansi-color-make-extent start-marker
(point))
428 ;; save face and point
429 (setq ansi-color-context-region
430 (list face
(copy-marker (match-beginning 0)))))
431 ;; if the rest of the region should have a face, put it there
434 (ansi-color-set-extent-face
435 (ansi-color-make-extent start-marker end-marker
)
437 (setq ansi-color-context-region
(list face
)))
439 (setq ansi-color-context-region nil
))))))
441 ;; This function helps you look for overlapping overlays. This is
442 ;; usefull in comint-buffers. Overlapping overlays should not happen!
443 ;; A possible cause for bugs are the markers. If you create an overlay
444 ;; up to the end of the region, then that end might coincide with the
445 ;; process-mark. As text is added BEFORE the process-mark, the overlay
446 ;; will keep growing. Therefore, as more overlays are created later on,
447 ;; there will be TWO OR MORE overlays covering the buffer at that point.
448 ;; This function helps you check your buffer for these situations.
449 ; (defun ansi-color-debug-overlays ()
451 ; (let ((pos (point-min)))
452 ; (while (< pos (point-max))
453 ; (if (<= 2 (length (overlays-at pos)))
456 ; (error "%d overlays at %d" (length (overlays-at pos)) pos))
457 ; (let (message-log-max)
458 ; (message "Reached %d." pos)))
459 ; (setq pos (next-overlay-change pos)))))
461 ;; Emacs/XEmacs compatibility layer
463 (defun ansi-color-make-face (property color
)
464 "Return a face with PROPERTY set to COLOR.
465 PROPERTY can be either symbol `foreground' or symbol `background'.
467 For Emacs, we just return the cons cell \(PROPERTY . COLOR).
468 For XEmacs, we create a temporary face and return it."
469 (if (featurep 'xemacs
)
470 (let ((face (make-face (intern (concat color
"-" (symbol-name property
)))
471 "Temporary face created by ansi-color."
473 (set-face-property face property color
)
475 (cond ((eq property
'foreground
)
476 (cons 'foreground-color color
))
477 ((eq property
'background
)
478 (cons 'background-color color
))
480 (cons property color
)))))
482 (defun ansi-color-make-extent (from to
&optional object
)
483 "Make an extent for the range [FROM, TO) in OBJECT.
485 OBJECT defaults to the current buffer. XEmacs uses `make-extent', Emacs
486 uses `make-overlay'. XEmacs can use a buffer or a string for OBJECT,
487 Emacs requires OBJECT to be a buffer."
488 (if (functionp 'make-extent
)
489 (make-extent from to object
)
490 ;; In Emacs, the overlay might end at the process-mark in comint
491 ;; buffers. In that case, new text will be inserted before the
492 ;; process-mark, ie. inside the overlay (using insert-before-marks).
493 ;; In order to avoid this, we use the `insert-behind-hooks' overlay
494 ;; property to make sure it works.
495 (let ((overlay (make-overlay from to object
)))
496 (overlay-put overlay
'modification-hooks
'(ansi-color-freeze-overlay))
499 (defun ansi-color-freeze-overlay (overlay is-after begin end
&optional len
)
500 "Prevent OVERLAY from being extended.
501 This function can be used for the `modification-hooks' overlay
503 ;; if stuff was inserted at the end of the overlay
506 (= end
(overlay-end overlay
)))
507 ;; reset the end of the overlay
508 (move-overlay overlay
(overlay-start overlay
) begin
)))
510 (defun ansi-color-set-extent-face (extent face
)
511 "Set the `face' property of EXTENT to FACE.
512 XEmacs uses `set-extent-face', Emacs uses `overlay-put'."
513 (if (functionp 'set-extent-face
)
514 (set-extent-face extent face
)
515 (overlay-put extent
'face face
)))
519 (defun ansi-color-apply-sequence (escape-sequence faces
)
520 "Apply ESCAPE-SEQ to FACES and return the new list of faces.
522 ESCAPE-SEQ is an escape sequences parsed by `ansi-color-get-face'.
524 If the new faces start with the symbol `default', then the new
525 faces are returned. If the faces start with something else,
526 they are appended to the front of the FACES list, and the new
527 list of faces is returned.
529 If `ansi-color-get-face' returns nil, then we either got a
530 null-sequence, or we stumbled upon some garbage. In either
532 (let ((new-faces (ansi-color-get-face escape-sequence
)))
533 (cond ((null new-faces
)
535 ((eq (car new-faces
) 'default
)
538 ;; Like (append NEW-FACES FACES)
539 ;; but delete duplicates in FACES.
540 (let ((modified-faces (copy-sequence faces
)))
541 (dolist (face (nreverse new-faces
))
542 (setq modified-faces
(delete face modified-faces
))
543 (push face modified-faces
))
546 (defun ansi-color-make-color-map ()
547 "Creates a vector of face definitions and returns it.
549 The index into the vector is an ANSI code. See the documentation of
550 `ansi-color-map' for an example.
552 The face definitions are based upon the variables
553 `ansi-color-faces-vector' and `ansi-color-names-vector'."
554 (let ((ansi-color-map (make-vector 50 nil
))
556 ;; miscellaneous attributes
558 (function (lambda (e)
559 (aset ansi-color-map index e
)
560 (setq index
(1+ index
)) ))
561 ansi-color-faces-vector
)
562 ;; foreground attributes
565 (function (lambda (e)
566 (aset ansi-color-map index
567 (ansi-color-make-face 'foreground e
))
568 (setq index
(1+ index
)) ))
569 ansi-color-names-vector
)
570 ;; background attributes
573 (function (lambda (e)
574 (aset ansi-color-map index
575 (ansi-color-make-face 'background e
))
576 (setq index
(1+ index
)) ))
577 ansi-color-names-vector
)
580 (defvar ansi-color-map
(ansi-color-make-color-map)
581 "A brand new color map suitable for `ansi-color-get-face'.
583 The value of this variable is usually constructed by
584 `ansi-color-make-color-map'. The values in the array are such that the
585 numbers included in an SGR control sequences point to the correct
586 foreground or background colors.
588 Example: The sequence \033[34m specifies a blue foreground. Therefore:
589 (aref ansi-color-map 34)
590 => \(foreground-color . \"blue\")")
592 (defun ansi-color-map-update (symbol value
)
593 "Update `ansi-color-map'.
595 Whenever the vectors used to construct `ansi-color-map' are changed,
596 this function is called. Therefore this function is listed as the :set
597 property of `ansi-color-faces-vector' and `ansi-color-names-vector'."
598 (set-default symbol value
)
599 (setq ansi-color-map
(ansi-color-make-color-map)))
601 (defun ansi-color-get-face-1 (ansi-code)
602 "Get face definition from `ansi-color-map'.
603 ANSI-CODE is used as an index into the vector."
605 (aref ansi-color-map ansi-code
)
606 ('args-out-of-range nil
)))
608 (defun ansi-color-get-face (escape-seq)
609 "Create a new face by applying all the parameters in ESCAPE-SEQ.
611 Should any of the parameters result in the default face (usually this is
612 the parameter 0), then the effect of all previous parameters is cancelled.
614 ESCAPE-SEQ is a SGR control sequences such as \\033[34m. The parameter
615 34 is used by `ansi-color-get-face-1' to return a face definition."
616 (let ((ansi-color-r "[0-9][0-9]?")
619 (while (string-match ansi-color-r escape-seq i
)
620 (setq i
(match-end 0)
621 val
(ansi-color-get-face-1
622 (string-to-number (match-string 0 escape-seq
) 10)))
627 (unless (member val f
)
631 (provide 'ansi-color
)
633 ;;; arch-tag: 00726118-9432-44fd-b72d-d2af7591c99c
634 ;;; ansi-color.el ends here