Support separate fg and bg colors in ansi-color.el
[emacs.git] / lisp / ansi-color.el
blobff7edf40dcb0c4ed5bafaf50b35548efb69ee27f
1 ;;; ansi-color.el --- translate ANSI escape sequences into faces
3 ;; Copyright (C) 1999-2011 Free Software Foundation, Inc.
5 ;; Author: Alex Schroeder <alex@gnu.org>
6 ;; Maintainer: Alex Schroeder <alex@gnu.org>
7 ;; Version: 3.4.2
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
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; This file provides a function that takes a string or a region
28 ;; containing Select Graphic Rendition (SGR) control sequences (formerly
29 ;; known as ANSI escape sequences) and tries to translate these into
30 ;; faces.
32 ;; This allows you to run ls --color=yes in shell-mode. It is now
33 ;; enabled by default; to disable it, set ansi-color-for-comint-mode
34 ;; to nil.
36 ;; Note that starting your shell from within Emacs might set the TERM
37 ;; environment variable. The new setting might disable the output of
38 ;; SGR control sequences. Using ls --color=yes forces ls to produce
39 ;; these.
41 ;; SGR control sequences are defined in section 3.8.117 of the ECMA-48
42 ;; standard (identical to ISO/IEC 6429), which is freely available as a
43 ;; PDF file <URL:http://www.ecma.ch/ecma1/STAND/ECMA-048.HTM>. The
44 ;; "Graphic Rendition Combination Mode (GRCM)" implemented is
45 ;; "cumulative mode" as defined in section 7.2.8. Cumulative mode means
46 ;; that whenever possible, SGR control sequences are combined (ie. blue
47 ;; and bold).
49 ;; The basic functions are:
51 ;; `ansi-color-apply' to colorize a string containing SGR control
52 ;; sequences.
54 ;; `ansi-color-filter-apply' to filter SGR control sequences from a
55 ;; string.
57 ;; `ansi-color-apply-on-region' to colorize a region containing SGR
58 ;; control sequences.
60 ;; `ansi-color-filter-region' to filter SGR control sequences from a
61 ;; region.
63 ;;; Thanks
65 ;; Georges Brun-Cottan <gbruncot@emc.com> for improving ansi-color.el
66 ;; substantially by adding the code needed to cope with arbitrary chunks
67 ;; of output and the filter functions.
69 ;; Markus Kuhn <Markus.Kuhn@cl.cam.ac.uk> for pointing me to ECMA-48.
71 ;; Stefan Monnier <foo@acm.com> explaing obscure font-lock stuff and
72 ;; code suggestions.
76 ;;; Code:
78 (defvar comint-last-output-start)
80 ;; Customization
82 (defgroup ansi-colors nil
83 "Translating SGR control sequences to faces.
84 This translation effectively colorizes strings and regions based upon
85 SGR control sequences embedded in the text. SGR (Select Graphic
86 Rendition) control sequences are defined in section 3.8.117 of the
87 ECMA-48 standard \(identical to ISO/IEC 6429), which is freely available
88 as a PDF file <URL:http://www.ecma.ch/ecma1/STAND/ECMA-048.HTM>."
89 :version "21.1"
90 :group 'processes)
92 (defcustom ansi-color-faces-vector
93 [default bold default italic underline bold bold-italic modeline]
94 "Faces used for SGR control sequences determining a face.
95 This vector holds the faces used for SGR control sequence parameters 0
96 to 7.
98 Parameter Description Face used by default
99 0 default default
100 1 bold bold
101 2 faint default
102 3 italic italic
103 4 underlined underline
104 5 slowly blinking bold
105 6 rapidly blinking bold-italic
106 7 negative image modeline
108 Note that the symbol `default' is special: It will not be combined
109 with the current face.
111 This vector is used by `ansi-color-make-color-map' to create a color
112 map. This color map is stored in the variable `ansi-color-map'."
113 :type '(vector face face face face face face face face)
114 :set 'ansi-color-map-update
115 :initialize 'custom-initialize-default
116 :group 'ansi-colors)
118 (defcustom ansi-color-names-vector
119 ["black" "red" "green" "yellow" "blue" "magenta" "cyan" "white"]
120 "Colors used for SGR control sequences determining a color.
121 This vector holds the colors used for SGR control sequences parameters
122 30 to 37 \(foreground colors) and 40 to 47 (background colors).
124 Parameter Color
125 30 40 black
126 31 41 red
127 32 42 green
128 33 43 yellow
129 34 44 blue
130 35 45 magenta
131 36 46 cyan
132 37 47 white
134 This vector is used by `ansi-color-make-color-map' to create a color
135 map. This color map is stored in the variable `ansi-color-map'.
137 Each element may also be a cons cell where the car and cdr specify the
138 foreground and background colors, respectively."
139 :type '(vector (choice color (cons color color))
140 (choice color (cons color color))
141 (choice color (cons color color))
142 (choice color (cons color color))
143 (choice color (cons color color))
144 (choice color (cons color color))
145 (choice color (cons color color))
146 (choice color (cons color color)))
147 :set 'ansi-color-map-update
148 :initialize 'custom-initialize-default
149 :group 'ansi-colors)
151 (defconst ansi-color-regexp "\033\\[\\([0-9;]*m\\)"
152 "Regexp that matches SGR control sequences.")
154 (defconst ansi-color-drop-regexp
155 "\033\\[\\([ABCDsuK]\\|2J\\|=[0-9]+[hI]\\|[0-9;]*[Hf]\\)"
156 "Regexp that matches ANSI control sequences to silently drop.")
158 (defconst ansi-color-parameter-regexp "\\([0-9]*\\)[m;]"
159 "Regexp that matches SGR control sequence parameters.")
162 ;; Convenience functions for comint modes (eg. shell-mode)
165 (defcustom ansi-color-for-comint-mode t
166 "Determines what to do with comint output.
167 If nil, do nothing.
168 If the symbol `filter', then filter all SGR control sequences.
169 If anything else (such as t), then translate SGR control sequences
170 into text properties.
172 In order for this to have any effect, `ansi-color-process-output' must
173 be in `comint-output-filter-functions'.
175 This can be used to enable colorized ls --color=yes output
176 in shell buffers. You set this variable by calling one of:
177 \\[ansi-color-for-comint-mode-on]
178 \\[ansi-color-for-comint-mode-off]
179 \\[ansi-color-for-comint-mode-filter]"
180 :type '(choice (const :tag "Do nothing" nil)
181 (const :tag "Filter" filter)
182 (const :tag "Translate" t))
183 :group 'ansi-colors
184 :version "23.2")
186 ;;;###autoload
187 (defun ansi-color-for-comint-mode-on ()
188 "Set `ansi-color-for-comint-mode' to t."
189 (interactive)
190 (setq ansi-color-for-comint-mode t))
192 (defun ansi-color-for-comint-mode-off ()
193 "Set `ansi-color-for-comint-mode' to nil."
194 (interactive)
195 (setq ansi-color-for-comint-mode nil))
197 (defun ansi-color-for-comint-mode-filter ()
198 "Set `ansi-color-for-comint-mode' to symbol `filter'."
199 (interactive)
200 (setq ansi-color-for-comint-mode 'filter))
202 ;;;###autoload
203 (defun ansi-color-process-output (ignored)
204 "Maybe translate SGR control sequences of comint output into text properties.
206 Depending on variable `ansi-color-for-comint-mode' the comint output is
207 either not processed, SGR control sequences are filtered using
208 `ansi-color-filter-region', or SGR control sequences are translated into
209 text properties using `ansi-color-apply-on-region'.
211 The comint output is assumed to lie between the marker
212 `comint-last-output-start' and the process-mark.
214 This is a good function to put in `comint-output-filter-functions'."
215 (let ((start-marker (or comint-last-output-start
216 (point-min-marker)))
217 (end-marker (process-mark (get-buffer-process (current-buffer)))))
218 (cond ((eq ansi-color-for-comint-mode nil))
219 ((eq ansi-color-for-comint-mode 'filter)
220 (ansi-color-filter-region start-marker end-marker))
222 (ansi-color-apply-on-region start-marker end-marker)))))
224 (add-hook 'comint-output-filter-functions
225 'ansi-color-process-output)
227 (defalias 'ansi-color-unfontify-region 'font-lock-default-unfontify-region)
228 (make-obsolete 'ansi-color-unfontify-region "not needed any more" "24.1")
230 ;; Working with strings
231 (defvar ansi-color-context nil
232 "Context saved between two calls to `ansi-color-apply'.
233 This is a list of the form (FACES FRAGMENT) or nil. FACES is a list of
234 faces the last call to `ansi-color-apply' ended with, and FRAGMENT is a
235 string starting with an escape sequence, possibly the start of a new
236 escape sequence.")
237 (make-variable-buffer-local 'ansi-color-context)
239 (defun ansi-color-filter-apply (string)
240 "Filter out all ANSI control sequences from STRING.
242 Every call to this function will set and use the buffer-local variable
243 `ansi-color-context' to save partial escape sequences. This information
244 will be used for the next call to `ansi-color-apply'. Set
245 `ansi-color-context' to nil if you don't want this.
247 This function can be added to `comint-preoutput-filter-functions'."
248 (let ((start 0) end result)
249 ;; if context was saved and is a string, prepend it
250 (if (cadr ansi-color-context)
251 (setq string (concat (cadr ansi-color-context) string)
252 ansi-color-context nil))
253 ;; find the next escape sequence
254 (while (setq end (string-match ansi-color-regexp string start))
255 (setq result (concat result (substring string start end))
256 start (match-end 0)))
257 ;; save context, add the remainder of the string to the result
258 (let (fragment)
259 (if (string-match "\033" string start)
260 (let ((pos (match-beginning 0)))
261 (setq fragment (substring string pos)
262 result (concat result (substring string start pos))))
263 (setq result (concat result (substring string start))))
264 (setq ansi-color-context (if fragment (list nil fragment))))
265 result))
267 (defun ansi-color-apply (string)
268 "Translates SGR control sequences into text properties.
269 Delete all other control sequences without processing them.
271 Applies SGR control sequences setting foreground and background colors
272 to STRING using text properties and returns the result. The colors used
273 are given in `ansi-color-faces-vector' and `ansi-color-names-vector'.
274 See function `ansi-color-apply-sequence' for details.
276 Every call to this function will set and use the buffer-local variable
277 `ansi-color-context' to save partial escape sequences and current face.
278 This information will be used for the next call to `ansi-color-apply'.
279 Set `ansi-color-context' to nil if you don't want this.
281 This function can be added to `comint-preoutput-filter-functions'."
282 (let ((face (car ansi-color-context))
283 (start 0) end escape-sequence result
284 colorized-substring)
285 ;; If context was saved and is a string, prepend it.
286 (if (cadr ansi-color-context)
287 (setq string (concat (cadr ansi-color-context) string)
288 ansi-color-context nil))
289 ;; Find the next escape sequence.
290 (while (setq end (string-match ansi-color-regexp string start))
291 (setq escape-sequence (match-string 1 string))
292 ;; Colorize the old block from start to end using old face.
293 (when face
294 (put-text-property start end 'font-lock-face face string))
295 (setq colorized-substring (substring string start end)
296 start (match-end 0))
297 ;; Eliminate unrecognized ANSI sequences.
298 (while (string-match ansi-color-drop-regexp colorized-substring)
299 (setq colorized-substring
300 (replace-match "" nil nil colorized-substring)))
301 (push colorized-substring result)
302 ;; Create new face, by applying escape sequence parameters.
303 (setq face (ansi-color-apply-sequence escape-sequence face)))
304 ;; if the rest of the string should have a face, put it there
305 (when face
306 (put-text-property start (length string) 'font-lock-face face string))
307 ;; save context, add the remainder of the string to the result
308 (let (fragment)
309 (if (string-match "\033" string start)
310 (let ((pos (match-beginning 0)))
311 (setq fragment (substring string pos))
312 (push (substring string start pos) result))
313 (push (substring string start) result))
314 (setq ansi-color-context (if (or face fragment) (list face fragment))))
315 (apply 'concat (nreverse result))))
317 ;; Working with regions
319 (defvar ansi-color-context-region nil
320 "Context saved between two calls to `ansi-color-apply-on-region'.
321 This is a list of the form (FACES MARKER) or nil. FACES is a list of
322 faces the last call to `ansi-color-apply-on-region' ended with, and
323 MARKER is a buffer position within an escape sequence or the last
324 position processed.")
325 (make-variable-buffer-local 'ansi-color-context-region)
327 (defun ansi-color-filter-region (begin end)
328 "Filter out all ANSI control sequences from region BEGIN to END.
330 Every call to this function will set and use the buffer-local variable
331 `ansi-color-context-region' to save position. This information will be
332 used for the next call to `ansi-color-apply-on-region'. Specifically,
333 it will override BEGIN, the start of the region. Set
334 `ansi-color-context-region' to nil if you don't want this."
335 (let ((end-marker (copy-marker end))
336 (start (or (cadr ansi-color-context-region) begin)))
337 (save-excursion
338 (goto-char start)
339 ;; Delete unrecognized escape sequences.
340 (while (re-search-forward ansi-color-drop-regexp end-marker t)
341 (replace-match ""))
342 (goto-char start)
343 ;; Delete SGR escape sequences.
344 (while (re-search-forward ansi-color-regexp end-marker t)
345 (replace-match ""))
346 ;; save context, add the remainder of the string to the result
347 (if (re-search-forward "\033" end-marker t)
348 (setq ansi-color-context-region (list nil (match-beginning 0)))
349 (setq ansi-color-context-region nil)))))
351 (defun ansi-color-apply-on-region (begin end)
352 "Translates SGR control sequences into overlays or extents.
353 Delete all other control sequences without processing them.
355 SGR control sequences are applied by setting foreground and
356 background colors to the text between BEGIN and END using
357 overlays. The colors used are given in `ansi-color-faces-vector'
358 and `ansi-color-names-vector'. See `ansi-color-apply-sequence'
359 for details.
361 Every call to this function will set and use the buffer-local variable
362 `ansi-color-context-region' to save position and current face. This
363 information will be used for the next call to
364 `ansi-color-apply-on-region'. Specifically, it will override BEGIN, the
365 start of the region and set the face with which to start. Set
366 `ansi-color-context-region' to nil if you don't want this."
367 (let ((face (car ansi-color-context-region))
368 (start-marker (or (cadr ansi-color-context-region)
369 (copy-marker begin)))
370 (end-marker (copy-marker end))
371 escape-sequence)
372 ;; First, eliminate unrecognized ANSI control sequences.
373 (save-excursion
374 (goto-char start-marker)
375 (while (re-search-forward ansi-color-drop-regexp end-marker t)
376 (replace-match "")))
377 (save-excursion
378 (goto-char start-marker)
379 ;; Find the next SGR sequence.
380 (while (re-search-forward ansi-color-regexp end-marker t)
381 ;; Colorize the old block from start to end using old face.
382 (when face
383 (ansi-color-set-extent-face
384 (ansi-color-make-extent start-marker (match-beginning 0))
385 face))
386 ;; store escape sequence and new start position
387 (setq escape-sequence (match-string 1)
388 start-marker (copy-marker (match-end 0)))
389 ;; delete the escape sequence
390 (replace-match "")
391 ;; create new face by applying all the parameters in the escape
392 ;; sequence
393 (setq face (ansi-color-apply-sequence escape-sequence face)))
394 ;; search for the possible start of a new escape sequence
395 (if (re-search-forward "\033" end-marker t)
396 (progn
397 ;; if the rest of the region should have a face, put it there
398 (when face
399 (ansi-color-set-extent-face
400 (ansi-color-make-extent start-marker (point))
401 face))
402 ;; save face and point
403 (setq ansi-color-context-region
404 (list face (copy-marker (match-beginning 0)))))
405 ;; if the rest of the region should have a face, put it there
406 (if face
407 (progn
408 (ansi-color-set-extent-face
409 (ansi-color-make-extent start-marker end-marker)
410 face)
411 (setq ansi-color-context-region (list face)))
412 ;; reset context
413 (setq ansi-color-context-region nil))))))
415 ;; This function helps you look for overlapping overlays. This is
416 ;; usefull in comint-buffers. Overlapping overlays should not happen!
417 ;; A possible cause for bugs are the markers. If you create an overlay
418 ;; up to the end of the region, then that end might coincide with the
419 ;; process-mark. As text is added BEFORE the process-mark, the overlay
420 ;; will keep growing. Therefore, as more overlays are created later on,
421 ;; there will be TWO OR MORE overlays covering the buffer at that point.
422 ;; This function helps you check your buffer for these situations.
423 ; (defun ansi-color-debug-overlays ()
424 ; (interactive)
425 ; (let ((pos (point-min)))
426 ; (while (< pos (point-max))
427 ; (if (<= 2 (length (overlays-at pos)))
428 ; (progn
429 ; (goto-char pos)
430 ; (error "%d overlays at %d" (length (overlays-at pos)) pos))
431 ; (let (message-log-max)
432 ; (message "Reached %d." pos)))
433 ; (setq pos (next-overlay-change pos)))))
435 ;; Emacs/XEmacs compatibility layer
437 (defun ansi-color-make-face (property color)
438 "Return a face with PROPERTY set to COLOR.
439 PROPERTY can be either symbol `foreground' or symbol `background'.
441 For Emacs, we just return the cons cell \(PROPERTY . COLOR).
442 For XEmacs, we create a temporary face and return it."
443 (if (featurep 'xemacs)
444 (let ((face (make-face (intern (concat color "-" (symbol-name property)))
445 "Temporary face created by ansi-color."
446 t)))
447 (set-face-property face property color)
448 face)
449 (cond ((eq property 'foreground)
450 (cons 'foreground-color color))
451 ((eq property 'background)
452 (cons 'background-color color))
454 (cons property color)))))
456 (defun ansi-color-make-extent (from to &optional object)
457 "Make an extent for the range [FROM, TO) in OBJECT.
459 OBJECT defaults to the current buffer. XEmacs uses `make-extent', Emacs
460 uses `make-overlay'. XEmacs can use a buffer or a string for OBJECT,
461 Emacs requires OBJECT to be a buffer."
462 (if (fboundp 'make-extent)
463 (make-extent from to object)
464 ;; In Emacs, the overlay might end at the process-mark in comint
465 ;; buffers. In that case, new text will be inserted before the
466 ;; process-mark, ie. inside the overlay (using insert-before-marks).
467 ;; In order to avoid this, we use the `insert-behind-hooks' overlay
468 ;; property to make sure it works.
469 (let ((overlay (make-overlay from to object)))
470 (overlay-put overlay 'modification-hooks '(ansi-color-freeze-overlay))
471 overlay)))
473 (defun ansi-color-freeze-overlay (overlay is-after begin end &optional len)
474 "Prevent OVERLAY from being extended.
475 This function can be used for the `modification-hooks' overlay
476 property."
477 ;; if stuff was inserted at the end of the overlay
478 (when (and is-after
479 (= 0 len)
480 (= end (overlay-end overlay)))
481 ;; reset the end of the overlay
482 (move-overlay overlay (overlay-start overlay) begin)))
484 (defun ansi-color-set-extent-face (extent face)
485 "Set the `face' property of EXTENT to FACE.
486 XEmacs uses `set-extent-face', Emacs uses `overlay-put'."
487 (if (featurep 'xemacs)
488 (set-extent-face extent face)
489 (overlay-put extent 'face face)))
491 ;; Helper functions
493 (defun ansi-color-apply-sequence (escape-sequence faces)
494 "Apply ESCAPE-SEQ to FACES and return the new list of faces.
496 ESCAPE-SEQ is an escape sequences parsed by `ansi-color-get-face'.
498 If the new faces start with the symbol `default', then the new
499 faces are returned. If the faces start with something else,
500 they are appended to the front of the FACES list, and the new
501 list of faces is returned.
503 If `ansi-color-get-face' returns nil, then we either got a
504 null-sequence, or we stumbled upon some garbage. In either
505 case we return nil."
506 (let ((new-faces (ansi-color-get-face escape-sequence)))
507 (cond ((null new-faces)
508 nil)
509 ((eq (car new-faces) 'default)
510 (cdr new-faces))
512 ;; Like (append NEW-FACES FACES)
513 ;; but delete duplicates in FACES.
514 (let ((modified-faces (copy-sequence faces)))
515 (dolist (face (nreverse new-faces))
516 (setq modified-faces (delete face modified-faces))
517 (push face modified-faces))
518 modified-faces)))))
520 (defun ansi-color-make-color-map ()
521 "Creates a vector of face definitions and returns it.
523 The index into the vector is an ANSI code. See the documentation of
524 `ansi-color-map' for an example.
526 The face definitions are based upon the variables
527 `ansi-color-faces-vector' and `ansi-color-names-vector'."
528 (let ((ansi-color-map (make-vector 50 nil))
529 (index 0))
530 ;; miscellaneous attributes
531 (mapc
532 (function (lambda (e)
533 (aset ansi-color-map index e)
534 (setq index (1+ index)) ))
535 ansi-color-faces-vector)
536 ;; foreground attributes
537 (setq index 30)
538 (mapc
539 (function (lambda (e)
540 (aset ansi-color-map index
541 (ansi-color-make-face 'foreground
542 (if (consp e) (car e) e)))
543 (setq index (1+ index)) ))
544 ansi-color-names-vector)
545 ;; background attributes
546 (setq index 40)
547 (mapc
548 (function (lambda (e)
549 (aset ansi-color-map index
550 (ansi-color-make-face 'background
551 (if (consp e) (cdr e) e)))
552 (setq index (1+ index)) ))
553 ansi-color-names-vector)
554 ansi-color-map))
556 (defvar ansi-color-map (ansi-color-make-color-map)
557 "A brand new color map suitable for `ansi-color-get-face'.
559 The value of this variable is usually constructed by
560 `ansi-color-make-color-map'. The values in the array are such that the
561 numbers included in an SGR control sequences point to the correct
562 foreground or background colors.
564 Example: The sequence \033[34m specifies a blue foreground. Therefore:
565 (aref ansi-color-map 34)
566 => \(foreground-color . \"blue\")")
568 (defun ansi-color-map-update (symbol value)
569 "Update `ansi-color-map'.
571 Whenever the vectors used to construct `ansi-color-map' are changed,
572 this function is called. Therefore this function is listed as the :set
573 property of `ansi-color-faces-vector' and `ansi-color-names-vector'."
574 (set-default symbol value)
575 (setq ansi-color-map (ansi-color-make-color-map)))
577 (defun ansi-color-get-face-1 (ansi-code)
578 "Get face definition from `ansi-color-map'.
579 ANSI-CODE is used as an index into the vector."
580 (condition-case nil
581 (aref ansi-color-map ansi-code)
582 (args-out-of-range nil)))
584 (defun ansi-color-get-face (escape-seq)
585 "Create a new face by applying all the parameters in ESCAPE-SEQ.
587 Should any of the parameters result in the default face (usually this is
588 the parameter 0), then the effect of all previous parameters is cancelled.
590 ESCAPE-SEQ is a SGR control sequences such as \\033[34m. The parameter
591 34 is used by `ansi-color-get-face-1' to return a face definition."
592 (let ((i 0)
593 f val)
594 (while (string-match ansi-color-parameter-regexp escape-seq i)
595 (setq i (match-end 0)
596 val (ansi-color-get-face-1
597 (string-to-number (match-string 1 escape-seq) 10)))
598 (cond ((not val))
599 ((eq val 'default)
600 (setq f (list val)))
602 (unless (member val f)
603 (push val f)))))
606 (provide 'ansi-color)
608 ;;; ansi-color.el ends here