LoginSignup
14
13

More than 5 years have passed since last update.

SwiftでESCを使う(コマンドライン出力に色をつける)

Last updated at Posted at 2015-11-21

C言語だとESC(27 = \x1b = \033)を使って"\x1b[31mあああ"としてやれば、コマンドライン出力に色をつけたりできるけど、swiftでは違うみたいなので調べた。

swiftだと"\u{nn}"で1バイトのユニコードスカラ値を表現するので、"\u{1b}[31mあああ"となる.

ちなみに他の言語だと"\e"がESCとして使えるのが結構ある

ANSI escape code

➜  ~  swift --version
Apple Swift version 2.2 (swiftlang-703.0.18.1 clang-703.0.29)
Target: x86_64-apple-macosx10.9

gist:colorTest

colorTest.swift
#!/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")

スクリーンショット 2015-11-22 5.54.45.png

14
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
13