improves plak

This commit is contained in:
2026-10-17 17:33:13 +02:00
parent 7b891819b0
commit a92d6f8871
633 changed files with 17623 additions and 7556 deletions
+114
View File
@@ -0,0 +1,114 @@
/// The kinds of code that get their own colour.
public enum CodeTokenKind: Sendable, Equatable {
case keyword
case string
case number
case comment
case variable
case tag
/// An attribute name in XML, a key in JSON.
case attribute
}
/// A highlighted piece of code; the range counts UTF-16 units, as NSRange does.
public struct CodeToken: Sendable, Equatable {
public let kind: CodeTokenKind
public let range: Range<Int>
public init(_ kind: CodeTokenKind, _ range: Range<Int>) {
self.kind = kind
self.range = range
}
}
/// The highlighted pieces of a code body; text between them is plain code.
public enum CodeHighlighter {
public static func tokens(_ body: String, kind: FenceKind) -> [CodeToken] {
switch kind {
case .php: PHPTokenizer.tokens(body)
case .json: JSONTokenizer.tokens(body)
case .xml: XMLTokenizer.tokens(body)
case .csv: []
}
}
}
/// Walks the UTF-16 units of a code body; all syntax that matters is ASCII.
struct CodeScanner {
let units: [UInt16]
var index = 0
private(set) var tokens: [CodeToken] = []
init(_ text: String) {
units = Array(text.utf16)
}
var atEnd: Bool {
index >= units.count
}
func peek(_ offset: Int = 0) -> UInt16? {
index + offset < units.count ? units[index + offset] : nil
}
func peekIs(_ character: Character, _ offset: Int = 0) -> Bool {
peek(offset) == character.utf16.first
}
func starts(with text: String) -> Bool {
var offset = 0
for unit in text.utf16 {
guard peek(offset) == unit else { return false }
offset += 1
}
return true
}
func text(from start: Int) -> String {
String(decoding: units[start..<index], as: UTF16.self)
}
mutating func add(_ kind: CodeTokenKind, from start: Int) {
if index > start { tokens.append(CodeToken(kind, start..<index)) }
}
mutating func skip(while condition: (UInt16) -> Bool) {
while let unit = peek(), condition(unit) { index += 1 }
}
/// Moves past `end`, or to the end when it never comes.
mutating func skip(past end: String) {
while !atEnd, !starts(with: end) { index += 1 }
index = min(units.count, index + end.utf16.count)
}
/// From an opening quote to past its closing quote.
mutating func skipQuoted(escapes: Bool) {
let quote = units[index]
index += 1
while let unit = peek() {
index += 1
if escapes, unit == 0x5C {
index = min(units.count, index + 1)
} else if unit == quote {
return
}
}
}
static func isLetter(_ unit: UInt16) -> Bool {
(unit >= 0x41 && unit <= 0x5A) || (unit >= 0x61 && unit <= 0x7A) || unit == 0x5F || unit >= 0x80
}
static func isDigit(_ unit: UInt16) -> Bool {
unit >= 0x30 && unit <= 0x39
}
static func isWord(_ unit: UInt16) -> Bool {
isLetter(unit) || isDigit(unit)
}
static func isSpace(_ unit: UInt16) -> Bool {
unit == 0x20 || unit == 0x09 || unit == 0x0A || unit == 0x0D
}
}
+27
View File
@@ -0,0 +1,27 @@
/// JSON: keys apart from string values, numbers, and true, false and null.
enum JSONTokenizer {
static func tokens(_ body: String) -> [CodeToken] {
var scanner = CodeScanner(body)
while let unit = scanner.peek() {
let start = scanner.index
if scanner.peekIs("\"") {
scanner.skipQuoted(escapes: true)
let end = scanner.index
scanner.skip(while: CodeScanner.isSpace)
let isKey = scanner.peekIs(":")
scanner.index = end
scanner.add(isKey ? .attribute : .string, from: start)
} else if scanner.peekIs("-") || CodeScanner.isDigit(unit) {
scanner.index += 1
scanner.skip { CodeScanner.isDigit($0) || $0 == 0x2E || $0 == 0x65 || $0 == 0x45 || $0 == 0x2B || $0 == 0x2D }
scanner.add(.number, from: start)
} else if CodeScanner.isLetter(unit) {
scanner.skip(while: CodeScanner.isWord)
if ["true", "false", "null"].contains(scanner.text(from: start)) { scanner.add(.keyword, from: start) }
} else {
scanner.index += 1
}
}
return scanner.tokens
}
}
+72
View File
@@ -0,0 +1,72 @@
/// PHP: keywords, strings and heredocs, comments, `$variables`, numbers and the open and close tags.
enum PHPTokenizer {
static let keywords: Set<String> = [
"abstract", "and", "array", "as", "bool", "break", "callable", "case", "catch", "class", "clone", "const",
"continue", "declare", "default", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor",
"endforeach", "endif", "endswitch", "endwhile", "enum", "extends", "false", "final", "finally", "float", "fn",
"for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof",
"insteadof", "int", "interface", "isset", "iterable", "list", "match", "mixed", "namespace", "never", "new",
"null", "object", "or", "parent", "print", "private", "protected", "public", "readonly", "require",
"require_once", "return", "self", "static", "string", "switch", "throw", "trait", "true", "try", "unset", "use",
"var", "void", "while", "xor", "yield",
]
static func tokens(_ body: String) -> [CodeToken] {
var scanner = CodeScanner(body)
while let unit = scanner.peek() {
let start = scanner.index
if scanner.starts(with: "<?php") || scanner.starts(with: "<?=") || scanner.starts(with: "?>") {
scanner.index += scanner.starts(with: "<?php") ? 5 : scanner.starts(with: "<?=") ? 3 : 2
scanner.add(.tag, from: start)
} else if scanner.starts(with: "//") || (scanner.peekIs("#") && !scanner.peekIs("[", 1)) {
scanner.skip { $0 != 0x0A }
scanner.add(.comment, from: start)
} else if scanner.starts(with: "/*") {
scanner.skip(past: "*/")
scanner.add(.comment, from: start)
} else if scanner.starts(with: "<<<") {
heredoc(&scanner)
scanner.add(.string, from: start)
} else if scanner.peekIs("'") || scanner.peekIs("\"") {
scanner.skipQuoted(escapes: true)
scanner.add(.string, from: start)
} else if scanner.peekIs("$"), let next = scanner.peek(1), CodeScanner.isLetter(next) {
scanner.index += 1
scanner.skip(while: CodeScanner.isWord)
scanner.add(.variable, from: start)
} else if CodeScanner.isDigit(unit) {
scanner.skip { CodeScanner.isWord($0) || $0 == 0x2E }
scanner.add(.number, from: start)
} else if CodeScanner.isLetter(unit) {
scanner.skip(while: CodeScanner.isWord)
if keywords.contains(scanner.text(from: start).lowercased()) { scanner.add(.keyword, from: start) }
} else {
scanner.index += 1
}
}
return scanner.tokens
}
/// `<<<ID`, `<<<"ID"` or `<<<'ID'` up to the line that starts with ID, indented or not.
private static func heredoc(_ scanner: inout CodeScanner) {
scanner.index += 3
scanner.skip { $0 == 0x20 || $0 == 0x09 }
let quoted = scanner.peekIs("'") || scanner.peekIs("\"")
if quoted { scanner.index += 1 }
let nameStart = scanner.index
scanner.skip(while: CodeScanner.isWord)
let name = scanner.text(from: nameStart)
if quoted { scanner.index += 1 }
guard !name.isEmpty else { return }
while !scanner.atEnd {
scanner.skip { $0 != 0x0A }
guard !scanner.atEnd else { return }
scanner.index += 1
scanner.skip { $0 == 0x20 || $0 == 0x09 }
if scanner.starts(with: name), !(scanner.peek(name.utf16.count).map(CodeScanner.isWord) ?? false) {
scanner.index += name.utf16.count
return
}
}
}
}
+55
View File
@@ -0,0 +1,55 @@
/// XML: tags, attribute names, attribute values, comments and CDATA.
enum XMLTokenizer {
static func tokens(_ body: String) -> [CodeToken] {
var scanner = CodeScanner(body)
while !scanner.atEnd {
let start = scanner.index
if scanner.starts(with: "<!--") {
scanner.skip(past: "-->")
scanner.add(.comment, from: start)
} else if scanner.starts(with: "<![CDATA[") {
scanner.skip(past: "]]>")
scanner.add(.string, from: start)
} else if scanner.peekIs("<"), let next = scanner.peek(1),
CodeScanner.isLetter(next) || next == 0x2F || next == 0x3F || next == 0x21 {
tag(&scanner)
} else {
scanner.index += 1
}
}
return scanner.tokens
}
/// From `<` up to and including `>`, `/>` or `?>`.
private static func tag(_ scanner: inout CodeScanner) {
let start = scanner.index
scanner.index += 1
if scanner.peekIs("/") || scanner.peekIs("?") || scanner.peekIs("!") { scanner.index += 1 }
scanner.skip(while: isName)
scanner.add(.tag, from: start)
while let unit = scanner.peek() {
let piece = scanner.index
if scanner.starts(with: "/>") || scanner.starts(with: "?>") {
scanner.index += 2
scanner.add(.tag, from: piece)
return
} else if scanner.peekIs(">") {
scanner.index += 1
scanner.add(.tag, from: piece)
return
} else if scanner.peekIs("\"") || scanner.peekIs("'") {
scanner.skipQuoted(escapes: false)
scanner.add(.string, from: piece)
} else if CodeScanner.isLetter(unit) {
scanner.skip(while: isName)
scanner.add(.attribute, from: piece)
} else {
scanner.index += 1
}
}
}
private static func isName(_ unit: UInt16) -> Bool {
CodeScanner.isWord(unit) || unit == 0x3A || unit == 0x2D || unit == 0x2E
}
}
+70 -7
View File
@@ -1,17 +1,25 @@
import Foundation
/// The info string of a fenced block that the page shows as one object: a code block, or a table for csv.
public enum FenceKind: String, Sendable, CaseIterable {
case php, json, xml, csv
}
/// The page file as lines, with the created date of each block; reads the text and writes it back unchanged.
public struct PageFile: Sendable, Equatable {
public enum Line: Sendable, Equatable {
case text(String)
/// An image line; the path is relative to the page file folder, as `images/<name>`.
case image(String)
/// A code block or table: the whole fenced block, whose body may hold newlines and blank lines.
case fenced(FenceKind, String)
/// The line as it stands in the page file.
public var text: String {
switch self {
case let .text(text): text
case let .image(path): PageFile.imageLine(path)
case let .fenced(kind, body): PageFile.fencedBlock(kind, body)
}
}
@@ -44,16 +52,28 @@ public struct PageFile: Sendable, Equatable {
if startsBlock, index + 1 < raw.count, !Self.isBlank(raw[index + 1]),
let date = CreatedDate.date(fromLine: line, timeZone: timeZone) {
dates[lines.count] = date
lines.append(Self.line(raw[index + 1]))
index += 2
continue
index += 1
}
lines.append(Self.line(line))
index += 1
let (parsed, next) = Self.line(raw, at: index, timeZone: timeZone)
lines.append(parsed)
index = next
}
self.init(lines: lines, dates: dates)
}
/// The lines of pasted text: image lines and fenced blocks, but no dates.
public static func lines(pasted text: String) -> [Line] {
let raw = text.replacingOccurrences(of: "\r\n", with: "\n").components(separatedBy: "\n")
var lines: [Line] = []
var index = 0
while index < raw.count {
let (parsed, next) = Self.line(raw, at: index, timeZone: .current)
lines.append(parsed)
index = next
}
return lines
}
/// The page file text: every line, the date line above each dated block, and a trailing newline.
public func text(timeZone: TimeZone = .current) -> String {
guard !lines.isEmpty else { return "" }
@@ -101,7 +121,50 @@ public struct PageFile: Sendable, Equatable {
"![](\(path))"
}
private static func line(_ text: String) -> Line {
imagePath(fromLine: text).map(Line.image) ?? .text(text)
/// The fence line, the body and the closing fence; the fence is longer than any run of backticks that starts a body line.
public static func fencedBlock(_ kind: FenceKind, _ body: String) -> String {
let fence = fence(for: body)
return "\(fence)\(kind.rawValue)\n\(body)\n\(fence)"
}
/// Every line break as LF: a CR or CRLF in a body would hide a fence line inside it.
public static func unixNewlines(_ text: String) -> String {
text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")
}
/// Split on "\n" itself: as a Character, "\r\n" is one grapheme and would not split.
static func fence(for body: String) -> String {
var longest = 0
for line in body.components(separatedBy: "\n") {
longest = max(longest, line.prefix(while: { $0 == "`" }).count)
}
return String(repeating: "`", count: max(3, longest + 1))
}
/// The line that starts at `raw[index]`, and the index of the line after it.
private static func line(_ raw: [String], at index: Int, timeZone: TimeZone) -> (Line, next: Int) {
if let fenced = fencedBlock(raw, at: index, timeZone: timeZone) { return fenced }
let text = raw[index]
return (imagePath(fromLine: text).map(Line.image) ?? .text(text), index + 1)
}
/// A fence of a known kind with a body of at least one line and a closing fence of the same length.
///
/// A fence that is not the one `fencedBlock` would write stays text, so the round trip stays exact. A body
/// with a date line after a blank line stays text too: a stray fence must not swallow the dated blocks below it.
private static func fencedBlock(_ raw: [String], at index: Int, timeZone: TimeZone) -> (Line, next: Int)? {
let open = raw[index]
let ticks = open.prefix(while: { $0 == "`" }).count
guard ticks >= 3, let kind = FenceKind(rawValue: String(open.dropFirst(ticks))) else { return nil }
let fence = String(repeating: "`", count: ticks)
var close = index + 1
while close < raw.count, raw[close] != fence { close += 1 }
guard close < raw.count, close > index + 1 else { return nil }
for line in (index + 2)..<close where isBlank(raw[line - 1]) && CreatedDate.date(fromLine: raw[line], timeZone: timeZone) != nil {
return nil
}
let body = raw[(index + 1)..<close].joined(separator: "\n")
guard Self.fence(for: body) == fence else { return nil }
return (.fenced(kind, body), close + 1)
}
}
+150
View File
@@ -0,0 +1,150 @@
import Foundation
/// A table read from CSV text, quote-aware as RFC 4180, and written back with its own delimiter.
public struct CSVTable: Sendable, Equatable {
/// In order of preference when more than one gives a table.
public static let delimiters: [Character] = ["\t", ";", ","]
public var rows: [[String]]
public let delimiter: Character
public init(rows: [[String]], delimiter: Character = ",") {
self.rows = rows
self.delimiter = delimiter
}
/// Reads the body of a stored table: the delimiter that gives every row the same field count, else the one
/// that splits the first row most.
public init(text: String) {
if let table = Self.detect(text, minimumRows: 1) {
self = table
return
}
let splits = Self.delimiters.map { (delimiter: $0, records: Self.records(text, delimiter: $0).records) }
let best = splits.max { ($0.records.first?.count ?? 0) < ($1.records.first?.count ?? 0) }
let split = best.flatMap { ($0.records.first?.count ?? 0) > 1 ? $0 : nil } ?? splits[splits.count - 1]
self.init(rows: split.records, delimiter: split.delimiter)
let width = columnCount
rows = rows.map { $0 + Array(repeating: "", count: width - $0.count) }
}
/// Pasted text as a table: at least two rows, every row the same number of fields, two or more, and no open quote.
public static func detect(_ text: String) -> CSVTable? {
detect(text, minimumRows: 2)
}
private static func detect(_ text: String, minimumRows: Int) -> CSVTable? {
for delimiter in delimiters {
let (records, closed) = records(text, delimiter: delimiter)
guard closed, records.count >= minimumRows, let count = records.first?.count, count >= 2,
records.allSatisfy({ $0.count == count }) else { continue }
return CSVTable(rows: records, delimiter: delimiter)
}
return nil
}
/// The records of CSV text; empty lines are skipped, and `closed` is false when a quote is never closed.
public static func records(_ text: String, delimiter: Character) -> (records: [[String]], closed: Bool) {
var records: [[String]] = []
var fields: [String] = []
var field = ""
var inQuotes = false
var quoted = false
var recordQuoted = false
let characters = Array(text.replacingOccurrences(of: "\r\n", with: "\n"))
func endRecord() {
fields.append(field)
if !(fields.count == 1 && fields[0].isEmpty && !recordQuoted) { records.append(fields) }
fields = []
field = ""
quoted = false
recordQuoted = false
}
var index = 0
while index < characters.count {
let character = characters[index]
if inQuotes {
if character == "\"" {
if index + 1 < characters.count, characters[index + 1] == "\"" {
field.append("\"")
index += 1
} else {
inQuotes = false
}
} else {
field.append(character)
}
} else if character == "\"", field.isEmpty, !quoted {
inQuotes = true
quoted = true
recordQuoted = true
} else if character == delimiter {
fields.append(field)
field = ""
quoted = false
} else if character == "\n" {
endRecord()
} else {
field.append(character)
}
index += 1
}
if !field.isEmpty || !fields.isEmpty || recordQuoted { endRecord() }
return (records, !inQuotes)
}
/// The CSV text, rows padded to the same width; a field is quoted only when it must be.
public func text() -> String {
let width = columnCount
return rows.map { row in
let padded = row + Array(repeating: "", count: width - row.count)
// A lone empty field would be an empty line, which reads back as no row at all.
if padded.count == 1, padded[0].isEmpty { return "\"\"" }
return padded.map(quoted).joined(separator: String(delimiter))
}.joined(separator: "\n")
}
private func quoted(_ field: String) -> String {
// Any delimiter, not only its own: a read-back picks the delimiter that splits every row the same.
guard field.contains(where: { Self.delimiters.contains($0) || $0 == "\"" || $0 == "\n" || $0 == "\r" }) else { return field }
return "\"" + field.replacingOccurrences(of: "\"", with: "\"\"") + "\""
}
public var columnCount: Int {
rows.map(\.count).max() ?? 0
}
/// A table without a cell is no table any more.
public var isEmpty: Bool {
rows.isEmpty || columnCount == 0
}
public subscript(row: Int, column: Int) -> String {
get { column < rows[row].count ? rows[row][column] : "" }
set {
if rows[row].count <= column { rows[row] += Array(repeating: "", count: column + 1 - rows[row].count) }
rows[row][column] = newValue
}
}
public mutating func addRow() {
rows.append(Array(repeating: "", count: max(1, columnCount)))
}
public mutating func addColumn() {
let width = columnCount
rows = rows.map { $0 + Array(repeating: "", count: width + 1 - $0.count) }
}
public mutating func removeRow(at index: Int) {
rows.remove(at: index)
}
public mutating func removeColumn(at index: Int) {
rows = rows.map { row in
var row = row
if index < row.count { row.remove(at: index) }
return row
}
}
}
@@ -0,0 +1,64 @@
/// Pretty-prints JSON text with a 2-space indent.
///
/// It works on the text itself, not on a parsed value: a parse loses the key order and the
/// spelling of numbers (`1.50`, `1e3`).
public enum JSONFormatter {
public static func pretty(_ text: String) -> String {
let scalars = Array(text.unicodeScalars)
var out = String.UnicodeScalarView()
var depth = 0
func newline() {
out.append("\n")
out.append(contentsOf: String(repeating: " ", count: max(0, depth)).unicodeScalars)
}
var index = 0
while index < scalars.count {
let scalar = scalars[index]
switch scalar {
case "\"":
out.append(scalar)
index += 1
while index < scalars.count {
out.append(scalars[index])
if scalars[index] == "\\", index + 1 < scalars.count {
index += 1
out.append(scalars[index])
} else if scalars[index] == "\"" {
break
}
index += 1
}
case "{", "[":
let close: Unicode.Scalar = scalar == "{" ? "}" : "]"
var next = index + 1
while next < scalars.count, isSpace(scalars[next]) { next += 1 }
if next < scalars.count, scalars[next] == close {
out.append(scalar)
out.append(close)
index = next
} else {
out.append(scalar)
depth += 1
newline()
}
case "}", "]":
depth -= 1
newline()
out.append(scalar)
case ",":
out.append(scalar)
newline()
case ":":
out.append(contentsOf: ": ".unicodeScalars)
default:
if !isSpace(scalar) { out.append(scalar) }
}
index += 1
}
return String(out)
}
private static func isSpace(_ scalar: Unicode.Scalar) -> Bool {
scalar == " " || scalar == "\t" || scalar == "\n" || scalar == "\r"
}
}
+42
View File
@@ -0,0 +1,42 @@
import Foundation
/// What a paste of plain text becomes: text as it is, or a code block or table.
public enum PasteKind: Sendable, Equatable {
case text
/// The kind and the body of the object; one-line JSON comes pretty-printed.
case object(FenceKind, String)
/// Looks at the whole pasted text, trimmed: PHP, JSON, XML, then CSV.
public init(_ pasted: String) {
let text = pasted.replacingOccurrences(of: "\r\n", with: "\n").trimmingCharacters(in: .whitespacesAndNewlines)
if text.hasPrefix("<?php") || text.hasPrefix("<?=") {
self = .object(.php, text)
} else if Self.isJSON(text) {
self = .object(.json, text.contains("\n") ? text : JSONFormatter.pretty(text))
} else if Self.isXML(text) {
self = .object(.xml, text)
} else if let csv = Self.csvText(pasted), CSVTable.detect(csv) != nil {
self = .object(.csv, csv)
} else {
self = .text
}
}
/// The text without its blank first and last lines; a tab at the edge is an empty cell, so it stays.
private static func csvText(_ pasted: String) -> String? {
var lines = PageFile.unixNewlines(pasted).components(separatedBy: "\n")
while let first = lines.first, first.allSatisfy({ $0 == " " }) { lines.removeFirst() }
while let last = lines.last, last.allSatisfy({ $0 == " " }) { lines.removeLast() }
return lines.isEmpty ? nil : lines.joined(separator: "\n")
}
private static func isJSON(_ text: String) -> Bool {
guard text.hasPrefix("{") || text.hasPrefix("[") else { return false }
return (try? JSONSerialization.jsonObject(with: Data(text.utf8))) != nil
}
private static func isXML(_ text: String) -> Bool {
guard text.hasPrefix("<") else { return false }
return XMLParser(data: Data(text.utf8)).parse()
}
}