Repository navigation
Expand file tree
/
Copy pathMarkdownToken.swift
More file actions
77 lines (71 loc) · 2.8 KB
/
Copy pathMarkdownToken.swift
File metadata and controls
77 lines (71 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//
// MarkdownToken.swift
// MarkdownEngine
//
// Created by Luca Chen on 18.02.26.
//
// Defines the basic Markdown building blocks the editor works with (bold,
// links, code, LaTeX, etc.).
import Foundation
enum MarkdownTokenKind: Equatable {
case italic
case boldItalic
case bold
case link
case wikiLink
case heading
/// One blockquote line; `markerRanges[0]` is the `>` run, nesting = count of `>`.
case blockquote
case codeBlock
case inlineCode
case blockLatex
case inlineLatex
case imageEmbed
case imageLink
case table
/// A CommonMark backslash escape; marker is the `\`, content the escaped literal char.
case backslashEscape
/// A span contributed by a registered `MarkdownExtension`,
/// carrying the extension's id (e.g. `.extensionSpan("highlight")`).
case extensionSpan(String)
/// A fenced block contributed by a registered `MarkdownExtension`,
/// carrying the extension's id (e.g. `.extensionBlock("container")`).
case extensionBlock(String)
}
struct MarkdownToken {
let kind: MarkdownTokenKind
let range: NSRange
let contentRange: NSRange
let markerRanges: [NSRange]
}
extension MarkdownToken {
func standaloneParagraphRange(in text: NSString) -> NSRange? {
let paragraphRange = text.paragraphRange(for: range)
let paragraphText = text.substring(with: paragraphRange) as NSString
let tokenRelativeRange = NSRange(
location: range.location - paragraphRange.location,
length: range.length
)
let mutableParagraph = paragraphText.mutableCopy() as! NSMutableString
mutableParagraph.replaceCharacters(in: tokenRelativeRange, with: "")
return mutableParagraph.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? paragraphRange : nil
}
func containsSelectionOrStandaloneParagraph(_ selectionLocation: Int, in text: NSString) -> Bool {
let start = range.location
let end = NSMaxRange(range) - 1
if selectionLocation >= start && selectionLocation <= end {
return true
}
guard let paragraphRange = standaloneParagraphRange(in: text) else {
return false
}
let paragraphEnd = NSMaxRange(paragraphRange)
// Reveal source when caret is at document end right after the image, unless that line ends in a newline.
let endsWithNewline = paragraphEnd > paragraphRange.location
&& (text.character(at: paragraphEnd - 1) == 0x0A || text.character(at: paragraphEnd - 1) == 0x0D)
let isAtLastParagraphEnd = selectionLocation == text.length
&& paragraphEnd == text.length && !endsWithNewline
return (selectionLocation >= paragraphRange.location && selectionLocation < paragraphEnd)
|| isAtLastParagraphEnd
}
}