Terminal string styling for Swift.

Overview

ColorizeSwift

Swift License

Terminal string styling for Swift.

Integration

Swift Package Manager (SPM)

You can use The Swift Package Manager to install ColorizeSwift by adding it to your Package.swift file:

// swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "MyLibrary",
    products: [
        .library(name: "MyLibrary", targets: ["MyLibrary"]),
    ],
    dependencies: [
         .package(url: "https://github.com/mtynior/ColorizeSwift.git", from: "1.5.0"),
    ],
    targets: [
        .target(name: "MyLibrary", dependencies: ["ColorizeSwift"]),
        .testTarget(name: "MyLibraryTests", dependencies: ["MyLibrary", "ColorizeSwift"]),
    ]
)

Manually

You can also manually add ColorizeSwift to you project:

  1. Download ColorizeSwift.swift file,
  2. Drag ColorizeSwift.swift into you project's tree.

CocoaPods

From version 1.5 ColorizeSwift does not support CocoaPods!

Please use SPM or add ColorizeSwift.swift file manually to your project. If you use CocoaPods, you can still use version 1.2. At the moment, latest version1.5, only removed support for CocoaPods and has the same functionality as 1.2, but it might change in the future.

You can use CocoaPods to install ColorizeSwift by adding it to your Podfile:

platform :ios, '9.0'
use_frameworks!

target 'MyApp' do
	pod 'ColorizeSwift'
end

Run pods install to intagrate pods with your project.

Example

You can run sample application:

  1. Open Terminal and go to Example folder.
  2. Run ./build.sh script to build sample application.
  3. Run ./example pacman to launch sample.

Available samples:

  1. styles - prints available styles

    Example - Styles

  2. f1 - prints F1 cars

    Example - F1

  3. pacman - prints Pacman

    Example - Pacman

  4. mario - prints mario

    Example - Mario

Usage

print("Normal")
print("Bold".bold())
print("Dim".dim())
print("Italic".italic())
print("Underline".underline())
print("Blink".blink())
print("Reverse".reverse())
print("hidden".hidden())
print("strikethrough".strikethrough())
print("Red".red())
print("On yellow".onYellow())
print("256 foreground".foregroundColor(.orange1))
print("226 background".backgroundColor(.orange1))
print("Awful combination".colorize(.yellow, background: .red))
    
let nested = "with a blue substring".blue().underline()
print("A bold, green line \(nested) that becomes bold and green again".green().bold())

Styles

Modifiers

  • bold()
  • dim()
  • italic() (not widely supported)
  • underline()
  • reverse()
  • hidden()
  • strikethrough() (not widely supported)
  • reset()

Foreground colors

  • black()
  • red()
  • green()
  • yellow()
  • blue()
  • magenta()
  • cyan()
  • lightGray()
  • darkGray()
  • lightRed()
  • lightGreen()
  • lightYellow()
  • lightBlue()
  • lightMagenta()
  • lightCyan()
  • white()

Background colors

  • onBlack()
  • onRed()
  • onGreen()
  • onYellow()
  • onBlue()
  • onMagenta()
  • onCyan()
  • onLightGray()
  • onDarkGray()
  • onLightRed()
  • onLightGreen()
  • onLightYellow()
  • onLightBlue()
  • onLightMagenta()
  • onLightCyan()
  • onWhite()

256-colors

You can also use 256 colors, but keep in mind that not all Terminal clients support them.

  • foregroundColor(color: TerminalColor)
  • backgroundColor(color: TerminalColor)
  • colorize(foreground: TerminalColor, background: TerminalColor)

Available colors

You can access 256 colors using TerminalColor enumeration.

256 Colors

Escape codes

Sometimes you only need the open code for a modifier. You can access them using TerminalStyle enum:

TerminalStyle.bold.open // "\u{001B}[1m"
TerminalStyle.bold.close  // "\u{001B}[22m"

For 256 colors use:

TerminalColor.red.foregroundStyleCode().open //"\u{001B}[38;5;9m"
TerminalColor.red.backgroundStyleCode().open //"\u{001B}[48;5;9m"

Uncolorize

To get string without any colorization use uncolorized() method:

let styledString = "Awful combination".colorize(.yellow, background: .red) // \u{001B}[48;5;9m\u{001B}[38;5;11mAwful combination\u{001B}[0m\u{001B}[48;5;9m\u{001B}[0m
let withoutStyles = styledString.uncolorized() // "Awful combination"

Disabling colorization

Colorization can be disabled globally:

String.isColorizationEnabled = false // Default: true

You can use this to support a command line option (./example --no-color):

String.isColorizationEnabled = !CommandLine.arguments.contains("--no-color")

To disable colorization when program is running in a pipe (./example | wc) or when not writing to stdout (./example > output.txt):

String.isColorizationEnabled = (isatty(fileno(stdout)) == 1)

Credits

License

ColorizeSwift is released under the MIT license. See LICENSE for details.

You might also like...
 SwiftShell - A Swift framework for shell scripting.
SwiftShell - A Swift framework for shell scripting.

Run shell commands | Parse command line arguments | Handle files and directories Swift 5.1 - 5.3 | Swift 4 | Swift 3 | Swift 2 SwiftShell A library fo

SwiftyTextTable - A lightweight Swift library for generating text tables
SwiftyTextTable - A lightweight Swift library for generating text tables

SwiftyTextTable A lightweight Swift library for generating text tables. Swift Language Support SwiftyTextTable is now Swift 4.0 compatible! The last r

Shell scripting in Swift

Shwift Shell-scripting in Swift DISCLAIMER: Shwift depends on Swift's incoming concurrency features. As such, it requires a recent Swift toolchain, an

Swift utilities for running commands.

Swift Commands Swift utilities for running commands. The Commands module allows you to take a system command as a string and return the standard outpu

A CLI too powered by Swift to provision environments using an up.toml manifest file

tuist-up tuist up was originally a Tuist built-in command to provision environments by reading the requirements in a manifest file Setup.swift. Althou

Simple & Elegant Command Line Interfaces in Swift
Simple & Elegant Command Line Interfaces in Swift

An elegant pure Swift library for building command line applications. Features Tons of class, but no classes. 100% organic pure value types. Auto gene

A starting point to create CLI utilities with swift

cli tuist template A starting point to create CLI utilities with swift Installation Just create a Tuist folder and a Templates folder inside it. Creat

A Tuist Template to quickly create CLI apps in Swift

macOS CLI Template Motivation I'm writing more and more Swift CLI apps these days. And as I solve more problems with this litte tools, I find that I'm

A cli program written in swift (with async/await) that removes the unnecessary parts of xcframeworks.

xctrim A cli program written in swift (with async/await) that removes the unnecessary parts of xcframeworks. Usecase Say you downloaded firebase sdk a

Comments
  • Update to v4 of package format

    Update to v4 of package format

    When adding this to my Package.swift manifest, using swift-tools-version:4.2, when I update, I get the following warning:

    warning: PackageDescription API v3 is deprecated and will be removed in the future; used by package(s): ColorizeSwift
    

    The documentation for how to add this as a package also appears to use v3 format.

    Can this all be updated to v4 please?

    opened by KatherineBertelsen 9
  • Add function to get length of string without terminal codes

    Add function to get length of string without terminal codes

    I have been noodling around with a side project using this framework. I really like it!

    One thing I have been doing is composing strings across different functions, and certain points I would like to know the length of the string, but without color formatting options.

    I put together this janky bit of code to help with that, not sure if it's something you'd like to incorporate into your framework or not.

    extension NSRegularExpression {
        convenience init(_ pattern: String) {
            do {
                try self.init(pattern: pattern, options: [.caseInsensitive, .allowCommentsAndWhitespace])
            } catch {
                preconditionFailure("Illegal regular expression: \(pattern).")
            }
        }
    }
    
    extension String {
        private static let regexPattern = """
        \u{001B}
        \\[
        [0-9]{1,3}
        m
        """
        private static let regex = NSRegularExpression(regexPattern)
        var colorlessCount: Int {
            get {
                let range = NSRange(location: 0, length: self.utf16.count)
                let out = String.regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: "")
                return out.count
            }
        }
    }
    
    opened by atommclain 2
  • SwiftPM can't resolve dependency graph

    SwiftPM can't resolve dependency graph

    Hi there, wanted to intergrate the package via spm but encountered this issue:

    The package dependency graph can not be resolved; unable find any available tag for the following requirements:

    https://github.com/mtynior/ColorizeSwift — 1.2.0..<2.0.0

    Any ideas how to resolve it? Thanks in advance.

    opened by ValiHar 2
  • Add Package@swift-4.swift

    Add [email protected]

    Adds support for the swift package manager v4 format.

    Swift 3.x should still work w/ Package.swift while 4.x users should now be supported w/ [email protected].

    Closes #3

    opened by noahbass 0
Owner
Michał Tynior
My name is Michal Tynior and I am a software engineer, iOS developer, consultant, and trouble maker in general.
Michał Tynior
Util for executing shell commands, and getting the results easily(data, string, and any decodable).

ShellExecutor Util for executing shell commands, and getting the results easily(data, string, and any decodable). Requirements Xcode 14.0+ Swift 5.7+

Yozone Wang 2 Jul 30, 2022
Linenoise-Swift A pure Swift implementation of the Linenoise library. A minimal, zero-config readline replacement.

Linenoise-Swift A pure Swift implementation of the Linenoise library. A minimal, zero-config readline replacement. Supports Mac OS and Linux Line edit

Andy Best 114 Dec 14, 2022
Swift tool to generate Module Interfaces for Swift projects.

ModuleInterface Swift tool to generate Module Interfaces for Swift projects. What is a Module Interface A Module Interface is what we commonly get usi

Jorge Revuelta 75 Dec 21, 2022
Swift-cli - Example of building command-line tools in Swift

swift-cli Example of building command-line tools in Swift Step 1: Create CLI wit

Noah Gift 2 Jan 17, 2022
Compose beautiful command line interfaces in Swift

Commander is a small Swift framework allowing you to craft beautiful command line interfaces in a composable way. Usage Simple Hello World i

Kyle Fuller 1.5k Dec 29, 2022
CommandLineKit - A pure Swift library for creating command-line interfaces

CommandLineKit A pure Swift library for creating command-line interfaces. Note: This project is no longer maintained. It's preserved here for historic

Ben Gollmer 1.1k Dec 1, 2022
Guaka - Smart and beautiful POSIX compliant CLI framework for Swift.

Guaka - Smart and beautiful POSIX compliant CLI framework for Swift. It helps you create modern and familiar CLI apps in the vein of widely used proje

Omar Abdelhafith 1.1k Dec 24, 2022
Progress.swift ⌛ Add beautiful progress bars to your loops.

Progress.swift ⌛ Just wrap the SequenceType in your loop with the Progress SequenceType and you'll automatically get beautiful progress bars. Updating

Justus Kandzi 304 Dec 1, 2022
Straightforward, type-safe argument parsing for Swift

Swift Argument Parser Usage Begin by declaring a type that defines the information that you need to collect from the command line. Decorate each store

Apple 2.9k Jan 7, 2023
SwiftCLI - A powerful framework for developing CLIs in Swift

SwiftCLI A powerful framework for developing CLIs, from the simplest to the most complex, in Swift.

Jake Heiser 793 Jan 4, 2023