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.

Issues
  • 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
  • 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
  • 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
  • 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
  • How to build the framework without cocoapods

    How to build the framework without cocoapods

    I want to use just the framework but I cant build it. Is there a way to just build it without cocoapods?

    opened by p0fi 5
  • 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
  • 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
  • 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
  • CodeAttributedString with auto detection

    CodeAttributedString with auto detection

    Support language auto-detection (#7) is very good, but it cannot be used with CodeAttributedString.

    opened by tnantoka 4
  • 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
  • Better SwiftUI Support

    Better SwiftUI Support

    Is it possible to let Highlightr support SwiftUI better?

    opened by L1cardo 5
  • 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
  • Abandoned?

    Abandoned?

    Is this project abandoned? Have not seen to be any updates last year and no pull requests are merged?

    opened by appfrilans 7
  • 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
  • Pull request # 9000

    Pull request # 9000

    Pulling in something

    opened by Skeeetd 0
  • maybe there's an issue related to Objective C bridge

    maybe there's an issue related to Objective C bridge

    There's a crash on Highlightr init, specially at follow code line:

    let value = jsContext.evaluateScript(hgJs)

    XCode shows the follow message: Warning: could not execute support code to read Objective-C class data in the process.

    Can someone help me with this ?

    opened by rafaelreis-hotmart 0
  • Consider using lowlight

    Consider using lowlight

    Hi! 👋 I actually don’t use Swift, or this project, but I have spent time thinking about a similar problem: how to use highlight.js if not compiling to HTML.

    Highlight.js (and Prism, another popular highlighter in JS) rely heavily on HTML, but I built lowlight and refractor to work around that. Instead, they return JSON, which you could use to create NS strings instead so you don’t need an HTML parser!

    This is also what’s used in react-syntax-highlighter and react-native-syntax-highlighter

    Anyway, just an idea, feel free to close!

    opened by wooorm 1
Releases(2.1.2)
Owner
J.P. Illanes
J.P. Illanes
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 Jan 10, 2022
[iOS] A fully themeable markdown editor with live syntax highlighting.

Usage let notepad = Notepad(frame: view.bounds, themeFile: "one-dark") view.addSubview(notepad) Notepad is just like any other UITextView, but you nee

Rudd Fawcett 740 Jan 4, 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 545 Dec 4, 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 Jan 7, 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 342 Jul 6, 2021
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.7k Jan 7, 2022
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 671 Dec 2, 2021
String (and more) validation for iOS

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

George Kaimakas 234 Dec 9, 2021
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 Jan 4, 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 20, 2019
🌍⏩📄 Convert ISO8859 1-16 Encoded Text to String in Swift. Supports iOS, tvOS, watchOS and macOS.

ISO8859 Convert ISO8859 1-16 Encoded Text to String in Swift. Usage let encoding = ISO8859.part1 let string = String([...], iso8859Encoding: encoding)

Devran Cosmo Uenal 17 Nov 12, 2020
iOS port from libphonenumber (Google's phone number handling library)

libPhoneNumber for iOS NBPhoneNumberUtil NBAsYouTypeFormatter ARC only Update Log https://github.com/iziz/libPhoneNumber-iOS/wiki/Update-Log Issue You

iziz 2.3k Jan 6, 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 266 Jan 1, 2022
Markdown View for iOS.

MarkdownView MarkdownView is a WKWebView based UI element, and internally use bootstrap, highlight.js, markdown-it. How to use import MarkdownView le

Keita Oouchi 1.7k Jan 14, 2022
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 166 Nov 8, 2021
CodeMirror-Swift is a lightweight wrapper of CodeMirror for macOS and iOS

CodeMirror-Swift is a lightweight wrapper of CodeMirror for macOS and iOS. Features ?? Lightweight CodeMirror wrapper (build 5.52.2) ✅ 100% Native Swi

Proxyman 64 Dec 13, 2021
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 Dec 31, 2021
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 249 Apr 13, 2021
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 72 Jun 3, 2021