1 ! Copyright (C) 2014 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
4 USING: accessors arrays assocs destructors formatting fry io
5 io.streams.string io.styles kernel math math.functions
6 math.vectors namespaces sequences strings strings.tables ;
14 ! System colors (8 colors)
24 ! "Bright" version of 8 colors
32 { { 255 255 255 } 15 }
35 : color>rgb ( color -- rgb )
36 [ red>> ] [ green>> ] [ blue>> ] tri
37 [ 255 * round >integer ] tri@ 3array ;
39 : color>ansi ( color -- ansi bold? )
40 color>rgb '[ _ distance ]
41 colors [ keys swap infimum-by ] [ at ] bi
42 dup 8 >= [ 8 - t ] [ f ] if ;
44 : color>foreground ( color -- string )
45 color>ansi [ 30 + ] [ "m" ";1m" ? ] bi* "\e[%d%s" sprintf ;
47 : color>background ( color -- string )
48 color>ansi [ 40 + ] [ "m" ";1m" ? ] bi* "\e[%d%s" sprintf ;
50 : font-styles ( font-style -- string )
54 { bold-italic "\e[1m\e[3m" }
61 M: ansi stream-write1 stream>> stream-write1 ;
62 M: ansi stream-write stream>> stream-write ;
63 M: ansi stream-flush stream>> stream-flush ;
64 M: ansi stream-nl stream>> stream-nl ;
68 [ foreground of [ color>foreground ] [ "" ] if* ]
69 [ background of [ color>background ] [ "" ] if* ]
70 [ font-style of [ font-styles ] [ "" ] if* ]
71 tri 3append [ "\e[0m" surround ] unless-empty
72 ] dip stream>> stream-write ;
74 M: ansi make-span-stream
75 swap <style-stream> <ignore-close-stream> ;
77 M: ansi make-block-stream
78 swap <style-stream> <ignore-close-stream> ;
80 ! FIXME: color codes take up formatting space
82 M: ansi stream-write-table
85 [ [ stream>> >string ] map ] map format-table
86 [ nl ] [ write ] interleave
87 ] with-output-stream* ;
89 M: ansi make-cell-stream
90 2drop <string-writer> <ansi> ;
92 M: ansi dispose drop ;
96 : with-ansi ( quot -- )
97 output-stream get <ansi> swap with-output-stream* ; inline