HighlightedEditorView is a reusable macOS framework containing a SwiftUI text editing view with real-time syntax highlighting. The syntax highlighting supports 58 computer languages:
- Ada
- Assembly
- Asp
- Basic
- C#
- C
- C++
- Cascading StyleSheet
- Clojure
- D
- Dart
- DOS Batch
- Elixir
- EMF
- Euphoria
- F#
- Fortran
- Gherkin
- GLSL
- Go
- Groovy
- Haskell
- HLSL
- HTML
- Java
- JavaScript
- Julia
- Kotlin
- Lua
- Modula
- Nasa CLIPS
- Nim
- NVidia Cg
- Objective-C
- Objective-C++
- OCaml
- Pascal
- Perl
- PHP
- Power Builder
- PowerShell
- Python
- R
- RenderMan
- Ruby
- Rust
- Scala
- SQL
- Swift
- Tcl
- TypeScript
- Unix shell
- UnrealScript
- Vala
- VHDL
- WGSL
- XML
- Zig
This project utilizes native code for highlighting. The speed of the syntax highlighting update on edit was measured in milliseconds, while other highlighters that use JavaScript parsers might be a bit slower.
You can add HighlightedEditorView as package to your Swift project. Open your project in Xcode, and from the menu bar, choose File, "Add Package Dependencies...".
Enter:
https://github.com/jsbakker/HighlightedEditorView
in the Package URL / Search field. Select the version you want and the project you want to add it to, and click Add Package. It should automatically be linked against from the default target of the project.
To use the syntax highlighted editor in your SwiftUI application, import HighlightedEditorView, and use HighlightedEditor in your content view.
import SwiftUI
import HighlightedEditorView
var sampleMultilineText = """
func registerAppWait(reply: @escaping (String) -> Void) {
queue.async {
if let text = self.pendingText {
// Work is already queued — deliver immediately
self.pendingText = nil
reply(text)
} else {
// No work yet — hold the reply until extension submits
self.appWaitReply = reply
}
}
}
"""
struct ContentView: View {
var body: some View {
HighlightedEditor(
text: Binding(
get: { sampleMultilineText },
set: { sampleMultilineText = $0 }
), language: .swift)
.frame(maxWidth: .infinity, alignment: .leading)
.cornerRadius(8)
.padding()
}
}
#Preview {
ContentView() // Yes, HighlightedEditor works in Previews
}Note, how we can edit the contents at runtime, and the editor's new value will be updated by the binding's setter.
You may also display a language picker with all of the supported languages, and bind it to a state variable.
@State private var language: WebCppLanguage = .swift
// later in view body ...
Picker("Language", selection: $language) {
ForEach(WebCppLanguage.allCases) { lang in
Text(lang.displayName)
.tag(lang)
}
}The syntax highlighting engine integrates code from Web C Plus Plus (webcpp), by Jeffrey Bakker. Webcpp development will be primarily done in HighlightedEditorView and backported to webcpp.
