restores Helder in all its glory

This commit is contained in:
2026-09-28 11:34:49 +02:00
parent c2b38b853c
commit 1d29d0952d
280 changed files with 29205 additions and 7 deletions
@@ -0,0 +1,57 @@
import Foundation
/// A pointer at code the agent understands: `path`, `path:42` or `path:42-58`.
public struct AgentReference: Sendable, Equatable, CustomStringConvertible {
public var path: String
/// First line, 1-based; nil for a whole-file (or folder) reference.
public var startLine: Int?
/// Last line; equal to `startLine` for a single line.
public var endLine: Int?
public init(path: String, startLine: Int? = nil, endLine: Int? = nil) {
self.path = path
self.startLine = startLine
self.endLine = endLine ?? startLine
}
/// A reference to a line range.
public init(path: String, lines: ClosedRange<Int>) {
self.init(path: path, startLine: lines.lowerBound, endLine: lines.upperBound)
}
public var description: String {
guard let start = startLine else { return path }
guard let end = endLine, end != start else { return "\(path):\(start)" }
return "\(path):\(start)-\(end)"
}
}
public enum PassOn {
/// The exact text a "Pass on …" action inserts into the agent.
///
/// With code: `note ref` then the code in a fenced block. Without: `note => ref`,
/// or just `ref` when the note is empty.
public static func compose(note: String, reference: String, code: String? = nil) -> String {
let n = note.trimmingCharacters(in: .whitespacesAndNewlines)
if let code {
let head = (n.isEmpty ? "" : n + " ") + reference
return head + "\n```\n" + code + "\n```"
}
return n.isEmpty ? reference : "\(n) => \(reference)"
}
}
public enum BracketedPaste {
public static let start = "\u{1b}[200~"
public static let end = "\u{1b}[201~"
/// Wraps text so the CLI treats it as pasted and does not submit it.
///
/// ESC and the 8-bit CSI are stripped from the payload: a file or note holding `ESC[201~`
/// would otherwise end the paste early and let the rest run as typed input.
public static func wrap(_ text: String, composerHasText: Bool) -> String {
var payload = String.UnicodeScalarView()
payload.append(contentsOf: text.unicodeScalars.lazy.filter { $0 != "\u{1b}" && $0 != "\u{9b}" })
return start + (composerHasText ? "\n" : "") + String(payload) + end
}
}
@@ -0,0 +1,45 @@
import Foundation
public enum TerminalKind: String, Sendable, Equatable, CaseIterable {
/// The top pane: a shell that runs the `claude` CLI.
case agent
/// The bottom pane: a plain login shell.
case shell
}
/// Executable, arguments and environment for one terminal pane.
public struct TerminalLaunch: Sendable, Equatable {
public var executable: String
public var arguments: [String]
public var environment: [String: String]
public var workingDirectory: String
public init(executable: String, arguments: [String], environment: [String: String], workingDirectory: String) {
self.executable = executable
self.arguments = arguments
self.environment = environment
self.workingDirectory = workingDirectory
}
/// The launch for a pane. The agent runs as `$SHELL -i -c <command>`: `-i` still sources the rc
/// files (nvm etc.) but leaves no prompt line or echoed command behind.
public static func make(kind: TerminalKind, config: HelderConfig, projectRoot: String?, environment base: [String: String]) -> TerminalLaunch {
let shell = config.terminal.shell ?? base["SHELL"] ?? "/bin/zsh"
let args = kind == .agent && config.ai.autoLaunch ? ["-i", "-c", config.ai.command] : []
let cwd = projectRoot ?? base["HOME"] ?? "/"
return TerminalLaunch(executable: shell, arguments: args, environment: environment(from: base), workingDirectory: cwd)
}
/// The child environment. A GUI launch inherits no locale and no COLORTERM, which turns
/// multibyte output into mojibake and shifts the CLI's 24-bit colours; npm's prefix
/// variables make nvm refuse to load.
public static func environment(from base: [String: String]) -> [String: String] {
var env = base
env["npm_config_prefix"] = nil
env["npm_config_globalconfig"] = nil
if env["LC_ALL"] == nil && env["LC_CTYPE"] == nil && env["LANG"] == nil { env["LANG"] = "en_US.UTF-8" }
if env["COLORTERM"] == nil { env["COLORTERM"] = "truecolor" }
env["TERM"] = "xterm-256color"
return env
}
}
@@ -0,0 +1,25 @@
import Foundation
extension HelderConfig {
/// Folder in the project root that holds Helder's per-project state.
public static let folderName = ".helder"
public static let overridesFileName = "config.json"
public static let defaultsFileName = "config.default.json"
/// The whole `.helder` folder is machine-local state, so it ignores itself.
public static let gitignoreBody = "# Helder — local, machine-specific state (do not commit).\n*\n"
/// The effective config for a sparse `config.json`; nil, empty or invalid JSON yields the defaults.
public static func resolved(overrides data: Data?) -> HelderConfig {
guard let data, !data.isEmpty else { return .defaults }
return (try? JSONDecoder().decode(HelderConfig.self, from: data)) ?? .defaults
}
/// Pretty JSON of every default, rewritten to `config.default.json` on each launch as documentation.
public static func defaultsJSON() -> Data {
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
var data = (try? encoder.encode(HelderConfig.defaults)) ?? Data()
data.append(0x0A)
return data
}
}
@@ -0,0 +1,291 @@
import Foundation
/// The view a changed file opens in. Raw values are what config files on disk hold;
/// an unknown value, such as an older config's "original", falls back to `.updated`.
public enum DefaultDiffMode: String, Codable, Sendable, CaseIterable {
case updated
case diff
}
/// Soft wrap of long lines: never, always, or only in Markdown files.
public enum WordWrap: String, Codable, Sendable, CaseIterable {
case off
case on
case markdown
}
public enum TerminalCursorStyle: String, Codable, Sendable, CaseIterable {
case bar
case block
case underline
}
/// The terminal colour table. Every value is a CSS colour string; only the selection entries may carry alpha.
public struct TerminalTheme: Codable, Sendable, Equatable {
public var background = "#101720"
public var foreground = "#E4E7E6"
public var cursor = "#E8913A"
public var cursorAccent = "#101720"
public var selectionBackground = "rgba(232,145,58,0.22)"
public var selectionInactiveBackground = "rgba(232,145,58,0.12)"
public var black = "#232C39"
public var red = "#C4741F"
public var green = "#8FBFB4"
public var yellow = "#F0B476"
public var blue = "#8FA9C4"
public var magenta = "#C3A6CE"
public var cyan = "#8FC4C4"
public var white = "#BAC0C0"
public var brightBlack = "#6C7783"
public var brightRed = "#E8913A"
public var brightGreen = "#A6D2C7"
public var brightYellow = "#F5C79A"
public var brightBlue = "#A9BFD6"
public var brightMagenta = "#D6BFDF"
public var brightCyan = "#A9D6D6"
public var brightWhite = "#F4F5F4"
public init() {}
/// The sixteen ANSI colours in SGR order (black … brightWhite).
public var ansi: [String] {
[black, red, green, yellow, blue, magenta, cyan, white,
brightBlack, brightRed, brightGreen, brightYellow, brightBlue, brightMagenta, brightCyan, brightWhite]
}
}
/// Effective project settings: `.helder/config.json` merged key by key over these defaults.
public struct HelderConfig: Codable, Sendable, Equatable {
public struct AI: Codable, Sendable, Equatable {
public var command = "claude"
public var autoLaunch = true
public init() {}
}
public struct Editor: Codable, Sendable, Equatable {
public var autoSave = false
public var tabSize = 4
public var wordWrap = WordWrap.markdown
public init() {}
}
public struct Git: Codable, Sendable, Equatable {
public var confirmDiscard = true
public var confirmStage = false
public var confirmUnstage = false
public var defaultDiffMode = DefaultDiffMode.updated
/// Milliseconds between git status polls; 0 disables the poll.
public var refreshInterval = 10_000
public init() {}
}
public struct Files: Codable, Sendable, Equatable {
/// Extra ripgrep globs to leave out of the tree and the search.
public var exclude: [String] = []
/// False on purpose: the tree and the search show git-ignored files such as `.env` unless a project opts in.
public var followGitignore = false
public init() {}
}
public struct Terminal: Codable, Sendable, Equatable {
/// Login shell for both panes; nil means `$SHELL`.
public var shell: String?
/// nil means the bundled IBM Plex Mono.
public var fontFamily: String?
/// nil means the Typography default for terminals.
public var fontSize: Double?
public var lineHeight = 1.7
public var letterSpacing = 0.0
public var cursorStyle = TerminalCursorStyle.bar
public var cursorBlink = true
/// Off keeps bold text in its own hue, so a CLI's bold labels do not wash out.
public var boldIsBright = false
public var scrollback = 8000
/// Needed for a CLI's ⌥↵ binding, but it stops Option from typing accents, hence off.
public var optionIsMeta = false
public var theme = TerminalTheme()
public init() {}
}
public struct Session: Codable, Sendable, Equatable {
public var restoreOnLaunch = true
public init() {}
}
public var ai = AI()
public var editor = Editor()
public var git = Git()
public var files = Files()
public var terminal = Terminal()
public var session = Session()
public init() {}
public static let defaults = HelderConfig()
}
// MARK: - Tolerant decoding
//
// A key that is missing, null or of the wrong type keeps its default, so a
// sparse or half-broken config.json never throws the whole file away.
extension KeyedDecodingContainer {
fileprivate func value<T: Decodable>(_ key: Key, _ fallback: T) -> T {
(try? decodeIfPresent(T.self, forKey: key)) ?? fallback
}
/// For optional settings, where an explicit `null` means "use the default behaviour".
fileprivate func optional<T: Decodable>(_ key: Key, _ fallback: T?) -> T? {
guard contains(key) else { return fallback }
if (try? decodeNil(forKey: key)) == true { return nil }
return (try? decode(T.self, forKey: key)) ?? fallback
}
}
extension HelderConfig {
private enum CodingKeys: String, CodingKey { case ai, editor, git, files, terminal, session }
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let d = HelderConfig.defaults
ai = c.value(.ai, d.ai)
editor = c.value(.editor, d.editor)
git = c.value(.git, d.git)
files = c.value(.files, d.files)
terminal = c.value(.terminal, d.terminal)
session = c.value(.session, d.session)
}
}
extension HelderConfig.AI {
private enum CodingKeys: String, CodingKey { case command, autoLaunch }
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let d = Self()
command = c.value(.command, d.command)
autoLaunch = c.value(.autoLaunch, d.autoLaunch)
}
}
extension HelderConfig.Editor {
private enum CodingKeys: String, CodingKey { case autoSave, tabSize, wordWrap }
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let d = Self()
autoSave = c.value(.autoSave, d.autoSave)
tabSize = c.value(.tabSize, d.tabSize)
wordWrap = c.value(.wordWrap, d.wordWrap)
}
}
extension HelderConfig.Git {
private enum CodingKeys: String, CodingKey {
case confirmDiscard, confirmStage, confirmUnstage, defaultDiffMode, refreshInterval
}
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let d = Self()
confirmDiscard = c.value(.confirmDiscard, d.confirmDiscard)
confirmStage = c.value(.confirmStage, d.confirmStage)
confirmUnstage = c.value(.confirmUnstage, d.confirmUnstage)
defaultDiffMode = c.value(.defaultDiffMode, d.defaultDiffMode)
refreshInterval = c.value(.refreshInterval, d.refreshInterval)
}
}
extension HelderConfig.Files {
private enum CodingKeys: String, CodingKey { case exclude, followGitignore }
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let d = Self()
exclude = c.value(.exclude, d.exclude)
followGitignore = c.value(.followGitignore, d.followGitignore)
}
}
extension HelderConfig.Terminal {
private enum CodingKeys: String, CodingKey {
case shell, fontFamily, fontSize, lineHeight, letterSpacing, cursorStyle
case cursorBlink, boldIsBright, scrollback, optionIsMeta, theme
}
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let d = Self()
shell = c.optional(.shell, d.shell)
fontFamily = c.optional(.fontFamily, d.fontFamily)
fontSize = c.optional(.fontSize, d.fontSize)
lineHeight = c.value(.lineHeight, d.lineHeight)
letterSpacing = c.value(.letterSpacing, d.letterSpacing)
cursorStyle = c.value(.cursorStyle, d.cursorStyle)
cursorBlink = c.value(.cursorBlink, d.cursorBlink)
boldIsBright = c.value(.boldIsBright, d.boldIsBright)
scrollback = c.value(.scrollback, d.scrollback)
optionIsMeta = c.value(.optionIsMeta, d.optionIsMeta)
theme = c.value(.theme, d.theme)
}
/// Writes explicit nulls, because config.default.json documents every key.
public func encode(to encoder: Encoder) throws {
var c = encoder.container(keyedBy: CodingKeys.self)
try c.encode(shell, forKey: .shell)
try c.encode(fontFamily, forKey: .fontFamily)
try c.encode(fontSize, forKey: .fontSize)
try c.encode(lineHeight, forKey: .lineHeight)
try c.encode(letterSpacing, forKey: .letterSpacing)
try c.encode(cursorStyle, forKey: .cursorStyle)
try c.encode(cursorBlink, forKey: .cursorBlink)
try c.encode(boldIsBright, forKey: .boldIsBright)
try c.encode(scrollback, forKey: .scrollback)
try c.encode(optionIsMeta, forKey: .optionIsMeta)
try c.encode(theme, forKey: .theme)
}
}
extension HelderConfig.Session {
private enum CodingKeys: String, CodingKey { case restoreOnLaunch }
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
restoreOnLaunch = c.value(.restoreOnLaunch, Self().restoreOnLaunch)
}
}
extension TerminalTheme {
private enum CodingKeys: String, CodingKey {
case background, foreground, cursor, cursorAccent, selectionBackground, selectionInactiveBackground
case black, red, green, yellow, blue, magenta, cyan, white
case brightBlack, brightRed, brightGreen, brightYellow, brightBlue, brightMagenta, brightCyan, brightWhite
}
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let d = Self()
background = c.value(.background, d.background)
foreground = c.value(.foreground, d.foreground)
cursor = c.value(.cursor, d.cursor)
cursorAccent = c.value(.cursorAccent, d.cursorAccent)
selectionBackground = c.value(.selectionBackground, d.selectionBackground)
selectionInactiveBackground = c.value(.selectionInactiveBackground, d.selectionInactiveBackground)
black = c.value(.black, d.black)
red = c.value(.red, d.red)
green = c.value(.green, d.green)
yellow = c.value(.yellow, d.yellow)
blue = c.value(.blue, d.blue)
magenta = c.value(.magenta, d.magenta)
cyan = c.value(.cyan, d.cyan)
white = c.value(.white, d.white)
brightBlack = c.value(.brightBlack, d.brightBlack)
brightRed = c.value(.brightRed, d.brightRed)
brightGreen = c.value(.brightGreen, d.brightGreen)
brightYellow = c.value(.brightYellow, d.brightYellow)
brightBlue = c.value(.brightBlue, d.brightBlue)
brightMagenta = c.value(.brightMagenta, d.brightMagenta)
brightCyan = c.value(.brightCyan, d.brightCyan)
brightWhite = c.value(.brightWhite, d.brightWhite)
}
}
@@ -0,0 +1,27 @@
import Foundation
public enum ProjectTitle {
/// `APP_NAME` from a project's `.env` text, unquoted; nil when absent or empty. The last assignment wins.
public static func appName(fromEnv contents: String) -> String? {
var raw: String?
for line in contents.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline) {
let trimmed = line.drop(while: { $0 == " " || $0 == "\t" })
if trimmed.hasPrefix("#") { continue }
guard trimmed.hasPrefix("APP_NAME") else { continue }
let rest = trimmed.dropFirst("APP_NAME".count).drop(while: { $0 == " " || $0 == "\t" })
guard rest.first == "=" else { continue }
raw = String(rest.dropFirst())
}
guard var value = raw?.trimmingCharacters(in: .whitespaces) else { return nil }
if value.count >= 2, let first = value.first, first == "\"" || first == "'", value.last == first {
value = String(value.dropFirst().dropLast())
}
value = value.trimmingCharacters(in: .whitespaces)
return value.isEmpty ? nil : value
}
/// The title a window shows: `APP_NAME` when the project sets one, else the folder name.
public static func title(folderName: String, envContents: String?) -> String {
envContents.flatMap(appName(fromEnv:)) ?? folderName
}
}
+122
View File
@@ -0,0 +1,122 @@
import Foundation
/// One line of a unified diff: unchanged, removed or added.
public enum DiffSign: String, Sendable, Equatable {
case same = " "
case removed = "-"
case added = "+"
}
public struct DiffRow: Sendable, Equatable {
public var sign: DiffSign
/// 1-based line number in the original; nil for an added line.
public var oldNo: Int?
/// 1-based line number in the updated text; nil for a removed line.
public var newNo: Int?
public var text: String
public init(sign: DiffSign, oldNo: Int?, newNo: Int?, text: String) {
self.sign = sign
self.oldNo = oldNo
self.newNo = newNo
self.text = text
}
}
public enum LineMark: String, Sendable, Equatable {
case added
case removed
}
/// One line of one side of the diff, with its 1-based number in that side.
public struct SideLine: Sendable, Equatable {
public var no: Int
public var text: String
public var mark: LineMark?
public init(no: Int, text: String, mark: LineMark? = nil) {
self.no = no
self.text = text
self.mark = mark
}
}
/// A row of the side-by-side view; a nil side is the filler opposite an unpaired add or remove.
public struct SplitRow: Sendable, Equatable {
public var left: SideLine?
public var right: SideLine?
public init(left: SideLine?, right: SideLine?) {
self.left = left
self.right = right
}
}
/// Everything the Actual view and the Diff need, derived from one (original, updated) pair.
public struct Diff: Sendable, Equatable {
public var rows: [DiffRow]
public var left: [SideLine]
public var right: [SideLine]
public var split: [SplitRow]
public var added: Int
public var removed: Int
public var isDeletedFile: Bool
public var isAddedFile: Bool
public var original: String
public var updated: String
/// Built from a change over the diff cap: the texts are empty, not the file.
public var isTooBig = false
public init(
rows: [DiffRow], left: [SideLine], right: [SideLine], split: [SplitRow],
added: Int, removed: Int, isDeletedFile: Bool, isAddedFile: Bool,
original: String, updated: String
) {
self.rows = rows
self.left = left
self.right = right
self.split = split
self.added = added
self.removed = removed
self.isDeletedFile = isDeletedFile
self.isAddedFile = isAddedFile
self.original = original
self.updated = updated
}
}
/// Which half of a file's changes a Diff shows: HEAD vs index, or index vs disk.
/// Absent (nil) means the whole file, HEAD vs disk, which Actual always shows.
public enum DiffSide: String, Codable, Sendable, Equatable {
case staged
case unstaged
}
/// How a line is painted in the read-only editor panes.
public enum ViewLineStyle: String, Sendable, Equatable {
/// Full tint: a line the change added (Actual view).
case added
}
/// Where a removed run's rule sits, since removed lines own no line of their own in Actual.
public enum GapEdge: String, Sendable, Equatable {
case above
case below
}
/// A line descriptor for the editor panes.
public struct ViewLine: Sendable, Equatable {
public var no: Int?
public var text: String
public var sign: DiffSign?
public var style: ViewLineStyle?
public var gap: GapEdge?
public init(no: Int?, text: String, sign: DiffSign? = nil, style: ViewLineStyle? = nil, gap: GapEdge? = nil) {
self.no = no
self.text = text
self.sign = sign
self.style = style
self.gap = gap
}
}
+40
View File
@@ -0,0 +1,40 @@
import Foundation
public enum DiffViews {
/// The Actual view: the updated file with added lines tinted.
///
/// A run of removed lines with no added line beside it puts its rule on the edge of
/// the next surviving line (`gap: .above`), or under the last line when the run ends
/// the file (`gap: .below`). A run that also added lines gets no gap rule.
public static func actual(_ diff: Diff) -> [ViewLine] {
var above = Set<Int>()
var endsWithRemoval = false
var removed = 0, added = 0
func flush(nextNew: Int?) {
if removed > 0 && added == 0 {
if let nextNew { above.insert(nextNew) } else { endsWithRemoval = true }
}
removed = 0
added = 0
}
for row in diff.rows {
switch row.sign {
case .removed: removed += 1
case .added: added += 1
case .same: flush(nextNew: row.newNo)
}
}
flush(nextNew: nil)
let last = diff.right.last?.no
return diff.right.map { line in
let gap: GapEdge? = above.contains(line.no) ? .above : (endsWithRemoval && line.no == last ? .below : nil)
return ViewLine(no: line.no, text: line.text, style: line.mark == .added ? .added : nil, gap: gap)
}
}
/// A plain file with no diff, numbered from 1.
public static func plain(_ text: String) -> [ViewLine] {
LineDiff.droppingTrailingNewline(text).components(separatedBy: "\n").enumerated().map { ViewLine(no: $0.offset + 1, text: $0.element) }
}
}
+205
View File
@@ -0,0 +1,205 @@
import Foundation
public enum LineDiff {
/// Largest LCS matrix built in one go (4M cells); bigger regions are split on unique anchor lines.
public static let maxCells = 4_000_000
/// "" is zero lines, and one trailing "\n" is dropped.
public static func lines(_ text: String) -> [String] {
if text.isEmpty { return [] }
return droppingTrailingNewline(text).components(separatedBy: "\n")
}
/// Drops one final "\n". `hasSuffix("\n")` misses it after a "\r", where "\r\n" is one Character.
static func droppingTrailingNewline(_ text: String) -> String {
text.utf8.last == 10 ? String(decoding: text.utf8.dropLast(), as: UTF8.self) : text
}
/// Line-based LCS diff of two texts into rows, both sides and aligned split rows.
///
/// On a tie the DP takes the deletion before the addition; flipping that reorders
/// removed and added lines in every view.
public static func build(original: String, updated: String, status: GitStatus? = nil) -> Diff {
let a = lines(original)
let b = lines(updated)
let (ia, ib) = intern(a, b)
var ops: [Op] = []
ops.reserveCapacity(max(a.count, b.count))
region(ia, ib, 0, ia.count, 0, ib.count, &ops)
var rows: [DiffRow] = []
rows.reserveCapacity(ops.count)
var removedLines = Set<Int>(), addedLines = Set<Int>()
for op in ops {
switch op {
case let .same(i, j): rows.append(DiffRow(sign: .same, oldNo: i + 1, newNo: j + 1, text: a[i]))
case let .del(i):
rows.append(DiffRow(sign: .removed, oldNo: i + 1, newNo: nil, text: a[i]))
removedLines.insert(i)
case let .add(j):
rows.append(DiffRow(sign: .added, oldNo: nil, newNo: j + 1, text: b[j]))
addedLines.insert(j)
}
}
let left = a.enumerated().map { SideLine(no: $0.offset + 1, text: $0.element, mark: removedLines.contains($0.offset) ? .removed : nil) }
let right = b.enumerated().map { SideLine(no: $0.offset + 1, text: $0.element, mark: addedLines.contains($0.offset) ? .added : nil) }
return Diff(
rows: rows, left: left, right: right, split: splitRows(ops, a, b),
added: addedLines.count, removed: removedLines.count,
isDeletedFile: status == .deleted, isAddedFile: status == .added,
original: original, updated: updated
)
}
private enum Op {
case same(Int, Int)
case del(Int)
case add(Int)
}
/// Maps every distinct line to an integer so the DP compares ints, not strings.
private static func intern(_ a: [String], _ b: [String]) -> ([Int], [Int]) {
var ids: [String: Int] = [:]
func id(_ line: String) -> Int {
if let known = ids[line] { return known }
let next = ids.count
ids[line] = next
return next
}
return (a.map(id), b.map(id))
}
/// Removed and added runs between two unchanged lines pair up side by side.
private static func splitRows(_ ops: [Op], _ a: [String], _ b: [String]) -> [SplitRow] {
var split: [SplitRow] = []
var removed: [SideLine] = [], added: [SideLine] = []
func flush() {
for k in 0..<max(removed.count, added.count) {
split.append(SplitRow(left: k < removed.count ? removed[k] : nil, right: k < added.count ? added[k] : nil))
}
removed.removeAll(keepingCapacity: true)
added.removeAll(keepingCapacity: true)
}
for op in ops {
switch op {
case let .same(i, j):
flush()
split.append(SplitRow(left: SideLine(no: i + 1, text: a[i]), right: SideLine(no: j + 1, text: b[j])))
case let .del(i): removed.append(SideLine(no: i + 1, text: a[i], mark: .removed))
case let .add(j): added.append(SideLine(no: j + 1, text: b[j], mark: .added))
}
}
flush()
return split
}
private static func region(_ a: [Int], _ b: [Int], _ a0In: Int, _ a1In: Int, _ b0In: Int, _ b1In: Int, _ ops: inout [Op]) {
var a0 = a0In, a1 = a1In, b0 = b0In, b1 = b1In
while a0 < a1 && b0 < b1 && a[a0] == b[b0] {
ops.append(.same(a0, b0))
a0 += 1
b0 += 1
}
var tail: [Op] = []
while a1 > a0 && b1 > b0 && a[a1 - 1] == b[b1 - 1] {
a1 -= 1
b1 -= 1
tail.append(.same(a1, b1))
}
let n = a1 - a0, m = b1 - b0
func replaceAll() {
for i in a0..<a1 { ops.append(.del(i)) }
for j in b0..<b1 { ops.append(.add(j)) }
}
if n == 0 || m == 0 {
replaceAll()
} else if n * m <= maxCells {
dynamicProgram(a, b, a0, a1, b0, b1, &ops)
} else {
let pins = anchors(a, b, a0, a1, b0, b1)
if pins.isEmpty {
replaceAll()
} else {
var ai = a0, bi = b0
for (ax, bx) in pins {
region(a, b, ai, ax, bi, bx, &ops)
ops.append(.same(ax, bx))
ai = ax + 1
bi = bx + 1
}
region(a, b, ai, a1, bi, b1, &ops)
}
}
ops.append(contentsOf: tail.reversed())
}
private static func dynamicProgram(_ a: [Int], _ b: [Int], _ a0: Int, _ a1: Int, _ b0: Int, _ b1: Int, _ ops: inout [Op]) {
let n = a1 - a0, m = b1 - b0
let width = m + 1
var dp = [Int32](repeating: 0, count: (n + 1) * width)
for i in stride(from: n - 1, through: 0, by: -1) {
for j in stride(from: m - 1, through: 0, by: -1) {
dp[i * width + j] = a[a0 + i] == b[b0 + j]
? dp[(i + 1) * width + j + 1] + 1
: max(dp[(i + 1) * width + j], dp[i * width + j + 1])
}
}
var i = 0, j = 0
while i < n && j < m {
if a[a0 + i] == b[b0 + j] {
ops.append(.same(a0 + i, b0 + j))
i += 1
j += 1
} else if dp[(i + 1) * width + j] >= dp[i * width + j + 1] {
ops.append(.del(a0 + i))
i += 1
} else {
ops.append(.add(b0 + j))
j += 1
}
}
while i < n { ops.append(.del(a0 + i)); i += 1 }
while j < m { ops.append(.add(b0 + j)); j += 1 }
}
/// Lines that appear exactly once on each side, in an order both sides share.
private static func anchors(_ a: [Int], _ b: [Int], _ a0: Int, _ a1: Int, _ b0: Int, _ b1: Int) -> [(Int, Int)] {
var countA: [Int: Int] = [:], countB: [Int: Int] = [:], atB: [Int: Int] = [:]
for i in a0..<a1 { countA[a[i], default: 0] += 1 }
for j in b0..<b1 {
countB[b[j], default: 0] += 1
atB[b[j]] = j
}
var pairs: [(Int, Int)] = []
for i in a0..<a1 where countA[a[i]] == 1 && countB[a[i]] == 1 {
if let j = atB[a[i]] { pairs.append((i, j)) }
}
return longestRun(pairs)
}
/// Longest strictly increasing subsequence over the b-index of each pair.
private static func longestRun(_ pairs: [(Int, Int)]) -> [(Int, Int)] {
var tails: [Int] = []
var prev = [Int](repeating: -1, count: pairs.count)
for k in pairs.indices {
let v = pairs[k].1
var lo = 0, hi = tails.count
while lo < hi {
let mid = (lo + hi) / 2
if pairs[tails[mid]].1 < v { lo = mid + 1 } else { hi = mid }
}
prev[k] = lo > 0 ? tails[lo - 1] : -1
if lo == tails.count { tails.append(k) } else { tails[lo] = k }
}
var out: [(Int, Int)] = []
var k = tails.last ?? -1
while k >= 0 {
out.append(pairs[k])
k = prev[k]
}
return out.reversed()
}
}
+21
View File
@@ -0,0 +1,21 @@
import Foundation
/// The view the editor shows for the open file. Raw values are stored in sessions, so `.actual` stays "updated".
///
/// `.diff` is the full-screen side-by-side overlay, not a pane mode.
public enum ViewMode: String, Codable, Sendable, CaseIterable {
/// The live buffer with changed lines marked.
case actual = "updated"
case diff
/// An unchanged file: the plain editable buffer.
case code
/// Rendered Markdown.
case preview
public init(_ mode: DefaultDiffMode) {
switch mode {
case .updated: self = .actual
case .diff: self = .diff
}
}
}
@@ -0,0 +1,126 @@
import Foundation
/// What was right-clicked.
public enum ContextTarget: Sendable, Equatable {
/// A line or selection in the editor; `code` is the selected text, if any.
case editor(reference: AgentReference, code: String?)
case file(path: String)
case directory(path: String)
/// A git row; the row carries its own half, since one file can have two rows.
case gitRow(path: String, staged: Bool)
/// The empty space under the tree: the project folder itself.
case projectRoot
case terminal(TerminalKind, hasSelection: Bool)
public var path: String {
switch self {
case let .editor(reference, _): reference.path
case let .file(path), let .directory(path), let .gitRow(path, _): path
case .projectRoot, .terminal: ""
}
}
}
public enum ContextAction: Sendable, Equatable {
/// Opens the pass-on prompt; with code for an editor selection.
case passOnReference(String, code: String?)
case copyReference(String)
case passOnFileName(String)
case copyFileName(String)
case newFile(inDirectory: String)
case newFolder(inDirectory: String)
case stage(String)
case unstage(String)
case openDiff(String)
case discard(String)
case rename(String, isDirectory: Bool)
case revealInFinder(String)
case delete(String, isDirectory: Bool)
case copyTerminalSelection(TerminalKind)
case pasteIntoTerminal(TerminalKind)
/// Destructive items read in amber-deep.
public var isDestructive: Bool {
switch self {
case .discard, .delete: true
default: false
}
}
}
/// A menu entry, or a separator between groups.
public enum ContextMenuEntry: Sendable, Equatable {
case action(ContextAction, label: String)
case separator
}
public enum ContextActions {
/// The header line of the menu: the reference, or `project/` for the root.
public static func header(for target: ContextTarget, projectName: String) -> String {
switch target {
case let .editor(reference, _): reference.description
case let .directory(path): path + "/"
case let .file(path), let .gitRow(path, _): path
case .projectRoot: projectName + "/"
case .terminal: ""
}
}
/// Menu entries: every "Pass on …" item has its "Copy …" twin directly below.
public static func entries(for target: ContextTarget) -> [ContextMenuEntry] {
switch target {
case let .editor(reference, code):
let ref = reference.description
let hasCode = !(code ?? "").isEmpty
return [
.action(.passOnReference(ref, code: hasCode ? code : nil), label: hasCode ? "Pass on selection" : "Pass on reference"),
.action(.copyReference(ref), label: "Copy reference"),
]
case .projectRoot:
return [
.action(.newFile(inDirectory: ""), label: "New file"),
.action(.revealInFinder(""), label: "Show in Finder"),
]
case let .file(path):
return fileHead(path) + [
.separator,
.action(.rename(path, isDirectory: false), label: "Rename file"),
.action(.revealInFinder(path), label: "Show in Finder"),
.action(.delete(path, isDirectory: false), label: "Delete file"),
]
case let .directory(path):
let ref = path + "/"
return [
.action(.passOnReference(ref, code: nil), label: "Pass on reference"),
.action(.copyReference(ref), label: "Copy reference"),
.separator,
.action(.newFile(inDirectory: path), label: "New file"),
.action(.newFolder(inDirectory: path), label: "New folder"),
.separator,
.action(.rename(path, isDirectory: true), label: "Rename folder"),
.action(.revealInFinder(path), label: "Show in Finder"),
.action(.delete(path, isDirectory: true), label: "Delete folder"),
]
case let .terminal(kind, hasSelection):
return (hasSelection ? [.action(.copyTerminalSelection(kind), label: "Copy")] : [])
+ [.action(.pasteIntoTerminal(kind), label: "Paste")]
case let .gitRow(path, staged):
return fileHead(path) + [
.separator,
staged ? .action(.unstage(path), label: "Unstage changes") : .action(.stage(path), label: "Stage changes"),
.action(.openDiff(path), label: "Open diff"),
.action(.discard(path), label: "Discard changes"),
]
}
}
private static func fileHead(_ path: String) -> [ContextMenuEntry] {
let name = PathUtils.basename(path)
return [
.action(.passOnReference(path, code: nil), label: "Pass on reference"),
.action(.copyReference(path), label: "Copy reference"),
.action(.passOnFileName(name), label: "Pass on file name"),
.action(.copyFileName(name), label: "Copy file name"),
]
}
}
+202
View File
@@ -0,0 +1,202 @@
import Foundation
public enum FileLimits {
/// Files above this size are left out of the content index.
public static let maxIndexedFileBytes = 300_000
public static let maxIndexedFiles = 6000
public static let maxImageBytes = 25_000_000
/// Git reads a file above this size as having no text, so one dump or lock file cannot stall the column.
public static let maxDiffFileBytes = 1_000_000
/// How deep the fallback directory walk goes.
public static let maxWalkDepth = 12
/// A NUL byte in the first 8000 bytes marks a file as binary, like git does.
public static func looksBinary(_ data: Data) -> Bool {
data.prefix(8000).contains(0)
}
public static let imageMimeTypes: [String: String] = [
"png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "jfif": "image/jpeg",
"gif": "image/gif", "webp": "image/webp", "svg": "image/svg+xml", "bmp": "image/bmp",
"ico": "image/x-icon", "avif": "image/avif", "apng": "image/apng",
]
}
public enum IgnoreRules {
/// Folders the fallback walk and the watcher never enter.
public static let walkIgnoredNames: Set<String> = [
"node_modules", ".git", "out", "dist", "build", ".next", ".nuxt",
".cache", "coverage", "vendor", ".idea", ".vscode", ".helder", ".turbo",
]
/// Always passed to ripgrep as `!glob`, on top of gitignore and `files.exclude`.
/// `.DS_Store` is here because `followGitignore` defaults to false (rg runs with --no-ignore).
public static let ripgrepBaseIgnore = [
"node_modules", ".git", "out", "dist", "build", ".cache",
"vendor", "coverage", ".helder", ".next", ".nuxt", ".turbo", ".idea", ".vscode",
".DS_Store",
]
/// Declarations are indexed inside `vendor/` too, so framework classes stay clickable.
public static let symbolDeclarationIgnore = ripgrepBaseIgnore.filter { $0 != "vendor" && $0 != ".DS_Store" }
/// References skip `vendor/`: nobody wants to read how a framework uses a class.
public static let symbolReferenceIgnore = ripgrepBaseIgnore.filter { $0 != ".DS_Store" }
/// True for a name the fallback walk skips.
public static func isWalkIgnored(_ name: String) -> Bool {
walkIgnoredNames.contains(name) || name == ".DS_Store"
}
/// True when any segment of a relative path is an ignored folder; the watcher drops such events.
public static func isWatchIgnored(_ relativePath: String) -> Bool {
relativePath.split(separator: "/").contains { walkIgnoredNames.contains(String($0)) }
}
/// Framework caches rewritten on every request or test run; watching them refreshes the project in a loop.
public static let watchIgnoredPrefixes = [
"storage/framework/", "bootstrap/cache/", ".phpunit.result.cache", ".phpunit.cache/",
]
/// `isWatchIgnored`, plus the framework caches and the project's `files.exclude` globs.
public static func isWatchIgnored(_ relativePath: String, exclude: [String]) -> Bool {
if isWatchIgnored(relativePath) { return true }
if watchIgnoredPrefixes.contains(where: { relativePath == $0 || relativePath.hasPrefix($0) || $0 == relativePath + "/" }) {
return true
}
return exclude.contains { !$0.isEmpty && globMatches($0, path: relativePath) }
}
/// The `--glob !x` pairs plus `--no-ignore` that make ripgrep honour the project's file settings.
public static func ripgrepArguments(files: HelderConfig.Files, base: [String] = ripgrepBaseIgnore) -> [String] {
var args: [String] = []
for glob in base { args += ["--glob", "!" + glob] }
for glob in files.exclude where !glob.isEmpty { args += ["--glob", "!" + glob] }
if !files.followGitignore { args.append("--no-ignore") }
return args
}
/// Gitignore-style glob match of a relative path, with ripgrep's `--glob` semantics.
///
/// A pattern without a slash matches a basename at any depth; `**` crosses folders, `*` and `?`
/// stop at a slash. A matching folder matches everything under it, as in ripgrep.
public static func globMatches(_ glob: String, path: String) -> Bool {
var pattern = Substring(glob)
while pattern.hasSuffix("/") { pattern = pattern.dropLast() }
let rooted = pattern.hasPrefix("/")
if rooted { pattern = pattern.dropFirst() }
guard !pattern.isEmpty else { return false }
let anchored = rooted || pattern.contains("/")
let candidates = PathUtils.ancestors(path) + [path]
for alternative in expandBraces(String(pattern)) {
let chars = Array(alternative)
for candidate in candidates {
let subject = Array(anchored ? candidate : PathUtils.basename(candidate))
var matcher = WildcardMatcher(pattern: chars, subject: subject)
if matcher.matches() { return true }
}
}
return false
}
/// `{a,b}` alternation expanded into plain patterns; nested braces expand recursively.
static func expandBraces(_ pattern: String) -> [String] {
let chars = Array(pattern)
guard let open = chars.firstIndex(of: "{") else { return [pattern] }
var depth = 0
var parts: [String] = []
var current = ""
for k in (open + 1)..<chars.count {
let c = chars[k]
if c == "{" { depth += 1 }
if c == "}" {
if depth == 0 {
parts.append(current)
let head = String(chars[..<open]), rest = String(chars[(k + 1)...])
return parts.flatMap { expandBraces(head + $0 + rest) }
}
depth -= 1
}
if c == "," && depth == 0 {
parts.append(current)
current = ""
} else {
current.append(c)
}
}
return [pattern]
}
}
/// Glob matcher: `**` crosses folders, `*` and `?` stop at a slash, `[...]` is a character class.
private struct WildcardMatcher {
let pattern: [Character]
let subject: [Character]
private var memo: [Bool?]
init(pattern: [Character], subject: [Character]) {
self.pattern = pattern
self.subject = subject
memo = Array(repeating: nil, count: (pattern.count + 1) * (subject.count + 1))
}
mutating func matches() -> Bool { match(0, 0) }
private mutating func match(_ p: Int, _ s: Int) -> Bool {
let key = p * (subject.count + 1) + s
if let known = memo[key] { return known }
let result = compute(p, s)
memo[key] = result
return result
}
private mutating func compute(_ p: Int, _ s: Int) -> Bool {
guard p < pattern.count else { return s == subject.count }
switch pattern[p] {
case "*":
if p + 1 < pattern.count && pattern[p + 1] == "*" {
let afterStars = p + 2
if afterStars < pattern.count && pattern[afterStars] == "/" && match(afterStars + 1, s) { return true }
for k in s...subject.count where match(afterStars, k) { return true }
return false
}
var k = s
while true {
if match(p + 1, k) { return true }
if k == subject.count || subject[k] == "/" { return false }
k += 1
}
case "?":
return s < subject.count && subject[s] != "/" && match(p + 1, s + 1)
case "[":
guard s < subject.count, subject[s] != "/", let (hit, next) = classMatch(p, subject[s]) else {
return s < subject.count && subject[s] == "[" && match(p + 1, s + 1)
}
return hit && match(next, s + 1)
case "\\" where p + 1 < pattern.count:
return s < subject.count && subject[s] == pattern[p + 1] && match(p + 2, s + 1)
default:
return s < subject.count && subject[s] == pattern[p] && match(p + 1, s + 1)
}
}
/// Whether `c` is in the class opening at `p`, and the index after it; nil for an unclosed `[`.
private func classMatch(_ p: Int, _ c: Character) -> (Bool, Int)? {
var k = p + 1
let negated = k < pattern.count && (pattern[k] == "!" || pattern[k] == "^")
if negated { k += 1 }
var hit = false
var first = true
while k < pattern.count {
if pattern[k] == "]" && !first { return (hit != negated, k + 1) }
first = false
if k + 2 < pattern.count && pattern[k + 1] == "-" && pattern[k + 2] != "]" {
if pattern[k] <= c && c <= pattern[k + 2] { hit = true }
k += 3
} else {
if pattern[k] == c { hit = true }
k += 1
}
}
return nil
}
}
+125
View File
@@ -0,0 +1,125 @@
import Foundation
public struct FileNode: Sendable, Equatable, Identifiable {
public enum Kind: String, Sendable, Equatable {
case directory
case file
}
public var name: String
public var kind: Kind
/// Project-relative, "/"-separated; "" is the project root.
public var path: String
/// nil for files; an empty array for an empty folder.
public var children: [FileNode]?
public var id: String { path }
public var isDirectory: Bool { kind == .directory }
public var isHidden: Bool { name.hasPrefix(".") }
public init(name: String, kind: Kind, path: String, children: [FileNode]? = nil) {
self.name = name
self.kind = kind
self.path = path
self.children = kind == .directory ? (children ?? []) : nil
}
}
/// One visible row of the Explorer, in render order.
public struct TreeRow: Sendable, Equatable {
public var path: String
public var kind: FileNode.Kind
/// 0 for a top-level entry; the Explorer indents 16px per level.
public var depth: Int
public init(path: String, kind: FileNode.Kind, depth: Int) {
self.path = path
self.kind = kind
self.depth = depth
}
}
public enum FileTree {
/// Nested tree from relative file paths: folders first, then files, each sorted by name.
///
/// `emptyDirs` adds the folders that hold no file, which `rg --files` never lists.
/// Names sort case-insensitively, not in byte order.
public static func build(rootName: String, paths: [String], emptyDirs: [String] = []) -> FileNode {
var folders: [String: Set<String>] = ["": []]
var files: [String: Set<String>] = [:]
func ensureFolder(_ parts: ArraySlice<Substring>) -> String {
var parent = ""
for part in parts {
let path = PathUtils.join(parent, String(part))
if folders[path] == nil {
folders[path] = []
folders[parent, default: []].insert(path)
}
parent = path
}
return parent
}
for path in paths {
let parts = path.split(separator: "/")
guard let name = parts.last else { continue }
let parent = ensureFolder(parts.dropLast())
files[parent, default: []].insert(PathUtils.join(parent, String(name)))
}
for dir in emptyDirs {
_ = ensureFolder(dir.split(separator: "/")[...])
}
func node(folder path: String, name: String) -> FileNode {
let subfolders = (folders[path] ?? []).map { node(folder: $0, name: PathUtils.basename($0)) }
let leaves = (files[path] ?? []).map { FileNode(name: PathUtils.basename($0), kind: .file, path: $0) }
return FileNode(name: name, kind: .directory, path: path, children: sortedByName(subfolders) + sortedByName(leaves))
}
return node(folder: "", name: rootName)
}
/// Case-insensitive, locale-aware order.
static func sortedByName(_ nodes: [FileNode]) -> [FileNode] {
nodes.sorted { $0.name.compare($1.name, locale: sortLocale) == .orderedAscending }
}
private static let sortLocale = Locale(identifier: "en_US")
/// The node at a relative path ("" is the root), or nil.
public static func find(_ path: String, in tree: FileNode) -> FileNode? {
if path.isEmpty { return tree }
var node = tree
for part in path.split(separator: "/") {
guard let next = node.children?.first(where: { $0.name == part }) else { return nil }
node = next
}
return node
}
/// A copy of the tree with the children of the node at `path` replaced; unchanged when the path is absent.
public static func replacingChildren(of path: String, with children: [FileNode], in tree: FileNode) -> FileNode {
if tree.path == path {
var copy = tree
copy.children = children
return copy
}
guard let kids = tree.children, path.hasPrefix(tree.path) else { return tree }
var copy = tree
copy.children = kids.map { replacingChildren(of: path, with: children, in: $0) }
return copy
}
/// The visible rows under the root, honouring expanded folders and the hidden-files toggle.
public static func visibleRows(_ tree: FileNode, expanded: Set<String>, showHidden: Bool) -> [TreeRow] {
var rows: [TreeRow] = []
func walk(_ node: FileNode, depth: Int) {
for child in node.children ?? [] where showHidden || !child.isHidden {
rows.append(TreeRow(path: child.path, kind: child.kind, depth: depth))
if child.isDirectory && expanded.contains(child.path) { walk(child, depth: depth + 1) }
}
}
walk(tree, depth: 0)
return rows
}
}
+100
View File
@@ -0,0 +1,100 @@
import Foundation
/// A highlighter grammar.
public enum Language: String, Sendable, CaseIterable {
case php, javascript, jsx, typescript, tsx, python, markup, css, json, markdown, bash, yaml
}
/// One of the four badge fills; the UI maps each to a Palette colour.
public enum BadgeTint: String, Sendable {
case purple
case amber
case teal
case grey
}
/// The small extension chip in rows and headers: ink text on a tinted fill.
public struct FileBadge: Sendable, Equatable {
public var text: String
public var tint: BadgeTint
public init(_ text: String, _ tint: BadgeTint) {
self.text = text
self.tint = tint
}
}
public enum FileType {
/// Lowercased extension; any `.env*` file reads as `env`.
public static func ext(_ path: String) -> String {
let base = PathUtils.basename(path)
if base.hasPrefix(".env") { return "env" }
guard let dot = base.lastIndex(of: ".") else { return "" }
return base[base.index(after: dot)...].lowercased()
}
private static let languages: [String: Language] = [
"php": .php, "js": .javascript, "mjs": .javascript, "cjs": .javascript,
"jsx": .jsx, "ts": .typescript, "tsx": .tsx, "py": .python,
"html": .markup, "xml": .markup, "svg": .markup, "vue": .markup,
"css": .css, "scss": .css, "json": .json, "md": .markdown,
"sh": .bash, "bash": .bash, "yml": .yaml, "yaml": .yaml, "env": .bash,
]
public static func language(for path: String) -> Language? {
languages[ext(path)]
}
public static func isMarkdown(_ path: String) -> Bool {
language(for: path) == .markdown
}
private static let labels: [String: String] = [
"php": "PHP", "js": "JavaScript", "mjs": "JavaScript", "ts": "TypeScript",
"tsx": "TypeScript", "jsx": "JavaScript", "py": "Python", "html": "HTML",
"css": "CSS", "json": "JSON", "md": "Markdown", "sh": "Shell", "env": "Dotenv",
"yml": "YAML", "yaml": "YAML",
]
/// The status-bar language name.
public static func languageLabel(for path: String) -> String {
let e = ext(path)
return labels[e] ?? (e.isEmpty ? "Plain Text" : e.uppercased())
}
public static let imageExtensions: Set<String> = ["png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "ico", "avif", "apng", "jfif"]
/// Files the viewer shows as a picture instead of text.
public static func isImage(_ path: String) -> Bool {
imageExtensions.contains(ext(path))
}
/// Files that never open: the viewer flashes "Too big." instead.
public static let tooBigNames: Set<String> = ["composer.lock"]
private static let badges: [String: FileBadge] = [
"php": FileBadge("php", .purple), "blade": FileBadge("php", .purple),
"ts": FileBadge("ts", .purple), "tsx": FileBadge("tsx", .purple), "vue": FileBadge("vue", .purple),
"js": FileBadge("js", .amber), "mjs": FileBadge("js", .amber), "cjs": FileBadge("js", .amber),
"jsx": FileBadge("jsx", .amber), "json": FileBadge("json", .amber),
"yml": FileBadge("yml", .amber), "yaml": FileBadge("yml", .amber),
"css": FileBadge("css", .teal), "scss": FileBadge("scss", .teal), "pcss": FileBadge("css", .teal),
"html": FileBadge("html", .teal), "sh": FileBadge("sh", .teal), "env": FileBadge("env", .teal),
"py": FileBadge("py", .teal), "sql": FileBadge("sql", .teal),
"md": FileBadge("md", .grey), "txt": FileBadge("txt", .grey),
"lock": FileBadge("lock", .grey), "svg": FileBadge("svg", .grey),
]
private static let nameBadges: [String: FileBadge] = [
"composer.json": FileBadge("json", .purple),
"package.json": FileBadge("json", .amber),
".env": FileBadge("env", .teal),
]
/// The badge for a path; unknown extensions get a grey chip with up to four letters, or "·".
public static func badge(for path: String) -> FileBadge {
if let named = nameBadges[PathUtils.basename(path)] { return named }
let e = ext(path)
return badges[e] ?? FileBadge(e.isEmpty ? "·" : String(e.prefix(4)), .grey)
}
}
+63
View File
@@ -0,0 +1,63 @@
import Foundation
public enum PathUtils {
public static func basename(_ path: String) -> String {
path.split(separator: "/").last.map(String.init) ?? ""
}
/// Everything before the last segment; "" for a top-level entry.
public static func dirname(_ path: String) -> String {
guard let slash = path.lastIndex(of: "/") else { return "" }
return String(path[..<slash])
}
/// `dir/name`, or just `name` when `dir` is the root.
public static func join(_ dir: String, _ name: String) -> String {
dir.isEmpty ? name : dir + "/" + name
}
/// Every ancestor folder of a path, outermost first: `a/b/c.txt` → [a, a/b].
public static func ancestors(_ path: String) -> [String] {
let parts = path.split(separator: "/").map(String.init)
guard parts.count > 1 else { return [] }
return (1..<parts.count).map { parts[0..<$0].joined(separator: "/") }
}
/// True when any segment is a dotfile or dot-folder.
public static func isHidden(_ path: String) -> Bool {
path.split(separator: "/").contains { $0.hasPrefix(".") }
}
/// True for `path` itself and, when it is a folder, for everything under it.
public static func isInside(_ candidate: String, _ path: String, isDirectory: Bool) -> Bool {
candidate == path || (isDirectory && candidate.hasPrefix(path + "/"))
}
/// Carries a path over a rename of `from` to `to`; folders move everything under them.
public static func remap(_ candidate: String, from: String, to: String, isDirectory: Bool) -> String {
if candidate == from { return to }
if isDirectory && candidate.hasPrefix(from + "/") { return to + candidate.dropFirst(from.count) }
return candidate
}
/// A cleaned basename for a rename, or nil when it is empty, has a slash, or is `.`/`..`.
public static func validatedName(_ name: String) -> String? {
var clean = name.trimmingCharacters(in: .whitespacesAndNewlines)
while clean.hasSuffix("/") { clean.removeLast() }
if clean.isEmpty || clean.contains("/") || clean == "." || clean == ".." { return nil }
return clean
}
/// The relative path a create-in-folder action targets; leading and trailing slashes are dropped.
public static func newEntryPath(inDirectory dir: String, name: String) -> String {
var clean = Substring(name)
while clean.hasPrefix("/") { clean = clean.dropFirst() }
while clean.hasSuffix("/") { clean = clean.dropLast() }
return join(dir, String(clean))
}
/// A reference to a project entry: folders end in a slash.
public static func reference(_ path: String, isDirectory: Bool) -> String {
isDirectory ? path + "/" : path
}
}
@@ -0,0 +1,93 @@
import Foundation
public enum GitDerivation {
/// Turns a snapshot into rows plus per-row and per-file diffs; nil means "not a repository".
///
/// Per file, HEAD comes from the staged row's original and disk from the unstaged row's
/// updated; with one row both come from it. The unstaged row owns the file-level status,
/// so a file staged as modified but deleted on disk reads as deleted.
public static func derive(_ snapshot: GitSnapshot?) -> GitWorkingState {
guard let snapshot else { return .empty }
var state = GitWorkingState(branch: snapshot.branch, ahead: snapshot.ahead, canPush: snapshot.canPush, isRepository: true)
var wholeFile: [String: (head: String, disk: String, status: GitStatus, rows: Int, rowID: String)] = [:]
var tooBig = Set<String>()
for change in snapshot.changes {
var diff = LineDiff.build(original: change.original, updated: change.updated, status: change.status)
diff.isTooBig = change.isTooBig
if change.isTooBig { tooBig.insert(change.path) }
let row = Change(path: change.path, status: change.status, added: diff.added, removed: diff.removed,
staged: change.staged, originalPath: change.originalPath)
state.rowDiffs[row.id] = diff
state.changes.append(row)
if change.staged { state.stagedPaths.insert(change.path) }
if let previous = wholeFile[change.path] {
wholeFile[change.path] = change.staged
? (change.original, previous.disk, previous.status, previous.rows + 1, previous.rowID)
: (previous.head, change.updated, change.status, previous.rows + 1, previous.rowID)
} else {
wholeFile[change.path] = (change.original, change.updated, change.status, 1, row.id)
}
}
for (path, whole) in wholeFile {
var diff = whole.rows == 1
? state.rowDiffs[whole.rowID]
: LineDiff.build(original: whole.head, updated: whole.disk, status: whole.status)
diff?.isTooBig = tooBig.contains(path)
state.fileDiffs[path] = diff
}
return state
}
}
/// Rows of one folder in the Source Control list.
public struct ChangeGroup: Sendable, Equatable {
/// Folder path; "" is the project root.
public var dir: String
public var rows: [Change]
public init(dir: String, rows: [Change]) {
self.dir = dir
self.rows = rows
}
}
public enum SourceControlText {
/// Groups rows by folder in order of first appearance; keyboard navigation walks this same order.
public static func groupByDir(_ list: [Change]) -> [ChangeGroup] {
var groups: [ChangeGroup] = []
var indexByDir: [String: Int] = [:]
for change in list {
let dir = PathUtils.dirname(change.path)
if let index = indexByDir[dir] {
groups[index].rows.append(change)
} else {
indexByDir[dir] = groups.count
groups.append(ChangeGroup(dir: dir, rows: [change]))
}
}
return groups
}
/// The row order of the list: staged groups first, then unstaged, each folder by folder.
public static func navigationOrder(_ changes: [Change]) -> [Change] {
let staged = groupByDir(changes.filter(\.staged)).flatMap(\.rows)
let unstaged = groupByDir(changes.filter { !$0.staged }).flatMap(\.rows)
return staged + unstaged
}
/// Dictation tools capitalise and add line breaks; a commit subject is one lowercase line.
public static func normalizeCommitMessage(_ value: String) -> String {
value.lowercased().replacingOccurrences(of: "[ \\t]*[\\r\\n]+[ \\t]*", with: " ", options: .regularExpression)
}
public static func pushTooltip(canPush: Bool, ahead: Int) -> String {
if !canPush { return "Nothing to push (⌘P)" }
if ahead > 0 { return "Push \(ahead) commit\(ahead > 1 ? "s" : "") to remote (⌘P)" }
return "Push the branch to remote (⌘P)"
}
/// Git rows under `tests/` or `cypress/` render dimmed.
public static func isTestFile(_ path: String) -> Bool {
path.hasPrefix("tests/") || path.hasPrefix("cypress/")
}
}
+140
View File
@@ -0,0 +1,140 @@
import Foundation
/// The status letter a git row shows. Copies and untracked files read as `A`, conflicts as `M`.
public enum GitStatus: String, Codable, Sendable, CaseIterable {
case added = "A"
case modified = "M"
case deleted = "D"
case renamed = "R"
case unmerged = "U"
}
/// One file half as `git load` reads it: the text on each side of that half.
public struct GitFileChange: Sendable, Equatable {
public var path: String
public var status: GitStatus
/// True for the HEAD→index half, false for the index→disk half.
public var staged: Bool
public var original: String
public var updated: String
/// The source path of a rename or copy; nil otherwise.
public var originalPath: String?
/// A side was over the diff cap, so both texts are left empty.
public var isTooBig: Bool
public init(path: String, status: GitStatus, staged: Bool, original: String, updated: String, originalPath: String? = nil,
isTooBig: Bool = false) {
self.path = path
self.status = status
self.staged = staged
self.original = original
self.updated = updated
self.originalPath = originalPath
self.isTooBig = isTooBig
}
}
/// What one `git status` read of the working tree returns.
public struct GitSnapshot: Sendable, Equatable {
public var branch: String
/// Commits the remote does not have yet; 0 when unknown.
public var ahead: Int
/// True when a push would send something, including a branch without an upstream.
public var canPush: Bool
public var changes: [GitFileChange]
public init(branch: String, ahead: Int, canPush: Bool, changes: [GitFileChange]) {
self.branch = branch
self.ahead = ahead
self.canPush = canPush
self.changes = changes
}
}
/// A row in the Source Control column. A file staged and then edited again has two rows.
public struct Change: Sendable, Equatable, Identifiable {
/// Row identity; the path alone is not unique (see `staged`).
public var id: String
public var path: String
public var status: GitStatus
public var added: Int
public var removed: Int
public var isDeleted: Bool
public var staged: Bool
/// The source path of a rename or copy; nil otherwise.
public var originalPath: String?
public init(path: String, status: GitStatus, added: Int, removed: Int, staged: Bool, originalPath: String? = nil) {
self.id = Change.rowID(path: path, staged: staged)
self.path = path
self.status = status
self.added = added
self.removed = removed
self.isDeleted = status == .deleted
self.staged = staged
self.originalPath = originalPath
}
/// `s:path` for the staged half, `w:path` for the working-tree half.
public static func rowID(path: String, staged: Bool) -> String {
(staged ? "s:" : "w:") + path
}
}
/// The git slice of the workspace, derived from one snapshot.
public struct GitWorkingState: Sendable, Equatable {
public var branch: String
public var ahead: Int
public var canPush: Bool
public var changes: [Change]
/// Per path: HEAD vs disk. Drives the Actual view.
public var fileDiffs: [String: Diff]
/// Per row id: that row's own pair. Drives the Diff overlay.
public var rowDiffs: [String: Diff]
/// Paths that have a staged row.
public var stagedPaths: Set<String>
/// False when the project is not a git repository.
public var isRepository: Bool
public init(
branch: String = "—", ahead: Int = 0, canPush: Bool = false, changes: [Change] = [],
fileDiffs: [String: Diff] = [:], rowDiffs: [String: Diff] = [:],
stagedPaths: Set<String> = [], isRepository: Bool = false
) {
self.branch = branch
self.ahead = ahead
self.canPush = canPush
self.changes = changes
self.fileDiffs = fileDiffs
self.rowDiffs = rowDiffs
self.stagedPaths = stagedPaths
self.isRepository = isRepository
}
public static let empty = GitWorkingState()
/// Whole-project line counts for the status bar.
public var totals: (added: Int, removed: Int) {
changes.reduce((0, 0)) { ($0.0 + $1.added, $0.1 + $1.removed) }
}
public var stagedCount: Int { changes.filter(\.staged).count }
public var unstagedCount: Int { changes.count - stagedCount }
/// Distinct paths with an unstaged row, in row order: what "stage all" sends to git.
public var unstagedPaths: [String] {
var seen = Set<String>()
return changes.filter { !$0.staged && seen.insert($0.path).inserted }.map(\.path)
}
}
/// The outcome of a push, shown in a toast.
public struct PushResult: Sendable, Equatable {
public var ok: Bool
public var message: String
public init(ok: Bool, message: String) {
self.ok = ok
self.message = message
}
}
+146
View File
@@ -0,0 +1,146 @@
import Foundation
public struct StatusEntry: Sendable, Equatable {
/// The index column of the porcelain XY code (" " when clean).
public var index: Character
/// The working-tree column of the porcelain XY code.
public var working: Character
/// The destination path for renames and copies.
public var path: String
/// The source path of a rename or copy; nil otherwise.
public var originalPath: String?
public init(index: Character, working: Character, path: String, originalPath: String? = nil) {
self.index = index
self.working = working
self.path = path
self.originalPath = originalPath
}
/// True when the index column records a rename, whose source is gone from the index.
public var isStagedRename: Bool { index == "R" && originalPath != nil }
}
public struct ParsedStatus: Sendable, Equatable {
public var branch: String
public var ahead: Int
public var canPush: Bool
public var entries: [StatusEntry]
public init(branch: String, ahead: Int, canPush: Bool, entries: [StatusEntry]) {
self.branch = branch
self.ahead = ahead
self.canPush = canPush
self.entries = entries
}
}
/// One row a porcelain entry turns into.
public struct GitRowSpec: Sendable, Equatable {
public var status: GitStatus
public var staged: Bool
public init(status: GitStatus, staged: Bool) {
self.status = status
self.staged = staged
}
}
public enum Porcelain {
/// The arguments `GitService.load` passes to git; `-z` keeps paths unquoted.
public static let statusArguments = ["status", "--porcelain", "-b", "--untracked-files=all", "-z"]
/// Parses `git status --porcelain -b -z`: NUL-separated, the `## ` header first.
///
/// For a rename or copy (R or C in either column) the next NUL field is the source
/// path, not an entry of its own. A missing header leaves the branch at "HEAD".
public static func parseStatus(_ raw: String) -> ParsedStatus {
let parts = raw.split(separator: "\0", omittingEmptySubsequences: false)
var result = ParsedStatus(branch: "HEAD", ahead: 0, canPush: false, entries: [])
var sourceFollows = false
for part in parts {
if sourceFollows {
sourceFollows = false
result.entries[result.entries.count - 1].originalPath = String(part)
continue
}
if part.isEmpty { continue }
if part.hasPrefix("## ") {
let header = String(part.dropFirst(3))
result.branch = parseBranch(header: header)
(result.ahead, result.canPush) = parseAhead(header: header)
continue
}
let chars = Array(part.prefix(2))
let index = chars.first ?? " "
let working = chars.count > 1 ? chars[1] : " "
let path = String(part.dropFirst(3))
if index == "R" || index == "C" || working == "R" || working == "C" { sourceFollows = true }
result.entries.append(StatusEntry(index: index, working: working, path: path))
}
return result
}
/// The display branch of a header such as `main...origin/main [ahead 1]`,
/// `No commits yet on main` (→ "main") or `HEAD (no branch)` (→ "HEAD").
public static func parseBranch(header: String) -> String {
let noCommits = "No commits yet on "
if header.hasPrefix(noCommits) { return header.dropFirst(noCommits.count).trimmingCharacters(in: .whitespaces) }
if header.hasPrefix("HEAD ") { return "HEAD" }
let head = header.range(of: "...").map { header[..<$0.lowerBound] } ?? Substring(header)
let name = head.split(separator: " ", omittingEmptySubsequences: false).first.map(String.init) ?? ""
let trimmed = name.trimmingCharacters(in: .whitespaces)
return trimmed.isEmpty ? "HEAD" : trimmed
}
/// Push state from a header. `[ahead N]` → (N, true); no `...` upstream → (0, true),
/// because a first push still sends every commit; "No commits yet" or detached → (0, false).
public static func parseAhead(header: String) -> (ahead: Int, canPush: Bool) {
if header.hasPrefix("No commits yet on ") || header.hasPrefix("HEAD ") { return (0, false) }
if let match = header.firstMatch(of: /\[[^\]]*\bahead (\d+)/), let count = Int(match.1) { return (count, true) }
return (0, !header.contains("..."))
}
/// Maps one porcelain column letter to the letter the row shows.
public static func status(for code: Character) -> GitStatus {
switch code {
case "A", "C", "?": .added
case "D": .deleted
case "R": .renamed
default: .modified
}
}
/// A merge conflict. Neither half can be staged on its own, so it stays one row.
public static func isConflict(index: Character, working: Character) -> Bool {
index == "U" || working == "U" || (index == "A" && working == "A") || (index == "D" && working == "D")
}
/// Splits an XY pair into rows: "MM" is a staged row plus an unstaged row, never one folded row.
public static func classify(index: Character, working: Character) -> [GitRowSpec] {
if isConflict(index: index, working: working) { return [GitRowSpec(status: .modified, staged: true)] }
var rows: [GitRowSpec] = []
if index != " " && index != "?" { rows.append(GitRowSpec(status: status(for: index), staged: true)) }
if working != " " { rows.append(GitRowSpec(status: status(for: working), staged: false)) }
return rows.isEmpty ? [GitRowSpec(status: status(for: index), staged: true)] : rows
}
/// The toast line for a push: git reports on stderr, so the summary is pulled from there.
public static func pushSummary(exitCode: Int32, stdout: String, stderr: String) -> PushResult {
let source = stderr.isEmpty ? stdout : stderr
var lines = source.split(whereSeparator: \.isNewline)
.map { $0.trimmingCharacters(in: .whitespaces) }
.filter { !$0.isEmpty }
if exitCode != 0 { return PushResult(ok: false, message: lines.popLast() ?? "push failed") }
let summary = lines.first { line in
line.contains("->") || line.localizedCaseInsensitiveContains("up-to-date")
|| line.localizedCaseInsensitiveContains("new branch")
}
return PushResult(ok: true, message: summary ?? lines.popLast() ?? "Pushed")
}
/// True when a failed `git push` only needs `-u origin <branch>`.
public static func needsUpstream(stderr: String) -> Bool {
stderr.range(of: "no upstream branch|set-upstream", options: [.regularExpression, .caseInsensitive]) != nil
}
}
@@ -0,0 +1,155 @@
import Foundation
/// CSS, and SCSS too: nesting, `$vars` and `//` comments.
enum CSSGrammar {
private enum Context {
case selector, property, value
}
private static let important = Unit.literal("important")
private static let url = Unit.literal("url(")
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
let lineStart = lx.i
var context: Context = st.mode == .cssValue ? .value : statementContext(lx, depth: st.depth)
if st.mode == .cssValue { st.mode = .code }
while lx.i < lx.end {
if st.mode == .blockComment {
if lx.blockComment(from: lx.i, close: Literals.blockClose) { st.mode = .code }
continue
}
if lx.stop != nil && lx.atStop() { return }
let start = lx.i
let c = lx.u[start]
if Unit.isSpace(c) {
lx.i += 1
continue
}
switch c {
case Unit.slash where lx.peek(1) == Unit.star:
lx.i += 2
if !lx.blockComment(from: start, close: Literals.blockClose) { st.mode = .blockComment }
case Unit.slash where lx.peek(1) == Unit.slash && (start == lineStart || Unit.isSpace(lx.unit(at: start - 1))):
lx.lineComment()
case Unit.quote, Unit.apostrophe:
lx.i += 1
_ = lx.quoted(from: start, quote: c)
case Unit.lbrace:
lx.i += 1
st.depth += 1
context = statementContext(lx, depth: st.depth)
case Unit.rbrace:
lx.i += 1
st.depth = max(0, st.depth - 1)
context = statementContext(lx, depth: st.depth)
case Unit.semicolon:
lx.i += 1
context = statementContext(lx, depth: st.depth)
case Unit.at where Unit.isIdentStart(lx.peek(1)):
lx.i += 1
lx.identifier { $0 == Unit.minus }
lx.emit(start, lx.i, .keyword)
context = .value
case Unit.dollar where Unit.isIdentStart(lx.peek(1)):
lx.i += 1
lx.identifier { $0 == Unit.minus }
lx.emit(start, lx.i, .variable)
if lx.nextNonSpace() == Unit.colon { context = .value }
case Unit.bang where lx.startsIgnoringCase(with: important, at: start + 1):
lx.i += 1 + important.count
lx.emit(start, lx.i, .keyword)
default:
switch context {
case .selector: selectorPart(&lx)
case .property:
if Unit.isIdentStart(c) || c == Unit.minus {
lx.identifier { $0 == Unit.minus }
if lx.nextNonSpace() == Unit.colon {
lx.emit(start, lx.i, .variable)
lx.skipSpaces()
lx.i += 1
context = .value
} else {
lx.emit(start, lx.i, .number)
}
} else {
selectorPart(&lx)
}
case .value: valuePart(&lx)
}
}
}
if context == .value && st.depth > 0 && st.mode == .code { st.mode = .cssValue }
}
/// Whether what follows is a selector or a declaration: at the top level always a selector,
/// inside a block a selector only when a `{` comes before any `;` or `}` on the line.
private static func statementContext(_ lx: Lexer, depth: Int) -> Context {
if depth == 0 { return .selector }
var k = lx.i
while k < lx.end {
switch lx.u[k] {
case Unit.lbrace: return .selector
case Unit.semicolon, Unit.rbrace: return .property
default: k += 1
}
}
return .property
}
private static func selectorPart(_ lx: inout Lexer) {
let start = lx.i
let c = lx.u[start]
switch c {
case Unit.colon:
lx.i += 1
if lx.peek() == Unit.colon { lx.i += 1 }
lx.identifier { $0 == Unit.minus }
lx.emit(start, lx.i, .keyword)
case Unit.amp, Unit.greater, Unit.plus, Unit.tilde:
lx.i += 1
lx.emit(start, lx.i, .keyword)
case Unit.lbracket:
while lx.i < lx.end && lx.u[lx.i] != Unit.rbracket { lx.i += 1 }
lx.i = min(lx.i + 1, lx.end)
lx.emit(start, lx.i, .number)
case Unit.dot, Unit.hash, Unit.star, Unit.percent:
lx.i += 1
lx.identifier { $0 == Unit.minus }
lx.emit(start, lx.i, .number)
case _ where Unit.isIdentStart(c) || c == Unit.minus:
lx.identifier { $0 == Unit.minus }
lx.emit(start, lx.i, .number)
default:
lx.i += 1
}
}
private static func valuePart(_ lx: inout Lexer) {
let start = lx.i
let c = lx.u[start]
if c == Unit.hash && Unit.isHexDigit(lx.peek(1)) {
lx.i += 1
lx.identifier()
lx.emit(start, lx.i, .number)
} else if Unit.isDigit(c) || ((c == Unit.dot || c == Unit.minus || c == Unit.plus) && (Unit.isDigit(lx.peek(1)) || (lx.peek(1) == Unit.dot && Unit.isDigit(lx.peek(2))))) {
lx.i += 1
while lx.i < lx.end && (Unit.isDigit(lx.u[lx.i]) || lx.u[lx.i] == Unit.dot) { lx.i += 1 }
if lx.peek() == Unit.percent { lx.i += 1 } else { lx.identifier() }
lx.emit(start, lx.i, .number)
} else if lx.startsIgnoringCase(with: url) {
lx.i += url.count
let body = lx.i
while lx.i < lx.end && lx.u[lx.i] != Unit.rparen { lx.i += 1 }
lx.emit(body, lx.i, .string)
} else if c == Unit.minus && lx.peek(1) == Unit.minus {
lx.identifier { $0 == Unit.minus }
lx.emit(start, lx.i, .variable)
} else if Unit.isIdentStart(c) || c == Unit.minus {
lx.identifier { $0 == Unit.minus }
if lx.peek() != Unit.lparen { lx.emit(start, lx.i, .string) }
} else {
lx.i += 1
}
}
}
@@ -0,0 +1,44 @@
import Foundation
/// JSON with comments allowed, since tsconfig-style files carry them.
enum JSONGrammar {
private static let literals: Set<String> = ["true", "false", "null"]
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
while lx.i < lx.end {
if st.mode == .blockComment {
if lx.blockComment(from: lx.i, close: Literals.blockClose) { st.mode = .code }
continue
}
let start = lx.i
let c = lx.u[start]
switch c {
case Unit.slash where lx.peek(1) == Unit.slash:
lx.lineComment()
case Unit.slash where lx.peek(1) == Unit.star:
lx.i += 2
if !lx.blockComment(from: start, close: Literals.blockClose) { st.mode = .blockComment }
case Unit.quote:
lx.i += 1
var closed = false
while lx.i < lx.end && !closed {
if lx.u[lx.i] == Unit.backslash { lx.i += 1 } else if lx.u[lx.i] == Unit.quote { closed = true }
lx.i += 1
}
lx.i = min(lx.i, lx.end)
lx.emit(start, lx.i, lx.nextNonSpace() == Unit.colon ? .variable : .string)
case _ where Unit.isDigit(c) || (c == Unit.minus && Unit.isDigit(lx.peek(1))):
if c == Unit.minus {
lx.i += 1
lx.emit(start, lx.i, .number)
}
lx.number()
case _ where Unit.isAlpha(c):
lx.identifier()
if literals.contains(lx.text(start, lx.i)) { lx.emit(start, lx.i, .number) }
default:
lx.i += 1
}
}
}
}
@@ -0,0 +1,256 @@
import Foundation
enum JavaScriptGrammar {
static let keywords: Set<String> = [
"as", "async", "await", "break", "case", "catch", "class", "const", "continue", "debugger",
"default", "delete", "do", "else", "enum", "export", "extends", "finally", "for", "from",
"function", "get", "if", "implements", "import", "in", "instanceof", "interface", "let", "new",
"of", "package", "private", "protected", "public", "return", "set", "static", "super", "switch",
"this", "throw", "try", "typeof", "var", "void", "while", "with", "yield",
]
static let typeScriptKeywords: Set<String> = [
"abstract", "declare", "is", "keyof", "module", "namespace", "readonly", "type", "infer",
"satisfies", "override", "unique", "asserts", "accessor",
]
/// Painted as builtins, in the number colour.
static let typeScriptBuiltins: Set<String> = [
"string", "number", "boolean", "any", "void", "never", "unknown", "object", "symbol", "bigint",
]
static let constants: Set<String> = ["true", "false", "null", "undefined", "NaN", "Infinity"]
/// Keywords after which the next name is a class.
private static let classIntroducers: Set<String> = ["class", "extends", "implements", "new", "instanceof", "interface"]
/// Keywords after which a `/` starts a regex rather than a division.
private static let valueKeywords: Set<String> = ["this", "super"]
static func scan(_ lx: inout Lexer, _ st: inout GrammarState, typescript: Bool, jsx: Bool) {
var expectsValue = true
var classNext = false
while lx.i < lx.end {
switch st.mode {
case .blockComment:
if lx.blockComment(from: lx.i, close: Literals.blockClose) { st.mode = .code }
continue
case .template:
template(&lx, &st)
expectsValue = false
continue
case let .jsxTag(level, closing):
jsxTag(&lx, &st, level: level, closing: closing)
expectsValue = true
continue
case let .jsxText(level):
jsxText(&lx, &st, level: level)
expectsValue = true
continue
default:
break
}
if lx.stop != nil && lx.atStop() { return }
let c = lx.u[lx.i]
let start = lx.i
if Unit.isSpace(c) {
lx.i += 1
continue
}
switch c {
case Unit.slash where lx.peek(1) == Unit.slash:
lx.lineComment()
case Unit.slash where lx.peek(1) == Unit.star:
lx.i += 2
if !lx.blockComment(from: start, close: Literals.blockClose) { st.mode = .blockComment }
case Unit.slash where expectsValue && regex(&lx):
expectsValue = false
case Unit.quote, Unit.apostrophe:
lx.i += 1
_ = lx.quoted(from: start, quote: c)
expectsValue = false
case Unit.backtick:
lx.i += 1
lx.emit(start, lx.i, .string)
st.mode = .template
case _ where Unit.isDigit(c) || (c == Unit.dot && Unit.isDigit(lx.peek(1))):
lx.number()
expectsValue = false
case _ where Unit.isIdentStart(c) || c == Unit.dollar || (c == Unit.hash && Unit.isIdentStart(lx.peek(1))):
lx.i += 1
lx.identifier { $0 == Unit.dollar }
let word = lx.text(start, lx.i)
if keywords.contains(word) || (typescript && typeScriptKeywords.contains(word)) {
lx.emit(start, lx.i, .keyword)
classNext = classIntroducers.contains(word)
expectsValue = !valueKeywords.contains(word)
continue
}
if constants.contains(word) || (typescript && typeScriptBuiltins.contains(word)) {
lx.emit(start, lx.i, .number)
} else if classNext {
lx.emit(start, lx.i, .variable)
} else if isConstantName(lx, start, lx.i) {
lx.emit(start, lx.i, .number)
}
classNext = false
expectsValue = false
continue
case Unit.lbrace:
lx.i += 1
if !st.resumes.isEmpty { st.depth += 1 }
expectsValue = true
case Unit.rbrace:
lx.i += 1
if let resume = st.resumes.last, resume.depth == st.depth {
st.resumes.removeLast()
st.mode = resume.mode
} else if !st.resumes.isEmpty {
st.depth -= 1
}
expectsValue = true
case Unit.lparen, Unit.lbracket, Unit.comma, Unit.semicolon:
lx.i += 1
expectsValue = true
case Unit.rparen, Unit.rbracket:
lx.i += 1
expectsValue = false
case Unit.less where jsx && (expectsValue || lx.peek(1) == Unit.slash):
if !openJSX(&lx, &st, level: 0) { lx.operatorRun() }
case Unit.dot:
lx.i += 1
while lx.peek() == Unit.dot { lx.i += 1 }
if lx.i - start > 1 { lx.emit(start, lx.i, .keyword) }
expectsValue = lx.i - start > 1
case _ where Unit.isOperator(c):
lx.operatorRun()
expectsValue = true
default:
lx.i += 1
}
classNext = false
}
}
/// `FOO_BAR`: an all-caps name of two or more characters, painted as a constant.
static func isConstantName(_ lx: Lexer, _ from: Int, _ to: Int) -> Bool {
guard to - from >= 2, Unit.isUpper(lx.u[from]) else { return false }
for k in from..<to where Unit.isLower(lx.u[k]) { return false }
return true
}
/// A regex literal from the `/` at `lx.i`; false (nothing consumed) when the line ends before it closes.
private static func regex(_ lx: inout Lexer) -> Bool {
let start = lx.i
var k = start + 1
var inClass = false
while k < lx.end {
let c = lx.u[k]
if c == Unit.backslash {
k += 2
continue
}
if c == Unit.lbracket { inClass = true }
if c == Unit.rbracket { inClass = false }
if c == Unit.slash && !inClass { break }
k += 1
}
guard k < lx.end, k > start + 1 else { return false }
k += 1
while k < lx.end && Unit.isAlpha(lx.u[k]) { k += 1 }
lx.i = k
lx.emit(start, k, .string)
return true
}
/// Template-literal text up to the closing backtick, a `${`, or the end of the line.
private static func template(_ lx: inout Lexer, _ st: inout GrammarState) {
let start = lx.i
while lx.i < lx.end {
let c = lx.u[lx.i]
if c == Unit.backslash {
lx.i = min(lx.i + 2, lx.end)
continue
}
if c == Unit.backtick {
lx.i += 1
lx.emit(start, lx.i, .string)
st.mode = .code
return
}
if c == Unit.dollar && lx.peek(1) == Unit.lbrace {
lx.emit(start, lx.i, .string)
lx.i += 2
st.resumes.append(Resume(depth: st.depth, mode: .template))
st.mode = .code
return
}
lx.i += 1
}
lx.emit(start, lx.i, .string)
}
/// `<Name`, `</Name`, `<>` or `</>`; false (nothing consumed) for anything else.
private static func openJSX(_ lx: inout Lexer, _ st: inout GrammarState, level: Int) -> Bool {
var k = lx.i + 1
let closing = lx.unit(at: k) == Unit.slash
if closing { k += 1 }
let first = lx.unit(at: k)
if first == Unit.greater {
lx.i = k + 1
st.mode = children(closing ? level - 1 : level + 1)
return true
}
guard Unit.isAlpha(first) else { return false }
let nameStart = k
while k < lx.end && (Unit.isIdentPart(lx.u[k]) || lx.u[k] == Unit.dot || lx.u[k] == Unit.minus || lx.u[k] == Unit.colon) { k += 1 }
lx.emit(nameStart, k, .number)
lx.i = k
st.mode = .jsxTag(level: level, closing: closing)
return true
}
private static func children(_ open: Int) -> Mode {
open > 0 ? .jsxText(level: open) : .code
}
/// Attributes inside a JSX tag, up to `>` or `/>`; a `{` hands over to code until its `}`.
private static func jsxTag(_ lx: inout Lexer, _ st: inout GrammarState, level: Int, closing: Bool) {
while lx.i < lx.end {
let c = lx.u[lx.i]
let start = lx.i
if c == Unit.greater {
lx.i += 1
st.mode = children(closing ? level - 1 : level + 1)
return
} else if c == Unit.slash && lx.peek(1) == Unit.greater {
lx.i += 2
st.mode = children(level)
return
} else if c == Unit.lbrace {
lx.i += 1
st.resumes.append(Resume(depth: st.depth, mode: .jsxTag(level: level, closing: closing)))
st.mode = .code
return
} else if c == Unit.quote || c == Unit.apostrophe {
lx.i += 1
_ = lx.quoted(from: start, quote: c, escapes: false)
} else if Unit.isIdentStart(c) {
lx.identifier { $0 == Unit.minus || $0 == Unit.colon }
lx.emit(start, lx.i, .variable)
} else {
lx.i += 1
}
}
}
/// Children text: plain up to the next tag or `{` expression.
private static func jsxText(_ lx: inout Lexer, _ st: inout GrammarState, level: Int) {
while lx.i < lx.end {
let c = lx.u[lx.i]
if c == Unit.less && openJSX(&lx, &st, level: level) { return }
if c == Unit.lbrace {
lx.i += 1
st.resumes.append(Resume(depth: st.depth, mode: .jsxText(level: level)))
st.mode = .code
return
}
lx.i += 1
}
}
}
+206
View File
@@ -0,0 +1,206 @@
import Foundation
/// Where an embedded grammar hands control back to its host.
enum Terminator: Hashable, Sendable {
/// `?>` closes a PHP island inside markup.
case phpClose
/// `</name` closes a `<script>` or `<style>` body; the name is lowercase.
case closingTag(String)
/// A Markdown fence closes on a line of its own, which the Markdown grammar checks itself.
case fence
}
/// A cursor over UTF-16 units that collects non-plain tokens for one line at a time.
///
/// Grammars scan `i..<end` and must return when `i` reaches `end`, or when `atStop()`
/// is true at a code position, so the host grammar can take over.
struct Lexer {
let u: [UInt16]
var i: Int
var end: Int
var stop: Terminator?
let symbols: Set<String>
private(set) var tokens: [Token] = []
init(units: [UInt16], symbols: Set<String>) {
u = units
i = 0
end = units.count
self.symbols = symbols
}
/// The unit `k` places ahead, or 0 past the end of the line.
@inline(__always) func peek(_ k: Int = 0) -> UInt16 {
let j = i + k
return j < end ? u[j] : 0
}
func unit(at j: Int) -> UInt16 {
j >= 0 && j < end ? u[j] : 0
}
mutating func emit(_ from: Int, _ to: Int, _ role: TokenRole) {
guard to > from, role != .plain else { return }
if let last = tokens.last, last.role == role, last.location + last.length == from {
tokens[tokens.count - 1].length += to - from
} else {
tokens.append(Token(location: from, length: to - from, role: role))
}
}
func text(_ from: Int, _ to: Int) -> String {
String(decoding: u[from..<to], as: UTF16.self)
}
func starts(with literal: [UInt16], at j: Int? = nil) -> Bool {
let at = j ?? i
guard at + literal.count <= end else { return false }
for k in literal.indices where u[at + k] != literal[k] { return false }
return true
}
/// ASCII case-insensitive `starts(with:)`; `literal` must be lowercase.
func startsIgnoringCase(with literal: [UInt16], at j: Int? = nil) -> Bool {
let at = j ?? i
guard at + literal.count <= end else { return false }
for k in literal.indices where Unit.lower(u[at + k]) != literal[k] { return false }
return true
}
func atStop() -> Bool {
switch stop {
case .phpClose: return peek() == Unit.question && peek(1) == Unit.greater
case let .closingTag(name):
guard peek() == Unit.less, peek(1) == Unit.slash else { return false }
return startsIgnoringCase(with: Array(name.utf16), at: i + 2)
case .fence, nil: return false
}
}
mutating func skipSpaces() {
while i < end && Unit.isSpace(u[i]) { i += 1 }
}
/// The first non-space unit from `j` on, or 0.
func nextNonSpace(from j: Int? = nil) -> UInt16 {
var k = j ?? i
while k < end && Unit.isSpace(u[k]) { k += 1 }
return k < end ? u[k] : 0
}
mutating func identifier(extra: (UInt16) -> Bool = { _ in false }) {
while i < end && (Unit.isIdentPart(u[i]) || extra(u[i])) { i += 1 }
}
/// A comment to the end of the line, or to the stop marker a PHP `?>` or `</script` sets.
mutating func lineComment() {
let start = i
if stop == nil {
i = end
} else {
while i < end && !atStop() { i += 1 }
}
emit(start, i, .comment)
}
/// Consumes up to and including `close`; returns false when the line ends first.
mutating func blockComment(from start: Int, close: [UInt16]) -> Bool {
while i < end {
if starts(with: close) {
i += close.count
emit(start, i, .comment)
return true
}
i += 1
}
emit(start, i, .comment)
return false
}
/// A string body up to the closing `quote`, with backslash escapes; false when the line ends first.
mutating func quoted(from start: Int, quote: UInt16, escapes: Bool = true, role: TokenRole = .string) -> Bool {
while i < end {
let c = u[i]
if escapes && c == Unit.backslash {
i += 2
continue
}
i += 1
if c == quote {
emit(start, i, role)
return true
}
}
i = min(i, end)
emit(start, i, role)
return false
}
/// A numeric literal: hex/octal/binary prefixes, `_` separators, fraction, exponent and a letter suffix.
mutating func number() {
let start = i
if peek() == Unit.zero && Unit.isAlpha(peek(1)) && "xXoObB".utf16.contains(peek(1)) {
i += 2
while i < end && (Unit.isHexDigit(u[i]) || u[i] == Unit.underscore) { i += 1 }
} else {
while i < end && (Unit.isDigit(u[i]) || u[i] == Unit.underscore) { i += 1 }
if peek() == Unit.dot && Unit.isDigit(peek(1)) {
i += 1
while i < end && (Unit.isDigit(u[i]) || u[i] == Unit.underscore) { i += 1 }
}
if (peek() == Unit.lowerE || peek() == Unit.upperE)
&& (Unit.isDigit(peek(1)) || ((peek(1) == Unit.plus || peek(1) == Unit.minus) && Unit.isDigit(peek(2)))) {
i += 2
while i < end && Unit.isDigit(u[i]) { i += 1 }
}
}
while i < end && Unit.isAlpha(u[i]) { i += 1 }
emit(start, i, .number)
}
/// Consumes a run of operator characters and paints it as a keyword.
mutating func operatorRun(_ isOperator: (UInt16) -> Bool = Unit.isOperator) {
let start = i
while i < end && isOperator(u[i]) { i += 1 }
emit(start, i, .keyword)
}
}
enum Literals {
static let blockClose = Unit.literal("*/")
static let heredoc = Unit.literal("<<<")
}
/// UTF-16 character classes. Every unit at or above 0x80 counts as an identifier letter,
/// which keeps surrogate pairs and non-ASCII names in one token.
enum Unit {
static let tab: UInt16 = 9, space: UInt16 = 32, bang: UInt16 = 33, quote: UInt16 = 34
static let hash: UInt16 = 35, dollar: UInt16 = 36, percent: UInt16 = 37, amp: UInt16 = 38
static let apostrophe: UInt16 = 39, lparen: UInt16 = 40, rparen: UInt16 = 41, star: UInt16 = 42
static let plus: UInt16 = 43, comma: UInt16 = 44, minus: UInt16 = 45, dot: UInt16 = 46
static let slash: UInt16 = 47, zero: UInt16 = 48, colon: UInt16 = 58, semicolon: UInt16 = 59
static let less: UInt16 = 60, equals: UInt16 = 61, greater: UInt16 = 62, question: UInt16 = 63
static let at: UInt16 = 64, upperE: UInt16 = 69, lbracket: UInt16 = 91, backslash: UInt16 = 92
static let rbracket: UInt16 = 93, caret: UInt16 = 94, underscore: UInt16 = 95, backtick: UInt16 = 96
static let lowerE: UInt16 = 101, lbrace: UInt16 = 123, pipe: UInt16 = 124, rbrace: UInt16 = 125
static let tilde: UInt16 = 126
@inline(__always) static func isDigit(_ c: UInt16) -> Bool { c &- 48 < 10 }
@inline(__always) static func isUpper(_ c: UInt16) -> Bool { c &- 65 < 26 }
@inline(__always) static func isLower(_ c: UInt16) -> Bool { c &- 97 < 26 }
@inline(__always) static func isAlpha(_ c: UInt16) -> Bool { isUpper(c) || isLower(c) }
@inline(__always) static func isHexDigit(_ c: UInt16) -> Bool { isDigit(c) || (c | 0x20) &- 97 < 6 }
@inline(__always) static func isIdentStart(_ c: UInt16) -> Bool { isAlpha(c) || c == underscore || c >= 0x80 }
@inline(__always) static func isIdentPart(_ c: UInt16) -> Bool { isIdentStart(c) || isDigit(c) }
@inline(__always) static func isSpace(_ c: UInt16) -> Bool { c == space || c == tab || c == 13 || c == 12 || c == 11 }
@inline(__always) static func lower(_ c: UInt16) -> UInt16 { isUpper(c) ? c + 32 : c }
static func isOperator(_ c: UInt16) -> Bool {
switch c {
case plus, minus, star, slash, percent, equals, amp, pipe, caret, bang, tilde, less, greater, question, colon: true
default: false
}
}
static func literal(_ text: String) -> [UInt16] { Array(text.utf16) }
}
@@ -0,0 +1,156 @@
import Foundation
/// Markdown, with fenced code in a known language highlighted by that language.
enum MarkdownGrammar {
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
let lineStart = lx.i
if case let .fence(marker, count) = st.mode {
fencedLine(&lx, &st, marker: marker, count: count)
return
}
lx.skipSpaces()
let c = lx.peek()
if (c == Unit.backtick || c == Unit.tilde), let count = run(lx, of: c), count >= 3 {
let info = lx.text(lx.i + count, lx.end).trimmingCharacters(in: .whitespaces)
let word = String(info.prefix { !$0.isWhitespace })
lx.i = lx.end
lx.emit(lineStart, lx.end, .comment)
st.mode = .fence(marker: c, count: count)
if let grammar = Grammar(MarkdownParser.fenceLanguage(word), text: "") {
st.child = .grammar(grammar, GrammarState(), until: .fence)
}
return
}
if c == Unit.hash, let count = run(lx, of: c), count <= 6, lx.unit(at: lx.i + count) == 0 || Unit.isSpace(lx.unit(at: lx.i + count)) {
lx.i = lx.end
lx.emit(lineStart, lx.end, .keyword)
return
}
if isRule(lx) {
lx.i = lx.end
lx.emit(lineStart, lx.end, .comment)
return
}
while lx.peek() == Unit.greater {
lx.emit(lx.i, lx.i + 1, .comment)
lx.i += 1
lx.skipSpaces()
}
listMarker(&lx)
inline(&lx)
}
private static func fencedLine(_ lx: inout Lexer, _ st: inout GrammarState, marker: UInt16, count: Int) {
let lineStart = lx.i
var k = lineStart
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
var closing = k
while closing < lx.end && lx.u[closing] == marker { closing += 1 }
var rest = closing
while rest < lx.end && Unit.isSpace(lx.u[rest]) { rest += 1 }
if closing - k >= count && rest == lx.end {
lx.i = lx.end
lx.emit(lineStart, lx.end, .comment)
st.mode = .code
st.child = nil
return
}
if case let .grammar(grammar, inner, _)? = st.child {
var state = inner
Grammars.scan(grammar, &lx, &state)
st.child = .grammar(grammar, state, until: .fence)
}
lx.i = lx.end
}
/// How many `c` in a row start at the cursor.
private static func run(_ lx: Lexer, of c: UInt16) -> Int? {
var k = lx.i
while k < lx.end && lx.u[k] == c { k += 1 }
return k - lx.i
}
/// Three or more of one of `-`, `*`, `_`, spaces allowed between them.
private static func isRule(_ lx: Lexer) -> Bool {
let first = lx.peek()
guard first == Unit.minus || first == Unit.star || first == Unit.underscore else { return false }
var marks = 0
for k in lx.i..<lx.end {
if lx.u[k] == first {
marks += 1
} else if !Unit.isSpace(lx.u[k]) {
return false
}
}
return marks >= 3
}
/// `-`, `*`, `+` or `1.`/`1)` followed by a space.
private static func listMarker(_ lx: inout Lexer) {
var k = lx.i
let c = lx.peek()
if c == Unit.minus || c == Unit.star || c == Unit.plus {
k += 1
} else {
while k < lx.end && Unit.isDigit(lx.u[k]) { k += 1 }
guard k > lx.i, lx.unit(at: k) == Unit.dot || lx.unit(at: k) == Unit.rparen else { return }
k += 1
}
guard Unit.isSpace(lx.unit(at: k)) else { return }
lx.emit(lx.i, k, .comment)
lx.i = k
}
/// Code spans, link targets and autolinks in running text.
private static func inline(_ lx: inout Lexer) {
while lx.i < lx.end {
let start = lx.i
let c = lx.u[start]
if c == Unit.backslash {
lx.i = min(lx.i + 2, lx.end)
} else if c == Unit.backtick {
let ticks = run(lx, of: c) ?? 1
if let close = findRun(lx, of: c, count: ticks, from: start + ticks) {
lx.i = close + ticks
lx.emit(start, lx.i, .keyword)
} else {
lx.i += ticks
}
} else if c == Unit.rbracket && lx.peek(1) == Unit.lparen {
lx.i += 1
let open = lx.i
while lx.i < lx.end && lx.u[lx.i] != Unit.rparen { lx.i += 1 }
lx.i = min(lx.i + 1, lx.end)
lx.emit(open, lx.i, .variable)
} else if c == Unit.less && Unit.isAlpha(lx.peek(1)) {
var k = start + 1
while k < lx.end && lx.u[k] != Unit.greater && !Unit.isSpace(lx.u[k]) { k += 1 }
if lx.unit(at: k) == Unit.greater && lx.text(start + 1, k).contains(":") {
lx.i = k + 1
lx.emit(start, lx.i, .variable)
} else {
lx.i += 1
}
} else {
lx.i += 1
}
}
}
/// The start of the next run of exactly `count` × `c` from `from`, or nil.
private static func findRun(_ lx: Lexer, of c: UInt16, count: Int, from: Int) -> Int? {
var k = from
while k < lx.end {
if lx.u[k] == c {
var e = k
while e < lx.end && lx.u[e] == c { e += 1 }
if e - k == count { return k }
k = e
} else {
k += 1
}
}
return nil
}
}
@@ -0,0 +1,155 @@
import Foundation
/// HTML, XML, SVG and Vue, plus the markup around `<?php` blocks in PHP files.
enum MarkupGrammar {
private static let commentOpen = Unit.literal("<!--")
private static let commentClose = Unit.literal("-->")
private static let cdataOpen = Unit.literal("<![cdata[")
private static let cdataClose = Unit.literal("]]>")
private static let phpOpenTags = [Unit.literal("<?php"), Unit.literal("<?="), Unit.literal("<?")]
static func scan(_ lx: inout Lexer, _ st: inout GrammarState, phpIslands: Bool) {
while lx.i < lx.end {
switch st.mode {
case .markupComment:
if lx.blockComment(from: lx.i, close: commentClose) { st.mode = .code }
continue
case .cdata:
if lx.blockComment(from: lx.i, close: cdataClose) { st.mode = .code }
continue
case let .markupTag(name):
tag(&lx, &st, name: name, phpIslands: phpIslands)
if st.child != nil { return }
continue
case let .markupValue(quote, name):
value(&lx, &st, quote: quote, tag: name, from: lx.i, phpIslands: phpIslands)
if st.child != nil { return }
continue
default:
break
}
if lx.stop != nil && lx.atStop() { return }
if phpIslands && openIsland(&lx, &st) { return }
let start = lx.i
let c = lx.u[start]
if c == Unit.less {
openTag(&lx, &st)
} else if c == Unit.amp {
lx.i += 1
while lx.i < lx.end && (Unit.isIdentPart(lx.u[lx.i]) || lx.u[lx.i] == Unit.hash) { lx.i += 1 }
if lx.peek() == Unit.semicolon && lx.i > start + 1 {
lx.i += 1
lx.emit(start, lx.i, .variable)
}
} else {
lx.i += 1
while lx.i < lx.end && lx.u[lx.i] != Unit.less && lx.u[lx.i] != Unit.amp { lx.i += 1 }
}
}
}
/// Everything that starts with `<` in text: comments, CDATA, doctype, prolog and tags.
private static func openTag(_ lx: inout Lexer, _ st: inout GrammarState) {
let start = lx.i
if lx.starts(with: commentOpen) {
lx.i += commentOpen.count
if !lx.blockComment(from: start, close: commentClose) { st.mode = .markupComment }
return
}
if lx.startsIgnoringCase(with: cdataOpen) {
lx.i += cdataOpen.count
if !lx.blockComment(from: start, close: cdataClose) { st.mode = .cdata }
return
}
let next = lx.peek(1)
if next == Unit.bang || next == Unit.question {
let close = next == Unit.bang ? [Unit.greater] : [Unit.question, Unit.greater]
lx.i += 2
_ = lx.blockComment(from: start, close: close)
return
}
var k = start + 1
let closing = lx.unit(at: k) == Unit.slash
if closing { k += 1 }
guard Unit.isAlpha(lx.unit(at: k)) else {
lx.i += 1
return
}
let nameStart = k
while k < lx.end && (Unit.isIdentPart(lx.u[k]) || lx.u[k] == Unit.minus || lx.u[k] == Unit.colon || lx.u[k] == Unit.dot) { k += 1 }
lx.emit(nameStart, k, .number)
let name = lx.text(nameStart, k).lowercased()
lx.i = k
st.mode = .markupTag(closing ? "/" + name : name)
}
/// Attributes up to `>`; a `>` that closes `<script>` or `<style>` hands the body to JavaScript or CSS.
private static func tag(_ lx: inout Lexer, _ st: inout GrammarState, name: String, phpIslands: Bool) {
while lx.i < lx.end {
if phpIslands && openIsland(&lx, &st) { return }
let start = lx.i
let c = lx.u[start]
if Unit.isSpace(c) || c == Unit.equals {
lx.i += 1
} else if c == Unit.greater {
lx.i += 1
st.mode = .code
switch name {
case "script": st.child = .grammar(.javascript(typescript: false, jsx: false), GrammarState(), until: .closingTag("script"))
case "style": st.child = .grammar(.css, GrammarState(), until: .closingTag("style"))
default: break
}
return
} else if c == Unit.slash && lx.peek(1) == Unit.greater {
lx.i += 2
st.mode = .code
return
} else if c == Unit.quote || c == Unit.apostrophe {
lx.i += 1
value(&lx, &st, quote: c, tag: name, from: start, phpIslands: phpIslands)
if st.child != nil || st.mode != .markupTag(name) { return }
} else if c == Unit.slash {
lx.i += 1
} else {
while lx.i < lx.end && !isAttributeEnd(lx.u[lx.i]) { lx.i += 1 }
lx.emit(start, lx.i, lx.unit(at: start - 1) == Unit.equals ? .string : .variable)
}
}
}
private static func isAttributeEnd(_ c: UInt16) -> Bool {
Unit.isSpace(c) || c == Unit.equals || c == Unit.greater || c == Unit.slash || c == Unit.quote || c == Unit.apostrophe
}
/// A quoted attribute value; it may run over lines and may hold a PHP island.
private static func value(_ lx: inout Lexer, _ st: inout GrammarState, quote: UInt16, tag: String, from start: Int, phpIslands: Bool) {
while lx.i < lx.end {
if phpIslands && lx.peek() == Unit.less && lx.peek(1) == Unit.question {
lx.emit(start, lx.i, .string)
st.mode = .markupValue(quote: quote, tag: tag)
_ = openIsland(&lx, &st)
return
}
if lx.u[lx.i] == quote {
lx.i += 1
lx.emit(start, lx.i, .string)
st.mode = .markupTag(tag)
return
}
lx.i += 1
}
lx.emit(start, lx.i, .string)
st.mode = .markupValue(quote: quote, tag: tag)
}
/// `<?php`, `<?=` or `<?` starts a PHP island that runs until `?>`.
private static func openIsland(_ lx: inout Lexer, _ st: inout GrammarState) -> Bool {
guard lx.peek() == Unit.less, lx.peek(1) == Unit.question else { return false }
let start = lx.i
let open = phpOpenTags.first { lx.startsIgnoringCase(with: $0) } ?? phpOpenTags[2]
lx.i += open.count
lx.emit(start, lx.i, .keyword)
st.child = .grammar(.php, GrammarState(), until: .phpClose)
return true
}
}
@@ -0,0 +1,265 @@
import Foundation
enum PHPGrammar {
/// Matched lowercase: PHP keywords are case-insensitive.
static let keywords: Set<String> = [
"abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const",
"continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare",
"endfor", "endforeach", "endif", "endswitch", "endwhile", "enum", "eval", "exit", "extends",
"final", "finally", "fn", "for", "foreach", "from", "function", "global", "goto", "if",
"implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list",
"match", "namespace", "new", "or", "parent", "print", "private", "protected", "public", "readonly",
"require", "require_once", "return", "self", "static", "switch", "throw", "trait", "try", "unset",
"use", "var", "while", "xor", "yield",
"int", "float", "string", "bool", "void", "mixed", "never", "iterable", "object",
]
static let constants: Set<String> = ["true", "false", "null"]
/// Keywords after which the next name is a class.
private static let classIntroducers: Set<String> = [
"class", "interface", "trait", "enum", "extends", "implements", "instanceof", "insteadof", "new",
]
private static let scopeKeywords: Set<String> = ["self", "static", "parent"]
private static let openTags = [Unit.literal("<?php"), Unit.literal("<?="), Unit.literal("<?")]
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
var classNext = false
var namespaceNext = false
var afterArrow = false
var afterDoubleColon = false
while lx.i < lx.end {
switch st.mode {
case .blockComment:
if lx.blockComment(from: lx.i, close: Literals.blockClose) { st.mode = .code }
continue
case let .quoted(quote):
if interpolated(&lx, from: lx.i, close: quote, interpolates: quote != Unit.apostrophe) { st.mode = .code }
continue
case let .heredoc(id, interpolates):
heredocLine(&lx, &st, id: id, interpolates: interpolates)
continue
default:
break
}
if lx.stop != nil && lx.atStop() { return }
let c = lx.u[lx.i]
let start = lx.i
if Unit.isSpace(c) {
lx.i += 1
continue
}
switch c {
case Unit.hash where lx.peek(1) == Unit.lbracket:
lx.i += 2
classNext = true
continue
case Unit.hash:
lx.lineComment()
case Unit.slash where lx.peek(1) == Unit.slash:
lx.lineComment()
case Unit.slash where lx.peek(1) == Unit.star:
lx.i += 2
if !lx.blockComment(from: start, close: Literals.blockClose) { st.mode = .blockComment }
case Unit.apostrophe, Unit.quote, Unit.backtick:
lx.i += 1
if !interpolated(&lx, from: start, close: c, interpolates: c != Unit.apostrophe) { st.mode = .quoted(c) }
case Unit.less where lx.starts(with: Literals.heredoc):
heredocStart(&lx, &st)
case Unit.less where lx.peek(1) == Unit.question:
let tag = openTags.first { lx.startsIgnoringCase(with: $0) } ?? openTags[2]
lx.i += tag.count
lx.emit(start, lx.i, .keyword)
case Unit.question where lx.peek(1) == Unit.greater:
lx.i += 2
lx.emit(start, lx.i, .keyword)
case Unit.dollar where Unit.isIdentStart(lx.peek(1)) || lx.peek(1) == Unit.dollar:
while lx.peek() == Unit.dollar { lx.i += 1 }
lx.identifier()
lx.emit(start, lx.i, .variable)
case _ where Unit.isDigit(c) || (c == Unit.dot && Unit.isDigit(lx.peek(1))):
lx.number()
case Unit.minus where lx.peek(1) == Unit.greater, Unit.question where lx.peek(1) == Unit.minus && lx.peek(2) == Unit.greater:
lx.i += c == Unit.question ? 3 : 2
lx.emit(start, lx.i, .keyword)
afterArrow = true
continue
case Unit.colon where lx.peek(1) == Unit.colon:
lx.i += 2
lx.emit(start, lx.i, .keyword)
afterDoubleColon = true
continue
case _ where Unit.isIdentStart(c) || (c == Unit.backslash && Unit.isIdentStart(lx.peek(1))):
name(&lx, classNext: &classNext, namespaceNext: &namespaceNext, afterArrow: afterArrow, afterDoubleColon: afterDoubleColon)
case _ where Unit.isOperator(c) || c == Unit.dot || c == Unit.at:
lx.operatorRun { Unit.isOperator($0) || $0 == Unit.dot || $0 == Unit.at }
default:
lx.i += 1
}
afterArrow = false
afterDoubleColon = false
}
}
/// A name, possibly qualified (`\App\Models\Agent`): the namespace path reads as a string,
/// the last segment as a keyword, class, constant or function.
private static func name(_ lx: inout Lexer, classNext: inout Bool, namespaceNext: inout Bool, afterArrow: Bool, afterDoubleColon: Bool) {
let start = lx.i
var lastSegment = start
while lx.i < lx.end {
if lx.u[lx.i] == Unit.backslash && Unit.isIdentStart(lx.peek(1)) {
lx.i += 1
lastSegment = lx.i
} else if Unit.isIdentPart(lx.u[lx.i]) {
lx.i += 1
} else {
break
}
}
if lx.peek() == Unit.backslash {
// A group import, `use App\Models\{A, B}`: the whole prefix is a path.
lx.i += 1
lx.emit(start, lx.i, .string)
return
}
let end = lx.i
let qualified = lastSegment > start
if namespaceNext {
namespaceNext = false
lx.emit(start, end, .string)
return
}
lx.emit(start, lastSegment, .string)
let word = lx.text(lastSegment, end)
let next = lx.nextNonSpace()
let callsNext = next == Unit.lparen
if afterArrow {
lx.emit(lastSegment, end, callsNext ? .plain : .variable)
return
}
if afterDoubleColon {
let lower = word.lowercased()
if lower == "class" {
lx.emit(lastSegment, end, .keyword)
} else if !callsNext && JavaScriptGrammar.isConstantName(lx, lastSegment, end) {
lx.emit(lastSegment, end, .number)
}
return
}
if !qualified {
let lower = word.lowercased()
if constants.contains(lower) {
lx.emit(lastSegment, end, .number)
return
}
if scopeKeywords.contains(lower) {
lx.emit(lastSegment, end, .keyword)
return
}
if keywords.contains(lower) && !(lx.peek() == Unit.colon && lx.peek(1) == Unit.colon) {
lx.emit(lastSegment, end, .keyword)
classNext = classIntroducers.contains(lower)
namespaceNext = lower == "namespace"
return
}
}
let followedByScope = lx.peek() == Unit.colon && lx.peek(1) == Unit.colon
let isConstant = JavaScriptGrammar.isConstantName(lx, lastSegment, end)
let looksLikeClass = Unit.isUpper(lx.u[lastSegment]) && !isConstant && !callsNext
if classNext || followedByScope || looksLikeClass {
lx.emit(lastSegment, end, lx.symbols.contains(word) ? .symbol : .variable)
} else if isConstant && !callsNext {
lx.emit(lastSegment, end, .number)
}
classNext = false
}
/// A string body with `$var`, `$var->prop` and `{$…}` interpolation; false when the line ends first.
/// With `close` 0 it runs to the end of the line, for heredoc bodies.
static func interpolated(_ lx: inout Lexer, from start: Int, close: UInt16, interpolates: Bool) -> Bool {
var runStart = start
while lx.i < lx.end {
let c = lx.u[lx.i]
if c == Unit.backslash && close != 0 {
lx.i = min(lx.i + 2, lx.end)
continue
}
if c == close {
lx.i += 1
lx.emit(runStart, lx.i, .string)
return true
}
if interpolates && c == Unit.dollar && Unit.isIdentStart(lx.peek(1)) {
lx.emit(runStart, lx.i, .string)
let varStart = lx.i
lx.i += 1
lx.identifier()
if lx.peek() == Unit.minus && lx.peek(1) == Unit.greater && Unit.isIdentStart(lx.peek(2)) {
lx.i += 2
lx.identifier()
}
lx.emit(varStart, lx.i, .variable)
runStart = lx.i
continue
}
if interpolates && c == Unit.lbrace && lx.peek(1) == Unit.dollar {
lx.emit(runStart, lx.i, .string)
let varStart = lx.i
var depth = 0
while lx.i < lx.end {
if lx.u[lx.i] == Unit.lbrace { depth += 1 }
if lx.u[lx.i] == Unit.rbrace {
depth -= 1
if depth == 0 {
lx.i += 1
break
}
}
lx.i += 1
}
lx.emit(varStart, lx.i, .variable)
runStart = lx.i
continue
}
lx.i += 1
}
lx.emit(runStart, lx.i, .string)
return false
}
/// `<<<ID`, `<<<"ID"` or `<<<'ID'` (nowdoc): the rest of the line and every line up to the marker.
private static func heredocStart(_ lx: inout Lexer, _ st: inout GrammarState) {
let start = lx.i
var k = start + 3
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
let quote = lx.unit(at: k)
let quoted = quote == Unit.apostrophe || quote == Unit.quote
if quoted { k += 1 }
let idStart = k
while k < lx.end && Unit.isIdentPart(lx.u[k]) { k += 1 }
guard k > idStart else {
lx.i = start + 3
lx.emit(start, lx.i, .keyword)
return
}
let id = lx.text(idStart, k)
if quoted && lx.unit(at: k) == quote { k += 1 }
lx.i = k
lx.emit(start, k, .string)
st.mode = .heredoc(id: id, interpolates: quote != Unit.apostrophe)
}
/// One heredoc body line; the closing marker may be indented and followed by code.
private static func heredocLine(_ lx: inout Lexer, _ st: inout GrammarState, id: String, interpolates: Bool) {
let start = lx.i
var k = start
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
let marker = Array(id.utf16)
if lx.starts(with: marker, at: k) && !Unit.isIdentPart(lx.unit(at: k + marker.count)) {
lx.i = k + marker.count
lx.emit(start, lx.i, .string)
st.mode = .code
return
}
_ = interpolated(&lx, from: start, close: 0, interpolates: interpolates)
}
}
@@ -0,0 +1,109 @@
import Foundation
enum PythonGrammar {
static let keywords: Set<String> = [
"and", "as", "assert", "async", "await", "break", "case", "class", "continue", "def", "del",
"elif", "else", "except", "exec", "finally", "for", "from", "global", "if", "import", "in", "is",
"lambda", "match", "nonlocal", "not", "or", "pass", "print", "raise", "return", "try", "while",
"with", "yield",
]
/// Builtins and the three constants, painted in the number colour.
static let builtins: Set<String> = [
"True", "False", "None", "abs", "all", "any", "ascii", "bin", "bool", "bytearray", "bytes",
"callable", "chr", "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod",
"enumerate", "eval", "filter", "float", "format", "frozenset", "getattr", "globals", "hasattr",
"hash", "help", "hex", "id", "input", "int", "isinstance", "issubclass", "iter", "len", "list",
"locals", "map", "max", "memoryview", "min", "next", "object", "oct", "open", "ord", "pow",
"property", "range", "repr", "reversed", "round", "set", "setattr", "slice", "sorted",
"staticmethod", "str", "sum", "super", "tuple", "type", "vars", "zip", "__import__",
]
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
var classNext = false
while lx.i < lx.end {
if case let .triple(quote) = st.mode {
if triple(&lx, from: lx.i, quote: quote) { st.mode = .code }
continue
}
let start = lx.i
let c = lx.u[start]
if Unit.isSpace(c) {
lx.i += 1
continue
}
if let quote = stringQuote(lx) {
lx.i = quote.bodyStart
if quote.isTriple {
if !triple(&lx, from: start, quote: quote.unit) { st.mode = .triple(quote.unit) }
} else {
_ = lx.quoted(from: start, quote: quote.unit)
}
classNext = false
continue
}
switch c {
case Unit.hash:
lx.lineComment()
case Unit.at where Unit.isIdentStart(lx.peek(1)) && isLineStart(lx, start):
lx.i += 1
lx.identifier { $0 == Unit.dot }
lx.emit(start, lx.i, .keyword)
case _ where Unit.isDigit(c) || (c == Unit.dot && Unit.isDigit(lx.peek(1))):
lx.number()
case _ where Unit.isIdentStart(c):
lx.identifier()
let word = lx.text(start, lx.i)
if keywords.contains(word) {
lx.emit(start, lx.i, .keyword)
classNext = word == "class"
continue
}
if classNext {
lx.emit(start, lx.i, .variable)
} else if builtins.contains(word) {
lx.emit(start, lx.i, .number)
}
case _ where Unit.isOperator(c) && c != Unit.colon:
lx.operatorRun { Unit.isOperator($0) && $0 != Unit.colon }
default:
lx.i += 1
}
classNext = false
}
}
private static func isLineStart(_ lx: Lexer, _ j: Int) -> Bool {
var k = j - 1
while k >= 0 && Unit.isSpace(lx.u[k]) { k -= 1 }
return k < 0 || lx.u[k] == 10
}
/// A string opener at the cursor, with its `r`/`b`/`f`/`u` prefix.
private static func stringQuote(_ lx: Lexer) -> (unit: UInt16, isTriple: Bool, bodyStart: Int)? {
var k = lx.i
while k - lx.i < 2 && k < lx.end && "rRbBuUfF".utf16.contains(lx.u[k]) { k += 1 }
if k > lx.i && Unit.isIdentPart(lx.unit(at: lx.i - 1)) { return nil }
let q = lx.unit(at: k)
guard q == Unit.quote || q == Unit.apostrophe else { return nil }
if lx.unit(at: k + 1) == q && lx.unit(at: k + 2) == q { return (q, true, k + 3) }
return (q, false, k + 1)
}
/// A triple-quoted body up to its closing three quotes; false when the line ends first.
private static func triple(_ lx: inout Lexer, from start: Int, quote: UInt16) -> Bool {
while lx.i < lx.end {
if lx.u[lx.i] == Unit.backslash {
lx.i = min(lx.i + 2, lx.end)
continue
}
if lx.u[lx.i] == quote && lx.peek(1) == quote && lx.peek(2) == quote {
lx.i += 3
lx.emit(start, lx.i, .string)
return true
}
lx.i += 1
}
lx.emit(start, lx.i, .string)
return false
}
}
@@ -0,0 +1,187 @@
import Foundation
/// Shell scripts, and `.env` files.
enum ShellGrammar {
static let keywords: Set<String> = [
"if", "then", "else", "elif", "fi", "for", "while", "until", "do", "done", "case", "esac", "in",
"function", "select", "time", "return", "local", "export", "readonly", "declare", "unset", "shift",
"break", "continue", "exit", "source", "alias", "typeset", "let", "eval",
]
/// Painted in the number colour.
static let builtins: Set<String> = [
"echo", "cd", "pwd", "printf", "read", "test", "set", "trap", "wait", "kill", "exec", "true",
"false", "type", "hash", "getopts", "umask", "ulimit", "command", "builtin", "jobs", "fg", "bg",
"pushd", "popd", "dirs", "history", "shopt", "mapfile",
]
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
let lineStart = lx.i
while lx.i < lx.end {
switch st.mode {
case let .quoted(quote):
if string(&lx, from: lx.i, quote: quote) { st.mode = .code }
continue
case let .heredoc(id, interpolates):
heredocLine(&lx, &st, id: id, interpolates: interpolates)
continue
default:
break
}
let start = lx.i
let c = lx.u[start]
if Unit.isSpace(c) {
lx.i += 1
continue
}
switch c {
case Unit.hash where start == lineStart || isWordBreak(lx.unit(at: start - 1)):
lx.lineComment()
case Unit.apostrophe, Unit.quote:
lx.i += 1
if !string(&lx, from: start, quote: c) { st.mode = .quoted(c) }
case Unit.dollar:
variable(&lx)
case Unit.less where lx.peek(1) == Unit.less && lx.peek(2) != Unit.less:
heredocStart(&lx, &st)
case _ where isOperator(c):
lx.operatorRun(isOperator)
case _ where isWordBreak(c):
lx.i += 1
default:
word(&lx, atCommandStart: start == lineStart || isWordBreak(lx.unit(at: start - 1)))
}
}
}
private static func isOperator(_ c: UInt16) -> Bool {
c == Unit.less || c == Unit.greater || c == Unit.equals || c == Unit.bang || c == Unit.amp || c == Unit.pipe
}
private static func isWordBreak(_ c: UInt16) -> Bool {
switch c {
case Unit.space, Unit.tab, Unit.pipe, Unit.amp, Unit.semicolon, Unit.lparen, Unit.rparen,
Unit.less, Unit.greater, Unit.lbrace, Unit.rbrace, Unit.backtick, 13: true
default: false
}
}
/// One shell word: `NAME=` assigns, a bare keyword or builtin is coloured, digits are a number.
private static func word(_ lx: inout Lexer, atCommandStart: Bool) {
let start = lx.i
while lx.i < lx.end && Unit.isIdentPart(lx.u[lx.i]) { lx.i += 1 }
let identEnd = lx.i
if identEnd > start && atCommandStart && lx.peek() == Unit.equals && !Unit.isDigit(lx.u[start]) {
lx.emit(start, identEnd, .variable)
return
}
while lx.i < lx.end && !isWordBreak(lx.u[lx.i]) && !isQuoteOrDollar(lx.u[lx.i]) { lx.i += 1 }
guard lx.i == identEnd, identEnd > start else {
if lx.i == start { lx.i += 1 }
return
}
let text = lx.text(start, identEnd)
if keywords.contains(text) {
lx.emit(start, identEnd, .keyword)
} else if builtins.contains(text) || text.utf16.allSatisfy(Unit.isDigit) {
lx.emit(start, identEnd, .number)
}
}
private static func isQuoteOrDollar(_ c: UInt16) -> Bool {
c == Unit.quote || c == Unit.apostrophe || c == Unit.dollar
}
/// `$name`, `$1`, `$@`, `${…}`; `$(` is left plain for the command inside it.
private static func variable(_ lx: inout Lexer) {
let start = lx.i
lx.i += 1
let next = lx.peek()
if next == Unit.lbrace {
while lx.i < lx.end && lx.u[lx.i] != Unit.rbrace { lx.i += 1 }
lx.i = min(lx.i + 1, lx.end)
} else if Unit.isIdentStart(next) {
lx.identifier()
} else if Unit.isDigit(next) || "@*#?$!-".utf16.contains(next) {
lx.i += 1
} else {
return
}
lx.emit(start, lx.i, .variable)
}
/// A quoted body; double quotes interpolate `$…`. False when the line ends first.
private static func string(_ lx: inout Lexer, from start: Int, quote: UInt16) -> Bool {
var runStart = start
while lx.i < lx.end {
let c = lx.u[lx.i]
if quote == Unit.quote && c == Unit.backslash {
lx.i = min(lx.i + 2, lx.end)
continue
}
if c == quote {
lx.i += 1
lx.emit(runStart, lx.i, .string)
return true
}
if quote == Unit.quote && c == Unit.dollar && (Unit.isIdentStart(lx.peek(1)) || lx.peek(1) == Unit.lbrace) {
lx.emit(runStart, lx.i, .string)
variable(&lx)
runStart = lx.i
continue
}
lx.i += 1
}
lx.emit(runStart, lx.i, .string)
return false
}
/// `<<ID`, `<<-ID`, `<<'ID'` or `<<"ID"`; a quoted marker turns interpolation off.
private static func heredocStart(_ lx: inout Lexer, _ st: inout GrammarState) {
let start = lx.i
var k = start + 2
if lx.unit(at: k) == Unit.minus { k += 1 }
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
let quote = lx.unit(at: k)
let quoted = quote == Unit.apostrophe || quote == Unit.quote
if quoted { k += 1 }
let idStart = k
while k < lx.end && Unit.isIdentPart(lx.u[k]) { k += 1 }
guard k > idStart else {
lx.i = start + 2
lx.emit(start, lx.i, .keyword)
return
}
let id = lx.text(idStart, k)
if quoted && lx.unit(at: k) == quote { k += 1 }
lx.emit(start, idStart - (quoted ? 1 : 0), .keyword)
lx.emit(idStart - (quoted ? 1 : 0), k, .string)
lx.i = k
st.mode = .heredoc(id: id, interpolates: !quoted)
}
private static func heredocLine(_ lx: inout Lexer, _ st: inout GrammarState, id: String, interpolates: Bool) {
let start = lx.i
var k = start
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
let marker = Array(id.utf16)
if lx.starts(with: marker, at: k) && k + marker.count == lx.end {
lx.i = lx.end
lx.emit(start, lx.i, .string)
st.mode = .code
return
}
var runStart = start
while lx.i < lx.end {
if interpolates && lx.u[lx.i] == Unit.dollar {
lx.emit(runStart, lx.i, .string)
let before = lx.i
variable(&lx)
if lx.i == before { lx.i += 1 }
runStart = lx.i
continue
}
lx.i += 1
}
lx.emit(runStart, lx.i, .string)
}
}
@@ -0,0 +1,236 @@
import Foundation
/// The six syntax roles of the design, plus the ⌘-clickable class name.
public enum TokenRole: String, Sendable, Equatable {
/// Plain text and function names.
case plain
/// Variables and properties.
case variable
case comment
/// Keywords, operators, pseudo-classes.
case keyword
/// Strings, values, type paths.
case string
/// Numbers, tags, hex literals.
case number
/// A class name the project declares, underlined while ⌘ is held (PHP only).
case symbol
}
/// A run of one role, as a UTF-16 range into the highlighted text (NSAttributedString-friendly).
public struct Token: Sendable, Equatable {
public var location: Int
public var length: Int
public var role: TokenRole
public init(location: Int, length: Int, role: TokenRole) {
self.location = location
self.length = length
self.role = role
}
}
/// What the tokenizer carries from the end of one line to the start of the next.
///
/// An editor keeps the state after every line; after an edit it re-tokenizes from the
/// edited line until the state it computes equals the one it stored.
public struct HighlightState: Sendable, Hashable {
let grammar: Grammar?
var state = GrammarState()
/// The state before the first line. A PHP buffer containing `<?` reads as HTML with PHP islands.
public init(language: Language?, text: String = "") {
grammar = Grammar(language, text: text)
}
/// True when a construct is still open, such as a block comment or a heredoc.
public var isInsideConstruct: Bool {
state.mode != .code || state.child != nil || !state.resumes.isEmpty
}
}
public enum SyntaxHighlighter {
/// Tokenises a whole buffer; unmarked stretches are `.plain`.
///
/// Runs on every keystroke in the editable view, so it must stay linear in the text
/// length. Multi-line constructs (block comments, heredocs, template strings) carry
/// state across lines. PHP class-name tokens found in `knownSymbols` become `.symbol`.
/// The tokens cover the text end to end, in order, adjacent runs of one role merged.
public static func tokens(for text: String, language: Language?, knownSymbols: Set<String> = []) -> [Token] {
let units = Array(text.utf16)
var state = HighlightState(language: language, text: text)
var lexer = Lexer(units: units, symbols: knownSymbols)
if state.grammar != nil {
var lineStart = 0
while lineStart <= units.count {
var lineEnd = lineStart
while lineEnd < units.count && units[lineEnd] != 10 { lineEnd += 1 }
lexer.i = lineStart
lexer.end = lineEnd
scanLine(&lexer, &state)
lineStart = lineEnd + 1
}
}
return filled(lexer.tokens, length: units.count)
}
/// Tokenises one line on its own, for the diff panes where every line stands alone.
public static func lineTokens(for line: String, language: Language?, knownSymbols: Set<String> = []) -> [Token] {
var state = HighlightState(language: language, text: line)
return lineTokens(for: line, state: &state, knownSymbols: knownSymbols)
}
/// Tokenises one line (without its newline) starting from `state`, and advances `state` past it.
public static func lineTokens(for line: String, state: inout HighlightState, knownSymbols: Set<String> = []) -> [Token] {
let units = Array(line.utf16)
var lexer = Lexer(units: units, symbols: knownSymbols)
scanLine(&lexer, &state)
return filled(lexer.tokens, length: units.count)
}
private static func scanLine(_ lexer: inout Lexer, _ state: inout HighlightState) {
guard let grammar = state.grammar else { return }
Grammars.scan(grammar, &lexer, &state.state)
}
/// Fills the gaps between role tokens with `.plain`, so the tokens tile the text.
private static func filled(_ tokens: [Token], length: Int) -> [Token] {
var out: [Token] = []
out.reserveCapacity(tokens.count * 2 + 1)
var position = 0
for token in tokens {
let start = max(token.location, position)
let end = min(token.location + token.length, length)
guard end > start else { continue }
if start > position { out.append(Token(location: position, length: start - position, role: .plain)) }
out.append(Token(location: start, length: end - start, role: token.role))
position = end
}
if position < length { out.append(Token(location: position, length: length - position, role: .plain)) }
return out
}
}
/// One tokenizer; several `Language`s share one (the JavaScript family), and PHP has two.
enum Grammar: Hashable, Sendable {
case javascript(typescript: Bool, jsx: Bool)
case php
/// HTML with `<?php … ?>` islands.
case phpTemplate
case markup
case css
case json
case markdown
case bash
case python
case yaml
init?(_ language: Language?, text: String) {
switch language {
case nil: return nil
case .php: self = text.contains("<?") ? .phpTemplate : .php
case .javascript: self = .javascript(typescript: false, jsx: false)
case .jsx: self = .javascript(typescript: false, jsx: true)
case .typescript: self = .javascript(typescript: true, jsx: false)
case .tsx: self = .javascript(typescript: true, jsx: true)
case .markup: self = .markup
case .css: self = .css
case .json: self = .json
case .markdown: self = .markdown
case .bash: self = .bash
case .python: self = .python
case .yaml: self = .yaml
}
}
}
/// The construct a grammar is inside at a line break.
enum Mode: Hashable, Sendable {
case code
case blockComment
/// A string that may run over lines: PHP and shell quotes.
case quoted(UInt16)
/// A JavaScript template literal.
case template
/// A Python triple-quoted string.
case triple(UInt16)
/// PHP `<<<ID` or shell `<<ID`; `interpolates` is false for nowdoc and quoted shell markers.
case heredoc(id: String, interpolates: Bool)
case markupComment
case cdata
/// Inside `<name …` before its `>`; closing tags keep their leading slash.
case markupTag(String)
case markupValue(quote: UInt16, tag: String)
/// Inside a JSX tag; `level` counts the elements open around it, a closing tag included.
case jsxTag(level: Int, closing: Bool)
/// JSX children text inside `level` open elements.
case jsxText(level: Int)
/// A CSS declaration value that did not end on its line.
case cssValue
/// A YAML `|` or `>` block, holding the indent of its key.
case yamlBlock(indent: Int)
/// A Markdown fence, closed by `count` or more `marker` characters.
case fence(marker: UInt16, count: Int)
}
struct GrammarState: Hashable, Sendable {
var mode: Mode = .code
/// Brace depth: CSS nesting, or the braces inside a `${…}` or JSX `{…}` expression.
var depth = 0
/// For each open `${` or JSX `{`, where its closing `}` returns to.
var resumes: [Resume] = []
var child: Embedded?
}
/// The brace depth at which a `}` ends an embedded expression, and the mode it returns to.
struct Resume: Hashable, Sendable {
var depth: Int
var mode: Mode
}
/// A grammar running inside another: PHP in HTML, a `<script>` body, a fenced block.
indirect enum Embedded: Hashable, Sendable {
case grammar(Grammar, GrammarState, until: Terminator)
}
enum Grammars {
/// Scans the rest of the line, handing over to and back from embedded grammars.
static func scan(_ grammar: Grammar, _ lx: inout Lexer, _ st: inout GrammarState) {
while true {
if case let .grammar(inner, innerState, terminator)? = st.child, terminator != .fence {
var state = innerState
let outerStop = lx.stop
lx.stop = terminator
scan(inner, &lx, &state)
lx.stop = outerStop
guard lx.i < lx.end else {
st.child = .grammar(inner, state, until: terminator)
return
}
if terminator == .phpClose {
lx.emit(lx.i, lx.i + 2, .keyword)
lx.i += 2
}
st.child = nil
}
guard lx.i < lx.end else { return }
scanOwn(grammar, &lx, &st)
guard case let .grammar(_, _, terminator)? = st.child, terminator != .fence, lx.i <= lx.end else { return }
}
}
private static func scanOwn(_ grammar: Grammar, _ lx: inout Lexer, _ st: inout GrammarState) {
switch grammar {
case let .javascript(typescript, jsx): JavaScriptGrammar.scan(&lx, &st, typescript: typescript, jsx: jsx)
case .php: PHPGrammar.scan(&lx, &st)
case .phpTemplate: MarkupGrammar.scan(&lx, &st, phpIslands: true)
case .markup: MarkupGrammar.scan(&lx, &st, phpIslands: false)
case .css: CSSGrammar.scan(&lx, &st)
case .json: JSONGrammar.scan(&lx, &st)
case .markdown: MarkdownGrammar.scan(&lx, &st)
case .bash: ShellGrammar.scan(&lx, &st)
case .python: PythonGrammar.scan(&lx, &st)
case .yaml: YAMLGrammar.scan(&lx, &st)
}
}
}
@@ -0,0 +1,113 @@
import Foundation
enum YAMLGrammar {
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
let lineStart = lx.i
var k = lineStart
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
let indent = k - lineStart
if case let .yamlBlock(parent) = st.mode {
if k == lx.end { return }
if indent > parent {
lx.i = lx.end
lx.emit(k, lx.end, .string)
return
}
st.mode = .code
}
var flow = 0
while lx.i < lx.end {
let start = lx.i
let c = lx.u[start]
if Unit.isSpace(c) {
lx.i += 1
continue
}
switch c {
case Unit.hash where start == lineStart || Unit.isSpace(lx.unit(at: start - 1)):
lx.lineComment()
case Unit.minus where isIndicator(lx, start + 1):
lx.i += 1
case Unit.quote, Unit.apostrophe:
var k = start + 1
while k < lx.end && lx.u[k] != c {
k += c == Unit.quote && lx.u[k] == Unit.backslash ? 2 : 1
}
lx.i = min(k + 1, lx.end)
lx.emit(start, lx.i, isKeyColon(lx, lx.i) ? .keyword : .string)
case Unit.amp, Unit.star:
lx.i += 1
while lx.i < lx.end && !Unit.isSpace(lx.u[lx.i]) && !isFlowPunctuation(lx.u[lx.i]) { lx.i += 1 }
lx.emit(start, lx.i, .keyword)
case Unit.bang:
while lx.i < lx.end && !Unit.isSpace(lx.u[lx.i]) { lx.i += 1 }
lx.emit(start, lx.i, .number)
case Unit.lbracket, Unit.lbrace:
flow += 1
lx.i += 1
case Unit.rbracket, Unit.rbrace:
flow = max(0, flow - 1)
lx.i += 1
case Unit.comma where flow > 0:
lx.i += 1
case Unit.pipe where isBlockIndicator(lx, start), Unit.greater where isBlockIndicator(lx, start):
lx.i = lx.end
st.mode = .yamlBlock(indent: indent)
default:
scalar(&lx, inFlow: flow > 0)
}
}
}
/// A `-` or `?` followed by a space or the line end.
private static func isIndicator(_ lx: Lexer, _ next: Int) -> Bool {
next >= lx.end || Unit.isSpace(lx.u[next])
}
private static func isFlowPunctuation(_ c: UInt16) -> Bool {
c == Unit.comma || c == Unit.rbracket || c == Unit.rbrace
}
/// A `:` right at `j` that ends a key.
private static func isKeyColon(_ lx: Lexer, _ j: Int) -> Bool {
lx.unit(at: j) == Unit.colon && isIndicator(lx, j + 1)
}
/// `|` or `>` with optional chomping/indent flags, then only a comment or nothing.
private static func isBlockIndicator(_ lx: Lexer, _ j: Int) -> Bool {
var k = j + 1
while k < lx.end && (lx.u[k] == Unit.minus || lx.u[k] == Unit.plus || Unit.isDigit(lx.u[k])) { k += 1 }
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
return k == lx.end || lx.u[k] == Unit.hash
}
/// A plain scalar: a key when a `: ` follows, else a boolean, null, number or plain text.
private static func scalar(_ lx: inout Lexer, inFlow: Bool) {
let start = lx.i
var lastSolid = start
while lx.i < lx.end {
let c = lx.u[lx.i]
if c == Unit.colon && isIndicator(lx, lx.i + 1) { break }
if c == Unit.hash && lx.i > start && Unit.isSpace(lx.u[lx.i - 1]) { break }
if inFlow && isFlowPunctuation(c) { break }
if !Unit.isSpace(c) { lastSolid = lx.i + 1 }
lx.i += 1
}
if lx.i == start {
lx.i += 1
return
}
if isKeyColon(lx, lx.i) {
lx.emit(start, lastSolid, .keyword)
lx.i += 1
return
}
let value = lx.text(start, lastSolid).lowercased()
if value == "true" || value == "false" || value == "null" || value == "~" {
lx.emit(start, lastSolid, .keyword)
} else if value.wholeMatch(of: /[+-]?(?:0x[0-9a-f]+|0o[0-7]+|(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?|\.inf|\.nan)/) != nil {
lx.emit(start, lastSolid, .number)
}
}
}
@@ -0,0 +1,94 @@
import Foundation
/// The inline pass: a fixed order of rewrite rules that build nodes.
///
/// Each rule swaps its match for a placeholder that points at the node it built, so a later
/// rule can wrap earlier nodes (`**[a](b)**`) but never re-reads their text.
enum MarkdownInlineParser {
private static let open: Character = "\u{E000}"
private static let close: Character = "\u{E001}"
static func parse(_ source: String, baseDir: String) -> [MarkdownInline] {
var held: [MarkdownInline] = []
func hold(_ node: MarkdownInline) -> String {
held.append(node)
return "\(open)\(held.count - 1)\(close)"
}
func expand(_ text: Substring) -> [MarkdownInline] {
expandPlaceholders(text, held)
}
var s = source.replacing(/`([^`]+)`/) { hold(.code(String($0.1))) }
s = s.replacing(/!\[([^\]]*)\]\(([^)]*)\)/) { match in
let alt = plainText(expand(match.1))
let (url, title) = destination(match.2)
guard let safe = MarkdownParser.safeURL(url), !safe.isEmpty else { return alt }
let source: ImageSource
if MarkdownParser.isLocalURL(safe) {
source = .local(path: MarkdownParser.resolveRelative(baseDir: baseDir, url: safe))
} else if let remote = URL(string: safe) {
source = .remote(remote)
} else {
return alt
}
return hold(.image(alt: alt, source: source, title: title))
}
s = s.replacing(/\[([^\]]+)\]\(([^)]*)\)/) { match in
let (url, title) = destination(match.2)
guard let safe = MarkdownParser.safeURL(url), !safe.isEmpty else { return String(match.1) }
return hold(.link(text: expand(match.1), url: safe, title: title))
}
s = s.replacing(/\*\*([^*]+)\*\*/) { hold(.strong(expand($0.1))) }
s = s.replacing(/__([^_]+)__/) { hold(.strong(expand($0.1))) }
s = s.replacing(/\*([^*]+)\*/) { hold(.emphasis(expand($0.1))) }
s = s.replacing(/(^|[^a-zA-Z0-9_])_([^_]+)_(?=[^a-zA-Z0-9_]|$)/) { String($0.1) + hold(.emphasis(expand($0.2))) }
s = s.replacing(/~~([^~]+)~~/) { hold(.strikethrough(expand($0.1))) }
return expand(Substring(s))
}
/// Splits `(url)`, `(url "title")` or `(<url> 'title')` into the URL and the optional title.
static func destination(_ raw: Substring) -> (url: String, title: String?) {
guard let match = raw.wholeMatch(of: /\s*(?:<([^>]*)>|([^\s)]*))(?:\s+["'(]([^"')]*)["')])?\s*/) else {
return (raw.trimmingCharacters(in: .whitespaces), nil)
}
let url = (match.1 ?? match.2 ?? "").trimmingCharacters(in: .whitespaces)
let title = match.3.map(String.init).flatMap { $0.isEmpty ? nil : $0 }
return (url, title)
}
/// Text with placeholders turned back into the nodes they stand for.
private static func expandPlaceholders(_ text: Substring, _ held: [MarkdownInline]) -> [MarkdownInline] {
var nodes: [MarkdownInline] = []
var plain = ""
var index = text.startIndex
while index < text.endIndex {
let c = text[index]
if c == open, let end = text[index...].firstIndex(of: close),
let slot = Int(text[text.index(after: index)..<end]), held.indices.contains(slot) {
if !plain.isEmpty {
nodes.append(.text(plain))
plain = ""
}
nodes.append(held[slot])
index = text.index(after: end)
continue
}
plain.append(c)
index = text.index(after: index)
}
if !plain.isEmpty { nodes.append(.text(plain)) }
return nodes
}
/// The visible text of nodes, for an image's alt text.
static func plainText(_ nodes: [MarkdownInline]) -> String {
nodes.map { node in
switch node {
case let .text(text), let .code(text): text
case let .strong(children), let .emphasis(children), let .strikethrough(children): plainText(children)
case let .link(children, _, _): plainText(children)
case let .image(alt, _, _): alt
}
}.joined()
}
}
@@ -0,0 +1,33 @@
import Foundation
public enum TableAlignment: String, Sendable, Equatable {
case left, center, right
}
public enum ImageSource: Sendable, Equatable {
/// A project-relative file, read through FileServicing.
case local(path: String)
case remote(URL)
}
public indirect enum MarkdownInline: Sendable, Equatable {
case text(String)
case code(String)
case strong([MarkdownInline])
case emphasis([MarkdownInline])
case strikethrough([MarkdownInline])
case link(text: [MarkdownInline], url: String, title: String?)
case image(alt: String, source: ImageSource, title: String?)
}
public indirect enum MarkdownBlock: Sendable, Equatable {
case heading(level: Int, content: [MarkdownInline])
case paragraph([MarkdownInline])
/// A fenced block; `language` is nil when the info string is unknown.
case code(language: Language?, text: String)
case quote([MarkdownBlock])
case list(ordered: Bool, items: [[MarkdownInline]])
/// Header cells, per-column alignment, then body rows padded to the header width.
case table(header: [[MarkdownInline]], alignments: [TableAlignment?], rows: [[[MarkdownInline]]])
case rule
}
@@ -0,0 +1,215 @@
import Foundation
public enum MarkdownParser {
/// Parses a subset of Markdown: ATX headings, fenced code, rules, GFM
/// tables, block quotes (recursive), bullet and ordered lists, paragraphs, and inline
/// code, images, links, strong, emphasis and strikethrough.
///
/// Code spans are protected before any other inline rule runs. `baseDir` is the
/// document's folder, used to resolve local image paths. Unsafe URL schemes are dropped.
public static func parse(_ text: String, baseDir: String = "") -> [MarkdownBlock] {
let normalized = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")
let lines = normalized.components(separatedBy: "\n")
var blocks: [MarkdownBlock] = []
var paragraph: [String] = []
func flushParagraph() {
guard !paragraph.isEmpty else { return }
blocks.append(.paragraph(MarkdownInlineParser.parse(paragraph.joined(separator: " "), baseDir: baseDir)))
paragraph = []
}
func inline(_ text: String) -> [MarkdownInline] {
MarkdownInlineParser.parse(text, baseDir: baseDir)
}
var i = 0
while i < lines.count {
let line = lines[i]
if let fence = line.wholeMatch(of: /```\s*([\w+-]*)\s*/) {
flushParagraph()
var code: [String] = []
i += 1
while i < lines.count && lines[i].wholeMatch(of: /```\s*/) == nil {
code.append(lines[i])
i += 1
}
i += 1
blocks.append(.code(language: fenceLanguage(String(fence.1)), text: code.joined(separator: "\n")))
continue
}
if isBlank(line) {
flushParagraph()
i += 1
continue
}
if let heading = line.wholeMatch(of: /(#{1,6})\s+(.*)/) {
flushParagraph()
blocks.append(.heading(level: heading.1.count, content: inline(trimmed(heading.2))))
i += 1
continue
}
if isRule(line) {
flushParagraph()
blocks.append(.rule)
i += 1
continue
}
if line.contains("|") && i + 1 < lines.count {
let header = splitRow(line)
if let alignments = tableAlignments(lines[i + 1]), alignments.count == header.count {
flushParagraph()
i += 2
var rows: [[[MarkdownInline]]] = []
while i < lines.count && lines[i].contains("|") && !isBlank(lines[i]) {
let cells = splitRow(lines[i])
rows.append(header.indices.map { inline($0 < cells.count ? cells[$0] : "") })
i += 1
}
blocks.append(.table(header: header.map(inline), alignments: alignments, rows: rows))
continue
}
}
if line.prefixMatch(of: /\s*>/) != nil {
flushParagraph()
var quoted: [String] = []
while i < lines.count, let marker = lines[i].prefixMatch(of: /\s*>\s?/) {
quoted.append(String(lines[i][marker.range.upperBound...]))
i += 1
}
blocks.append(.quote(parse(quoted.joined(separator: "\n"), baseDir: baseDir)))
continue
}
if let items = listItems(lines, &i, marker: /\s*[-*+]\s+/) {
flushParagraph()
blocks.append(.list(ordered: false, items: items.map(inline)))
continue
}
if let items = listItems(lines, &i, marker: /\s*\d+[.)]\s+/) {
flushParagraph()
blocks.append(.list(ordered: true, items: items.map(inline)))
continue
}
paragraph.append(trimmed(line))
i += 1
}
flushParagraph()
return blocks
}
/// The consecutive lines that start with `marker`, stripped of it; nil when line `i` does not.
private static func listItems(_ lines: [String], _ i: inout Int, marker: Regex<Substring>) -> [String]? {
var items: [String] = []
while i < lines.count, let match = lines[i].prefixMatch(of: marker) {
items.append(String(lines[i][match.range.upperBound...]))
i += 1
}
return items.isEmpty ? nil : items
}
private static func isBlank(_ line: String) -> Bool {
line.allSatisfy(\.isWhitespace)
}
private static func trimmed<S: StringProtocol>(_ text: S) -> String {
text.trimmingCharacters(in: .whitespacesAndNewlines)
}
/// Three or more of one of `-`, `*`, `_`, spaces allowed between them.
private static func isRule(_ line: String) -> Bool {
let marks = line.filter { !$0.isWhitespace }
guard marks.count >= 3, let first = marks.first, "-*_".contains(first) else { return false }
return marks.allSatisfy { $0 == first }
}
/// One GFM table row split into trimmed cells; `\\|` is a literal pipe, not a divider.
static func splitRow(_ line: String) -> [String] {
var row = Substring(trimmed(line))
if row.hasPrefix("|") { row = row.dropFirst() }
if row.hasSuffix("|") && !row.dropLast().hasSuffix("\\") { row = row.dropLast() }
var cells: [String] = []
var current = ""
var index = row.startIndex
while index < row.endIndex {
let c = row[index]
let next = row.index(after: index)
if c == "\\" && next < row.endIndex && row[next] == "|" {
current.append("|")
index = row.index(after: next)
continue
}
if c == "|" {
cells.append(current)
current = ""
} else {
current.append(c)
}
index = next
}
cells.append(current)
return cells.map { trimmed($0) }
}
/// The `---`/`:---:` row under a table header, as per-column alignments; nil when the line is not one.
static func tableAlignments(_ line: String) -> [TableAlignment?]? {
if !line.contains("|") && line.wholeMatch(of: /\s*:?-+:?\s*/) == nil { return nil }
var alignments: [TableAlignment?] = []
for cell in splitRow(line) {
guard cell.wholeMatch(of: /:?-+:?/) != nil else { return nil }
let left = cell.hasPrefix(":"), right = cell.hasSuffix(":")
alignments.append(left && right ? .center : right ? .right : left ? .left : nil)
}
return alignments
}
private static let fenceLanguages: [String: Language] = [
"php": .php, "js": .javascript, "javascript": .javascript, "mjs": .javascript,
"jsx": .jsx, "ts": .typescript, "typescript": .typescript, "tsx": .tsx,
"py": .python, "python": .python, "html": .markup, "xml": .markup, "vue": .markup,
"css": .css, "scss": .css, "json": .json, "sh": .bash, "bash": .bash, "shell": .bash,
"yml": .yaml, "yaml": .yaml, "md": .markdown, "markdown": .markdown,
]
/// The highlighter grammar for a fence info string.
public static func fenceLanguage(_ info: String) -> Language? {
fenceLanguages[info.lowercased()]
}
/// Keeps http(s), mailto, anchors and relative paths; returns nil for any other scheme (e.g. `javascript:`).
public static func safeURL(_ url: String) -> String? {
let u = url.trimmingCharacters(in: .whitespaces)
if u.range(of: "^(https?:|mailto:|#|\\.?\\.?/)", options: [.regularExpression, .caseInsensitive]) != nil { return u }
if u.range(of: "^[a-z][a-z0-9+.-]*:", options: [.regularExpression, .caseInsensitive]) != nil { return nil }
return u
}
/// True when a URL names a file next to the document rather than a remote resource.
public static func isLocalURL(_ url: String) -> Bool {
url.range(of: "^(https?:|data:|mailto:|#)", options: [.regularExpression, .caseInsensitive]) == nil
}
/// Resolves a document link to a project-relative path; a leading `/` means the project root.
public static func resolveRelative(baseDir: String, url: String) -> String {
var u = String(url.split(separator: "#", omittingEmptySubsequences: false).first ?? "")
u = String(u.split(separator: "?", omittingEmptySubsequences: false).first ?? "")
u = u.removingPercentEncoding ?? u
let joined = u.hasPrefix("/") ? u : baseDir + "/" + u
var out: [Substring] = []
for segment in joined.split(separator: "/", omittingEmptySubsequences: true) {
if segment == "." { continue }
if segment == ".." {
_ = out.popLast()
continue
}
out.append(segment)
}
return out.joined(separator: "/")
}
}
+62
View File
@@ -0,0 +1,62 @@
import Foundation
public enum Fuzzy {
/// Case-insensitive subsequence match: the matched character offsets in `text`, or nil.
public static func match(_ query: String, in text: String) -> [Int]? {
let q = Array(query.lowercased())
var indices: [Int] = []
var qi = 0
for (offset, ch) in text.lowercased().enumerated() where qi < q.count {
if ch == q[qi] {
indices.append(offset)
qi += 1
}
}
return qi == q.count ? indices : nil
}
/// File-name results: basename matches before path matches, then earlier first hit, then shorter path.
public static func rankFileNames(query: String, paths: [String], showHidden: Bool) -> [FileNameMatch] {
let term = query.trimmingCharacters(in: .whitespaces)
guard !term.isEmpty else { return [] }
var out: [FileNameMatch] = []
for path in paths {
if !showHidden && PathUtils.isHidden(path) { continue }
if let indices = match(term, in: PathUtils.basename(path)) {
out.append(FileNameMatch(path: path, nameIndices: indices, rank: 0, position: indices[0]))
} else if let indices = match(term, in: path) {
out.append(FileNameMatch(path: path, nameIndices: nil, rank: 1, position: indices[0]))
}
}
return out.sorted {
($0.rank, $0.position, $0.path.count) < ($1.rank, $1.position, $1.path.count)
}
}
}
public enum InFileSearch {
/// Case-insensitive substring hits in one buffer, for the search overlay's "this file" column.
public static func hits(query: String, in text: String) -> [ContentHit] {
let term = query.trimmingCharacters(in: .whitespaces)
guard !term.isEmpty else { return [] }
var hits: [ContentHit] = []
for (index, line) in text.components(separatedBy: "\n").enumerated() {
if let range = line.range(of: term, options: .caseInsensitive) {
hits.append(ContentHit(line: index + 1, text: line, matchOffset: line.utf16.distance(from: line.startIndex, to: range.lowerBound)))
}
}
return hits
}
/// Extension chips for the result set: most matches first, then alphabetical, capped at 12.
public static func extensionCounts(paths: [String]) -> [(ext: String, count: Int)] {
var counts: [String: Int] = [:]
for path in paths {
let e = FileType.ext(path)
if !e.isEmpty { counts[e, default: 0] += 1 }
}
return counts.sorted { $0.value != $1.value ? $0.value > $1.value : $0.key < $1.key }
.prefix(SearchLimits.maxExtensionChips)
.map { (ext: $0.key, count: $0.value) }
}
}
+114
View File
@@ -0,0 +1,114 @@
import Foundation
/// One `"type":"match"` event from `rg --json`.
public struct RipgrepMatch: Sendable, Equatable {
/// The path as ripgrep printed it (absolute when the search root was absolute).
public var path: String
public var line: Int
/// The line text without its trailing newline.
public var text: String
/// Byte offset of the first submatch, as ripgrep reports it.
public var byteOffset: Int
public init(path: String, line: Int, text: String, byteOffset: Int) {
self.path = path
self.line = line
self.text = text
self.byteOffset = byteOffset
}
}
public enum RipgrepJSON {
/// Decodes one line of `rg --json` output; nil for every event that is not a match.
///
/// An event carrying `path.bytes` or `lines.bytes` (base64, non-UTF-8 data) is skipped.
/// Offsets stay in bytes here; `ContentGrouper` turns them into UTF-16.
public static func parseLine(_ line: String) -> RipgrepMatch? {
guard line.contains("\"match\""),
let event = try? JSONDecoder().decode(Event.self, from: Data(line.utf8)),
event.type == "match",
let data = event.data,
let path = data.path?.text,
var text = data.lines?.text
else { return nil }
if text.unicodeScalars.last == "\n" { text.unicodeScalars.removeLast() }
if text.unicodeScalars.last == "\r" { text.unicodeScalars.removeLast() }
return RipgrepMatch(path: path, line: data.line_number ?? 0, text: text, byteOffset: data.submatches?.first?.start ?? 0)
}
/// The slice of an `rg --json` event this reader needs; a `bytes` field decodes as a nil `text`.
private struct Event: Decodable {
struct TextField: Decodable {
var text: String?
}
struct Submatch: Decodable {
var start: Int
}
struct Payload: Decodable {
var path: TextField?
var lines: TextField?
var line_number: Int?
var submatches: [Submatch]?
}
var type: String
var data: Payload?
}
/// Makes a ripgrep path relative to the project root, "/"-separated.
public static func relativePath(_ path: String, root: String) -> String {
let base = root.hasSuffix("/") ? root : root + "/"
return path.hasPrefix(base) ? String(path.dropFirst(base.count)) : path
}
}
/// Collects matches into per-file groups in first-seen order, honouring the search limits.
public struct ContentGrouper: Sendable {
public let root: String
public private(set) var groups: [ContentGroup] = []
public init(root: String) {
self.root = root
}
/// Adds a match: new files beyond `SearchLimits.maxFiles` are dropped, the line text is
/// capped at `maxLineLength`, and the byte offset becomes a clamped UTF-16 `matchOffset`.
public mutating func add(_ match: RipgrepMatch) {
let path = RipgrepJSON.relativePath(match.path, root: root)
let index: Int
if let existing = indexByPath[path] {
index = existing
} else {
guard groups.count < SearchLimits.maxFiles else { return }
index = groups.count
indexByPath[path] = index
groups.append(ContentGroup(path: path, hits: []))
}
guard groups[index].hits.count < SearchLimits.maxHitsPerFile else { return }
let text = ContentGrouper.capped(match.text)
let offset = ContentGrouper.utf16Offset(ofByte: match.byteOffset, in: match.text)
groups[index].hits.append(ContentHit(line: match.line, text: text, matchOffset: min(offset, text.utf16.count)))
}
private var indexByPath: [String: Int] = [:]
/// The line cut to `SearchLimits.maxLineLength` UTF-16 units, never inside a surrogate pair.
static func capped(_ text: String) -> String {
let utf16 = text.utf16
guard utf16.count > SearchLimits.maxLineLength else { return text }
var end = utf16.index(utf16.startIndex, offsetBy: SearchLimits.maxLineLength)
while end > utf16.startIndex && UTF16.isTrailSurrogate(utf16[end]) { end = utf16.index(before: end) }
return String(utf16[..<end]) ?? String(text.prefix(SearchLimits.maxLineLength))
}
/// ripgrep counts UTF-8 bytes; the views count UTF-16 units.
static func utf16Offset(ofByte byteOffset: Int, in text: String) -> Int {
let utf8 = text.utf8
guard byteOffset > 0 else { return 0 }
guard byteOffset < utf8.count else { return text.utf16.count }
var index = utf8.index(utf8.startIndex, offsetBy: byteOffset)
while index > utf8.startIndex && UTF8.isContinuation(utf8[index]) {
index = utf8.index(before: index)
}
return text.utf16.distance(from: text.utf16.startIndex, to: index)
}
}
@@ -0,0 +1,60 @@
import Foundation
/// One matching line.
public struct ContentHit: Sendable, Equatable {
/// 1-based line number.
public var line: Int
/// The line text, capped at `SearchLimits.maxLineLength` characters.
public var text: String
/// UTF-16 offset of the first match in `text`, clamped to its length.
public var matchOffset: Int
public init(line: Int, text: String, matchOffset: Int) {
self.line = line
self.text = text
self.matchOffset = matchOffset
}
}
/// All hits in one file, in the order ripgrep reported them.
public struct ContentGroup: Sendable, Equatable, Identifiable {
public var path: String
public var hits: [ContentHit]
public var id: String { path }
public init(path: String, hits: [ContentHit]) {
self.path = path
self.hits = hits
}
}
/// A file-name match in the search overlay's right column.
public struct FileNameMatch: Sendable, Equatable {
public var path: String
/// Matched character offsets in the basename; nil when only the full path matched.
public var nameIndices: [Int]?
/// 0 = basename match, 1 = path-only match; lower sorts first.
public var rank: Int
/// Offset of the first matched character; lower sorts first.
public var position: Int
public init(path: String, nameIndices: [Int]?, rank: Int, position: Int) {
self.path = path
self.nameIndices = nameIndices
self.rank = rank
self.position = position
}
}
public enum SearchLimits {
/// Content search starts at two characters; the in-file column at one.
public static let minContentQuery = 2
public static let maxFiles = 400
public static let maxLineLength = 1000
public static let maxHitsPerFile = 50
public static let maxFileNameResults = 40
public static let maxInFileResults = 200
public static let maxExtensionChips = 12
/// Keystroke debounce before a content search runs.
public static let debounceMilliseconds = 120
}
@@ -0,0 +1,62 @@
import Foundation
/// Which side of the window has focus; drives the fluid widths below 1600pt.
public enum FocusZone: String, Sendable, Equatable {
case neutral
case editor
case terminal
}
/// Pixel widths of the three fixed columns; the editor takes the remainder.
public struct ColumnWidths: Sendable, Equatable {
public var sourceControl: Double
public var explorer: Double
public var agent: Double
public init(sourceControl: Double, explorer: Double, agent: Double) {
self.sourceControl = sourceControl
self.explorer = explorer
self.agent = agent
}
}
public enum ColumnLayout {
/// At and above this width every column fits and focus changes nothing.
public static let roomyWidth = 1600.0
public static let minEditorWidth = 280.0
public static let splitterWidth = 1.0
public static let sourceControlRange = 160.0...460.0
public static let explorerRange = 160.0...520.0
/// Fluid widths for a window. Roomy: 13.4% · 16.4% · flex · 27.3% (the design's
/// 236 · 288 · flex · 480 on a 1760 frame). Tight: 15% · 15%, and the agent column
/// takes 30%, or 20% with the editor focused, or 50% with a terminal focused.
public static func fluid(windowWidth w: Double, focus: FocusZone) -> ColumnWidths {
if w >= roomyWidth {
return ColumnWidths(sourceControl: (w * 0.134).rounded(), explorer: (w * 0.164).rounded(), agent: (w * 0.273).rounded())
}
let agentShare = focus == .terminal ? 0.5 : focus == .editor ? 0.2 : 0.3
return ColumnWidths(sourceControl: (w * 0.15).rounded(), explorer: (w * 0.15).rounded(), agent: (w * agentShare).rounded())
}
/// Scales the fixed columns down so the editor keeps `minEditorWidth`; unchanged when they fit.
public static func fitted(_ widths: ColumnWidths, windowWidth: Double, sourceControlVisible: Bool) -> ColumnWidths {
let splitters = (sourceControlVisible ? 3.0 : 2.0) * splitterWidth
let budget = windowWidth - splitters - minEditorWidth
let total = (sourceControlVisible ? widths.sourceControl : 0) + widths.explorer + widths.agent
guard total > budget, total > 0 else { return widths }
let k = max(0, budget) / total
return ColumnWidths(
sourceControl: sourceControlVisible ? (widths.sourceControl * k).rounded(.down) : widths.sourceControl,
explorer: (widths.explorer * k).rounded(.down),
agent: (widths.agent * k).rounded(.down)
)
}
/// The widest the agent column may be dragged: until the editor would drop below its minimum.
public static func maxAgentWidth(windowWidth: Double, widths: ColumnWidths, sourceControlVisible: Bool) -> Double {
let splitters = (sourceControlVisible ? 3.0 : 2.0) * splitterWidth
let others = (sourceControlVisible ? widths.sourceControl : 0) + widths.explorer
return max(minEditorWidth, windowWidth - splitters - others - minEditorWidth)
}
}
@@ -0,0 +1,44 @@
import Foundation
/// Caret position shown in the status bar; 1-based.
public struct Cursor: Sendable, Equatable {
public var path: String
public var line: Int
public var column: Int
public init(path: String, line: Int, column: Int) {
self.path = path
self.line = line
self.column = column
}
}
/// A line-range selection in a read-only pane; `anchor` is where the drag started.
public struct LineSelection: Sendable, Equatable {
public var path: String
public var start: Int
public var end: Int
public var anchor: Int
public init(path: String, start: Int, end: Int, anchor: Int) {
self.path = path
self.start = min(start, end)
self.end = max(start, end)
self.anchor = anchor
}
public var reference: AgentReference { AgentReference(path: path, startLine: start, endLine: end) }
}
/// How a file is opened: from a git row (`side`), at a line (search hit, symbol), or straight into Diff.
public struct OpenOptions: Sendable, Equatable {
public var side: DiffSide?
public var line: Int?
public var showDiff: Bool
public init(side: DiffSide? = nil, line: Int? = nil, showDiff: Bool = false) {
self.side = side
self.line = line
self.showDiff = showDiff
}
}
@@ -0,0 +1,78 @@
/// Per-project editor session, restored on launch when `session.restoreOnLaunch` is on.
public struct SessionState: Codable, Sendable, Equatable {
public var active: String?
public var modes: [String: ViewMode]
/// Which git row opened each file; only the Diff overlay follows it.
public var sides: [String: DiffSide]
public init(active: String? = nil, modes: [String: ViewMode] = [:], sides: [String: DiffSide] = [:]) {
self.active = active
self.modes = modes
self.sides = sides
}
private enum CodingKeys: String, CodingKey {
case active
case modes = "tabMode"
case sides = "tabSide"
}
/// A stored mode this build does not know is dropped, not the whole map.
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
active = try? c.decodeIfPresent(String.self, forKey: .active)
let raw = (try? c.decodeIfPresent([String: String].self, forKey: .modes)) ?? [:]
modes = raw.compactMapValues(ViewMode.init(rawValue:))
sides = (try? c.decodeIfPresent([String: DiffSide].self, forKey: .sides)) ?? [:]
}
/// The storage key; one session per project root.
public static func key(root: String) -> String { "helder.session:" + root }
}
/// Window-wide layout that survives a restart.
public struct LayoutState: Codable, Sendable, Equatable {
/// The agent pane's share of the right column's height.
public var agentFraction: Double
public init(agentFraction: Double = LayoutState.defaultAgentFraction) {
self.agentFraction = LayoutState.clampAgentFraction(agentFraction)
}
public static let key = "helder.topFrac"
public static let defaultAgentFraction = 0.52
public static let agentFractionRange = 0.18...0.82
public static func clampAgentFraction(_ value: Double) -> Double {
min(max(value, agentFractionRange.lowerBound), agentFractionRange.upperBound)
}
}
public struct RecentProject: Codable, Sendable, Equatable, Identifiable {
public var path: String
public var name: String
public var id: String { path }
public init(path: String, name: String) {
self.path = path
self.name = name
}
}
public enum RecentLists {
/// Recent files per project, in `.helder/recent.json`.
public static let maxFiles = 100
/// Recent projects, machine-wide.
public static let maxProjects = 20
public static let recentFilesName = "recent.json"
/// Moves `path` to the front, de-duplicated and capped.
public static func pushing(_ path: String, onto list: [String], limit: Int = maxFiles) -> [String] {
Array(([path] + list.filter { $0 != path }).prefix(limit))
}
/// Moves a project to the front, keyed on its path, capped at 20.
public static func pushing(_ project: RecentProject, onto list: [RecentProject]) -> [RecentProject] {
Array(([project] + list.filter { $0.path != project.path }).prefix(maxProjects))
}
}
@@ -0,0 +1,97 @@
import Foundation
public struct PHPDeclaration: Sendable, Equatable {
public var kind: String
public var name: String
public var parents: [String]
public var interfaces: [String]
public init(kind: String, name: String, parents: [String], interfaces: [String]) {
self.kind = kind
self.name = name
self.parents = parents
self.interfaces = interfaces
}
}
public enum PHPSymbols {
/// ripgrep pattern for declarations and `namespace X;` lines in one pass.
public static let declarationPattern = #"^\s*(namespace\s+[A-Za-z_\\][\w\\]*\s*;|(final\s+|abstract\s+|readonly\s+)*(class|interface|trait|enum)\s+\w+)"#
/// ripgrep pattern for an indented `use` inside a class body.
public static let traitUsePattern = #"^\s+use\s+[A-Za-z_\\][\w\\ \t,]*[;{]"#
/// The declaration on one line, or nil. `final`/`abstract`/`readonly` may precede the keyword.
///
/// Only this line is read, so an `implements` list wrapped onto the next line yields
/// fewer interfaces, never wrong ones. Namespaced parents are reduced to short names.
public static func parseDeclaration(_ line: String) -> PHPDeclaration? {
let declaration = /^[ \t]*(?:(?:final|abstract|readonly)[ \t]+)*(class|interface|trait|enum)[ \t]+([A-Za-z_]\w*)(.*)$/
guard let match = line.firstMatch(of: declaration) else { return nil }
let rest = match.3
let extends = rest.firstMatch(of: /\bextends\s+([^{]*?)(?:\s+implements\b|\s*\{|$)/)
let implements = rest.firstMatch(of: /\bimplements\s+([^{]*?)(?:\s*\{|$)/)
return PHPDeclaration(
kind: String(match.1), name: String(match.2),
parents: extends.map { clauseNames($0.1) } ?? [],
interfaces: implements.map { clauseNames($0.1) } ?? []
)
}
/// The namespace a `namespace X;` line declares, without a leading backslash, or nil.
public static func parseNamespace(_ line: String) -> String? {
guard let match = line.firstMatch(of: /^[ \t]*namespace[ \t]+([A-Za-z_\\][\w\\]*)[ \t]*;/) else { return nil }
let name = match.1
return String(name.hasPrefix("\\") ? name.dropFirst() : name)
}
/// The traits an indented `use A, B;` mixes in; `use function`, `use const` and anything else give [].
public static func parseTraitUse(_ line: String) -> [String] {
guard let match = line.firstMatch(of: /^[ \t]+use[ \t]+([A-Za-z_\\][\w\\ \t,]*?)[ \t]*[;{]/),
line.firstMatch(of: /^\s*use\s+(function|const)\b/) == nil
else { return [] }
return clauseNames(match.1)
}
/// Short class names out of an `extends`/`implements`/`use` clause.
private static func clauseNames(_ clause: Substring) -> [String] {
clause.split(separator: ",", omittingEmptySubsequences: false).compactMap { part in
let last = part.trimmingCharacters(in: .whitespaces).split(separator: "\\", omittingEmptySubsequences: false).last ?? ""
let name = last.trimmingCharacters(in: .whitespaces)
return isIdentifier(name) ? name : nil
}
}
/// A column-0 `use` line: a namespace import, which reference search drops as noise.
public static func isImportLine(_ line: String) -> Bool {
line.range(of: #"^use[ \t]+[^;]*;?[ \t\r]*$"#, options: .regularExpression) != nil
}
/// True for a bare PHP identifier, the only thing a lookup accepts.
public static func isIdentifier(_ name: String) -> Bool {
name.range(of: #"^[A-Za-z_]\w*$"#, options: .regularExpression) != nil
}
/// Project declarations before `vendor/` ones, then by path, capped at `SymbolLimits.maxDefinitions`.
public static func sortDefinitions(_ defs: [SymbolDef]) -> [SymbolDef] {
let sorted = defs.sorted {
let lv = $0.path.hasPrefix("vendor/"), rv = $1.path.hasPrefix("vendor/")
return lv != rv ? !lv : $0.path < $1.path
}
return Array(sorted.prefix(SymbolLimits.maxDefinitions))
}
/// The identifier around a UTF-16 offset, or "" when the caret is not on one.
public static func word(in text: String, at offset: Int) -> String {
let units = Array(text.utf16)
guard offset >= 0, offset <= units.count else { return "" }
func isWord(_ u: UInt16) -> Bool {
(u >= 48 && u <= 57) || (u >= 65 && u <= 90) || (u >= 97 && u <= 122) || u == 95
}
var start = offset
while start > 0 && isWord(units[start - 1]) { start -= 1 }
var end = offset
while end < units.count && isWord(units[end]) { end += 1 }
let word = String(decoding: units[start..<end], as: UTF16.self)
return isIdentifier(word) ? word : ""
}
}
@@ -0,0 +1,66 @@
import Foundation
/// One class, interface, trait or enum declaration.
public struct SymbolDef: Sendable, Equatable, Codable {
public var name: String
public var path: String
public var line: Int
/// `class`, `interface`, `trait` or `enum`.
public var kind: String
/// The file's namespace, for the fully qualified name; "" when none.
public var namespace: String
/// `extends` on the declaration line, short names.
public var parents: [String]
/// `implements` on the declaration line, short names.
public var interfaces: [String]
/// Traits mixed in by an indented `use` in the body.
public var traits: [String]
public init(name: String, path: String, line: Int, kind: String, namespace: String = "",
parents: [String] = [], interfaces: [String] = [], traits: [String] = []) {
self.name = name
self.path = path
self.line = line
self.kind = kind
self.namespace = namespace
self.parents = parents
self.interfaces = interfaces
self.traits = traits
}
public var qualifiedName: String { namespace.isEmpty ? name : namespace + "\\" + name }
}
/// References to one name within one file.
public struct RefGroup: Sendable, Equatable {
public var path: String
public var hits: [ContentHit]
public init(path: String, hits: [ContentHit]) {
self.path = path
self.hits = hits
}
}
/// What a ⌘-click on a class name returns: where it is declared and where it is used.
public struct SymbolLookup: Sendable, Equatable {
public var name: String
public var definitions: [SymbolDef]
public var references: [RefGroup]
public var referenceCount: Int
public init(name: String, definitions: [SymbolDef] = [], references: [RefGroup] = [], referenceCount: Int = 0) {
self.name = name
self.definitions = definitions
self.references = references
self.referenceCount = referenceCount
}
public static func empty(_ name: String) -> SymbolLookup { SymbolLookup(name: name) }
}
public enum SymbolLimits {
public static let maxDefinitions = 25
public static let maxReferenceFiles = 300
public static let maxLineLength = 1000
}