Sources/OrgPresentation/TagGap.swift

15d73b1f0d2ee9cac84fe463bbeaf4b409d8f9fb
orgstar/Sources/OrgPresentation/TagGap.swift

52 lines · 2295 bytes

 1import Foundation
 2import OrgCore
 3
 4/// A heading's tags and the spaces before them, which `org-tags-column` pads to line the tags
 5/// up. The editors and the reader draw the spaces as one gap so the line never wraps inside
 6/// the padding or the tags; the file keeps its spaces.
 7public struct TagGap: Sendable, Equatable {
 8    /// The spaces between the title and the tags.
 9    public let gap: Range<Int>
10    public let tags: Range<Int>
11
12    public init(gap: Range<Int>, tags: Range<Int>) {
13        self.gap = gap
14        self.tags = tags
15    }
16}
17
18extension Presentation {
19    /// The spaces before `tags`, when there are two or more. A gap with a tab is left as written.
20    public static func tagGap(tags: Range<Int>, in text: NSString) -> TagGap? {
21        var start = tags.lowerBound
22        while start > 0, text.character(at: start - 1) == 0x20 { start -= 1 }
23        guard tags.lowerBound - start > 1, start > 0, text.character(at: start - 1) != 0x09 else { return nil }
24        return TagGap(gap: start..<tags.lowerBound, tags: tags)
25    }
26
27    /// Every heading's tag gap, in document order.
28    public static func tagGaps(_ tree: OrgTree) -> [TagGap] {
29        var gaps: [TagGap] = []
30        let text = tree.text as NSString
31        func visit(_ node: SyntaxNode) {
32            for section in node.children where section.kind == .section {
33                if let tags = section.firstChild(.heading)?.tokens.first(where: { $0.kind == .tags }),
34                   tags.range.upperBound <= text.length, let gap = tagGap(tags: tags.range, in: text) {
35                    gaps.append(gap)
36                }
37                visit(section)
38            }
39        }
40        visit(tree.root)
41        return gaps
42    }
43
44    /// The width to draw a tag gap at, on a line `available` wide whose text before the gap is
45    /// `title` wide: nil, as written, when the line fits; else the tags at the right edge when
46    /// they fit after one space; else one space, and the line wraps before the tags.
47    public static func tagGapWidth(title: CGFloat, gap: CGFloat, space: CGFloat, tags: CGFloat, available: CGFloat) -> CGFloat? {
48        if title + gap + tags <= available { return nil }
49        if title + space + tags <= available { return available - title - tags }
50        return space
51    }
52}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form