splash/Sources/Splash/Output/AttributedStringOutputFormat.swift

68 lines
1.8 KiB
Swift
Raw Permalink Normal View History

2018-08-24 18:42:07 +02:00
/**
* Splash
* Copyright (c) John Sundell 2018
* MIT license - see LICENSE.md
*/
#if !os(Linux)
import Foundation
2018-08-24 18:42:07 +02:00
/// Output format to use to generate an NSAttributedString from the
/// highlighted code. A `Theme` is used to determine what fonts and
/// colors to use for the various tokens.
public struct AttributedStringOutputFormat: OutputFormat {
public var theme: Theme
2018-08-25 22:11:20 +03:00
2018-08-24 18:42:07 +02:00
public init(theme: Theme) {
self.theme = theme
}
2018-08-25 23:36:19 +03:00
2018-08-24 18:42:07 +02:00
public func makeBuilder() -> Builder {
return Builder(theme: theme)
}
}
public extension AttributedStringOutputFormat {
struct Builder: OutputBuilder {
private let theme: Theme
private lazy var font = theme.font.load()
2018-08-24 18:42:07 +02:00
private var string = NSMutableAttributedString()
2018-08-25 23:36:19 +03:00
2018-08-24 18:42:07 +02:00
fileprivate init(theme: Theme) {
self.theme = theme
}
2018-08-25 23:36:19 +03:00
2018-08-24 18:42:07 +02:00
public mutating func addToken(_ token: String, ofType type: TokenType) {
let color = theme.tokenColors[type] ?? Color(red: 1, green: 1, blue: 1)
string.append(token, font: font, color: color)
}
2018-08-25 23:36:19 +03:00
2018-08-24 18:42:07 +02:00
public mutating func addPlainText(_ text: String) {
string.append(text, font: font, color: theme.plainTextColor)
}
2018-08-25 23:36:19 +03:00
2018-08-24 18:42:07 +02:00
public mutating func addWhitespace(_ whitespace: String) {
let color = Color(red: 1, green: 1, blue: 1)
string.append(whitespace, font: font, color: color)
}
2018-08-25 23:36:19 +03:00
2018-08-24 18:42:07 +02:00
public func build() -> NSAttributedString {
return NSAttributedString(attributedString: string)
}
}
}
private extension NSMutableAttributedString {
func append(_ string: String, font: Font.Loaded, color: Color) {
let attributedString = NSAttributedString(string: string, attributes: [
.foregroundColor: color,
.font: font
])
append(attributedString)
}
}
2018-08-24 18:42:07 +02:00
#endif