scoop:scoop.terminal:0.1.0
src/style/styled_content.scoop
Selected production source · src/style/styled_content.scoop
1
package scoop.terminal.style3
import scoop.terminal.Command4
import scoop.terminal.toAnsiString6
/**7
* Applies the selected style without printing content or automatically restoring it.8
*/9
public struct SetStyle(val style: ContentStyle) : Command {10
/**11
* Writes this command's ANSI representation to the supplied writer without flushing it.12
* Parameter validation happens before or during serialization.13
*/14
public override fun writeAnsi(writer: TextWriter) { writer.write(styleSequence(style, isColorOutputEnabled())) }15
}17
internal fun styleSequence(style: ContentStyle, colors: Boolean): String {18
val background = when (style.backgroundColor) {19
case Some(val color) -> Colored.BackgroundColor(color).toAnsiString()20
case None -> ""21
}22
val foreground = when (style.foregroundColor) {23
case Some(val color) -> Colored.ForegroundColor(color).toAnsiString()24
case None -> ""25
}26
val underline = when (style.underlineColor) {27
case Some(val color) -> Colored.UnderlineColor(color).toAnsiString()28
case None -> ""29
}30
val writer = StringWriter()31
if (colors) {32
if (background != "") writer.write("\u001b[" + background + "m")33
if (foreground != "") writer.write("\u001b[" + foreground + "m")34
if (underline != "") writer.write("\u001b[" + underline + "m")35
}36
SetAttributes(style.attributes).writeAnsi(writer)37
return writer.toString()38
}40
/**41
* Serializes style, content, and the corresponding reset commands. It restores terminal defaults42
* for changed channels rather than saving and restoring an arbitrary prior style.43
*/44
public struct StyledContent<T : ToString>(val style: ContentStyle, val content: T) : Command, ToString {45
/**46
* Writes this command's ANSI representation to the supplied writer without flushing it.47
* Parameter validation happens before or during serialization.48
*/49
public override fun writeAnsi(writer: TextWriter) {50
val text = content.toString()51
val colors = isColorOutputEnabled()52
writer.write(styleSequence(style, colors))53
writer.write(text)54
if (!style.attributes.isEmpty) {55
ResetColor.writeAnsi(writer)56
} else if (colors) {57
if (style.backgroundColor != None) writer.write("\u001b[49m")58
if (style.foregroundColor != None) writer.write("\u001b[39m")59
if (style.underlineColor != None) writer.write("\u001b[59m")60
}61
}63
/**64
* Returns the complete ANSI-styled content string using the current color policy.65
*/66
public override fun toString(): String = toAnsiString()67
}