Terminal control/Coloured text
The task is to display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
- How the system should determine if the terminal supports colour
- Setting of the background colour
- How to cause blinking or flashing (if supported by the terminal)
AutoHotkey
AutoHotkey is not written for the command line, so we need to use the WinAPI directly. For simplicity, this example demonstrates only the foreground colours. <lang AHK>DllCall( "AllocConsole" ) ; create a console if not launched from one hConsole := DllCall( "GetStdHandle", int, STDOUT := -11 ) Loop 15 SetConsoleTextAttribute(hConsole, A_Index) ,WriteConsole(hConsole, "AutoHotkey`n")
MsgBox
SetConsoleTextAttribute(hConsole, Attributes){ return DllCall( "SetConsoleTextAttribute", UPtr, hConsole, UShort, Attributes) } WriteConsole(hConsole, text){ VarSetCapacity(out, 16) If DllCall( "WriteConsole", UPtr, hConsole, Str, text, UInt, StrLen(text) , UPtrP, out, uint, 0 ) return out return 0 }</lang>
BASIC
<lang qbasic>FOR n = 1 TO 15
COLOR n PRINT "Rosetta Code"
NEXT</lang>
C
On a terminal that understands ANSI escape sequences, such as color xterm, this shows you some annoyingly huge, annoyingly colorful tables. <lang c>#include <stdio.h>
void table(char *title, char *mode) { int f, b; printf("\n\033[1m%s\033[m\n bg\t fg\n", title); for (b = 40; b <= 107; b++) { if (b == 48) b = 100; printf("%3d\t\033[%s%dm", b, mode, b); for (f = 30; f <= 97; f++) { if (f == 38) f = 90; printf("\033[%dm%3d ", f, f); } puts("\033[m"); } }
int main(void) { int fg, bg, blink, inverse;
table("normal ( ESC[22m or ESC[m )", "22;"); table("bold ( ESC[1m )", "1;"); table("faint ( ESC[2m ), not well supported", "2;"); table("italic ( ESC[3m ), not well supported", "3;"); table("underline ( ESC[4m ), support varies", "4;"); table("blink ( ESC[5m )", "5;"); table("inverted ( ESC[7m )", "7;"); return 0; }</lang>
Mathematica
Delegating to tput on terminal enabled OS(Mac Os, Linux) <lang Mathematica>Run["tput setaf 1"]; Print["Coloured Text"]; Run["tput setaf 2"]; Print["Coloured Text"]; Run["tput setaf 3"]; Print["Coloured Text"]</lang>
OCaml
Using the library ANSITerminal in the interactive loop:
<lang ocaml>$ ocaml unix.cma -I +ANSITerminal ANSITerminal.cma
- open ANSITerminal ;;
- print_string [cyan; on_blue] "Hello\n" ;;
Hello - : unit = ()</lang>
PicoLisp
<lang PicoLisp>(unless (member (sys "TERM") '("linux" "xterm" "xterm-color" "rxvt"))
(quit "This application requires a colour terminal") )
- Coloured text
(for X '((1 . "Red") (4 . "Blue") (3 . "Yellow"))
(call 'tput "setaf" (car X)) (prinl (cdr X)) )
- Blinking
(out '(tput "-S")
(prinl "setab 1^Jsetaf 3^Jblink") )
(prin "Flashing text")
(call 'tput 'sgr0) # reset (prinl)</lang>
PureBasic
<lang purebasic>If OpenConsole()
PrintN("Background color# 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15") PrintN(" -----------------------------------------------") Define Foreground, Background For Foreground = 0 To 15 ConsoleColor(7, 0) ;grey foreground, black background Print("Foreground color# " + RSet(Str(Foreground), 2, "0") + " ") For Background = 0 To 15 ConsoleColor(Foreground, Background) Print(RSet(Str(Foreground), 2, "0")) ConsoleColor(7, 0) ;grey foreground, black background Print(" ") Next PrintN("") Next ConsoleColor(7, 0) ;grey foreground, black background Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole()
REXX
PC/REXX or Personal REXX
This REXX program only works under PC/REXX (also called Personal REXX).
PC/REXX can execute under MSDOS (or a Windows DOS window), or OS/2.
The prologue code (at the bottom of the program) is a collection of some general-purpose subroutines which determine:
- which environment (operating system) the REXX interpreter is running under
- if Windows/NT/XP/Vista/7/8 (the NT family) is running
- which REXX is being executed
- what literal to use to obtain the environmental variables (for the value bif)
- what the fileName, fileType/fileExt, fileMode/path is of the REXX program
- which command to use to clear the terminal screen
- invokes $H to show general documentation (1st and only arg = ?)
- invokes $H to show a flow diagram (1st and only arg = ?FLOW)
- invokes $H to show sample uses (1st and only arg = ?SAMPLE)
- invokes $H to show the author & contact info (1st and only arg = ?AUTHOR)
All the prologue was left intact to give a general feel of the scope of the boilerplate code.
The prologue code is in many REXX programs and it's easier to keep them on one line for copying purposes and sorting.
The program displays 16 lines, each of a different color with text stating the color of the text.
(The black text, of course, is essentiall invisible as the background is also black.)
<lang rexx>/*REXX*/parse arg !;if !all(arg()) then exit
if \!dos & \!os2 then exit /*if this isn't DOS, then exit. */ if \!pcrexx then exit /*if this isn't PC/REXX, exit. */
/* The "real" programs issue all errors through another */ /* program which has more verbage and explanation, and */ /* issues the error text in red (if color is avaiable).*/
color.0 = 'black' color.1 = 'dark blue' color.2 = 'dark green' color.3 = 'dark cyan/turquois' color.4 = 'dark red' color.5 = 'dark pink/magenta' color.6 = 'dark yellow (orange)' color.7 = 'dark white' color.8 = 'brite black (grey/gray)' color.9 = 'bright blue' color.10 = 'bright green' color.11 = 'bright cyan/turquois' color.12 = 'bright red' color.13 = 'bright pink/magenta' color.14 = 'bright yellow' color.15 = 'bright white'
do j=0 to 15 /*show all sixteen color codes. */ call scrwrite ,,'color code=['right(j,2)"]" color.j,,,j; say end /*the "SAY" forces a NEWLINE. */
exit /*stick a fork in it, we're done.*/
/*═════════════════════════════general 1-line subs══════════════════════*/ !all:!!=!;!=space(!);upper !;call !fid;!nt=right(!var('OS'),2)=='NT';!cls=word('CLS VMFCLEAR CLRSCREEN',1+!cms+!tso*2);if arg(1)\==1 then return 0;if wordpos(!,'? ?SAMPLES ?AUTHOR ?FLOW')==0 then return 0;!call=']$H';call '$H' !fn !;!call=;return 1 !cal:if symbol('!CALL')\=="VAR" then !call=;return !call !env:!env='ENVIRONMENT';if !sys=='MSDOS'|!brexx|!r4|!roo then !env='SYSTEM';if !os2 then !env='OS2'!env;!ebcdic=1=='f0'x;return !fid:parse upper source !sys !fun !fid . 1 . . !fn !ft !fm .;call !sys;if !dos then do;_=lastpos('\',!fn);!fm=left(!fn,_);!fn=substr(!fn,_+1);parse var !fn !fn '.' !ft;end;return word(0 !fn !ft !fm,1+('0'arg(1))) !rex:parse upper version !ver !vernum !verdate .;!brexx='BY'==!vernum;!kexx='KEXX'==!ver;!pcrexx='REXX/PERSONAL'==!ver|'REXX/PC'==!ver;!r4='REXX-R4'==!ver;!regina='REXX-REGINA'==left(!ver,11);!roo='REXX-ROO'==!ver;call !env;return !sys:!cms=!sys=='CMS';!os2=!sys=='OS2';!tso=!sys=='TSO'|!sys=='MVS';!vse=!sys=='VSE';!dos=pos('DOS',!sys)\==0|pos('WIN',!sys)\==0|!sys=='CMD';call !rex;return !var:call !fid;if !kexx then return space(dosenv(arg(1)));return space(value(arg(1),,!env)) </lang>
Tcl
This only works on Unix terminals as it delegates to the system tput command. <lang tcl># Utility interfaces to the low-level command proc capability cap {expr {![catch {exec tput -S << $cap}]}} proc colorterm {} {expr {[capability setaf] && [capability setab]}} proc tput args {exec tput -S << $args >/dev/tty} array set color {black 0 red 1 green 2 yellow 3 blue 4 magenta 5 cyan 6 white 7} proc foreground x {exec tput -S << "setaf $::color($x)" > /dev/tty} proc background x {exec tput -S << "setab $::color($x)" > /dev/tty} proc reset {} {exec tput sgr0 > /dev/tty}
- Demonstration of use
if {[colorterm]} {
foreground blue background yellow puts "Color output" reset
} else {
puts "Monochrome only"
}
if {[capability blink]} {
tput blink puts "Blinking output" reset
} else {
puts "Steady only"
}</lang>
UNIX Shell
<lang sh>#!/bin/sh
- Check if the terminal supports colour
case $TERM in
linux) ;; rxvt) ;; *) echo "HW65000 This application requires a colour terminal" >&2 exit 252 #ERLHW incompatible hardware ;;
esac
- Coloured text
tput setaf 1 #red echo "Red" tput setaf 4 #blue echo "Blue" tput setaf 3 # yellow echo "Yellow"
- Blinking
tput setab 1 # red background tput setaf 3 # yellow foreground
- tput blink # enable blinking (but does not work on some terminals)
echo "Flashing text"
tput sgr0 # reset everything before exiting</lang>
ZX Spectrum Basic
The ZX Spectrum will always output colour. However if the television is black and white, these will show as various levels of luminence corresponding to the numerical colour value. <lang zxbasic>10 FOR l=0 TO 7 20 READ c$: REM get our text for display 30 INK l: REM set the text colour 40 PRINT c$ 50 NEXT l 60 PAPER 2: REM red background 70 INK 6: REM yellow forground 80 FLASH 1: REM activate flashing 90 PRINT "Flashing!": REM this will flash red and yellow (alternating inverse) 100 PAPER 7: INK 0: FLASH 0: REM normalize colours before exit 110 STOP
900 DATA "Black","Blue","Red","Magenta","Green","Cyan","Yellow","White"</lang>