1 /// Tools for manipulating the console 2 module mecca.lib.console; 3 4 // Licensed under the Boost license. Full copyright information in the AUTHORS file 5 6 /** 7 * Encode an ANSI console sequence. 8 */ 9 struct ANSI { 10 private: 11 string code; 12 13 public: 14 /// Constructor for specific code 15 this(string code) pure nothrow @nogc { 16 assert(code.length > 0); 17 this.code = code; 18 } 19 20 /// Concatanate another code to the existing one 21 ANSI opBinary(string op)(ANSI rhs) const if (op == "|" || op == "+" || op == "~"){ 22 return ANSI(code ~ ";" ~ rhs.code); 23 } 24 25 /// Get the encoded ANSI sequence, including escapes 26 string opCall(string text) const { 27 return "\x1b[" ~ code ~ "m" ~ text ~ "\x1b[0m"; 28 } 29 30 /// Predefined ANSI sequences 31 enum reset = ANSI("0"); 32 enum inverse = ANSI("7"); /// ditto 33 alias negative = inverse; /// ditto 34 enum crossed = ANSI("9"); /// ditto 35 enum bold = ANSI("1"); /// ditto 36 alias intense = bold; /// ditto 37 } 38 39 /// Predefined foreground colors 40 struct FG { 41 enum black = ANSI("30"); /// Foreground color 42 enum red = ANSI("31"); /// ditto 43 enum green = ANSI("32"); /// ditto 44 enum yellow = ANSI("33"); /// ditto 45 enum blue = ANSI("34"); /// ditto 46 enum magenta = ANSI("35"); /// ditto 47 enum cyan = ANSI("36"); /// ditto 48 enum white = ANSI("37"); /// ditto 49 enum default_ = ANSI("39"); /// ditto 50 51 enum iblack = ANSI.intense | black; /// ditto 52 enum ired = ANSI.intense | red; /// ditto 53 enum igreen = ANSI.intense | green; /// ditto 54 enum iyellow = ANSI.intense | yellow; /// ditto 55 enum iblue = ANSI.intense | blue; /// ditto 56 enum imagenta = ANSI.intense | magenta; /// ditto 57 enum icyan = ANSI.intense | cyan; /// ditto 58 enum iwhite = ANSI.intense | white; /// ditto 59 60 alias grey = iblack; /// ditto 61 alias purple = imagenta; /// ditto 62 } 63 64 /// Predefined foreground colors 65 struct BG { 66 enum black = ANSI("40"); /// Background color 67 enum red = ANSI("41"); /// ditto 68 enum green = ANSI("42"); /// ditto 69 enum yellow = ANSI("43"); /// ditto 70 enum blue = ANSI("44"); /// ditto 71 enum magenta = ANSI("45"); /// ditto 72 enum cyan = ANSI("46"); /// ditto 73 enum white = ANSI("47"); /// ditto 74 enum default_ = ANSI("49"); /// ditto 75 } 76 77 78 unittest { 79 assert ("hello " ~ (FG.grey | BG.white)("moshe") ~ " of suburbia" == "hello \x1b[1;30;47mmoshe\x1b[0m of suburbia"); 80 }