Files
plak/Sources/PlakCore/Paste/PasteKind.swift
T

48 lines
2.1 KiB
Swift

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), let table = CSVTable.detect(csv), !Self.hasBraces(table) {
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")
}
/// Config and CSS split evenly on `;` too; a brace in a field means code, not data.
private static func hasBraces(_ table: CSVTable) -> Bool {
table.rows.contains { row in row.contains { $0.contains("{") || $0.contains("}") } }
}
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()
}
}