! Copyright (C) 2012 John Benediktsson ! See http://factorcode.org/license.txt for BSD license USING: accessors arrays assocs destructors environment formatting io io.streams.escape-codes io.streams.string io.styles kernel math math.functions math.vectors namespaces ranges sequences strings strings.tables ; IN: io.streams.256color [ [ dup dup 3array ] dip 232 + swap 256colors set-at ] each-index : color>rgb ( color -- rgb ) [ red>> ] [ green>> ] [ blue>> ] tri [ 255 * round >integer ] tri@ 3array ; : color>256color ( color -- 256color ) color>rgb '[ _ distance ] 256colors [ keys swap infimum-by ] [ at ] bi ; : color>foreground ( color -- string ) color>256color "\e[38;5;%sm" sprintf ; : color>background ( color -- string ) color>256color "\e[48;5;%sm" sprintf ; TUPLE: 256color < filter-writer ; C: <256color> 256color M: 256color stream-format [ [ foreground of [ color>foreground ] [ "" ] if* ] [ background of [ color>background ] [ "" ] if* ] [ font-style of [ font-styles ] [ "" ] if* ] tri 3append [ "\e[0m" surround ] unless-empty ] dip stream>> stream-write ; M: 256color make-span-stream swap ; M: 256color make-block-stream swap ; ! FIXME: color codes take up formatting space M: 256color stream-write-table [ drop [ [ stream>> >string ] map ] map format-table [ nl ] [ write ] interleave ] with-output-stream* ; M: 256color make-cell-stream 2drop <256color> ; M: 256color dispose drop ; PRIVATE> : 256color-terminal? ( -- ? ) "TERM" os-env "-256color" tail? ; : with-256color ( quot -- ) output-stream get <256color> swap with-output-stream* ; inline