Sources/OrgCore/Export/ASCIIText.swift
507 lines · 25663 bytes
1import Foundation
2
3/// What ox-ascii (Org 9.8.7) makes of a section's elements and a heading's title with
4/// `:ascii-charset utf-8` and links in place (`:ascii-links-to-notes nil`), as the iCalendar
5/// export writes summaries and descriptions: paragraphs filled to the text width, lists with
6/// `•` bullets, blocks in a partial box, tables drawn with box characters.
7struct ASCIIText {
8 let options: ExportOptions
9 /// Heading numbers by title, for fuzzy links without a description.
10 var headingNumbers: [String: String] = [:]
11
12 static let textWidth = 72
13 static let innerMargin = 2
14 static let quoteMargin = 6
15
16 /// The text width inside a section under a heading at `level` (`org-ascii--current-text-width`).
17 func width(level: Int?) -> Int {
18 guard let level else { return Self.textWidth }
19 return Self.textWidth - (level > options.headlineLevels ? (level - options.headlineLevels) * 2 : Self.innerMargin)
20 }
21
22 // MARK: - Elements
23
24 /// `nodes`, each followed by the blank lines after it in `source`, as `org-export-data`
25 /// joins elements. Elements the export leaves out add nothing.
26 func elements(_ nodes: [SyntaxNode], end: Int, source: NSString, width: Int) -> String {
27 var out = ""
28 for (index, node) in nodes.enumerated() {
29 guard let text = element(node, source: source, width: width), !text.isEmpty else { continue }
30 let next = index + 1 < nodes.count ? nodes[index + 1].range.lowerBound : end
31 out += Self.normalized(text) + String(repeating: "\n", count: Self.blankLines(source, from: node.range.upperBound, to: next))
32 }
33 return out
34 }
35
36 /// Blank lines between `from`, a line start, and `to`.
37 static func blankLines(_ source: NSString, from: Int, to: Int) -> Int {
38 guard to > from, from < source.length else { return 0 }
39 let gap = source.substring(with: NSRange(location: from, length: min(to, source.length) - from))
40 return gap.components(separatedBy: "\n").dropLast().count
41 }
42
43 /// `org-element-normalize-string`: one final newline.
44 static func normalized(_ s: String) -> String {
45 var s = s
46 while s.hasSuffix("\n") || s.hasSuffix(" ") || s.hasSuffix("\t") { s.removeLast() }
47 return s + "\n"
48 }
49
50 func element(_ node: SyntaxNode, source: NSString, width: Int) -> String? {
51 switch node.kind {
52 case .paragraph:
53 return paragraph(node, width: width)
54 case .plainList:
55 return list(node, source: source, width: width)
56 case .table:
57 return table(node)
58 case .tableEl:
59 return Self.removeIndentation(node.text.trimmingCharacters(in: .newlines))
60 case .block:
61 return block(node, width: width)
62 case .fixedWidth:
63 let lines = node.text.components(separatedBy: "\n").filter { !$0.isEmpty }.map { line -> String in
64 let trimmed = line.drop { $0 == " " || $0 == "\t" }
65 return trimmed.hasPrefix(": ") ? String(trimmed.dropFirst(2)) : String(trimmed.dropFirst(1))
66 }
67 return Self.box(Self.removeIndentation(lines.joined(separator: "\n")))
68 case .horizontalRule:
69 return String(repeating: "―", count: width)
70 case .drawer:
71 let name = node.text.firstMatch(of: /^[ \t]*:([\w-]+):/).map { String($0.1).uppercased() } ?? ""
72 if name == "LOGBOOK" { return nil }
73 return elements(node.children, end: node.range.upperBound, source: source, width: width)
74 case .dynamicBlock:
75 return elements(node.children, end: node.range.upperBound, source: source, width: width)
76 case .latexEnvironment:
77 return options.tex ? Self.removeIndentation(node.text.trimmingCharacters(in: .newlines)) : nil
78 case .keyword:
79 guard let m = node.text.firstMatch(of: /(?i)^[ \t]*#\+ASCII:[ \t]*(.*?)[ \t]*\n?$/) else { return nil }
80 return String(m.1)
81 default:
82 // Planning, drawers of properties, clocks, comments, keywords and footnote
83 // definitions export nothing here.
84 return nil
85 }
86 }
87
88 // MARK: Paragraphs
89
90 func paragraph(_ node: SyntaxNode, width: Int) -> String {
91 var text = inline(node, skippingTimestamps: Self.isolatedTimestamps(node))
92 // `org-remove-blank-lines`.
93 text = text.replacing(#/\n[ \t]*\n(?:[ \t]*\n)*/#, with: "\n")
94 return Self.fill(text, width: width)
95 }
96
97 /// Whether the paragraph holds only timestamps and whitespace, whose timestamps
98 /// `:with-timestamps` decides.
99 static func isolatedTimestamps(_ node: SyntaxNode) -> Bool {
100 var any = false
101 for element in node.elements {
102 switch element {
103 case .token(let token):
104 if !token.text.allSatisfy(\.isWhitespace) { return false }
105 case .node(let child):
106 guard child.kind == .timestamp else { return false }
107 any = true
108 }
109 }
110 return any
111 }
112
113 /// `org-ascii--fill-string`: `fill-region` with `fill-column` `width`,
114 /// `sentence-end-double-space` and hard newlines from line breaks.
115 static func fill(_ text: String, width: Int) -> String {
116 text.components(separatedBy: hardNewline).map { fillParagraph($0, width: width) }.joined(separator: "\n")
117 }
118
119 static let hardNewline = "\u{1}"
120
121 /// `fill-context-prefix` with `adaptive-fill-regexp`: the second line's prefix when the
122 /// first has its characters, else what they share; for one line, its prefix, as spaces
123 /// unless it is blank.
124 static func fillPrefix(_ lines: [String]) -> String {
125 func adaptive(_ line: String) -> String { String(line.prefix { "-–!|#%;>*·•‣⁃◦ \t".contains($0) }) }
126 let first = adaptive(lines[0])
127 guard lines.count >= 2 else {
128 return first.allSatisfy { $0 == " " || $0 == "\t" } ? first : String(repeating: " ", count: first.count)
129 }
130 let second = adaptive(lines[1])
131 var rest = Substring(first)
132 let inOrder = second.split(whereSeparator: { $0 == " " || $0 == "\t" }).allSatisfy { chunk in
133 guard let range = rest.range(of: chunk) else { return false }
134 rest = rest[range.upperBound...]
135 return true
136 }
137 if inOrder { return second }
138 return String(zip(first, second).prefix { $0 == $1 }.map(\.0))
139 }
140
141 /// The length of what `fill-delete-prefix` takes from the start of `line`: blanks, `prefix`
142 /// with any blanks in it, blanks.
143 static func deletedPrefix(_ line: String, _ prefix: String) -> Int {
144 let chars = Array(line)
145 var i = 0
146 func blanks() { while i < chars.count, chars[i] == " " || chars[i] == "\t" { i += 1 } }
147 blanks()
148 let core = prefix.split(whereSeparator: { $0 == " " || $0 == "\t" })
149 guard !core.isEmpty else { return i }
150 let start = i
151 for (n, chunk) in core.enumerated() {
152 if n > 0 { blanks() }
153 guard chars.count - i >= chunk.count, String(chars[i..<(i + chunk.count)]) == chunk else { i = start; break }
154 i += chunk.count
155 }
156 blanks()
157 return i
158 }
159
160 static func fillParagraph(_ text: String, width: Int) -> String {
161 var lines = text.components(separatedBy: "\n")
162 while lines.count > 1, lines.last!.allSatisfy({ $0 == " " || $0 == "\t" }) { lines.removeLast() }
163 guard !lines.isEmpty else { return "" }
164 let prefix = fillPrefix(lines)
165 let first = String(lines[0].prefix(deletedPrefix(lines[0], prefix)))
166 var parts: [String] = []
167 for (i, line) in lines.enumerated() {
168 var content = String(line.dropFirst(deletedPrefix(line, prefix)))
169 while content.hasSuffix(" ") || content.hasSuffix("\t") { content.removeLast() }
170 // A sentence ending a line gets the second space it would have.
171 if i < lines.count - 1, content.range(of: "[.?!…‽][]\"'”’)}»›]*$", options: .regularExpression) != nil { content += " " }
172 parts.append(content)
173 }
174 let joined = parts.joined(separator: " ").replacingOccurrences(of: "\t", with: " ")
175 // Words and the spaces after them, with `canonically-space-region`'s spacing.
176 var words: [(word: String, spaces: Int)] = []
177 var index = joined.startIndex
178 while index < joined.endIndex {
179 let wordEnd = joined[index...].firstIndex(of: " ") ?? joined.endIndex
180 let word = String(joined[index..<wordEnd])
181 let spaceEnd = joined[wordEnd...].firstIndex { $0 != " " } ?? joined.endIndex
182 var spaces = joined.distance(from: wordEnd, to: spaceEnd)
183 if spaces >= 2 {
184 let closers = word.reversed().drop { "]})\"'".contains($0) }
185 spaces = closers.first.map { ".?!".contains($0) } == true ? 2 : 1
186 }
187 if !word.isEmpty { words.append((word, spaces)) } else if var last = words.popLast() {
188 last.spaces += spaces
189 words.append(last)
190 }
191 index = spaceEnd
192 }
193 guard !words.isEmpty else { return first }
194 /// `fill-nobreak-p`: not after a period followed by a single space.
195 func breakable(after i: Int) -> Bool { !(words[i].spaces == 1 && words[i].word.hasSuffix(".")) }
196 var out: [String] = []
197 var start = 0
198 while start < words.count {
199 let lead = out.isEmpty ? first : prefix
200 var length = lead.count + words[start].word.count
201 var end = start
202 var lastBreak: Int?
203 while end + 1 < words.count {
204 let next = length + words[end].spaces + words[end + 1].word.count
205 if next > width {
206 if breakable(after: end) {
207 lastBreak = end
208 break
209 }
210 if lastBreak != nil { break }
211 } else if breakable(after: end) {
212 lastBreak = end
213 }
214 length = next
215 end += 1
216 }
217 let stop = end + 1 < words.count ? (lastBreak ?? end) : end
218 var line = lead
219 for i in start...stop {
220 line += words[i].word
221 if i < stop { line += String(repeating: " ", count: words[i].spaces) }
222 }
223 out.append(line)
224 start = stop + 1
225 }
226 return out.joined(separator: "\n")
227 }
228
229 // MARK: Lists
230
231 func list(_ node: SyntaxNode, source: NSString, width: Int) -> String {
232 let items = node.children.filter { $0.kind == .item }
233 var out = ""
234 var number = 0
235 // The first item decides the list's type, as `org-list-get-list-type` does.
236 let firstBullet = (items.first?.tokens.first { $0.kind == .bullet }?.text ?? "-").trimmingCharacters(in: .whitespaces)
237 let descriptive = items.first?.firstChild(.itemTag) != nil
238 let ordered = !descriptive && firstBullet.first.map { $0.isNumber || $0.isLetter } == true
239 for (index, item) in items.enumerated() {
240 let bulletText = (item.tokens.first { $0.kind == .bullet }?.text ?? "-").trimmingCharacters(in: .whitespaces)
241 let checkbox: String = switch item.tokens.first(where: { $0.kind == .checkbox })?.text {
242 case "[X]"?, "[x]"?: "☑ "
243 case "[ ]"?: "☐ "
244 case "[-]"?: "☒ "
245 default: ""
246 }
247 let tag = descriptive ? item.firstChild(.itemTag) : nil
248 let bullet: String
249 let indentation: Int
250 if descriptive {
251 bullet = checkbox + (tag.map { inline($0).trimmingCharacters(in: .whitespaces) } ?? "")
252 indentation = Self.quoteMargin
253 } else if ordered {
254 if let counter = item.tokens.first(where: { $0.kind == .counter })?.text,
255 let n = Int(counter.trimmingCharacters(in: CharacterSet(charactersIn: "[@] "))) {
256 number = n
257 } else {
258 number += 1
259 }
260 bullet = bulletText.replacing(/[0-9A-Za-z]+/, with: String(number)) + " "
261 indentation = bullet.count
262 } else {
263 bullet = ["-": "• ", "+": "⁃ ", "*": "‣ "][bulletText] ?? bulletText + " "
264 indentation = bullet.count
265 }
266 let children = item.children.filter { $0.kind != .itemTag }
267 let inner = descriptive ? width - Self.quoteMargin : width - indentation - checkbox.count
268 let contents = elements(children, end: item.range.upperBound, source: source, width: inner)
269 let indented = Self.indent(contents, indentation)
270 let firstIsParagraph = children.first { (element($0, source: source, width: inner) ?? "").contains(where: { !$0.isWhitespace }) }?.kind == .paragraph
271 var text = bullet + checkbox
272 if !descriptive, indented.contains(where: { !$0.isWhitespace }), firstIsParagraph {
273 text += indented.trimmingCharacters(in: .whitespacesAndNewlines)
274 } else {
275 text += "\n" + indented
276 }
277 let next = index + 1 < items.count ? items[index + 1].range.lowerBound : item.range.upperBound
278 out += Self.normalized(text) + String(repeating: "\n", count: Self.blankLines(source, from: item.range.upperBound, to: next))
279 }
280 return out
281 }
282
283 /// `org-ascii--indent-string`: `width` spaces before each line that isn't blank.
284 static func indent(_ s: String, _ width: Int) -> String {
285 let pad = String(repeating: " ", count: width)
286 return s.components(separatedBy: "\n").map { $0.contains(where: { !$0.isWhitespace }) ? pad + $0 : $0 }.joined(separator: "\n")
287 }
288
289 static func removeIndentation(_ s: String) -> String {
290 let lines = s.components(separatedBy: "\n")
291 let common = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " }.count }.min() ?? 0
292 return lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " }.count))) }.joined(separator: "\n")
293 }
294
295 /// `org-ascii--box-string` in UTF-8.
296 static func box(_ s: String) -> String {
297 let body = s.replacing(#/\n[ \t]*\z/#, with: "")
298 return "┌────\n" + body.components(separatedBy: "\n").map { "│ " + $0 }.joined(separator: "\n") + "\n└────"
299 }
300
301 // MARK: Blocks
302
303 func block(_ node: SyntaxNode, width: Int) -> String? {
304 var lines = node.text.components(separatedBy: "\n")
305 if lines.last == "" { lines.removeLast() }
306 guard let first = lines.first, let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)[ \t]*(.*)$/) else { return nil }
307 let type = m.1.lowercased()
308 var body = Array(lines.dropFirst().dropLast()).map {
309 $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression)
310 }
311 body = Self.removeIndentation(body.joined(separator: "\n")).components(separatedBy: "\n")
312 switch type {
313 case "src", "example":
314 let code = body.joined(separator: "\n")
315 return code.isEmpty ? "" : Self.box(code)
316 case "quote":
317 return Self.indent(nested(body.joined(separator: "\n"), width: width - 2 * Self.quoteMargin), Self.quoteMargin)
318 case "verse":
319 let tree = OrgParser.parse(body.joined(separator: "\n"))
320 let text = tree.root.descendants().filter { $0.kind == .paragraph }.map { inline($0) }.joined(separator: "\n\n")
321 return Self.indent(text, Self.quoteMargin)
322 case "export":
323 return m.2.lowercased().hasPrefix("ascii") ? body.joined(separator: "\n") : nil
324 case "comment":
325 return nil
326 default:
327 return nested(body.joined(separator: "\n"), width: width)
328 }
329 }
330
331 /// A block's contents, parsed as elements.
332 func nested(_ text: String, width: Int) -> String {
333 let tree = OrgParser.parse(text)
334 let ns = text as NSString
335 let children = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
336 return elements(children, end: ns.length, source: ns, width: width)
337 }
338
339 // MARK: Tables
340
341 func table(_ node: SyntaxNode) -> String {
342 let rows = node.children.filter { $0.kind == .tableRow }
343 let cells: [[String]?] = rows.map { row in
344 let cells = row.children.filter { $0.kind == .tableCell }
345 if cells.isEmpty { return nil }
346 return cells.map { inline($0).trimmingCharacters(in: .whitespaces) }
347 }
348 let data = cells.compactMap { $0 }
349 guard !data.isEmpty else { return "" }
350 let columns = data.map(\.count).max() ?? 0
351 let filled = data.map { $0 + Array(repeating: "", count: columns - $0.count) }
352 var widths = (0..<columns).map { c in filled.map { $0[c].count }.max() ?? 0 }
353 // Width cookies such as `<10>` widen the column, as `org-ascii-table-widen-columns`.
354 for row in filled where row.allSatisfy({ $0.isEmpty || $0.range(of: "^<[lrc]?[0-9]*>$", options: .regularExpression) != nil }) {
355 for (c, cell) in row.enumerated() { if let n = Int(cell.filter(\.isNumber)) { widths[c] = max(widths[c], n) } }
356 }
357 let cookieRows = Set(filled.indices.filter { r in
358 filled[r].contains { !$0.isEmpty } && filled[r].allSatisfy { $0.isEmpty || $0.range(of: "^<[lrc]?[0-9]*>$", options: .regularExpression) != nil }
359 })
360 let right = (0..<columns).map { c -> Bool in
361 let values = filled.indices.filter { !cookieRows.contains($0) }.map { filled[$0][c] }.filter { !$0.isEmpty }
362 guard !values.isEmpty else { return false }
363 let numbers = values.filter { $0.range(of: "^([><]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*|[-+]?0[xX][0-9a-fA-F.]+|[-+]?[0-9]+#[0-9a-zA-Z.]+|nan|[-+u]?inf)$", options: .regularExpression) != nil }
364 return Double(numbers.count) / Double(values.count) >= 0.5
365 }
366 func line(_ char: String) -> String { widths.map { String(repeating: char, count: $0 + 2) }.joined() }
367 var out = ""
368 var dataIndex = 0
369 let lastData = cells.lastIndex { $0 != nil }!
370 let firstData = cells.firstIndex { $0 != nil }!
371 for (r, row) in cells.enumerated() {
372 guard row != nil else { continue }
373 let rowIndex = dataIndex
374 dataIndex += 1
375 if cookieRows.contains(rowIndex) { continue }
376 if r == firstData {
377 out += line("━") + "\n"
378 } else if r > 0, cells[r - 1] == nil {
379 out += line("─") + "\n"
380 }
381 out += filled[rowIndex].enumerated().map { c, cell in
382 let pad = String(repeating: " ", count: max(0, widths[c] - cell.count))
383 return " " + (right[c] ? pad + cell : cell + pad) + " "
384 }.joined() + "\n"
385 if r == lastData { out += line("━") + "\n" }
386 }
387 return out
388 }
389
390 // MARK: - Objects
391
392 /// The objects in `node`, as ox-ascii writes them.
393 func inline(_ node: SyntaxNode, skippingTimestamps isolated: Bool = false) -> String {
394 var out = ""
395 for element in node.elements {
396 switch element {
397 case .token(let token):
398 switch token.kind {
399 case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority, .counter: continue
400 default: out += special(token.text)
401 }
402 case .node(let child):
403 if isolated, child.kind == .timestamp, ICalendarExport.skipsTimestamp(child.text, with: options.timestamps ?? "t") { continue }
404 out += object(child)
405 }
406 }
407 return out
408 }
409
410 /// `org-ascii-plain-text` with `:with-special-strings`.
411 func special(_ text: String) -> String {
412 guard options.specialStrings else { return text }
413 return text.replacingOccurrences(of: "\\-", with: "").replacingOccurrences(of: "---", with: "—")
414 .replacingOccurrences(of: "--", with: "–").replacingOccurrences(of: "...", with: "…")
415 }
416
417 /// The text between the markers.
418 static func value(_ node: SyntaxNode) -> String {
419 node.elements.compactMap { element -> String? in
420 guard case .token(let token) = element, token.kind != .marker else { return nil }
421 return token.text
422 }.joined()
423 }
424
425 func object(_ node: SyntaxNode) -> String {
426 switch node.kind {
427 case .bold: return "*\(inline(node))*"
428 case .italic: return "/\(inline(node))/"
429 case .underline: return "_\(inline(node))_"
430 case .strikeThrough: return "+\(inline(node))+"
431 case .verbatim, .code: return "`\(Self.value(node))'"
432 case .link: return link(node)
433 case .linkDescription: return inline(node)
434 case .timestamp: return special(Self.timestamp(node.text))
435 // The iCalendar backend leaves footnote references out.
436 case .footnoteReference: return ""
437 case .entity:
438 let name = node.text.dropFirst().replacingOccurrences(of: "{}", with: "")
439 return OrgEntities.display[name] ?? node.text
440 case .radioTarget: return String(node.text.dropFirst(3).dropLast(3))
441 case .target: return ""
442 case .superscript, .subscript:
443 let body = node.text.dropFirst()
444 let braced = body.hasPrefix("{") && body.hasSuffix("}")
445 if options.scripts == .off || (options.scripts == .braces && !braced) { return special(node.text) }
446 let mark = node.text.hasPrefix("_") ? "_" : "^"
447 return braced ? mark + "{" + String(body.dropFirst().dropLast()) + "}" : mark + String(body)
448 case .lineBreak: return Self.hardNewline
449 case .latexFragment: return options.tex ? node.text : ""
450 case .inlineSourceBlock:
451 if let m = node.text.firstMatch(of: /\{(.*)\}$/) { return "`\(m.1)'" }
452 return node.text
453 case .exportSnippet:
454 guard node.tokens.first?.text.lowercased() == "@@ascii:" else { return "" }
455 return node.tokens.filter { $0.kind != .marker }.map(\.text).joined()
456 case .statisticsCookie: return node.text
457 case .inlineBabelCall, .macro: return ""
458 default: return inline(node)
459 }
460 }
461
462 func link(_ node: SyntaxNode) -> String {
463 let description = node.firstChild(.linkDescription).map { inline($0) }
464 guard let path = node.linkPath else {
465 var target = node.text
466 if target.hasPrefix("<"), target.hasSuffix(">") { target = String(target.dropFirst().dropLast()) }
467 // A radio link is its text.
468 if !target.contains(":") { return target }
469 return "<\(target)>"
470 }
471 if path.hasPrefix("("), path.hasSuffix(")") { return description ?? String(path.dropFirst().dropLast()) }
472 let scheme = path.firstMatch(of: /^([A-Za-z][A-Za-z0-9+.-]*):/).map { String($0.1).lowercased() }
473 let isInternal = scheme == nil || scheme == "id" || path.hasPrefix("#") || path.hasPrefix("*")
474 if isInternal, !(scheme == nil && (path.hasPrefix("/") || path.hasPrefix("./") || path.hasPrefix("~"))) {
475 let title = path.hasPrefix("*") ? String(path.dropFirst()) : path
476 let number = headingNumbers[title]
477 if let description { return "[\(description)]" + (number.map { " (See section \($0))" } ?? "") }
478 return number ?? title
479 }
480 guard let description, description.contains(where: { !$0.isWhitespace }) else { return "<\(path)>" }
481 return "[\(description)] (<\(path)>)"
482 }
483
484 /// `org-timestamp-translate`: the timestamp as Org writes it, `9:00` as `09:00`.
485 static func timestamp(_ text: String) -> String {
486 guard let stamp = Timestamp.parse(text) else { return text }
487 let open = stamp.active ? "<" : "["
488 let close = stamp.active ? ">" : "]"
489 func day(_ p: Timestamp.Point) -> String {
490 let name = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][Days.weekday(Days.absolute(year: p.year, month: p.month, day: p.day))]
491 return String(format: "%04d-%02d-%02d ", p.year, p.month, p.day) + name
492 }
493 func time(_ p: Timestamp.Point) -> String { p.hour.map { String(format: " %02d:%02d", $0, p.minute ?? 0) } ?? "" }
494 var suffix = ""
495 if let r = stamp.repeater {
496 suffix += " " + r.kind.rawValue + "\(r.interval.value)\(r.interval.unit.rawValue)"
497 if let d = r.habitDeadline { suffix += "/\(d.value)\(d.unit.rawValue)" }
498 }
499 if let w = stamp.warning { suffix += " " + (w.firstOccurrenceOnly ? "--" : "-") + "\(w.interval.value)\(w.interval.unit.rawValue)" }
500 let start = stamp.start
501 guard let end = stamp.end else { return open + day(start) + time(start) + suffix + close }
502 if (end.year, end.month, end.day) == (start.year, start.month, start.day), start.hour != nil, end.hour != nil {
503 return open + day(start) + time(start) + "-" + String(time(end).dropFirst()) + suffix + close
504 }
505 return open + day(start) + time(start) + suffix + close + "--" + open + day(end) + time(end) + suffix + close
506 }
507}