Something went wrong. Try again.
tangled on ur phone
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249import SwiftUI
/// A small, line-at-a-time colouriser for the code browser. It knows about/// string literals, numbers, line comments and a keyword list per language/// family. It is deliberately not a parser: block comments are not tracked.enum SyntaxHighlighter { /// Maps a file path to the language name `highlight` understands. static func language(forPath path: String) -> String { switch URL(fileURLWithPath: path).pathExtension.lowercased() { case "swift": "swift" case "go": "go" case "rs": "rust" case "js", "jsx", "mjs", "cjs": "javascript" case "ts", "tsx": "typescript" case "py": "python" case "c", "h": "c" case "cc", "cpp", "cxx", "hpp", "hh", "hxx": "cpp" case "nix": "nix" case "sh", "bash", "zsh", "fish": "shell" case "rb": "ruby" case "hs": "haskell" case "lua": "lua" case "sql": "sql" case "yml", "yaml": "yaml" case "toml": "toml" case "json": "json" default: "text" } }
/// Returns one line with colour attributes. Unknown languages (including /// `"text"`) come back uncoloured. static func highlight(line: String, language: String) -> AttributedString { let syntax = syntax(for: language) let chars = Array(line) var builder = Builder() var i = 0
while i < chars.count { let c = chars[i]
if let marker = syntax.lineComment, matches(chars, at: i, marker) { builder.colored(String(chars[i...]), Color(.secondaryLabel)) break }
if c == "\"" || c == "'" { if let end = closingQuote(in: chars, from: i) { builder.colored(String(chars[i...end]), Color(.systemRed)) i = end + 1 continue } if c == "\"" { // An unterminated double quote colours the rest of the line. builder.colored(String(chars[i...]), Color(.systemRed)) break } // A lone apostrophe (e.g. a Rust lifetime) is just text. builder.plain(String(c)) i += 1 continue }
if c.isNumber { var end = i + 1 while end < chars.count, chars[end].isLetter || chars[end].isNumber || chars[end] == "." || chars[end] == "_" { end += 1 } builder.colored(String(chars[i..<end]), Color(.systemBlue)) i = end continue }
if c.isLetter || c == "_" { var end = i + 1 while end < chars.count, chars[end].isLetter || chars[end].isNumber || chars[end] == "_" { end += 1 } let word = String(chars[i..<end]) if syntax.keywords.contains(word) { builder.colored(word, Color(.systemPink)) } else { builder.plain(word) } i = end continue }
builder.plain(String(c)) i += 1 }
return builder.finish() }
// MARK: Languages
private struct Syntax { var lineComment: String? var keywords: Set<String> = [] }
private static func syntax(for language: String) -> Syntax { switch language { case "swift": Syntax(lineComment: "//", keywords: swiftKeywords) case "go": Syntax(lineComment: "//", keywords: goKeywords) case "rust": Syntax(lineComment: "//", keywords: rustKeywords) case "javascript", "typescript": Syntax(lineComment: "//", keywords: jsKeywords) case "c", "cpp": Syntax(lineComment: "//", keywords: cKeywords) case "python": Syntax(lineComment: "#", keywords: pythonKeywords) case "shell": Syntax(lineComment: "#", keywords: shellKeywords) case "nix": Syntax(lineComment: "#", keywords: nixKeywords) case "ruby", "yaml", "toml": Syntax(lineComment: "#") case "haskell": Syntax(lineComment: "--", keywords: haskellKeywords) case "lua": Syntax(lineComment: "--", keywords: luaKeywords) case "sql": Syntax(lineComment: "--", keywords: sqlKeywords) case "json": Syntax(keywords: ["true", "false", "null"]) default: Syntax() } }
private static let swiftKeywords: Set<String> = [ "actor", "any", "as", "async", "await", "break", "case", "catch", "class", "continue", "default", "defer", "do", "else", "enum", "extension", "fallthrough", "false", "fileprivate", "final", "for", "func", "guard", "if", "import", "in", "init", "inout", "internal", "is", "lazy", "let", "mutating", "nil", "override", "private", "protocol", "public", "repeat", "return", "self", "Self", "some", "static", "struct", "subscript", "super", "switch", "throw", "throws", "true", "try", "typealias", "var", "weak", "where", "while", ]
private static let goKeywords: Set<String> = [ "break", "case", "chan", "const", "continue", "default", "defer", "else", "fallthrough", "for", "func", "go", "goto", "if", "import", "interface", "map", "package", "range", "return", "select", "struct", "switch", "type", "var", "nil", "true", "false", "iota", ]
private static let rustKeywords: Set<String> = [ "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where", "while", "Some", "None", "Ok", "Err", ]
private static let jsKeywords: Set<String> = [ "async", "await", "break", "case", "catch", "class", "const", "continue", "default", "delete", "do", "else", "enum", "export", "extends", "false", "finally", "for", "from", "function", "if", "implements", "import", "in", "instanceof", "interface", "let", "new", "null", "of", "private", "protected", "public", "readonly", "return", "super", "switch", "this", "throw", "true", "try", "type", "typeof", "undefined", "var", "void", "while", "yield", ]
private static let cKeywords: Set<String> = [ "auto", "bool", "break", "case", "char", "class", "const", "continue", "default", "delete", "do", "double", "else", "enum", "extern", "false", "float", "for", "goto", "if", "inline", "int", "long", "namespace", "new", "nullptr", "private", "protected", "public", "register", "return", "short", "signed", "sizeof", "static", "struct", "switch", "template", "this", "throw", "true", "try", "typedef", "typename", "union", "unsigned", "using", "virtual", "void", "volatile", "while", ]
private static let pythonKeywords: Set<String> = [ "and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif", "else", "except", "False", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "None", "nonlocal", "not", "or", "pass", "raise", "return", "True", "try", "while", "with", "yield", ]
private static let shellKeywords: Set<String> = [ "case", "do", "done", "elif", "else", "esac", "export", "fi", "for", "function", "if", "in", "local", "readonly", "return", "set", "source", "then", "unset", "while", ]
private static let nixKeywords: Set<String> = [ "assert", "else", "false", "if", "import", "in", "inherit", "let", "null", "or", "rec", "then", "true", "with", ]
private static let haskellKeywords: Set<String> = [ "case", "class", "data", "do", "else", "if", "import", "in", "instance", "let", "module", "of", "return", "then", "type", "where", ]
private static let luaKeywords: Set<String> = [ "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while", ]
private static let sqlKeywords: Set<String> = [ "alter", "and", "as", "by", "case", "create", "delete", "distinct", "drop", "else", "end", "from", "group", "having", "in", "index", "inner", "insert", "into", "join", "left", "like", "limit", "not", "null", "on", "or", "order", "primary", "right", "select", "set", "table", "then", "union", "update", "values", "when", "where", ]
// MARK: Scanning
/// Accumulates coloured and plain runs into one `AttributedString`. private struct Builder { private var result = AttributedString() private var pending = ""
mutating func plain(_ text: String) { pending += text }
mutating func colored(_ text: String, _ color: Color) { flush() var piece = AttributedString(text) piece.foregroundColor = color result += piece }
mutating func finish() -> AttributedString { flush() return result }
private mutating func flush() { guard !pending.isEmpty else { return } result += AttributedString(pending) pending = "" } }
private static func matches(_ chars: [Character], at index: Int, _ marker: String) -> Bool { var i = index for expected in marker { guard i < chars.count, chars[i] == expected else { return false } i += 1 } return true }
/// The index of the quote that closes the literal opened at `start`. private static func closingQuote(in chars: [Character], from start: Int) -> Int? { let quote = chars[start] var i = start + 1 while i < chars.count { if chars[i] == "\\" { i += 2 continue } if chars[i] == quote { return i } i += 1 } return nil }}