iOS & OSX Syntax Highlighter.

Overview

Highlightr

Version Carthage Compatible CocoaPods License Platform

Highlightr is an iOS & macOS syntax highlighter built with Swift. It uses highlight.js as it core, supports 185 languages and comes with 89 styles.

Takes your lame string with code and returns a NSAttributtedString with proper syntax highlighting.

Sample Gif A Sample Gif B

Installation

Requirements

  • iOS 8.0+
  • macOS 10.10+

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:

$ gem install cocoapods

To integrate Highlightr into your Xcode project using CocoaPods, specify it in your Podfile:

source 'https://github.com/CocoaPods/Specs.git'
use_frameworks!

target '<Your Target Name>' do
    pod 'Highlightr'
end

Then, run the following command:

$ pod install

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate Highlightr into your Xcode project using Carthage, specify it in your Cartfile:

github "raspu/Highlightr"

Run carthage update to build the framework and drag the built Highlightr.framework into your Xcode project.Highlightr

Usage

Highlightr provides two main classes:

Highlightr

This is the main endpoint, you can use it to convert code strings into NSAttributed strings.

	let highlightr = Highlightr()
	highlightr.setTheme(to: "paraiso-dark")
	let code = "let a = 1"
	// You can omit the second parameter to use automatic language detection.
	let highlightedCode = highlightr.highlight(code, as: "swift") 
	

CodeAttributedString

A subclass of NSTextStorage, you can use it to highlight text on real time.

	let textStorage = CodeAttributedString()
	textStorage.language = "Swift"
	let layoutManager = NSLayoutManager()
	textStorage.addLayoutManager(layoutManager)

	let textContainer = NSTextContainer(size: view.bounds.size)
	layoutManager.addTextContainer(textContainer)

	let textView = UITextView(frame: yourFrame, textContainer: textContainer)

JavaScript?

Yes, Highlightr relies on iOS & macOS JavaScriptCore to parse the code using highlight.js. This is actually quite fast!

Performance

It will never be as fast as a native solution, but it's fast enough to be used on a real time editor.

It comes with a custom made HTML parser for creating NSAttributtedStrings, is pre-processing the themes and is preloading the JS libraries. As result it's taking around of 50 ms on my iPhone 6s for processing 500 lines of code.

Documentation

You can find the documentation for the latest release on cocoadocs.

License

Highlightr is available under the MIT license. See the LICENSE file for more info.

Highlight.js is available under the BSD license. You can find the license file here.

Comments
  • Support language auto-detection

    Support language auto-detection

    This pull request contains following improvements:

    • Fixed error #6
    • Uses languageAuto function in highlight.js to auto detect the programming languages. (This is useful if you can't determine the programming language via the file extension, eg: ".h")
    opened by Hengyu 7
  • Add support for Swift 4.2, dependency injection, and highlight.js' ignoreIllegals option

    Add support for Swift 4.2, dependency injection, and highlight.js' ignoreIllegals option

    Dependency injection allows one to use a custom highlight.min.js file instead of the one provided (eg. to add a custom language). Since the init parameters all have default values, this shouldn't be source-breaking.

    opened by kabiroberai 6
  • How to install Highlightr without issues?

    How to install Highlightr without issues?

    Hey, I installed 'Highlightr' the following way:

    cd "My_App"
    pod init
    Edited Podfile:
    source 'https://github.com/CocoaPods/Specs.git'
    use_frameworks!
    # Uncomment the next line to define a global platform for your project
    # platform :ios, '9.0'
    

    target 'My_Target' do pod 'Quick' pod 'Nimble' pod 'Highlightr' end

    I only want to use Highlightr for OSX.
    pod install
    Successful install is said in terminal. Open my_app.xworkspace... Building.... Build failed due to 23 issues, all related to Highlightr, f.ex. the first one saying "Swift Compiler Error" "[...]/Highlightr/Pod/Classes/CodeAttributedString.swift:93:24: Method does not override any method from its superclass"

    It's probably my mistake, but I don't know what to do. Could you help me out? Couldn't find any install instruction on the internet.

    Thanks in advance!

    opened by welljsjs 6
  • Theme not settings

    Theme not settings

    For some reason the theme isn't setting. It's probably really easy but i can't figure it out

    heres my code

    let layoutManager = NSLayoutManager()
            textStorage.addLayoutManager(layoutManager)
            
            let textContainer = NSTextContainer(size: view.bounds.size)
            layoutManager.addTextContainer(textContainer)
            
    //        highlightr = textStorage.highlightr
            
            self.textStorage.highlightr.setTheme(to: "hopscotch")
            
            textView = UITextView(frame: viewPlaceholder.bounds, textContainer: textContainer)
            textView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
            textView.autocorrectionType = UITextAutocorrectionType.no
            textView.autocapitalizationType = UITextAutocapitalizationType.none
    //        textView.textColor = UIColor(white: 0.8, alpha: 1.0)
    //        textView.inputAccessoryView = textToolbar
            viewPlaceholder.addSubview(textView)
            
            let code = try! String.init(contentsOfFile: Bundle.main.path(forResource: "index", ofType: "html")!)
            textView.text = code
    
    opened by JosephShenton 5
  • Swift 4 and Xcode 9 Compatible?

    Swift 4 and Xcode 9 Compatible?

    I am having a problem getting this to work with Swift 4 in Xcode 9. Can anyone confirm that has yet to be updated to support compilation for those versions?

    This seems like a great idea!

    Thanks.

    opened by GrfxGuru 5
  • Update for Swift 3 and xCode 8

    Update for Swift 3 and xCode 8

    This update changes the API a little bit, which I mentioned in CHANGELOG.md. Because this isn't backwards compatible I bumped the version of the podspec to 1.0.0.

    The pod lint passes without warnings, and the examples appear to work well. Let me know what you think, or if you'd like me to make any changes.

    Thanks!

    opened by rudedogg 5
  • Create a custom theme

    Create a custom theme

    Hi Raspu, Thank you for your amazing work. I have a question: is it possible to create a custom theme? Or in another way, is it possible to change the font and the color of the text? Because I have read something about it on other issues but I haven't understood it very well Thank you for your patience

    question 
    opened by ghost 4
  • Highlightr in a collection view

    Highlightr in a collection view

    How would u put highlightr in a collection view? my idea is that you can give a live preview of a document however due to the collectionview having to dequeue cells the entire code highlighting is re rendered and takes up way too much system resources. Is there a more efficient way to do this? Also, isit possible to take a snapshot of the view of the highlighted code, for now the snapshot captures the text only and not the code.

    question 
    opened by qin-guan 4
  • Does not work with Xcode 11

    Does not work with Xcode 11

    Some of the code is incompatible with swift 4.2 Happy to help with some direction, I've never worked in this codebase though. Is anyone working on this?

    opened by catilac 3
  • chathage install failed

    chathage install failed

    Build Failed
    	Task failed with exit code 65:
    	/usr/bin/xcrun xcodebuild -project /Users/zly/Project/test/BearCapture/Carthage/Checkouts/Highlightr/Highlightr.xcodeproj -scheme Highlightr-iOS -configuration Release -derivedDataPath /Users/zly/Library/Caches/org.carthage.CarthageKit/DerivedData/10.2.1_10E1001/Highlightr/2.1.0 -sdk iphoneos ONLY_ACTIVE_ARCH=NO CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES archive -archivePath /var/folders/sk/8_qnvmt550d0sr14czhv4k4h0000gp/T/Highlightr SKIP_INSTALL=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=NO CLANG_ENABLE_CODE_COVERAGE=NO STRIP_INSTALLED_PRODUCT=NO (launched in /Users/zly/Project/test/BearCapture/Carthage/Checkouts/Highlightr)
    
    This usually indicates that project itself failed to compile. Please check the xcodebuild log for more details: /var/folders/sk/8_qnvmt550d0sr14czhv4k4h0000gp/T/carthage-xcodebuild.nLipft.log
    
    opened by zlyBear 3
  • RTL Writing direction doesn't work

    RTL Writing direction doesn't work

    I'm using macOS. I've noticed that when setting the writing direction in a NSTextView by right-clicking, and choosing Writing Direction > Right to Left, whenever the text changes the direction gets un-set, but when all text is removed, the cursor correctly appears on the right hand side of the text view.

    I had a dig in to the code and believe this is happening in the highlight(_ range: NSRange) method of the CodeAttributedString class. I'm not sure exactly what is causing it, but think it has to do with the ranges being updated.

    For example

    If highlight() is called with the range {0, 1}, this represents a location of 0 and length of 1. The problem is that if the writing direction is Right to Left, and a single character is typed, then the range would be the exact same {0, 1}, since it's in location 0 and length 1, but this time from the right hand side of the text view.

    As a result, whatever is typed in the Right to Left direction gets updated correctly, but gets put in the left hand side of the text view as if the direction is Left to Right.

    I think fixing this may be fairly easy, as it should just require getting the writing direction and setting again somewhere, but it may not be trivial if some calculations need to be done around the range.

    Below is a simple demo

    highlightr

    opened by lukakerr 2
  • Build error in HTMLUtils.swift

    Build error in HTMLUtils.swift

    I'm trying to build my app with the latest Xcode 12.5 beta 3 and I'm getting a build error due to this code in HTMLUtils.swift

     class func decodeNumeric(_ string : String, base : Int32) -> Character? {
            let code = UInt32(strtoul(string, nil, base))
            return Character(UnicodeScalar(code)!)
        }
    

    I believe it's from the stroul() call.

    The error is:

    Undefined symbols for architecture arm64:
      "Swift._ArrayBuffer._copyContents(initializing: Swift.UnsafeMutableBufferPointer<A>) -> (Swift.IndexingIterator<Swift._ArrayBuffer<A>>, Swift.Int)", referenced from:
          generic specialization <serialized, Swift._ArrayBuffer<Swift.Int8>> of Swift._copyCollectionToContiguousArray<A where A: Swift.Collection>(A) 
    -> Swift.ContiguousArray<A.Element> in HTMLUtils.o
    ld: symbol(s) not found for architecture arm64
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    

    Does anyone have a solution for this or know a workaround?

    opened by brendand 3
  • Optional support for deployment targets: iOS 13 & OSX 10.15

    Optional support for deployment targets: iOS 13 & OSX 10.15

    I was updating my iOS app to have a minimum deployment target of iOS 13 and noticed that this library used a couple of deprecated APIs. I wanted to be able to pitch in and help modernize the code while still providing backward compatibility to existing users. In doing so, I left the majority of the code in place while simply wrapping the old/new API uses in #available checks. Let me know if you'd like me to make any changes to my approach (refactoring out to helpers, etc.). Thanks!

    I did verify these changes locally in the iOS app I'm working on. Please let me know if there are any other verifications that you'd like to see. I'll attach a screenshot showing that the rendering doesn't change between iOS 12 and iOS 13.

    Screen Shot 2020-12-15 at 9 53 23 AM Screen Shot 2020-12-15 at 10 28 25 AM

    opened by brunnerjosh 1
  • How to make scrollable in macOS

    How to make scrollable in macOS

    Hi this library is cool.. but i got problem when i want to make NSTextview scrollable when the the text is over the height of textview. how to make it possible? I have done many experiments but it still hasn't worked

    thanks

    opened by fadielse 2
  • CodeAttributedString manual rehighlight

    CodeAttributedString manual rehighlight

    It would be nice if there would be a way to manually trigger a rehighlight from the auto-highlight feature (CodeAttributedString). Essentially, on top of the highlighting, I am using a yellow highlighter to display certain text (like a Find feature). However, the only way to remove this highlighting is when a user start typing, so that it re-highlights the text.

    If anyone knows a simple work around that would be great. Calling processEditing causes an error because no edits were actually made I tried to reset the theme (setting it to itself), but to no luck

    opened by matteobart 2
  • Enable APPLICATION_EXTENSION_API_ONLY

    Enable APPLICATION_EXTENSION_API_ONLY

    In order to allow us to use Highlightr in app extensions, the APPLICATION_EXTENSION_API_ONLY flag needs to be set to YES. There doesn't seem to be a technical reason to keep this flag set to NO.

    opened by simonboots 0
Releases(2.1.2)
Owner
J.P. Illanes
J.P. Illanes
Notepad - A fully themeable iOS markdown editor with live syntax highlighting.

Notepad is just like any other UITextView, but you need to use the convenience initializer in order to use the themes. To create a new theme, copy one of the existing themes and edit the JSON.

Rudd Fawcett 802 Dec 31, 2022
A beautiful rich text WYSIWYG editor for iOS with a syntax highlighted source view

ZSSRichTextEditor The Editor ZSSRichTextEditor is a beautiful Rich Text WYSIWYG Editor for iOS. It includes all of the standard editor tools one would

Nic Hubbard 3.7k Dec 31, 2022
TextMate-style syntax highlighting

SyntaxKit SyntaxKit makes TextMate-style syntax highlighting easy. It works on iOS, watchOS, and OS X. SyntaxKit was abstracted from Whiskey. Building

Sam Soffes 466 Sep 9, 2022
An NSPredicate DSL for iOS, OSX, tvOS, & watchOS. Inspired by SnapKit and lovingly written in Swift.

PrediKit A Swift NSPredicate DSL for iOS & OS X inspired by SnapKit, lovingly written in Swift, and created by that weird dude at KrakenDev. If you're

Hector Matos 542 Sep 24, 2022
Fully open source text editor for iOS written in Swift.

Edhita Fully open source text editor for iOS written in Swift. http://edhita.bornneet.com/ What Edhita means? Edhita (Romaji) == エディタ (Katakana) == Ed

Tatsuya Tobioka 1.2k Jan 1, 2023
A library for formatting strings on iOS and macOS

Sprinter Introduction What? Why? How? Usage Installation Integration Localization Thread Safety Advanced Usage Introduction What? Sprinter is a librar

Nick Lockwood 168 Feb 6, 2022
Texstyle allows you to format iOS attributed strings easily.

Texstyle allows you to format attributed strings easily. Features Applying attributes with strong typing and autocompletion Cache for attributes Subst

Rosberry 79 Sep 9, 2022
A standalone, flexible API that provides a full-featured rich text editor for iOS applications.

Twitter Text Editor A standalone, flexible API that provides a full featured rich text editor for iOS applications. This provides a robust text attrib

Twitter 2.8k Dec 29, 2022
Markdown parser for iOS

Marky Mark Marky Mark is a parser written in Swift that converts markdown into native views. The way it looks it highly customizable and the supported

M2mobi 254 Jun 11, 2021
An iOS app to turn typed text into images of handwritten text in your own handwriting style.

Text-to-Handwritting © 2021 by Daniel Christopher Long An iOS app to turn typed text into images of handwritten text in your own handwriting style. ht

Daniel Long 11 Dec 29, 2022
BNR World Trotter ios App

WorldTrotter Using the information from the BNR textbook, the World Trotter App was modified to add points of interest and adding a "Find Me" button u

George 0 Nov 27, 2021
The iOS framework that grows only as fast as its documentation

Nimbus is an iOS framework whose feature set grows only as fast as its documentation. Support status Nimbus is in a supported maintenance mode, meanin

featherless 6.5k Nov 30, 2022
A rich-text editor for iOS

DTRichTextEditor This project aims to provide a replacement for Apple's severely limited UITextView and to allow for editing attributed strings. It co

Cocoanetics 346 Oct 8, 2022
Powerful text framework for iOS to display and edit rich text.

YYText Powerful text framework for iOS to display and edit rich text. (It's a component of YYKit) Features UILabel and UITextView API compatible High

null 8.8k Jan 4, 2023
Rich Markdown editing control for iOS

MarkdownTextView Rich Markdown Editing for iOS MarkdownTextView is an iOS framework for adding rich Markdown editing capabilities. Support for Markdow

Indragie Karunaratne 676 Dec 7, 2022
SZMentionsSwift is a lightweight mentions library for iOS.

SZMentionsSwift is a lightweight mentions library for iOS. This library was built to assist with the adding, removing and editing of a mention within a textview.

Steven Zweier 122 Dec 12, 2022
String (and more) validation for iOS

Swift Validators ?? String validation for iOS. Contents Installation Walkthrough Usage Available validators License ReactiveSwift + SwiftValidators Wa

George Kaimakas 241 Nov 13, 2022
Markdown parsing and rendering for iOS and OS X

CocoaMarkdown Markdown parsing and rendering for iOS and macOS CocoaMarkdown is a cross-platform framework for parsing and rendering Markdown, built o

Indragie Karunaratne 1.2k Dec 12, 2022
Swift String Validator. Simple lib for ios to validate string and UITextFields text for some criterias

Swift String validator About Library for easy and fastest string validation based on сciterias. Instalation KKStringValidator is available through Coc

Kostya 17 Dec 21, 2019