Sources/OrgCore/Commands/Emphasis.swift

63 lines · 3706 bytes

 1import Foundation
 2
 3/// `org-emphasize`: wraps the selection in an emphasis marker, replacing one it already has, or
 4/// with no selection inserts a pair and puts the caret between. A space removes the marker.
 5/// `marker` set is the command for one marker, as the Mac preset's ⌘B binds it.
 6public struct Emphasize: OrgCommand {
 7    let marker: Character?
 8    public init(marker: Character? = nil) { self.marker = marker }
 9
10    /// `org-emphasis-alist`'s markers, and the id and title of each one's own command.
11    static let markers: [(marker: Character, name: String, title: String)] = [
12        ("*", "bold", "Bold"), ("/", "italic", "Italic"), ("_", "underline", "Underline"),
13        ("=", "verbatim", "Verbatim"), ("~", "code", "Code"), ("+", "strike-through", "Strike-Through"),
14    ]
15    /// `org-emphasis-regexp-components`: what may come before and after a marker.
16    static let before: Set<Character> = ["-", "(", "'", "\"", "{", "\n"]
17    static let after: Set<Character> = ["-", ".", ",", ":", "!", "?", ";", "'", "\"", ")", "}", "\\", "[", "\n"]
18
19    public var id: String { marker.flatMap { m in Self.markers.first { $0.marker == m } }.map { "org.emphasize.\($0.name)" } ?? "org.emphasize" }
20    public var title: String { marker.flatMap { m in Self.markers.first { $0.marker == m } }.map(\.title) ?? "Emphasize…" }
21    public func applies(in context: EditContext) -> Bool { true }
22
23    public func run(in context: EditContext) -> CommandStep {
24        let answer: Character
25        if let marker {
26            answer = marker
27        } else if let given = context.answers["emphasis"]?.first {
28            answer = given
29        } else {
30            let items = Self.markers.map { FastSelection.Item.option(key: $0.marker, name: $0.name) } + [.option(key: " ", name: "remove")]
31            let message = "Emphasis marker or tag: [\(String(Self.markers.map(\.marker)))]"
32            return .prompt(Prompt(key: "emphasis", message: message, fast: FastSelection(items: items, multiple: false)))
33        }
34        guard answer == " " || Self.markers.contains(where: { $0.marker == answer }) else {
35            return .failed("No such emphasis marker: \"\(answer)\"")
36        }
37        let text = context.text as NSString
38        let selection = context.selection.first ?? context.caret..<context.caret
39        let move = selection.isEmpty
40        var inner = text.substring(with: NSRange(selection))
41        // A selection already emphasized loses its markers first.
42        while inner.count > 1, let first = inner.first, inner.last == first, Self.markers.contains(where: { $0.marker == first }) {
43            inner = String(inner.dropFirst().dropLast())
44        }
45        let marker = answer == " " ? "" : String(answer)
46        let string = marker + inner + marker
47        func char(at offset: Int) -> Character? {
48            guard offset >= 0, offset < text.length else { return nil }
49            return Character(text.substring(with: text.rangeOfComposedCharacterSequence(at: offset)))
50        }
51        let previous = char(at: selection.lowerBound - 1)
52        let next = char(at: selection.upperBound)
53        let lead = previous.map { $0.isWhitespace || Self.before.contains($0) } ?? true ? "" : " "
54        let trail = next.map { $0.isWhitespace || Self.after.contains($0) } ?? true ? "" : " "
55        let start = selection.lowerBound + lead.utf16.count
56        let caret = move && answer != " " ? start + string.utf16.count - 1 : start + string.utf16.count
57        return .commit(EditResult(
58            baseRevision: context.revision,
59            edits: [TextEdit(range: selection, replacement: lead + string + trail)],
60            selection: [caret..<caret]
61        ))
62    }
63}