improves plak
This commit is contained in:
@@ -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()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user