SyntaxKit makes TextMate-style syntax highlighting easy. It works on iOS, watchOS, and OS X.
SyntaxKit was originally abstracted from Whiskey.
SyntaxKit is written in Swift 5 so Xcode 10 is required. There aren't any dependencies besides system frameworks.
Carthage is the recommended way to install SyntaxKit. Add the following to your Cartfile:
github"soffes/SyntaxKit"You can also install with CocoaPods:
pod'SyntaxKit'For manual installation, I recommend adding the project as a subproject to your project or workspace and adding the appropriate framework as a target dependency.
SyntaxKit uses tmLanguage and tmTheme files to highlight source code. None are provided with SyntaxKit. Thankfully, there are tons available at TextMate's GitHub org.
Once you have a BundleManager, you can get started:
import SyntaxKit
letmanager=BundleManager(){ identifier, kind inURL(string:"Location of Bundles/"+ identifier +".plist")}letyaml= manager.language(withIdentifier:"source.yaml")!
letparser=Parser(language: yaml)Parser is a class that calls a block when it finds something the language file knows about. Let's print all of the elements in this string:
letinput="title: \"Hello World\"\n"
parser.parse(input){ scope, range inprint("\(scope) - \(range)")}scope is the name of an element. This is something like "string" or "constant.numeric". range is an NSRange struct representing where the scope falls in the input string.
SyntaxKit also comes with AttributedParser. This is a simple subclass of Parser that knows how to work with themes.
lettomorrow= manager.theme(withIdentifier:"tomorrow")!
letattributedParser=AttributedParser(language: yaml, theme: tomorrow)
attributedParser.parse(input){ scope, range, attributes inprint("\(scope) - \(range) - \(attributes)")}Notice that attributes is the third parameter to the block now. This is a dictionary of attributes you can give to NSAttributedString.
AttributedParser includes a convenience method for turning a String of source code into an NSAttributedString:
letattributedString= attributedParser.attributedString(for: input)Easy as that. This method takes an optional baseAttributes parameter to customize how the string is created. This is great if you want to specify a font, etc.
There is also a AttributedParsingOperation subclass of NSOperation that facilitates multithreaded parsing.
If you want to build your own parser (for example, to generate HTML) you can subclass whichever one meets your needs. Go wild.
Enjoy.