Create your own text control codes: Difference between revisions

Added Wren
(→‎{{header|Raku}}: Add a Raku example)
(Added Wren)
Line 90:
Spelled out: twelve thousand, three hundred forty-five
Inverted: ǝʌᴉɟ-ʎʇɹoɟ pǝɹpunɥ ǝǝɹɥʇ ‘puɐsnoɥʇ ǝʌꞁǝʍʇ</pre>
 
=={{header|Wren}}==
Wren's standard print statement, ''System.print'' (or ''System.write'' without a terminating new line), has no formatting capabilities whatsoever though it does support string interpolation.
 
When doing RC tasks, I often use methods in my own ''Wren-fmt'' module which does most of what C's ''printf'' statement does and other things besides. Although I could add anything I like to that, it's already more than 800 lines long and so I don't think it would be appropriate to patch it for the purposes of this task.
 
What I've done instead is to create a special class called ''Sgr'' (Select graphic rendition) which adds special effects when printing text to terminals which support ANSI escape sequences. For demonstration purposes, I've just added methods which color (''Sgr.c'') or underline (''Sgr.u'') a given piece of text (and then restore the default attributes) though several other effects could be added as well. ''System.print'' can then interpolate these method calls.
 
Although it would be possible to abbreviate the color arguments passed to ''Sgr.c'', I haven't done so because I didn't think it would be very user friendly.
<lang ecmascript>class Sgr {
// capitalize the initial letter for bright colors
static init_() {
__cm = { "black": 30, "red" : 31, "green": 32, "yellow": 33,
"blue" : 34, "magenta": 35, "cyan" : 36, "white" : 37,
"Black": 90, "Red" : 91, "Green": 92, "Yellow": 93,
"Blue" : 94, "Magenta": 95, "Cyan" : 96, "White" : 97,
"gray" : 90, "Gray" : 90
}
}
 
static c(fore, back, text) {
if (!__cm) init_()
var fcn = __cm[fore]
if (!fcn) Fiber.abort("Invalid foreground color.")
var bcn = __cm[back]
if (!bcn) Fiber.abort("Invalid background color.")
if (!(text is String)) text = text.toString
var reset = "\e[39;49m"
return "\e[%(fcn);%(bcn+10)m%(text)%(reset)"
}
 
static u(text) { "\e[4m%(text)\e[24m" }
}
 
System.print("%(Sgr.c("red", "green", "This")) is %(Sgr.u("just")) a %(Sgr.c("yellow", "blue", "test")).")</lang>
9,486

edits