fork download
  1. import std.conv;
  2. import std.stdio;
  3.  
  4. public struct Color
  5. {
  6. private enum Mode: bool
  7. {
  8. BASIC,
  9. EXTENDED
  10. }
  11.  
  12. private ubyte Data;
  13. private Mode DataMode;
  14.  
  15. public this(const double Red, const double Green, const double Blue)
  16. {
  17. // Pack RGB values into 8 bits for xterm-256color.
  18. Data += cast(ubyte)(Red * 5) * 36;
  19. Data += cast(ubyte)(Green * 5) * 6;
  20. Data += cast(ubyte)(Blue * 5);
  21.  
  22. Data += 16; // The first 16 values are for system colors.
  23.  
  24. DataMode = Mode.EXTENDED;
  25. }
  26.  
  27. // Module-protected. Allows for special basic color support.
  28. this(const ubyte Index)
  29. {
  30. Data = Index;
  31. DataMode = Mode.BASIC;
  32. }
  33.  
  34. /**
  35. * Returns an ANSI escape code to make any following text
  36. * the color represented by this object.
  37. **/
  38. @property string TextColorCode() const
  39. {
  40. // "ESC" would be replaced with the actual escape character.
  41. // "ESC" is used here to more easily see what's going on.
  42.  
  43. if (DataMode == Mode.BASIC)
  44. {
  45. return "ESC[" ~ to!string(30 + Data) ~ "m";
  46. }
  47.  
  48. else
  49. {
  50. return "ESC[38;5;" ~ to!string(Data) ~ "m";
  51. }
  52. }
  53. }
  54.  
  55. public
  56. {
  57. immutable Color BLACK = Color(cast(ubyte)0);
  58. immutable Color RED = Color(cast(ubyte)1);
  59. immutable Color GREEN = Color(cast(ubyte)2);
  60. immutable Color YELLOW = Color(cast(ubyte)3);
  61. immutable Color BLUE = Color(cast(ubyte)4);
  62. immutable Color MAGENTA = Color(cast(ubyte)5);
  63. immutable Color CYAN = Color(cast(ubyte)6);
  64. immutable Color WHITE = Color(cast(ubyte)7);
  65.  
  66. immutable Color DEFAULT = Color(cast(ubyte)9);
  67. }
  68.  
  69. public void Output(const string Text, const Color TextColor = DEFAULT)
  70. {
  71. write(TextColor.TextColorCode);
  72. write(Text);
  73. write("ESC[0m");
  74. }
  75.  
  76. void main()
  77. {
  78. Output("Hello, ");
  79. Output("world!\n", BLUE);
  80. Output("XTerm 256-color is supported.\n", Color(1.0, 1.0, 0.0));
  81. }
Success #stdin #stdout 0.01s 2068KB
stdin
Standard input is empty
stdout
ESC[39mHello, ESC[0mESC[34mworld!
ESC[0mESC[38;5;226mXTerm 256-color is supported.
ESC[0m