]> code.delx.au - gnu-emacs/blob - lisp/ansi-color.el
Convert consecutive FSF copyright years to ranges.
[gnu-emacs] / lisp / ansi-color.el
1 ;;; ansi-color.el --- translate ANSI escape sequences into faces
2
3 ;; Copyright (C) 1999-2011 Free Software Foundation, Inc.
4
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
9
10 ;; This file is part of GNU Emacs.
11
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.
16
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.
21
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/>.
24
25 ;;; Commentary:
26
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.
31 ;;
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.
35 ;;
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.
40 ;;
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).
48
49 ;; The basic functions are:
50 ;;
51 ;; `ansi-color-apply' to colorize a string containing SGR control
52 ;; sequences.
53 ;;
54 ;; `ansi-color-filter-apply' to filter SGR control sequences from a
55 ;; string.
56 ;;
57 ;; `ansi-color-apply-on-region' to colorize a region containing SGR
58 ;; control sequences.
59 ;;
60 ;; `ansi-color-filter-region' to filter SGR control sequences from a
61 ;; region.
62
63 ;;; Thanks
64
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.
68 ;;
69 ;; Markus Kuhn <Markus.Kuhn@cl.cam.ac.uk> for pointing me to ECMA-48.
70 ;;
71 ;; Stefan Monnier <foo@acm.com> explaing obscure font-lock stuff and
72 ;; code suggestions.
73
74 \f
75
76 ;;; Code:
77
78 (defvar comint-last-output-start)
79
80 ;; Customization
81
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)
91
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.
97
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
107
108 Note that the symbol `default' is special: It will not be combined
109 with the current face.
110
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)
117
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).
123
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
133
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'."
136 :type '(vector string string string string string string string string)
137 :set 'ansi-color-map-update
138 :initialize 'custom-initialize-default
139 :group 'ansi-colors)
140
141 (defconst ansi-color-regexp "\033\\[\\([0-9;]*m\\)"
142 "Regexp that matches SGR control sequences.")
143
144 (defconst ansi-color-drop-regexp
145 "\033\\[\\([ABCDsuK]\\|2J\\|=[0-9]+[hI]\\|[0-9;]*[Hf]\\)"
146 "Regexp that matches ANSI control sequences to silently drop.")
147
148 (defconst ansi-color-parameter-regexp "\\([0-9]*\\)[m;]"
149 "Regexp that matches SGR control sequence parameters.")
150
151
152 ;; Convenience functions for comint modes (eg. shell-mode)
153
154
155 (defcustom ansi-color-for-comint-mode t
156 "Determines what to do with comint output.
157 If nil, do nothing.
158 If the symbol `filter', then filter all SGR control sequences.
159 If anything else (such as t), then translate SGR control sequences
160 into text properties.
161
162 In order for this to have any effect, `ansi-color-process-output' must
163 be in `comint-output-filter-functions'.
164
165 This can be used to enable colorized ls --color=yes output
166 in shell buffers. You set this variable by calling one of:
167 \\[ansi-color-for-comint-mode-on]
168 \\[ansi-color-for-comint-mode-off]
169 \\[ansi-color-for-comint-mode-filter]"
170 :type '(choice (const :tag "Do nothing" nil)
171 (const :tag "Filter" filter)
172 (const :tag "Translate" t))
173 :group 'ansi-colors
174 :version "23.2")
175
176 ;;;###autoload
177 (defun ansi-color-for-comint-mode-on ()
178 "Set `ansi-color-for-comint-mode' to t."
179 (interactive)
180 (setq ansi-color-for-comint-mode t))
181
182 (defun ansi-color-for-comint-mode-off ()
183 "Set `ansi-color-for-comint-mode' to nil."
184 (interactive)
185 (setq ansi-color-for-comint-mode nil))
186
187 (defun ansi-color-for-comint-mode-filter ()
188 "Set `ansi-color-for-comint-mode' to symbol `filter'."
189 (interactive)
190 (setq ansi-color-for-comint-mode 'filter))
191
192 ;;;###autoload
193 (defun ansi-color-process-output (ignored)
194 "Maybe translate SGR control sequences of comint output into text properties.
195
196 Depending on variable `ansi-color-for-comint-mode' the comint output is
197 either not processed, SGR control sequences are filtered using
198 `ansi-color-filter-region', or SGR control sequences are translated into
199 text properties using `ansi-color-apply-on-region'.
200
201 The comint output is assumed to lie between the marker
202 `comint-last-output-start' and the process-mark.
203
204 This is a good function to put in `comint-output-filter-functions'."
205 (let ((start-marker (or comint-last-output-start
206 (point-min-marker)))
207 (end-marker (process-mark (get-buffer-process (current-buffer)))))
208 (cond ((eq ansi-color-for-comint-mode nil))
209 ((eq ansi-color-for-comint-mode 'filter)
210 (ansi-color-filter-region start-marker end-marker))
211 (t
212 (ansi-color-apply-on-region start-marker end-marker)))))
213
214 (add-hook 'comint-output-filter-functions
215 'ansi-color-process-output)
216
217 (defalias 'ansi-color-unfontify-region 'font-lock-default-unfontify-region)
218 (make-obsolete 'ansi-color-unfontify-region "not needed any more" "24.1")
219
220 ;; Working with strings
221 (defvar ansi-color-context nil
222 "Context saved between two calls to `ansi-color-apply'.
223 This is a list of the form (FACES FRAGMENT) or nil. FACES is a list of
224 faces the last call to `ansi-color-apply' ended with, and FRAGMENT is a
225 string starting with an escape sequence, possibly the start of a new
226 escape sequence.")
227 (make-variable-buffer-local 'ansi-color-context)
228
229 (defun ansi-color-filter-apply (string)
230 "Filter out all ANSI control sequences from STRING.
231
232 Every call to this function will set and use the buffer-local variable
233 `ansi-color-context' to save partial escape sequences. This information
234 will be used for the next call to `ansi-color-apply'. Set
235 `ansi-color-context' to nil if you don't want this.
236
237 This function can be added to `comint-preoutput-filter-functions'."
238 (let ((start 0) end result)
239 ;; if context was saved and is a string, prepend it
240 (if (cadr ansi-color-context)
241 (setq string (concat (cadr ansi-color-context) string)
242 ansi-color-context nil))
243 ;; find the next escape sequence
244 (while (setq end (string-match ansi-color-regexp string start))
245 (setq result (concat result (substring string start end))
246 start (match-end 0)))
247 ;; save context, add the remainder of the string to the result
248 (let (fragment)
249 (if (string-match "\033" string start)
250 (let ((pos (match-beginning 0)))
251 (setq fragment (substring string pos)
252 result (concat result (substring string start pos))))
253 (setq result (concat result (substring string start))))
254 (setq ansi-color-context (if fragment (list nil fragment))))
255 result))
256
257 (defun ansi-color-apply (string)
258 "Translates SGR control sequences into text properties.
259 Delete all other control sequences without processing them.
260
261 Applies SGR control sequences setting foreground and background colors
262 to STRING using text properties and returns the result. The colors used
263 are given in `ansi-color-faces-vector' and `ansi-color-names-vector'.
264 See function `ansi-color-apply-sequence' for details.
265
266 Every call to this function will set and use the buffer-local variable
267 `ansi-color-context' to save partial escape sequences and current face.
268 This information will be used for the next call to `ansi-color-apply'.
269 Set `ansi-color-context' to nil if you don't want this.
270
271 This function can be added to `comint-preoutput-filter-functions'."
272 (let ((face (car ansi-color-context))
273 (start 0) end escape-sequence result
274 colorized-substring)
275 ;; If context was saved and is a string, prepend it.
276 (if (cadr ansi-color-context)
277 (setq string (concat (cadr ansi-color-context) string)
278 ansi-color-context nil))
279 ;; Find the next escape sequence.
280 (while (setq end (string-match ansi-color-regexp string start))
281 (setq escape-sequence (match-string 1 string))
282 ;; Colorize the old block from start to end using old face.
283 (when face
284 (put-text-property start end 'font-lock-face face string))
285 (setq colorized-substring (substring string start end)
286 start (match-end 0))
287 ;; Eliminate unrecognized ANSI sequences.
288 (while (string-match ansi-color-drop-regexp colorized-substring)
289 (setq colorized-substring
290 (replace-match "" nil nil colorized-substring)))
291 (push colorized-substring result)
292 ;; Create new face, by applying escape sequence parameters.
293 (setq face (ansi-color-apply-sequence escape-sequence face)))
294 ;; if the rest of the string should have a face, put it there
295 (when face
296 (put-text-property start (length string) 'font-lock-face face string))
297 ;; save context, add the remainder of the string to the result
298 (let (fragment)
299 (if (string-match "\033" string start)
300 (let ((pos (match-beginning 0)))
301 (setq fragment (substring string pos))
302 (push (substring string start pos) result))
303 (push (substring string start) result))
304 (setq ansi-color-context (if (or face fragment) (list face fragment))))
305 (apply 'concat (nreverse result))))
306
307 ;; Working with regions
308
309 (defvar ansi-color-context-region nil
310 "Context saved between two calls to `ansi-color-apply-on-region'.
311 This is a list of the form (FACES MARKER) or nil. FACES is a list of
312 faces the last call to `ansi-color-apply-on-region' ended with, and
313 MARKER is a buffer position within an escape sequence or the last
314 position processed.")
315 (make-variable-buffer-local 'ansi-color-context-region)
316
317 (defun ansi-color-filter-region (begin end)
318 "Filter out all ANSI control sequences from region BEGIN to END.
319
320 Every call to this function will set and use the buffer-local variable
321 `ansi-color-context-region' to save position. This information will be
322 used for the next call to `ansi-color-apply-on-region'. Specifically,
323 it will override BEGIN, the start of the region. Set
324 `ansi-color-context-region' to nil if you don't want this."
325 (let ((end-marker (copy-marker end))
326 (start (or (cadr ansi-color-context-region) begin)))
327 (save-excursion
328 (goto-char start)
329 ;; Delete unrecognized escape sequences.
330 (while (re-search-forward ansi-color-drop-regexp end-marker t)
331 (replace-match ""))
332 (goto-char start)
333 ;; Delete SGR escape sequences.
334 (while (re-search-forward ansi-color-regexp end-marker t)
335 (replace-match ""))
336 ;; save context, add the remainder of the string to the result
337 (if (re-search-forward "\033" end-marker t)
338 (setq ansi-color-context-region (list nil (match-beginning 0)))
339 (setq ansi-color-context-region nil)))))
340
341 (defun ansi-color-apply-on-region (begin end)
342 "Translates SGR control sequences into overlays or extents.
343 Delete all other control sequences without processing them.
344
345 SGR control sequences are applied by setting foreground and
346 background colors to the text between BEGIN and END using
347 overlays. The colors used are given in `ansi-color-faces-vector'
348 and `ansi-color-names-vector'. See `ansi-color-apply-sequence'
349 for details.
350
351 Every call to this function will set and use the buffer-local variable
352 `ansi-color-context-region' to save position and current face. This
353 information will be used for the next call to
354 `ansi-color-apply-on-region'. Specifically, it will override BEGIN, the
355 start of the region and set the face with which to start. Set
356 `ansi-color-context-region' to nil if you don't want this."
357 (let ((face (car ansi-color-context-region))
358 (start-marker (or (cadr ansi-color-context-region)
359 (copy-marker begin)))
360 (end-marker (copy-marker end))
361 escape-sequence)
362 ;; First, eliminate unrecognized ANSI control sequences.
363 (save-excursion
364 (goto-char start-marker)
365 (while (re-search-forward ansi-color-drop-regexp end-marker t)
366 (replace-match "")))
367 (save-excursion
368 (goto-char start-marker)
369 ;; Find the next SGR sequence.
370 (while (re-search-forward ansi-color-regexp end-marker t)
371 ;; Colorize the old block from start to end using old face.
372 (when face
373 (ansi-color-set-extent-face
374 (ansi-color-make-extent start-marker (match-beginning 0))
375 face))
376 ;; store escape sequence and new start position
377 (setq escape-sequence (match-string 1)
378 start-marker (copy-marker (match-end 0)))
379 ;; delete the escape sequence
380 (replace-match "")
381 ;; create new face by applying all the parameters in the escape
382 ;; sequence
383 (setq face (ansi-color-apply-sequence escape-sequence face)))
384 ;; search for the possible start of a new escape sequence
385 (if (re-search-forward "\033" end-marker t)
386 (progn
387 ;; if the rest of the region should have a face, put it there
388 (when face
389 (ansi-color-set-extent-face
390 (ansi-color-make-extent start-marker (point))
391 face))
392 ;; save face and point
393 (setq ansi-color-context-region
394 (list face (copy-marker (match-beginning 0)))))
395 ;; if the rest of the region should have a face, put it there
396 (if face
397 (progn
398 (ansi-color-set-extent-face
399 (ansi-color-make-extent start-marker end-marker)
400 face)
401 (setq ansi-color-context-region (list face)))
402 ;; reset context
403 (setq ansi-color-context-region nil))))))
404
405 ;; This function helps you look for overlapping overlays. This is
406 ;; usefull in comint-buffers. Overlapping overlays should not happen!
407 ;; A possible cause for bugs are the markers. If you create an overlay
408 ;; up to the end of the region, then that end might coincide with the
409 ;; process-mark. As text is added BEFORE the process-mark, the overlay
410 ;; will keep growing. Therefore, as more overlays are created later on,
411 ;; there will be TWO OR MORE overlays covering the buffer at that point.
412 ;; This function helps you check your buffer for these situations.
413 ; (defun ansi-color-debug-overlays ()
414 ; (interactive)
415 ; (let ((pos (point-min)))
416 ; (while (< pos (point-max))
417 ; (if (<= 2 (length (overlays-at pos)))
418 ; (progn
419 ; (goto-char pos)
420 ; (error "%d overlays at %d" (length (overlays-at pos)) pos))
421 ; (let (message-log-max)
422 ; (message "Reached %d." pos)))
423 ; (setq pos (next-overlay-change pos)))))
424
425 ;; Emacs/XEmacs compatibility layer
426
427 (defun ansi-color-make-face (property color)
428 "Return a face with PROPERTY set to COLOR.
429 PROPERTY can be either symbol `foreground' or symbol `background'.
430
431 For Emacs, we just return the cons cell \(PROPERTY . COLOR).
432 For XEmacs, we create a temporary face and return it."
433 (if (featurep 'xemacs)
434 (let ((face (make-face (intern (concat color "-" (symbol-name property)))
435 "Temporary face created by ansi-color."
436 t)))
437 (set-face-property face property color)
438 face)
439 (cond ((eq property 'foreground)
440 (cons 'foreground-color color))
441 ((eq property 'background)
442 (cons 'background-color color))
443 (t
444 (cons property color)))))
445
446 (defun ansi-color-make-extent (from to &optional object)
447 "Make an extent for the range [FROM, TO) in OBJECT.
448
449 OBJECT defaults to the current buffer. XEmacs uses `make-extent', Emacs
450 uses `make-overlay'. XEmacs can use a buffer or a string for OBJECT,
451 Emacs requires OBJECT to be a buffer."
452 (if (fboundp 'make-extent)
453 (make-extent from to object)
454 ;; In Emacs, the overlay might end at the process-mark in comint
455 ;; buffers. In that case, new text will be inserted before the
456 ;; process-mark, ie. inside the overlay (using insert-before-marks).
457 ;; In order to avoid this, we use the `insert-behind-hooks' overlay
458 ;; property to make sure it works.
459 (let ((overlay (make-overlay from to object)))
460 (overlay-put overlay 'modification-hooks '(ansi-color-freeze-overlay))
461 overlay)))
462
463 (defun ansi-color-freeze-overlay (overlay is-after begin end &optional len)
464 "Prevent OVERLAY from being extended.
465 This function can be used for the `modification-hooks' overlay
466 property."
467 ;; if stuff was inserted at the end of the overlay
468 (when (and is-after
469 (= 0 len)
470 (= end (overlay-end overlay)))
471 ;; reset the end of the overlay
472 (move-overlay overlay (overlay-start overlay) begin)))
473
474 (defun ansi-color-set-extent-face (extent face)
475 "Set the `face' property of EXTENT to FACE.
476 XEmacs uses `set-extent-face', Emacs uses `overlay-put'."
477 (if (featurep 'xemacs)
478 (set-extent-face extent face)
479 (overlay-put extent 'face face)))
480
481 ;; Helper functions
482
483 (defun ansi-color-apply-sequence (escape-sequence faces)
484 "Apply ESCAPE-SEQ to FACES and return the new list of faces.
485
486 ESCAPE-SEQ is an escape sequences parsed by `ansi-color-get-face'.
487
488 If the new faces start with the symbol `default', then the new
489 faces are returned. If the faces start with something else,
490 they are appended to the front of the FACES list, and the new
491 list of faces is returned.
492
493 If `ansi-color-get-face' returns nil, then we either got a
494 null-sequence, or we stumbled upon some garbage. In either
495 case we return nil."
496 (let ((new-faces (ansi-color-get-face escape-sequence)))
497 (cond ((null new-faces)
498 nil)
499 ((eq (car new-faces) 'default)
500 (cdr new-faces))
501 (t
502 ;; Like (append NEW-FACES FACES)
503 ;; but delete duplicates in FACES.
504 (let ((modified-faces (copy-sequence faces)))
505 (dolist (face (nreverse new-faces))
506 (setq modified-faces (delete face modified-faces))
507 (push face modified-faces))
508 modified-faces)))))
509
510 (defun ansi-color-make-color-map ()
511 "Creates a vector of face definitions and returns it.
512
513 The index into the vector is an ANSI code. See the documentation of
514 `ansi-color-map' for an example.
515
516 The face definitions are based upon the variables
517 `ansi-color-faces-vector' and `ansi-color-names-vector'."
518 (let ((ansi-color-map (make-vector 50 nil))
519 (index 0))
520 ;; miscellaneous attributes
521 (mapc
522 (function (lambda (e)
523 (aset ansi-color-map index e)
524 (setq index (1+ index)) ))
525 ansi-color-faces-vector)
526 ;; foreground attributes
527 (setq index 30)
528 (mapc
529 (function (lambda (e)
530 (aset ansi-color-map index
531 (ansi-color-make-face 'foreground e))
532 (setq index (1+ index)) ))
533 ansi-color-names-vector)
534 ;; background attributes
535 (setq index 40)
536 (mapc
537 (function (lambda (e)
538 (aset ansi-color-map index
539 (ansi-color-make-face 'background e))
540 (setq index (1+ index)) ))
541 ansi-color-names-vector)
542 ansi-color-map))
543
544 (defvar ansi-color-map (ansi-color-make-color-map)
545 "A brand new color map suitable for `ansi-color-get-face'.
546
547 The value of this variable is usually constructed by
548 `ansi-color-make-color-map'. The values in the array are such that the
549 numbers included in an SGR control sequences point to the correct
550 foreground or background colors.
551
552 Example: The sequence \033[34m specifies a blue foreground. Therefore:
553 (aref ansi-color-map 34)
554 => \(foreground-color . \"blue\")")
555
556 (defun ansi-color-map-update (symbol value)
557 "Update `ansi-color-map'.
558
559 Whenever the vectors used to construct `ansi-color-map' are changed,
560 this function is called. Therefore this function is listed as the :set
561 property of `ansi-color-faces-vector' and `ansi-color-names-vector'."
562 (set-default symbol value)
563 (setq ansi-color-map (ansi-color-make-color-map)))
564
565 (defun ansi-color-get-face-1 (ansi-code)
566 "Get face definition from `ansi-color-map'.
567 ANSI-CODE is used as an index into the vector."
568 (condition-case nil
569 (aref ansi-color-map ansi-code)
570 (args-out-of-range nil)))
571
572 (defun ansi-color-get-face (escape-seq)
573 "Create a new face by applying all the parameters in ESCAPE-SEQ.
574
575 Should any of the parameters result in the default face (usually this is
576 the parameter 0), then the effect of all previous parameters is cancelled.
577
578 ESCAPE-SEQ is a SGR control sequences such as \\033[34m. The parameter
579 34 is used by `ansi-color-get-face-1' to return a face definition."
580 (let ((i 0)
581 f val)
582 (while (string-match ansi-color-parameter-regexp escape-seq i)
583 (setq i (match-end 0)
584 val (ansi-color-get-face-1
585 (string-to-number (match-string 1 escape-seq) 10)))
586 (cond ((not val))
587 ((eq val 'default)
588 (setq f (list val)))
589 (t
590 (unless (member val f)
591 (push val f)))))
592 f))
593
594 (provide 'ansi-color)
595
596 ;;; ansi-color.el ends here