Terminal control/Coloured text: Difference between revisions
m
→{{header|Wren}}: Changed to Wren S/H
m (→{{header|Wren}}: Changed to Wren S/H) |
|||
(29 intermediate revisions by 18 users not shown) | |||
Line 13:
* 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 */
Line 100 ⟶ 236:
bx lr @ return
</syntaxhighlight>
=={{header|Arturo}}==
<
print
print
print
print
print
print
print
print
=={{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 135 ⟶ 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 142 ⟶ 293:
{{works with|QBasic}}
<
COLOR n
PRINT "Rosetta Code"
NEXT</
==={{header|Commodore BASIC}}===
Line 155 ⟶ 306:
Eight (8) colors available.
<
20 for i=0 to 7
30 poke 646,i:print "rosetta code!"
40 next i
50 poke 646,0:end</
====Commodore 64====
Line 165 ⟶ 316:
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.
<
20 for i=0 to 15
30 poke 646,i:print "rosetta code!"
40 next
50 poke 646,14:end</
====Commodore 128====
Line 175 ⟶ 326:
Outputs 16 colors to both the 80-column and 40-column displays, however the palette between the two displays is not exactly the same.
<
20 for i=0 to 15
30 color 5,i:print "rosetta code!"
Line 183 ⟶ 334:
70 color 5,i:print "rosetta code!"
80 next i
90 end</
====Commodore Plus/4====
Line 189 ⟶ 340:
This machine is capable of 8 luminance values for 15 colors, plus black, yielding a total of 121 unique colors.
<
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</
=={{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 240 ⟶ 391:
table("inverted ( ESC[7m )", "7;");
return 0;
}</
=={{header|C sharp|C#}}==
Line 247 ⟶ 398:
Visual Studios Intellisense will list all available colours.
<
static void Main(string[] args)
{
Line 260 ⟶ 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 266 ⟶ 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 354 ⟶ 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 410 ⟶ 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 430 ⟶ 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.
<
DECIMAL
( support routines)
Line 454 ⟶ 680:
: TEXT ( color ) 30 + ATTR ; ( use: YELLOW TEXT )
: BACKGROUND ( color ) 40 + ATTR ; ( use: BLUE BACKGROUND )
</
With the code loaded into Forth, color control is a part of the language
<
BLUE TEXT BOLD ATTR ok
CYAN TEXT ok</
=={{header|Fortran}}==
<
! and ANSI supporting terminal (tested Linux, various terminals).
program coloured_terminal_text
Line 497 ⟶ 723:
write(ERROR_UNIT, '(a)') background_green // 'Bonus Round' // reset
end program coloured_terminal_text</
===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 521 ⟶ 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 536 ⟶ 772:
reset()
println( RED + 'Red', GREEN + 'Green', BLUE + 'Blue', MAGENTA + 'Magenta', CYAN + 'Cyan', YELLOW + 'Yellow' + RESET )</
=={{header|Go}}==
===External command===
<
import (
Line 567 ⟶ 803:
cmd.Stdout = os.Stdout
cmd.Run()
}</
Optional tasks
<
import (
Line 603 ⟶ 839:
cmd.Stdout = os.Stdout
return cmd.Run()
}</
===ANSI escape codes===
<
import "fmt"
Line 613 ⟶ 849:
fmt.Println("\033[32mGreen")
fmt.Println("\033[34mBlue")
}</
Optional tasks
<
import "fmt"
Line 625 ⟶ 861:
fmt.Println(" Blinking Red ")
fmt.Print("\033[25;40m") // blink off, black background
}</
===Ncurses===
{{libheader|Curses}}
<
import (
Line 658 ⟶ 894:
s.Println("Blue")
s.GetChar()
}</
Optional tasks
<
import (
Line 689 ⟶ 925:
s.Print(" Blinking Red ")
s.GetChar()
}</
=={{header|Golo}}==
<
----
This module demonstrates terminal colours.
Line 729 ⟶ 965:
}
println("")
}</
=={{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 737 ⟶ 982:
{{Works with|ansi-terminal|0.5.5.1}}
<
import System.Console.ANSI
Line 753 ⟶ 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 760 ⟶ 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 788 ⟶ 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 827 ⟶ 1,220:
println("This terminal appears not to support color.")
end
</syntaxhighlight>
{{out}}
Line 843 ⟶ 1,236:
=={{header|Kotlin}}==
{{Works with|Ubuntu|14.04}}
<
const val ESC = "\u001B"
Line 868 ⟶ 1,261:
}
println(WHITE) // set foreground color to normal white
}</
=={{header|Lasso}}==
<
define ec(code::string) => {
Line 902 ⟶ 1,295:
stdoutnl('So this is the Rosetta Code!')
stdout( ec('normal'))
</syntaxhighlight>
=={{header|Locomotive Basic}}==
<
20 print "Mode 1 (4 colors):"
30 for y=0 to 3
Line 940 ⟶ 1,333:
330 print "*End of color demo*"
340 locate 1,25:print "<Press any key>";:call &bb06
350 mode 1</
=={{header|Lua}}==
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 972 ⟶ 1,378:
setForegroundColor(fgMagenta)
echo "RosettaCode!"</
=={{header|OCaml}}==
Line 978 ⟶ 1,384:
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 1,118 ⟶ 1,524:
end
return
</syntaxhighlight>
This is what the output looks like:
Line 1,127 ⟶ 1,533:
=={{header|PARI/GP}}==
<
=={{header|Pascal}}==
Line 1,133 ⟶ 1,539:
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.
<
uses CRT;
Line 1,151 ⟶ 1,557:
TextBackground(White);
TextColor(Black);
end.</
=={{header|Perl}}==
<
red => "\e[1;31m",
green => "\e[1;32m",
Line 1,175 ⟶ 1,581:
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 1,221 ⟶ 1,678:
(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}}==
<
PrintN("Background color# 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15")
PrintN(" -----------------------------------------------")
Line 1,248 ⟶ 1,705:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
[[Image:terminal_control,colored_text.png]]
=={{header|Python}}==
{{libheader|colorama}}
<
from colorama import init, Fore, Back, Style
init(autoreset=True)
Line 1,265 ⟶ 1,722:
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 1,285 ⟶ 1,742:
color(7)
raw_input("holding cmd")
</syntaxhighlight>
=={{header|Racket}}==
{{trans|Tcl}}
<
#lang racket
Line 1,314 ⟶ 1,771:
(reset))
(displayln "Steady only"))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
say colored('RED ON WHITE', 'bold red on_white');
Line 1,325 ⟶ 1,782:
say colored('MAGENTA', 'bold magenta');
say colored('CYAN ON RED', 'bold cyan on_red');
say colored('YELLOW', 'bold yellow');</
=={{header|REXX}}==
Line 1,349 ⟶ 1,806:
<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,382 ⟶ 1,839:
!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,397 ⟶ 1,854:
cc_print(forecolor | CC_BG_WHITE, "Rosetta Code" + nl)
next
</syntaxhighlight>
Output image:
Line 1,406 ⟶ 1,863:
{{libheader|colored}}
<
require 'rubygems'
require 'colored'
Line 1,429 ⟶ 1,886:
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,460 ⟶ 1,943:
println(white) // set foreground color to normal white
}
</syntaxhighlight>
=={{header|Sidef}}==
{{trans|Raku}}
<
say a.colored('RED ON WHITE', 'bold red on_white');
Line 1,471 ⟶ 1,954:
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,500 ⟶ 1,983:
} else {
puts "Steady only"
}</
==
<
This is red
--color green
Line 1,514 ⟶ 1,997:
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,559 ⟶ 2,051:
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,577 ⟶ 2,089:
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,591 ⟶ 2,103:
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,611 ⟶ 2,123:
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,627 ⟶ 2,139:
110 STOP
900 DATA "Black","Blue","Red","Magenta","Green","Cyan","Yellow","White"</
{{omit from|Axe}}
|