Terminal control/Coloured text: Difference between revisions
Content deleted Content added
Thundergnat (talk | contribs) m →{{header|Ring}}: Remove vanity tags |
→{{header|Locomotive Basic}}: add screenshots |
||
(47 intermediate revisions by 26 users not shown) | |||
Line 1:
{{task}}
[[Category:Terminal control]]
;Task:
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)
<br><br>
=={{header|8086 Assembly}}==
{{works with|MS-DOS}}
Prints the letter 'A' to the screen in bright cyan (color 11 in VGA)
<syntaxhighlight lang="asm"> .model small
.stack 1024
.data
.code
start:
mov ax,@data
mov ds,ax
mov ax,@code
mov es,ax
cld ;String functions are set to auto-increment
mov ax,13h ;select 320x200 VGA
int 10h
mov ah,0Eh
mov al,'A' ;select char to print
mov bx,11 ;select color to print it in
int 10h
ExitDOS:
mov ax,4C00h ;return to dos
int 21h
end start</syntaxhighlight>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program colorterminal64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessStartPgm: .asciz "Program start \n"
szMessEndPgm: .asciz "Program normal end.\n"
szMessColorRed: .asciz "Color red.\n"
szCodeInit: .asciz "\033[0m" //color reinit
szCodeRed: .asciz "\033[31m" //color red
szMessBlue: .asciz "\033[34mColor Blue\n" //color blue
szMessTwoColor: .asciz "\033[32mColor Green \033[35m Color Velvet\n"
szMessTest: .asciz "\033[33m\033[1mMessage yellow bold\n"
szCarriageReturn: .asciz "\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main:
ldr x0,qAdrszMessStartPgm //display start message
bl affichageMess
ldr x0,qAdrszCodeRed //color red
bl affichageMess
ldr x0,qAdrszMessColorRed
bl affichageMess
ldr x0,qAdrszMessBlue //message color blue
bl affichageMess
ldr x0,qAdrszMessTwoColor //message two colors
bl affichageMess
ldr x0,qAdrszMessTest
bl affichageMess
ldr x0,qAdrszCodeInit //color reinitialize
bl affichageMess
ldr x0,qAdrszMessEndPgm //display end message
bl affichageMess
100: //standard end of the program
mov x0,0 //return code
mov x8,EXIT //request to exit program
svc 0 //perform system call
qAdrszMessStartPgm: .quad szMessStartPgm
qAdrszMessEndPgm: .quad szMessEndPgm
qAdrszCodeInit: .quad szCodeInit
qAdrszCodeRed: .quad szCodeRed
qAdrszMessBlue: .quad szMessBlue
qAdrszMessColorRed: .quad szMessColorRed
qAdrszMessTwoColor: .quad szMessTwoColor
qAdrszMessTest: .quad szMessTest
qAdrszCarriageReturn: .quad szCarriageReturn
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
<pre>
Program start
Color red.
Color Blue
Color Green Color Velvet
Message yellow bold
Program normal end.
</pre>
=={{header|Ada}}==
{{libheader|ANSIAda}}
<syntaxhighlight lang="ada">with Ada.Text_Io;
with Ansi;
procedure Coloured is
use Ada.Text_Io;
subtype Ansi_Colors is Ansi.Colors
range Ansi.Black .. Ansi.Colors'Last; -- Avoid default
begin
for Fg_Color in Ansi_Colors loop
Put ("Rosetta ");
Put (Ansi.Foreground (Fg_Color));
for Bg_Color in Ansi_Colors loop
Put (Ansi.Background (Bg_Color));
Put ("Code");
end loop;
Put (Ansi.Reset);
New_Line;
end loop;
end Coloured;</syntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program colorText.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ BUFFERSIZE, 100
/* Initialized data */
.data
szMessStartPgm: .asciz "Program start \n"
szMessEndPgm: .asciz "Program normal end.\n"
szMessColorRed: .asciz "Color red.\n"
szCodeInit: .asciz "\033[0m" @ color reinit
szCodeRed: .asciz "\033[31m" @ color red
szMessBlue: .asciz "\033[34mColor Blue\n" @ color blue
szMessTwoColor: .asciz "\033[32mColor Green \033[35m Color Velvet\n"
szMessTest: .asciz "\033[33m\033[1mMessage yellow bold\n"
szCarriageReturn: .asciz "\n"
/* UnInitialized data */
.bss
/* code section */
.text
.global main
main:
ldr r0,iAdrszMessStartPgm @ display start message
bl affichageMess
ldr r0,iAdrszCodeRed @ color red
bl affichageMess
ldr r0,iAdrszMessColorRed
bl affichageMess
ldr r0,iAdrszMessBlue @ message color blue
bl affichageMess
ldr r0,iAdrszMessTwoColor @ message two colors
bl affichageMess
ldr r0,iAdrszMessTest
bl affichageMess
ldr r0,iAdrszCodeInit @ color reinitialize
bl affichageMess
ldr r0,iAdrszMessEndPgm @ display end message
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessStartPgm: .int szMessStartPgm
iAdrszMessEndPgm: .int szMessEndPgm
iAdrszCodeInit: .int szCodeInit
iAdrszCodeRed: .int szCodeRed
iAdrszMessBlue: .int szMessBlue
iAdrszMessColorRed: .int szMessColorRed
iAdrszMessTwoColor: .int szMessTwoColor
iAdrszMessTest: .int szMessTest
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registers
mov r2,#0 @ counter length */
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call system
pop {r0,r1,r2,r7,lr} @ restaur registers
bx lr @ return
</syntaxhighlight>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">str: "Hello World"
print color #red str
print color #green str
print color #blue str
print color #magenta str
print color #yellow str
print color #cyan str
print color #black str
print color #white str</syntaxhighlight>
=={{header|AutoHotkey}}==
[[Image:AutoHotkey_terminal_control_coloured_text.jpeg|thumb|right]]
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.
<
hConsole := DllCall( "GetStdHandle", int, STDOUT := -11 )
Loop 15
Line 28 ⟶ 271:
return out
return 0
}</
=={{header|BaCon}}==
<syntaxhighlight lang="freebasic">' ANSI terminal coloured text
COLOR FG TO BLACK
PRINT "a word"
COLOR FG TO RED
PRINT "a word"
COLOR FG TO GREEN
PRINT "a word"
' Other colours include YELLOW, BLUE, MAGENTA, CYAN, WHITE
' Second keyword can be BG for background colour control
' The COLOR command also accepts keywords of NORMAL, INTENSE, INVERSE, RESET</syntaxhighlight>
=={{header|BASIC}}==
Line 35 ⟶ 293:
{{works with|QBasic}}
<
COLOR n
PRINT "Rosetta Code"
NEXT</
==={{header|Commodore BASIC}}===
Color palettes vary across the Commodore 8-bit computers that have color capability.
====Commodore VIC-20====
Eight (8) colors available.
<syntaxhighlight lang="gwbasic">10 print chr$(147)
20 for i=0 to 7
30 poke 646,i:print "rosetta code!"
40 next i
50 poke 646,0:end</syntaxhighlight>
====Commodore 64====
Sixteen (16) colors available. This program also works on the rare Commodore CBM-II P500, which featured the same VIC-II video chip as the Commodore 64. Simply change the memory address from 646 to 236.
<syntaxhighlight lang="gwbasic">10 print chr$(147)
20 for i=0 to 15
30 poke 646,i:print "rosetta code!"
40 next
50 poke 646,14:end</syntaxhighlight>
====Commodore 128====
Outputs 16 colors to both the 80-column and 40-column displays, however the palette between the two displays is not exactly the same.
<syntaxhighlight lang="gwbasic">10 graphic 5,1
20 for i=0 to 15
30 color 5,i:print "rosetta code!"
40 next i
50 graphic 0,1
60 for i=0 to 15
70 color 5,i:print "rosetta code!"
80 next i
90 end</syntaxhighlight>
====Commodore Plus/4====
This machine is capable of 8 luminance values for 15 colors, plus black, yielding a total of 121 unique colors.
<syntaxhighlight lang="gwbasic">10 graphic 0,1
20 for c=1 to 16
30 for b=0 to 7
40 color 1,c,b:print "rosetta code!"
50 next b:next c
60 color 1,0:end</syntaxhighlight>
=={{header|BBC BASIC}}==
<
COLOUR col% : REM foreground
COLOUR 128+(15-col%) : REM background
PRINT "Rosetta Code"
NEXT</
[[File:coloured_text_bbc.gif]]
=={{header|Befunge}}==
Assuming a terminal with support for ANSI escape sequences, this displays the words ''Red'', ''Green'', ''Blue'', ''Magenta'', ''Cyan'' and ''Yellow'', using the corresponding text colour and a "complementary" background colour.
<
,_:!#@_:"m3["39*,,,\,,"m4["39*,,,\"g"\->:#,_55+"m["39*,,,</
=={{header|C}}==
On a terminal that understands ANSI escape sequences, such as color xterm, this shows you some annoyingly huge, annoyingly colorful tables.
<
void table(const char *title, const char *mode)
Line 84 ⟶ 391:
table("inverted ( ESC[7m )", "7;");
return 0;
}</
=={{header|C sharp|C#}}==
Line 91 ⟶ 398:
Visual Studios Intellisense will list all available colours.
<
static void Main(string[] args)
{
Line 104 ⟶ 411:
Console.ReadKey();
}
</syntaxhighlight>
=={{header|C++}}==
Coloured text and the background colour can be set using ANSI escape codes.
For a list of these codes see: https://en.wikipedia.org/wiki/ANSI_escape_code.
There are also many useful codes given in the Java example.
<syntaxhighlight lang="c++">
#include <iostream>
int main() {
std::cout << "\033[42m";
std::cout << "\033[4;37m";
std::cout << "Green background with underlined white text" << std::endl;
std::cout << "\033[0m" << std::endl;
std::cout << "\033[0;103m";
std::cout << "\033[1;34m";
std::cout << "Bright yellow background with bold blue text" << std::endl;
std::cout << "\033[0m" << std::endl;
std::cout << "\033[46m";
std::cout << "\033[1;95m";
std::cout << "Cyan background with bold bright magenta text" << std::endl;
std::cout << "\033[0m" << std::endl;
}
</syntaxhighlight>
[[Media:ColouredTextC++.PNG]]
=={{header|COBOL}}==
Line 110 ⟶ 443:
{{works with|OpenCOBOL}}
<!-- I couldn't find a way to upload a picture of the output. The 'Upload File' option isn't there for me. Would someone else mind uploading it? -->
<
IDENTIFICATION DIVISION.
PROGRAM-ID. coloured-text.
Line 198 ⟶ 531:
GOBACK
.</
=={{header|Common Lisp}}==
==={{header|ncurses}}===
To interface the ncurses C library from Lisp, the ''croatoan'' library is used.
<syntaxhighlight lang="lisp">(defun coloured-text ()
(with-screen (scr :input-blocking t :input-echoing nil :cursor-visible nil)
(dolist (i '(:red :green :yellow :blue :magenta :cyan :white))
(add-string scr (format nil "~A~%" i) :fgcolor i))
(refresh scr)
;; wait for keypress
(get-char scr)))</syntaxhighlight>
=={{header|D}}==
For terminals that understand color escape sequences:
<
std.conv,
std.stdio;
Line 254 ⟶ 598:
"Hello, world!".color(c).writeln;
}
}</
=={{header|Dc}}==
I'm just assuming an ANSI terminal like "xterm". That is what I'm working with every day. What kind of terminal is present "dc" cannot determine.
Regarding blinking... may be I add that later.
<syntaxhighlight lang="dc">## after PARI/GP
# C: for( initcode ; condcode ; incrcode ) {body}
# .[q] [1] [2] [3] [4]
# # [initcode] [condcode] [incrcode] [body] (for)
[ [q]S. 4:.3:.2:.x [2;.x 0=. 4;.x 3;.x 0;.x]d0:.x
Os.L.o
]sF # F = for
[
27P ## ESC
91P ## Bra ... together: CSI
n ## colour 1 (fg)
[;]P ## ";"
n ## colour 2 (bg)
[;1m]P ## ";1m"
]sS
[
27P ## ESC
91P ## Bra ... together: CSI
[0m]P ## "0m"
]sR
[0q]s0 [<0 1]sL ## L: isle
## for b=40 b<=47 ++b
## for f=30 f<=37 ++f
[40sb] [lb 47 lLx] [lb 1+ sb] [
[30sf] [lf 37 lLx] [lf 1+ sf] [
lb lf lSx [colour-blind]P lRx [ ]P
] lFx ## for b
AP
] lFx ## for f</syntaxhighlight>
=={{header|F_Sharp|F#}}==
{{trans|C#}}
<
Console.ForegroundColor <- ConsoleColor.Red
Line 274 ⟶ 656:
Console.ResetColor()
Console.WriteLine("Back to normal")
Console.ReadKey()</
=={{header|Forth}}==
ANS/ISO Forth does not specify how screen color is handled. This demonstration creates a set of commands for an ANSI terminal that give the programmer control of text color.
<syntaxhighlight lang="forth">( ANSI terminal control lexicon Colored Text)
DECIMAL
( support routines)
27 CONSTANT ESC
: <##> ( n -- ) ( sends n, radix 10, no spaces)
BASE @ >R 0 <# #S #> TYPE R> BASE ! ;
: ESC[ ( -- ) ESC EMIT ." [" ;
( Attributes )
1 CONSTANT BOLD 2 CONSTANT DIM 3 CONSTANT ITALIC
5 CONSTANT BLINK 7 CONSTANT REV 8 CONSTANT BLANK
( Colors )
0 CONSTANT BLACK 1 CONSTANT RED 2 CONSTANT GREEN
3 CONSTANT YELLOW 4 CONSTANT BLUE 5 CONSTANT MAGENTA
6 CONSTANT CYAN 7 CONSTANT WHITE
: ATTR ( attribute ) ESC[ <##> ." m" ; ( use: BOLD ATTR )
: TEXT ( color ) 30 + ATTR ; ( use: YELLOW TEXT )
: BACKGROUND ( color ) 40 + ATTR ; ( use: BLUE BACKGROUND )
</syntaxhighlight>
With the code loaded into Forth, color control is a part of the language
<syntaxhighlight lang="forth">WHITE TEXT BLUE BACKGROUND ok
BLUE TEXT BOLD ATTR ok
CYAN TEXT ok</syntaxhighlight>
=={{header|Fortran}}==
<syntaxhighlight lang="fortran">! Standard Fortran, should work with any modern compiler (tested gfortran 9)
! and ANSI supporting terminal (tested Linux, various terminals).
program coloured_terminal_text
use, intrinsic :: iso_fortran_env, only: ERROR_UNIT
implicit none
! Some parameters for our ANSI escape codes
character(*), parameter :: esc = achar(27) ! Escape character.
character(*), parameter :: reset = esc // '[0m' ! Terminates an ANSI code.
! Foreground(font) Colours
character(*), parameter :: red = esc // '[31m'
character(*), parameter :: green = esc // '[32m'
character(*), parameter :: yellow = esc // '[33m'
character(*), parameter :: blue = esc // '[34m'
character(*), parameter :: magenta = esc // '[35m'
character(*), parameter :: cyan = esc // '[36m'
character(*), parameter :: grey = esc // '[90m' !Bright-Black
! One background colour
character(*), parameter :: background_green = esc // '[42m'
! Some other formatting
character(*), parameter :: bold = esc // '[1m'
character(*), parameter :: bold_blink = esc // '[1;5m'
! Write to terminal (stderr, use OUTPUT_UNIT for stdout)
write(ERROR_UNIT, '(a)') bold // 'Coloured words:' // reset
write(ERROR_UNIT, '(4x, a)') &
red // 'Red' // reset, &
green // 'Green' // reset, &
yellow // 'Yellow' // reset, &
blue // 'Blue' // reset, &
magenta // 'Magenta' // reset, &
cyan // 'Cyan' // reset, &
grey // 'Grey' // reset
write(ERROR_UNIT, '(a)') bold_blink // 'THE END ;-)' // reset
write(ERROR_UNIT, '(a)') background_green // 'Bonus Round' // reset
end program coloured_terminal_text</syntaxhighlight>
===Intel Fortran on Windows===
Using Windows API functions, see for instance '''[https://msdn.microsoft.com/en-us/library/ms686047.aspx SetConsoleTextAttribute]''' in MSDN. On can set foreground and background colors, available attributes are [https://msdn.microsoft.com/en-us/library/ms682088.aspx here]. It's not possible to cause blinking without using a thread to change attributes at time intervals. The program reverts the console attributes to the preceding values. Failing to do that, it is still possible to reset console colors with the '''color''' command, without arguments.
<
use kernel32
implicit none
Line 299 ⟶ 747:
print "(A)", "This is a red string."
q = SetConsoleTextAttribute(hConsole, csbi%wAttributes)
end program</
=={{header|FreeBASIC}}==
Draws a 4x4 grid of coloured text with coloured backgrounds. Auto-blinking text isn't supported.
<syntaxhighlight lang="freebasic">for i as uinteger = 0 to 15
color i, 15-i
print "Colour "+str(i),
if i mod 4 = 3 then color 0,0: print
next i</syntaxhighlight>
=={{header|FunL}}==
<
bold()
Line 314 ⟶ 772:
reset()
println( RED + 'Red', GREEN + 'Green', BLUE + 'Blue', MAGENTA + 'Magenta', CYAN + 'Cyan', YELLOW + 'Yellow' + RESET )</
=={{header|Go}}==
===External command===
<
import (
Line 345 ⟶ 803:
cmd.Stdout = os.Stdout
cmd.Run()
}</
Optional tasks
<
import (
Line 381 ⟶ 839:
cmd.Stdout = os.Stdout
return cmd.Run()
}</
===ANSI escape codes===
<
import "fmt"
Line 391 ⟶ 849:
fmt.Println("\033[32mGreen")
fmt.Println("\033[34mBlue")
}</
Optional tasks
<
import "fmt"
Line 403 ⟶ 861:
fmt.Println(" Blinking Red ")
fmt.Print("\033[25;40m") // blink off, black background
}</
===Ncurses===
{{libheader|Curses}}
<
import (
Line 436 ⟶ 894:
s.Println("Blue")
s.GetChar()
}</
Optional tasks
<
import (
Line 467 ⟶ 925:
s.Print(" Blinking Red ")
s.GetChar()
}</
=={{header|Golo}}==
<syntaxhighlight lang="golo">#!/usr/bin/env golosh
----
This module demonstrates terminal colours.
----
module Terminalcontrolcoloredtext
import gololang.AnsiCodes
function main = |args| {
# these are lists of pointers to the ansi functions in the golo library.
# {} doesn't do anything so it's got no effect on the text.
let foregrounds = vector[
^fg_red, ^fg_blue, ^fg_magenta, ^fg_white, ^fg_black, ^fg_cyan, ^fg_green, ^fg_yellow
]
let backgrounds = vector[
^bg_red, ^bg_blue, ^bg_magenta, ^bg_white, ^bg_black, ^bg_cyan, ^bg_green, ^bg_yellow
]
let effects = vector[
{}, ^bold, ^blink, ^underscore, ^concealed, ^reverse_video
]
println("Terminal supports ansi code: " + likelySupported())
foreach fg in foregrounds {
foreach bg in backgrounds {
foreach effect in effects {
fg()
bg()
effect()
print("Rosetta Code")
reset()
}
}
}
println("")
}</syntaxhighlight>
=={{header|GW-BASIC}}==
Sixteen foreground colours, in non-flashing and flashing, and eight background colours.
<syntaxhighlight lang="gwbasic">10 FOR I = 0 TO 31
20 COLOR I, 7 - (I MOD 8)
30 PRINT I;
40 IF I MOD 4 = 3 THEN COLOR 7, 0 : PRINT
50 NEXT I</syntaxhighlight>
=={{header|Haskell}}==
Line 475 ⟶ 982:
{{Works with|ansi-terminal|0.5.5.1}}
<
import System.Console.ANSI
Line 491 ⟶ 998:
colorStrLn Vivid Green Dull Black "This is green on black."
colorStrLn Vivid Yellow Dull Black "This is yellow on black."
colorStrLn Dull Black Vivid Blue "This is black on light blue."</
=={{header|J}}==
Line 498 ⟶ 1,005:
<!--WARNING-->
Quite different from the fixed c solution, we flexibly construct character vectors that combine various functions. This code constructs two such sequences, DB is useful to write vertical text, and the noun J output to the terminal draws to the extent of my artistic ability the J icon at the relative position.
<
CSI=: 27 91 { a.
Line 526 ⟶ 1,033:
J=: J , (backward 5),'\____/'
smoutput(color BLACK),(clear 2),(move 8 22),J,(WHITE color BLACK),(downward 2)
</syntaxhighlight>
=={{header|Java}}==
<syntaxhighlight lang="java">
public class TerminalControlColouredText {
public static void main(String[] args) {
System.out.print(Color.GREEN_BACKGROUND);
System.out.print(Color.WHITE_UNDERLINED);
System.out.println("Green background with underlined white text");
System.out.println(Color.RESET);
System.out.print(Color.YELLOW_BACKGROUND_BRIGHT);
System.out.print(Color.BLUE_BOLD);
System.out.println("Bright yellow background with bold blue text");
System.out.println(Color.RESET);
System.out.print(Color.CYAN_BACKGROUND);
System.out.print(Color.MAGENTA_BOLD_BRIGHT);
System.out.println("Cyan background with bold bright magenta text");
System.out.println(Color.RESET);
}
private enum Color {
// Restore original background and text colours
RESET("\033[0m"),
// Text colours
BLACK("\033[0;30m"),
RED("\033[0;31m"),
GREEN("\033[0;32m"),
YELLOW("\033[0;33m"),
BLUE("\033[0;34m"),
MAGENTA("\033[0;35m"),
CYAN("\033[0;36m"),
WHITE("\033[0;37m"),
// Bold text colours
BLACK_BOLD("\033[1;30m"),
RED_BOLD("\033[1;31m"),
GREEN_BOLD("\033[1;32m"),
YELLOW_BOLD("\033[1;33m"),
BLUE_BOLD("\033[1;34m"),
MAGENTA_BOLD("\033[1;35m"),
CYAN_BOLD("\033[1;36m"),
WHITE_BOLD("\033[1;37m"),
// Underlined text colours
BLACK_UNDERLINED("\033[4;30m"),
RED_UNDERLINED("\033[4;31m"),
GREEN_UNDERLINED("\033[4;32m"),
YELLOW_UNDERLINED("\033[4;33m"),
BLUE_UNDERLINED("\033[4;34m"),
MAGENTA_UNDERLINED("\033[4;35m"),
CYAN_UNDERLINED("\033[4;36m"),
WHITE_UNDERLINED("\033[4;37m"),
// Bright text colours
BLACK_BRIGHT("\033[0;90m"),
RED_BRIGHT("\033[0;91m"),
GREEN_BRIGHT("\033[0;92m"),
YELLOW_BRIGHT("\033[0;93m"),
BLUE_BRIGHT("\033[0;94m"),
MAGENTA_BRIGHT("\033[0;95m"),
CYAN_BRIGHT("\033[0;96m"),
WHITE_BRIGHT("\033[0;97m"),
// Bold and bright text colours
BLACK_BOLD_BRIGHT("\033[1;90m"),
RED_BOLD_BRIGHT("\033[1;91m"),
GREEN_BOLD_BRIGHT("\033[1;92m"),
YELLOW_BOLD_BRIGHT("\033[1;93m"),
BLUE_BOLD_BRIGHT("\033[1;94m"),
MAGENTA_BOLD_BRIGHT("\033[1;95m"),
CYAN_BOLD_BRIGHT("\033[1;96m"),
WHITE_BOLD_BRIGHT("\033[1;97m"),
// Background colours
BLACK_BACKGROUND("\033[40m"),
RED_BACKGROUND("\033[41m"),
GREEN_BACKGROUND("\033[42m"),
YELLOW_BACKGROUND("\033[43m"),
BLUE_BACKGROUND("\033[44m"),
MAGENTA_BACKGROUND("\033[45m"),
CYAN_BACKGROUND("\033[46m"),
WHITE_BACKGROUND("\033[47m"),
// Bright background colours
BLACK_BACKGROUND_BRIGHT("\033[0;100m"),
RED_BACKGROUND_BRIGHT("\033[0;101m"),
GREEN_BACKGROUND_BRIGHT("\033[0;102m"),
YELLOW_BACKGROUND_BRIGHT("\033[0;103m"),
BLUE_BACKGROUND_BRIGHT("\033[0;104m"),
MAGENTA_BACKGROUND_BRIGHT("\033[0;105m"),
CYAN_BACKGROUND_BRIGHT("\033[0;106m"),
WHITE_BACKGROUND_BRIGHT("\033[0;107m");
private Color(String aCode) {
code = aCode;
}
@Override
public String toString() {
return code;
}
private final String code;
}
}
</syntaxhighlight>
[[Media:ColouredTextJava.PNG]]
=={{header|jq}}==
''Adapted from [[#Wren|Wren]]''
{{works with|jq}}
''Also works with gojq, the Go implmentation of jq''
<syntaxhighlight lang="jq">
# Pseudosleep for at least the given number of seconds,
# and emit the actual number of seconds that have elapsed.
def sleep($seconds):
now
| . as $now
| until( . - $now >= $seconds; now)
| . - $now ;
def esc: "\u001b";
def colors: ["Black", "Red", "Green", "Yellow", "Blue", "Magenta", "Cyan", "White"];
# display words using 'bright' colors
(range(1; 1 + (colors|length)) | "\(esc)[\(30+.);1m\(colors[.])"), # red to white
sleep(3), # wait for 3 seconds
"\(esc)[47m", # set background color to white
"\(esc)[2J", # clear screen to background color
"\(esc)[H", # home the cursor
# display words again using 'blinking' colors
"\(esc)[5m", # blink on
(range(0;6) | "\(esc)[\(30+.);1m\(colors[.])"), # black to cyan
sleep(3), # wait for 3 more seconds
"\(esc)[0m", # reset all attributes
"\(esc)[2J", # clear screen to background color
"\(esc)[H" # home the cursor
</syntaxhighlight>
''Invocation''
Using jq: jq -nrf coloured_text.jq
=={{header|Julia}}==
Julia has rudimentary color terminal support built-in. Slightly more elaborate color and effect support is available with the <code>AnsiColor</code> package.
<syntaxhighlight lang="julia">
using AnsiColor
Line 565 ⟶ 1,220:
println("This terminal appears not to support color.")
end
</syntaxhighlight>
{{out}}
Line 581 ⟶ 1,236:
=={{header|Kotlin}}==
{{Works with|Ubuntu|14.04}}
<
const val ESC = "\u001B"
Line 606 ⟶ 1,261:
}
println(WHITE) // set foreground color to normal white
}</
=={{header|Lasso}}==
<
define ec(code::string) => {
Line 640 ⟶ 1,295:
stdoutnl('So this is the Rosetta Code!')
stdout( ec('normal'))
</syntaxhighlight>
=={{header|Locomotive Basic}}==
[[File:Cpcbasic colored text mode1.png|thumb|Graphics mode 1]]
[[File:Cpcbasic colored text mode0.png|thumb|Graphics mode 0]]
<syntaxhighlight lang="locobasic">10 mode 1:defint a-z
20 print "Mode 1 (4 colors):"
30 for y=0 to 3
Line 678 ⟶ 1,334:
330 print "*End of color demo*"
340 locate 1,25:print "<Press any key>";:call &bb06
350 mode 1</
=={{header|
Assumes an ansi-capable terminal..
<syntaxhighlight lang="lua">print("Normal \027[1mBold\027[0m \027[4mUnderline\027[0m \027[7mInverse\027[0m")
colors = { 30,31,32,33,34,35,36,37,90,91,92,93,94,95,96,97 }
for _,bg in ipairs(colors) do
for _,fg in ipairs(colors) do
io.write("\027["..fg..";"..(bg+10).."mX")
end
print("\027[0m") -- be nice, reset
end</syntaxhighlight>
{{out}}
''(image upload is broken)''
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Delegating to tput on terminal enabled OS(Mac Os, Linux)
<
Run["tput setaf 2"]; Print["Coloured Text"];
Run["tput setaf 3"]; Print["Coloured Text"]</
[[File:colouredtextmma.png]]
=={{header|Nim}}==
<
setForegroundColor(fgRed)
echo "FATAL ERROR! Cannot write to /boot/vmlinuz-3.2.0-33-generic"
Line 710 ⟶ 1,379:
setForegroundColor(fgMagenta)
echo "RosettaCode!"</
=={{header|OCaml}}==
Line 716 ⟶ 1,385:
Using the library [http://forge.ocamlcore.org/projects/ansiterminal/ ANSITerminal] in the interactive loop:
<
# open ANSITerminal ;;
# print_string [cyan; on_blue] "Hello\n" ;;
Hello
- : unit = ()</
=={{header|ooRexx}}==
This program is based on the shell script in the Bash Prompt HowTo at
http://www.tldp.org/, by Giles Orr. It uses object-oriented features of Open Object Rexx.
<syntaxhighlight lang="rexx">
#!/usr/bin/rexx
/*.----------------------------------------------------------------------.*/
Line 857 ⟶ 1,525:
end
return
</syntaxhighlight>
This is what the output looks like:
Line 866 ⟶ 1,534:
=={{header|PARI/GP}}==
<
=={{header|
The CRT unit allows us to play with the console window, since at least the old Turbo Pascal days. We can clear the screen and specify colors by number or by name, among other tricks.
<syntaxhighlight lang="pascal">program Colorizer;
uses CRT;
const SampleText = 'Lorem ipsum dolor sit amet';
var fg, bg: 0..15;
begin
ClrScr;
for fg := 0 to 7 do begin
bg := 15 - fg;
TextBackground(bg);
TextColor(fg);
writeln(SampleText)
end;
TextBackground(White);
TextColor(Black);
end.</syntaxhighlight>
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
##
uses System;
Console.ForegroundColor := ConsoleColor.Red;
Console.BackgroundColor := ConsoleColor.Yellow;
Console.WriteLine('Red on Yellow');
Console.ForegroundColor := ConsoleColor.Black;
Console.BackgroundColor := ConsoleColor.White;
Console.WriteLine('Black on White');
</syntaxhighlight>
=={{header|Perl}}==
<syntaxhighlight lang="perl">my %colors = (
red => "\e[1;31m",
green => "\e[1;32m",
yellow => "\e[1;33m",
blue => "\e[1;34m",
magenta => "\e[1;35m",
cyan => "\e[1;36m"
);
$clr = "\e[0m";
print "$colors{$_}$_ text $clr\n" for sort keys %colors;
# the Raku code also works
use feature 'say';
use Term::ANSIColor;
say colored('RED ON WHITE', 'bold red on_white');
Line 876 ⟶ 1,594:
say colored('MAGENTA', 'bold magenta');
say colored('CYAN ON RED', 'bold cyan on_red');
say colored('YELLOW', 'bold yellow');</
<syntaxhighlight lang="perl">
#ON WINDOWS USING POWERSHELL or WT.EXE
$ForegroundColor = {
BLACK => "\e[1;30m",
DARK_RED => "\e[1;31m",
DARK_GREEN => "\e[1;32m",
DARK_YELLOW => "\e[1;33m",
DARK_BLUE => "\e[1;34m",
DARK_MAGENTA => "\e[1;35m",
DARK_CYAN => "\e[1;36m",
LIGHT_GREY => "\e[1;37m",
DARK_GREY => "\e[1;90m",
RED => "\e[1;91m",
GREEN => "\e[1;92m",
YELLOW => "\e[1;93m",
BLUE => "\e[1;94m",
MAGENTA => "\e[1;95m",
CYAN => "\e[1;96m",
WHITE => "\e[1;97m"
};
$BackgroundColor = {
BLACK => "\e[1;40m",
DARK_RED => "\e[1;41m",
DARK_GREEN => "\e[1;42m",
DARK_YELLOW => "\e[1;43m",
DARK_BLUE => "\e[1;44m",
DARK_MAGENTA => "\e[1;45m",
DARK_CYAN => "\e[1;46m",
LIGHT_GREY => "\e[1;47m",
DARK_GREY => "\e[1;100m",
RED => "\e[1;101m",
GREEN => "\e[1;102m",
YELLOW => "\e[1;103m",
BLUE => "\e[1;104m",
MAGENTA => "\e[1;105m",
CYAN => "\e[1;106m",
WHITE => "\e[1;107m"
};
$ClearColors = "\e[1;0m";
print $ForegroundColor->{WHITE};
print $BackgroundColor->{DARK_BLUE};
print "White On Blue";
print $ClearColors;
</syntaxhighlight>
=={{header|Phix}}==
{{trans|PureBasic}}
The following builtin constants (0..15) may be used:
BLACK, BLUE,
BRIGHT_BLUE, BRIGHT_GREEN, BRIGHT_CYAN, BRIGHT_RED, BRIGHT_MAGENTA,
YELLOW, BRIGHT_WHITE
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Coloured_text.exw
-- ==============================
--</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #7060A8;">text_color</span><span style="color: #0000FF;">(</span><span style="color: #004600;">GRAY</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">bk_color</span><span style="color: #0000FF;">(</span><span style="color: #004600;">BLACK</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Background color# 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" -----------------------------------------------\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">foreground</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">15</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Foreground color# %02d "</span><span style="color: #0000FF;">,</span><span style="color: #000000;">foreground</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">background</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">15</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">text_color</span><span style="color: #0000FF;">(</span><span style="color: #000000;">foreground</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">bk_color</span><span style="color: #0000FF;">(</span><span style="color: #000000;">background</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%02d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">foreground</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">text_color</span><span style="color: #0000FF;">(</span><span style="color: #004600;">GRAY</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">bk_color</span><span style="color: #0000FF;">(</span><span style="color: #004600;">BLACK</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n\npress enter to exit"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
Output matches PureBasic
=={{header|PicoLisp}}==
{{trans|UNIX Shell}}
<
(quit "This application requires a colour terminal") )
Line 922 ⟶ 1,691:
(call 'tput 'sgr0) # reset
(prinl)</
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
foreach ($color in [enum]::GetValues([System.ConsoleColor])) {Write-Host "$color color." -ForegroundColor $color}
</syntaxhighlight>
=={{header|PureBasic}}==
<syntaxhighlight 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()
EndIf</syntaxhighlight>
[[Image:terminal_control,colored_text.png]]
=={{header|Python}}==
{{libheader|colorama}}
<
from colorama import init, Fore, Back, Style
init(autoreset=True)
Line 943 ⟶ 1,735:
print Fore.MAGENTA + "Rosetta Code!"
print Back.YELLOW + Fore.BLUE + Style.BRIGHT + " " * 40 + " == Good Bye!"
</syntaxhighlight>
This is a windows only solution without colorama
<
from ctypes import *
Line 963 ⟶ 1,755:
color(7)
raw_input("holding cmd")
</syntaxhighlight>
=={{header|Racket}}==
{{trans|Tcl}}
<
#lang racket
Line 1,015 ⟶ 1,784:
(reset))
(displayln "Steady only"))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>use Terminal::ANSIColor;
say colored('RED ON WHITE', 'bold red on_white');
say colored('GREEN', 'bold green');
say colored('BLUE ON YELLOW', 'bold blue on_yellow');
say colored('MAGENTA', 'bold magenta');
say colored('CYAN ON RED', 'bold cyan on_red');
say colored('YELLOW', 'bold yellow');</syntaxhighlight>
=={{header|REXX}}==
Line 1,039 ⟶ 1,819:
<br><br>The program displays 16 lines, each of a different color with text stating the color of the text.
<br>(The black text, of course, is essentially invisible as the background is also black.)
<
parse arg !; if !all() then exit /*exit if documentation specified*/
if \!dos & \!os2 then exit /*if this isn't DOS, then exit. */
Line 1,072 ⟶ 1,852:
!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))</
=={{header|Ring}}==
<
# Project : Terminal control/Coloured text
Line 1,087 ⟶ 1,867:
cc_print(forecolor | CC_BG_WHITE, "Rosetta Code" + nl)
next
</syntaxhighlight>
Output image:
Line 1,096 ⟶ 1,876:
{{libheader|colored}}
<
require 'rubygems'
require 'colored'
Line 1,119 ⟶ 1,899:
puts 'white on green'.white_on_green
puts 'white on magenta'.white_on_magenta
puts 'white on red'.white_on_red</
[[File:Colored-text-ruby.png]]
=={{header|Rust}}==
<syntaxhighlight lang="rust">const ESC: &str = "\x1B[";
const RESET: &str = "\x1B[0m";
fn main() {
println!("Foreground¦Background--------------------------------------------------------------");
print!(" ¦");
for i in 40..48 {
print!(" ESC[{}m ", i);
}
println!("\n----------¦------------------------------------------------------------------------");
for i in 30..38 {
print!("{}ESC[{}m ¦{}{1}m", RESET, i, ESC);
for j in 40..48 {
print!("{}{}m Rosetta ", ESC, j);
}
println!("{}", RESET);
print!("{}ESC[{};1m ¦{}{1};1m", RESET, i, ESC);
for j in 40..48 {
print!("{}{}m Rosetta ", ESC, j);
}
println!("{}", RESET);
}
}</syntaxhighlight>
=={{header|Scala}}==
===Scala idiom (Functional Programming)===
{{Works with|Ubuntu|14.04}}
<
val ESC = "\u001B"
val (normal, bold, blink, black, white) =
Line 1,150 ⟶ 1,956:
println(white) // set foreground color to normal white
}
</syntaxhighlight>
=={{header|Sidef}}==
{{trans|
<
say a.colored('RED ON WHITE', 'bold red on_white');
Line 1,160 ⟶ 1,967:
say a.colored('MAGENTA', 'bold magenta');
say a.colored('CYAN ON RED', 'bold cyan on_red');
say a.colored('YELLOW', 'bold yellow');</
=={{header|Tcl}}==
This only works on Unix terminals as it delegates to the system <tt>tput</tt> command.
<
proc capability cap {expr {![catch {exec tput -S << $cap}]}}
proc colorterm {} {expr {[capability setaf] && [capability setab]}}
Line 1,189 ⟶ 1,996:
} else {
puts "Steady only"
}</
==
<
This is red
--color green
Line 1,203 ⟶ 2,010:
This is magenta
--color yellow
This is yellow</
=={{header|True BASIC}}==
<syntaxhighlight lang="qbasic">FOR n = 1 TO 15
SET COLOR n
PRINT "Rosetta Code"
NEXT n
END</syntaxhighlight>
=={{header|UNIX Shell}}==
<syntaxhighlight lang="sh">#!/bin/sh
# Check if the terminal supports colour
Line 1,248 ⟶ 2,064:
echo "Flashing text"
tput sgr0 # reset everything before exiting</
=={{header|Wren}}==
<syntaxhighlight lang="wren">import "timer" for Timer
var colors = ["Black", "Red", "Green", "Yellow", "Blue", "Magenta", "Cyan", "White"]
// display words using 'bright' colors
for (i in 1..7) System.print("\e[%(30+i);1m%(colors[i])") // red to white
Timer.sleep(3000) // wait for 3 seconds
System.write("\e[47m") // set background color to white
System.write("\e[2J") // clear screen to background color
System.write("\e[H") // home the cursor
// display words again using 'blinking' colors
System.write("\e[5m") // blink on
for (i in 0..6) System.print("\e[%(30+i);1m%(colors[i])") // black to cyan
Timer.sleep(3000) // wait for 3 more seconds
System.write("\e[0m") // reset all attributes
System.write("\e[2J") // clear screen to background color
System.write("\e[H") // home the cursor</syntaxhighlight>
=={{header|XPL0}}==
Line 1,266 ⟶ 2,102:
PCs and by simulators, such as DOSBox, on other computers.
<
def Black, Blue, Green, Cyan, Red, Magenta, Brown, White, \attribute colors
Gray, LBlue, LGreen, LCyan, LRed, LMagenta, Yellow, BWhite; \EGA palette
Line 1,280 ⟶ 2,116:
Attrib(Cyan<<4+Black); \black on cyan
ChOut(6,^r);
]</
=={{header|zkl}}==
{{trans|C}}
Terminal window on Linux, prints tables of colored glyphs.
<
println("\n\e[1m%s\e[m\n bg\t fg".fmt(title));
foreach b in ([40..48].chain([100..107])){
Line 1,300 ⟶ 2,136:
table("underline ( ESC[4m ), support varies", "4;");
table("blink ( ESC[5m )", "5;");
table("inverted ( ESC[7m )", "7;");</
==
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.
<
20 READ c$: REM get our text for display
30 INK l: REM set the text colour
Line 1,316 ⟶ 2,152:
110 STOP
900 DATA "Black","Blue","Red","Magenta","Green","Cyan","Yellow","White"</
{{omit from|Axe}}
|