Last active
April 24, 2016 14:21
-
-
Save kanetai/d57189e7f13f49158ee8c7f9056ce69c to your computer and use it in GitHub Desktop.
[Swift]text coloring by escape code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/swift | |
import Foundation | |
public enum ESCCode : UInt { | |
case Reset = 0, Bold = 1, Faint, UnderLine = 4, BlinkSlow, Negative = 7 | |
case Black = 30, Red, Green, Yellow, Blue, Magenda, Cyan, White | |
case BackgroundBlack = 40, BackgroundRed, BackgroundGreen, BackgroundYellow, BackgroundBlue, BackgroundMagenda, BackgroundCyan, BackgroundWhite | |
static let backGroundColorOffset: UInt = 10 | |
static func escapeCode(value: UInt) -> String { return "\u{1b}[\(value)m" } | |
var escString: String { return self.dynamicType.escapeCode(self.rawValue) } | |
} | |
extension String { | |
func escape(esc: ESCCode, reset: Bool = true) -> String { | |
return "\(esc.escString)\(self)\(reset ? ESCCode.Reset.escString : "")" | |
} | |
} | |
public func printError(message: String, exit shouldTerminate: Bool = false, terminator: String = "\n") { | |
if let data = "\(message.escape(.Red))\(terminator)".dataUsingEncoding(NSUTF8StringEncoding) { | |
NSFileHandle.fileHandleWithStandardError().writeData(data) | |
} | |
if shouldTerminate { exit(1) } | |
} | |
let str: String = "abcABC" | |
for i: UInt in ESCCode.Bold.rawValue..<ESCCode.Negative.rawValue+1 { | |
if let esc = ESCCode(rawValue: i) { | |
print("\\x1b[\(esc.rawValue)m \(str.escape(esc))") | |
} | |
} | |
print("") | |
print(" | \\x1b[3*m | \\x1b[4*m |") | |
print("___ | ________ | ________ |") | |
for i: UInt in ESCCode.Black.rawValue ..< ESCCode.White.rawValue+1 { | |
if let color = ESCCode(rawValue: i), bcolor = ESCCode(rawValue: i+ESCCode.backGroundColorOffset) { | |
print("*=\(i-ESCCode.Black.rawValue) | \(str.escape(color)) | \(str.escape(bcolor)) | "); | |
} | |
} | |
print("") | |
printError("警告") | |
printError("warning", exit: true) | |
print("unreachable") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment