Sources/OrgSwift/Tables.swift
53 lines · 1499 bytes
1import Foundation
2
3func isTableLine(_ line: String) -> Bool {
4 line.hasPrefix("|") && line.hasSuffix("|")
5}
6
7func parseTableRow(_ line: String) -> [String] {
8 line
9 .split(separator: "|", omittingEmptySubsequences: false)
10 .dropFirst()
11 .dropLast()
12 .map { String($0).trimmingCharacters(in: .whitespaces) }
13}
14
15func parseOrgTableSeparatorRow(_ line: String) -> [String] {
16 var content = line.trimmingCharacters(in: .whitespaces)
17 if content.hasPrefix("|") {
18 content.removeFirst()
19 }
20 if content.hasSuffix("|") {
21 content.removeLast()
22 }
23 return content
24 .split(separator: "+", omittingEmptySubsequences: false)
25 .map { String($0).trimmingCharacters(in: .whitespaces) }
26}
27
28func isTableSeparatorCell(_ cell: String) -> Bool {
29 tableAlignment(for: cell) != nil
30}
31
32func tableAlignment(for cell: String) -> String? {
33 let trimmed = cell.trimmingCharacters(in: .whitespaces)
34 guard !trimmed.isEmpty else { return nil }
35
36 let core = trimmed.replacingOccurrences(of: ":", with: "")
37 guard !core.isEmpty, core.allSatisfy({ $0 == "-" || $0 == "+" }) else {
38 return nil
39 }
40
41 let isLeftAligned = trimmed.hasPrefix(":")
42 let isRightAligned = trimmed.hasSuffix(":")
43 switch (isLeftAligned, isRightAligned) {
44 case (true, true):
45 return "center"
46 case (true, false):
47 return "left"
48 case (false, true):
49 return "right"
50 case (false, false):
51 return ""
52 }
53}