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
+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()
}
}