Commit 49c5da9709
Verified · cmc
Changed files (39)
- Sources/OrgApp/DocumentSession.swift +11 −2
- Sources/OrgApp/ReplaceInFiles.swift +1 −1
- Sources/OrgCore/Commands/OrgOnlyCommands.swift added +28
- Sources/OrgCore/Markdown/MarkdownSpans.swift added +394
- Sources/OrgCore/Markdown/MarkdownStructure.swift added +272
- Sources/OrgEditorAppKit/Modal.swift +1 −1
- Sources/OrgEditorAppKit/OrgEditor+Folding.swift +15 −2
- Sources/OrgEditorAppKit/OrgEditor+Shrink.swift +6 −6
- Sources/OrgEditorAppKit/OrgEditor+Styling.swift +8
- Sources/OrgEditorAppKit/OrgEditor.swift +45 −9
- Sources/OrgEditorAppKit/ViewToggles.swift +12 −1
- Sources/OrgIndex/FileRecord.swift +37
- Sources/OrgPresentation/MarkdownDisplay.swift added +179
- Sources/OrgPresentation/Restyling.swift +3
- Sources/OrgWorkspace/Discovery.swift +3 −1
- Sources/Orgstar/ContentView.swift +3 −4
- Sources/Orgstar/PaneView.swift +1 −1
- Sources/Orgstar/Sidebar.swift +3 −2
- Sources/OrgstarMobile/EditorScreen.swift +3 −2
- Sources/OrgstarMobile/FoldersScreen.swift +2 −2
- Sources/OrgstarMobile/MobileEditor+Display.swift +8 −6
- Sources/OrgstarMobile/MobileEditor+Snippets.swift +1 −1
- Sources/OrgstarMobile/MobileEditor+Spelling.swift +1 −1
- Sources/OrgstarMobile/MobileEditor+Styling.swift +15 −4
- Sources/OrgstarMobile/MobileEditor.swift +56 −13
- Sources/OrgstarMobile/OrgstarMobileApp.swift +11 −2
- Sources/OrgstarMobile/SearchScreen.swift +2 −2
- Tests/OrgAppTests/AppTests.swift +14
- Tests/OrgCoreTests/MarkdownTests.swift added +134
- Tests/OrgEditorAppKitTests/GateTests.swift +22 −2
- Tests/OrgEditorAppKitTests/MarkdownModeTests.swift added +113
- Tests/OrgIndexTests/TextFileRecordTests.swift added +43
- Tests/OrgPresentationTests/MarkdownDisplayTests.swift added +87
- Tests/OrgWorkspaceTests/DiscoveryTests.swift +6 −2
- Tests/OrgWorkspaceTests/ReconcileTests.swift +1 −1
- docs/manual/guide/01-files-and-folders.org +26 −6
- docs/manual/guide/02-the-editor.org +4
- docs/manual/guide/14-ios.org +8 −3
- l10n/Localizable.xcstrings +34
Sources/OrgApp/DocumentSession.swift +11 −2 · view
| @@ -333,6 +333,15 @@ public final class DocumentSession { | ||
| 333 | 333 | path.hasSuffix(".org") || path.hasSuffix(".org_archive") || path.hasSuffix(".org.gpg") |
| 334 | 334 | } |
| 335 | 335 | |
| 336 | /// Whether the open file is Markdown, which has highlighting, heading folds and an outline. | |
| 337 | public var isMarkdown: Bool { path.map(Markdown.isPath) ?? false } | |
| 338 | ||
| 339 | /// The outline of `path`'s text: org headings, or Markdown's; none for other files. | |
| 340 | static func outline(_ path: String, _ state: DocumentState) -> [OutlineEntry] { | |
| 341 | if isOrgPath(path) { return Presentation.outline(state.tree) } | |
| 342 | return Markdown.isPath(path) ? MarkdownDocument(state.text).outline : [] | |
| 343 | } | |
| 344 | ||
| 336 | 345 | /// The caret in the open file. |
| 337 | 346 | public var caret: Int { buffer?.selection.first?.lowerBound ?? 0 } |
| 338 | 347 | private var name: String { path.map { ($0 as NSString).lastPathComponent } ?? "" } |
| @@ -559,7 +568,7 @@ public final class DocumentSession { | ||
| 559 | 568 | outlineUpdates[path] = Task { [weak self, weak entry] in |
| 560 | 569 | try? await Task.sleep(for: .milliseconds(300)) |
| 561 | 570 | guard !Task.isCancelled, let self, let entry else { return } |
| 562 | let outline = Self.isOrgPath(path) ? Presentation.outline(entry.buffer.document.tree) : [] | |
| 571 | let outline = Self.outline(path, entry.buffer.document) | |
| 563 | 572 | for pane in self.panes(showing: path) { |
| 564 | 573 | pane.outline = outline |
| 565 | 574 | pane.editVersion += 1 |
| @@ -582,7 +591,7 @@ public final class DocumentSession { | ||
| 582 | 591 | if pane.isReadOnly == state.isEditable { pane.isReadOnly = !state.isEditable } |
| 583 | 592 | if pane.conflict != entry.conflict { pane.conflict = entry.conflict } |
| 584 | 593 | if updateOutline { |
| 585 | pane.outline = Self.isOrgPath(entry.path) ? Presentation.outline(state.tree) : [] | |
| 594 | pane.outline = Self.outline(entry.path, state) | |
| 586 | 595 | pane.editVersion += 1 |
| 587 | 596 | } |
| 588 | 597 | } |
Sources/OrgApp/ReplaceInFiles.swift +1 −1 · view
| @@ -136,7 +136,7 @@ public final class ReplaceInFiles { | ||
| 136 | 136 | guard scope == nil || entry.root == scope, !EncryptedText.isEncryptedFile(entry.path) else { return false } |
| 137 | 137 | switch entry.kind { |
| 138 | 138 | case .org, .archive: return true |
| 139 | case .other: | |
| 139 | case .text, .other: | |
| 140 | 140 | if case .replace = mode { return Self.textExtensions.contains((entry.path as NSString).pathExtension.lowercased()) } |
| 141 | 141 | return false |
| 142 | 142 | case .conflict: return false |
Sources/OrgCore/Commands/OrgOnlyCommands.swift added +28 · view
| @@ -0,0 +1,28 @@ | ||
| 1 | /// Commands that read or write org syntax in the open file, refused in Markdown and other | |
| 2 | /// text files so none of them writes org into one. | |
| 3 | public enum OrgOnlyCommands { | |
| 4 | /// Visibility commands, which fold Markdown headings as they fold org ones. | |
| 5 | public static func folds(_ id: String) -> Bool { | |
| 6 | id == "org.cycle" || id == "org.cycle-global" || id.hasPrefix("org.fold.") | |
| 7 | } | |
| 8 | ||
| 9 | /// Whether `id` is refused in a file that isn't org; `markdown` lets the fold commands run. | |
| 10 | public static func refuses(_ id: String, markdown: Bool) -> Bool { | |
| 11 | if markdown, folds(id) { return false } | |
| 12 | if id.hasPrefix("org.") || id.hasPrefix("app.attach.") { return true } | |
| 13 | if id.hasPrefix("app.export.") { return !id.hasPrefix("app.export.icalendar-") } | |
| 14 | return appCommands.contains(id) | |
| 15 | } | |
| 16 | ||
| 17 | /// App commands that act on the open file's entries, tables, links or Denote front matter. | |
| 18 | static let appCommands: Set<String> = [ | |
| 19 | "app.refile", "app.refile.copy", "app.archive", "app.clock.in", "app.clock.default", "app.copy-rich-text", | |
| 20 | "app.export-dialog", "app.export-subtree-dialog", "app.export-subtree", "app.export-body-only", "app.share-subtree", | |
| 21 | "app.table-import", "app.table-export", "app.table-export.tsv", "app.plot", | |
| 22 | "app.crypt.encrypt-entry", "app.crypt.encrypt-entries", "app.crypt.open-entry", "app.crypt.decrypt-entry", | |
| 23 | "app.node.insert", "app.node.rename", "app.node.rename-from-front-matter", | |
| 24 | "app.node.sequence-convert", "app.node.sequence-link", "app.node.sequence-rename-as-parent", "app.node.sequence-reparent", | |
| 25 | "app.node.sequence-reparent-recursive", "app.node.sequence-new-child-of-current", "app.node.sequence-new-sibling-of-current", | |
| 26 | "app.publish.current-file", | |
| 27 | ] | |
| 28 | } | |
Sources/OrgCore/Markdown/MarkdownSpans.swift added +394 · view
| @@ -0,0 +1,394 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | extension Markdown { | |
| 4 | /// What a range of a Markdown line is, for highlighting. | |
| 5 | public struct Span: Sendable, Equatable { | |
| 6 | public enum Kind: Sendable, Equatable { | |
| 7 | case heading(level: Int) | |
| 8 | case code, bold, italic, strikeThrough | |
| 9 | /// Emphasis and code delimiters, list bullets and block quote markers. | |
| 10 | case marker | |
| 11 | case link | |
| 12 | /// A link's brackets and destination. | |
| 13 | case linkMarkup | |
| 14 | case comment, rule, table, quote, checkbox | |
| 15 | } | |
| 16 | ||
| 17 | public let kind: Kind | |
| 18 | public let range: Range<Int> | |
| 19 | ||
| 20 | public init(_ kind: Kind, _ range: Range<Int>) { | |
| 21 | self.kind = kind | |
| 22 | self.range = range | |
| 23 | } | |
| 24 | } | |
| 25 | ||
| 26 | static let backslash: UInt16 = 92 | |
| 27 | static let lessThan: UInt16 = 60 | |
| 28 | static let greaterThan: UInt16 = 62 | |
| 29 | static let openBracket: UInt16 = 91 | |
| 30 | static let closeBracket: UInt16 = 93 | |
| 31 | static let openParen: UInt16 = 40 | |
| 32 | static let closeParen: UInt16 = 41 | |
| 33 | static let bang: UInt16 = 33 | |
| 34 | static let star: UInt16 = 42 | |
| 35 | static let underscore: UInt16 = 95 | |
| 36 | static let dash: UInt16 = 45 | |
| 37 | static let plus: UInt16 = 43 | |
| 38 | static let pipe: UInt16 = 124 | |
| 39 | static let colon: UInt16 = 58 | |
| 40 | ||
| 41 | /// Spans of the Markdown line from `start` to `end` (its newline excluded), which is | |
| 42 | /// outside front matter and fences. Outer spans come before the spans inside them. | |
| 43 | public static func lineSpans(_ u: [UInt16], _ start: Int, _ end: Int) -> [Span] { | |
| 44 | var spans: [Span] = [] | |
| 45 | lineSpans(u, start, end, into: &spans) | |
| 46 | return spans.sorted { $0.range.lowerBound != $1.range.lowerBound ? $0.range.lowerBound < $1.range.lowerBound : $0.range.upperBound > $1.range.upperBound } | |
| 47 | } | |
| 48 | ||
| 49 | static func lineSpans(_ u: [UInt16], _ start: Int, _ end: Int, into spans: inout [Span]) { | |
| 50 | if let heading = atxHeading(u, start, end) { | |
| 51 | spans.append(Span(.heading(level: heading.level), start..<end)) | |
| 52 | inline(u, heading.title, line: start..<end, into: &spans) | |
| 53 | return | |
| 54 | } | |
| 55 | if isThematicBreak(u, start, end) { | |
| 56 | spans.append(Span(.rule, start..<end)) | |
| 57 | return | |
| 58 | } | |
| 59 | var i = start | |
| 60 | // Block quote markers, nested or not. | |
| 61 | var quoted = false | |
| 62 | while true { | |
| 63 | var j = i | |
| 64 | var indent = 0 | |
| 65 | while j < end, u[j] == space, indent < 3 { j += 1; indent += 1 } | |
| 66 | guard j < end, u[j] == greaterThan else { break } | |
| 67 | spans.append(Span(.marker, j..<(j + 1))) | |
| 68 | i = j + 1 | |
| 69 | if i < end, u[i] == space || u[i] == tab { i += 1 } | |
| 70 | quoted = true | |
| 71 | } | |
| 72 | if quoted, i < end { spans.append(Span(.quote, i..<end)) } | |
| 73 | // A list item's bullet or number, and a task's box. | |
| 74 | var j = i | |
| 75 | while j < end, u[j] == space || u[j] == tab { j += 1 } | |
| 76 | if let marker = listMarker(u, j, end) { | |
| 77 | spans.append(Span(.marker, j..<marker)) | |
| 78 | var k = marker | |
| 79 | while k < end, u[k] == space || u[k] == tab { k += 1 } | |
| 80 | if k + 2 < end, u[k] == openBracket, u[k + 2] == closeBracket, [space, 120, 88].contains(u[k + 1]), k + 3 == end || isBlank(u[k + 3]) { | |
| 81 | spans.append(Span(.checkbox, k..<(k + 3))) | |
| 82 | k += 3 | |
| 83 | } | |
| 84 | i = k | |
| 85 | } else if j < end, u[j] == pipe { | |
| 86 | spans.append(Span(.table, j..<trimmedEnd(u, j, end))) | |
| 87 | } else if let definition = linkDefinition(u, j, end) { | |
| 88 | spans.append(Span(.linkMarkup, j..<definition.lowerBound)) | |
| 89 | spans.append(Span(.link, definition)) | |
| 90 | return | |
| 91 | } | |
| 92 | inline(u, i..<end, line: start..<end, into: &spans) | |
| 93 | } | |
| 94 | ||
| 95 | /// Three or more `-`, `*` or `_`, the same one, with only spaces between. | |
| 96 | static func isThematicBreak(_ u: [UInt16], _ start: Int, _ end: Int) -> Bool { | |
| 97 | var i = start | |
| 98 | var indent = 0 | |
| 99 | while i < end, u[i] == space, indent < 3 { i += 1; indent += 1 } | |
| 100 | guard i < end, [dash, star, underscore].contains(u[i]) else { return false } | |
| 101 | let char = u[i] | |
| 102 | var count = 0 | |
| 103 | while i < end { | |
| 104 | if u[i] == char { count += 1 } else if !isBlank(u[i]) { return false } | |
| 105 | i += 1 | |
| 106 | } | |
| 107 | return count >= 3 | |
| 108 | } | |
| 109 | ||
| 110 | /// The end of a list marker at `i`: `-`, `*` or `+`, or up to nine digits and `.` or `)`, | |
| 111 | /// followed by a space, a tab or the end of the line. | |
| 112 | static func listMarker(_ u: [UInt16], _ i: Int, _ end: Int) -> Int? { | |
| 113 | guard i < end else { return nil } | |
| 114 | var j = i | |
| 115 | if u[i] == dash || u[i] == star || u[i] == plus { | |
| 116 | j += 1 | |
| 117 | } else { | |
| 118 | while j < end, j - i < 9, u[j] >= 48, u[j] <= 57 { j += 1 } | |
| 119 | guard j > i, j < end, u[j] == 46 || u[j] == closeParen else { return nil } | |
| 120 | j += 1 | |
| 121 | } | |
| 122 | return j == end || u[j] == space || u[j] == tab ? j : nil | |
| 123 | } | |
| 124 | ||
| 125 | /// `[label]: destination`: the destination's range. | |
| 126 | static func linkDefinition(_ u: [UInt16], _ i: Int, _ end: Int) -> Range<Int>? { | |
| 127 | guard i < end, u[i] == openBracket else { return nil } | |
| 128 | var j = i + 1 | |
| 129 | while j < end, u[j] != closeBracket { j += 1 } | |
| 130 | guard j > i + 1, j + 1 < end, u[j + 1] == colon else { return nil } | |
| 131 | var k = j + 2 | |
| 132 | while k < end, isBlank(u[k]) { k += 1 } | |
| 133 | var e = k | |
| 134 | while e < end, !isBlank(u[e]) { e += 1 } | |
| 135 | return e > k ? k..<e : nil | |
| 136 | } | |
| 137 | ||
| 138 | // MARK: - Inline | |
| 139 | ||
| 140 | /// Code spans, comments, autolinks and links first, as they hide what's inside them from | |
| 141 | /// emphasis; then bare URLs and emphasis in the text between. | |
| 142 | static func inline(_ u: [UInt16], _ range: Range<Int>, line: Range<Int>, into spans: inout [Span]) { | |
| 143 | let upper = range.upperBound | |
| 144 | var plain: [Range<Int>] = [] | |
| 145 | var segment = range.lowerBound | |
| 146 | var i = range.lowerBound | |
| 147 | func take(_ end: Int) { | |
| 148 | plain.append(segment..<i) | |
| 149 | i = end | |
| 150 | segment = end | |
| 151 | } | |
| 152 | while i < upper { | |
| 153 | let c = u[i] | |
| 154 | if c == backslash { | |
| 155 | i += 2 | |
| 156 | continue | |
| 157 | } | |
| 158 | if c == backtick { | |
| 159 | var runEnd = i | |
| 160 | while runEnd < upper, u[runEnd] == backtick { runEnd += 1 } | |
| 161 | if let close = backtickRun(u, from: runEnd, to: upper, count: runEnd - i) { | |
| 162 | let end = close + runEnd - i | |
| 163 | spans.append(Span(.code, i..<end)) | |
| 164 | spans.append(Span(.marker, i..<runEnd)) | |
| 165 | spans.append(Span(.marker, close..<end)) | |
| 166 | take(end) | |
| 167 | } else { | |
| 168 | i = runEnd | |
| 169 | } | |
| 170 | continue | |
| 171 | } | |
| 172 | if c == lessThan { | |
| 173 | if starts(u, i, upper, "<!--"), let close = find(u, from: i + 4, to: upper, "-->") { | |
| 174 | spans.append(Span(.comment, i..<(close + 3))) | |
| 175 | take(close + 3) | |
| 176 | continue | |
| 177 | } | |
| 178 | if let close = autolink(u, i, upper) { | |
| 179 | spans.append(Span(.linkMarkup, i..<(i + 1))) | |
| 180 | spans.append(Span(.link, (i + 1)..<close)) | |
| 181 | spans.append(Span(.linkMarkup, close..<(close + 1))) | |
| 182 | take(close + 1) | |
| 183 | continue | |
| 184 | } | |
| 185 | } | |
| 186 | if c == openBracket || (c == bang && i + 1 < upper && u[i + 1] == openBracket) { | |
| 187 | let open = c == bang ? i + 1 : i | |
| 188 | if let link = link(u, open, upper) { | |
| 189 | spans.append(Span(.linkMarkup, i..<(open + 1))) | |
| 190 | spans.append(Span(.link, (open + 1)..<link.textEnd)) | |
| 191 | spans.append(Span(.linkMarkup, link.textEnd..<link.end)) | |
| 192 | plain.append(segment..<i) | |
| 193 | inline(u, (open + 1)..<link.textEnd, line: line, into: &spans) | |
| 194 | i = link.end | |
| 195 | segment = link.end | |
| 196 | continue | |
| 197 | } | |
| 198 | } | |
| 199 | i += 1 | |
| 200 | } | |
| 201 | plain.append(segment..<upper) | |
| 202 | for part in plain where !part.isEmpty { | |
| 203 | var from = part.lowerBound | |
| 204 | for url in bareURLs(u, part) { | |
| 205 | spans.append(Span(.link, url)) | |
| 206 | emphasis(u, from..<url.lowerBound, line: line, into: &spans) | |
| 207 | from = url.upperBound | |
| 208 | } | |
| 209 | emphasis(u, from..<part.upperBound, line: line, into: &spans) | |
| 210 | } | |
| 211 | } | |
| 212 | ||
| 213 | static func starts(_ u: [UInt16], _ i: Int, _ upper: Int, _ prefix: String) -> Bool { | |
| 214 | let p = Array(prefix.utf16) | |
| 215 | return i + p.count <= upper && Array(u[i..<(i + p.count)]) == p | |
| 216 | } | |
| 217 | ||
| 218 | static func find(_ u: [UInt16], from: Int, to upper: Int, _ needle: String) -> Int? { | |
| 219 | var i = from | |
| 220 | while i < upper { | |
| 221 | if starts(u, i, upper, needle) { return i } | |
| 222 | i += 1 | |
| 223 | } | |
| 224 | return nil | |
| 225 | } | |
| 226 | ||
| 227 | /// The start of the next run of exactly `count` backticks. | |
| 228 | static func backtickRun(_ u: [UInt16], from: Int, to upper: Int, count: Int) -> Int? { | |
| 229 | var i = from | |
| 230 | while i < upper { | |
| 231 | guard u[i] == backtick else { | |
| 232 | i += 1 | |
| 233 | continue | |
| 234 | } | |
| 235 | var e = i | |
| 236 | while e < upper, u[e] == backtick { e += 1 } | |
| 237 | if e - i == count { return i } | |
| 238 | i = e | |
| 239 | } | |
| 240 | return nil | |
| 241 | } | |
| 242 | ||
| 243 | /// `<scheme:…>` or `<name@host>`: the offset of the closing `>`. | |
| 244 | static func autolink(_ u: [UInt16], _ i: Int, _ upper: Int) -> Int? { | |
| 245 | var j = i + 1 | |
| 246 | var sawScheme = false | |
| 247 | var sawAt = false | |
| 248 | while j < upper, u[j] != greaterThan { | |
| 249 | let c = u[j] | |
| 250 | if c == space || c == tab || c == lessThan { return nil } | |
| 251 | if c == colon, j > i + 2 { sawScheme = true } | |
| 252 | if c == 64 { sawAt = true } | |
| 253 | j += 1 | |
| 254 | } | |
| 255 | guard j < upper, j > i + 1, sawScheme || sawAt else { return nil } | |
| 256 | let first = u[i + 1] | |
| 257 | guard (first >= 65 && first <= 90) || (first >= 97 && first <= 122) || (first >= 48 && first <= 57) else { return nil } | |
| 258 | return j | |
| 259 | } | |
| 260 | ||
| 261 | /// `[text](destination)` or `[text][label]` from the `[` at `open`: the `]` closing the | |
| 262 | /// text, and the end of the link. | |
| 263 | static func link(_ u: [UInt16], _ open: Int, _ upper: Int) -> (textEnd: Int, end: Int)? { | |
| 264 | var depth = 0 | |
| 265 | var j = open | |
| 266 | while j < upper { | |
| 267 | let c = u[j] | |
| 268 | if c == backslash { | |
| 269 | j += 2 | |
| 270 | continue | |
| 271 | } | |
| 272 | if c == openBracket { depth += 1 } | |
| 273 | if c == closeBracket { | |
| 274 | depth -= 1 | |
| 275 | if depth == 0 { break } | |
| 276 | } | |
| 277 | j += 1 | |
| 278 | } | |
| 279 | guard j < upper, j + 1 < upper else { return nil } | |
| 280 | let textEnd = j | |
| 281 | if u[j + 1] == openParen { | |
| 282 | var parens = 0 | |
| 283 | var k = j + 1 | |
| 284 | while k < upper { | |
| 285 | let c = u[k] | |
| 286 | if c == backslash { | |
| 287 | k += 2 | |
| 288 | continue | |
| 289 | } | |
| 290 | if c == openParen { parens += 1 } | |
| 291 | if c == closeParen { | |
| 292 | parens -= 1 | |
| 293 | if parens == 0 { return (textEnd, k + 1) } | |
| 294 | } | |
| 295 | k += 1 | |
| 296 | } | |
| 297 | return nil | |
| 298 | } | |
| 299 | if u[j + 1] == openBracket { | |
| 300 | var k = j + 2 | |
| 301 | while k < upper, u[k] != closeBracket, u[k] != openBracket { k += 1 } | |
| 302 | return k < upper && u[k] == closeBracket ? (textEnd, k + 1) : nil | |
| 303 | } | |
| 304 | return nil | |
| 305 | } | |
| 306 | ||
| 307 | /// `http://` and `https://` URLs, without trailing punctuation. | |
| 308 | static func bareURLs(_ u: [UInt16], _ range: Range<Int>) -> [Range<Int>] { | |
| 309 | var urls: [Range<Int>] = [] | |
| 310 | var i = range.lowerBound | |
| 311 | while i < range.upperBound { | |
| 312 | guard u[i] == 104, starts(u, i, range.upperBound, "http://") || starts(u, i, range.upperBound, "https://"), | |
| 313 | i == range.lowerBound || !isWordCharacter(u[i - 1]) else { | |
| 314 | i += 1 | |
| 315 | continue | |
| 316 | } | |
| 317 | var e = i | |
| 318 | while e < range.upperBound, !isBlank(u[e]), u[e] != lessThan { e += 1 } | |
| 319 | while e > i, [46, 44, 58, 59, 33, 63, 39, 34, closeParen, star, underscore].contains(u[e - 1]) { e -= 1 } | |
| 320 | if e > i + 8 { urls.append(i..<e) } | |
| 321 | i = max(e, i + 1) | |
| 322 | } | |
| 323 | return urls | |
| 324 | } | |
| 325 | ||
| 326 | static func isWordCharacter(_ c: UInt16) -> Bool { | |
| 327 | (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c > 127 | |
| 328 | } | |
| 329 | ||
| 330 | static func isPunctuation(_ c: UInt16) -> Bool { | |
| 331 | (c >= 33 && c <= 47) || (c >= 58 && c <= 64) || (c >= 91 && c <= 96) || (c >= 123 && c <= 126) | |
| 332 | } | |
| 333 | ||
| 334 | struct Delimiter { | |
| 335 | var position: Int | |
| 336 | let char: UInt16 | |
| 337 | var count: Int | |
| 338 | let canOpen: Bool | |
| 339 | let canClose: Bool | |
| 340 | } | |
| 341 | ||
| 342 | /// `**bold**`, `__bold__`, `*italic*`, `_italic_` and `~~strike~~`, matched as | |
| 343 | /// CommonMark's delimiter runs are, within `range`. Characters outside `line` count as | |
| 344 | /// whitespace. | |
| 345 | static func emphasis(_ u: [UInt16], _ range: Range<Int>, line: Range<Int>, into spans: inout [Span]) { | |
| 346 | guard !range.isEmpty else { return } | |
| 347 | var delimiters: [Delimiter] = [] | |
| 348 | var i = range.lowerBound | |
| 349 | while i < range.upperBound { | |
| 350 | let c = u[i] | |
| 351 | if c == backslash { | |
| 352 | i += 2 | |
| 353 | continue | |
| 354 | } | |
| 355 | guard c == star || c == underscore || c == tilde else { | |
| 356 | i += 1 | |
| 357 | continue | |
| 358 | } | |
| 359 | var e = i | |
| 360 | while e < range.upperBound, u[e] == c { e += 1 } | |
| 361 | let before: UInt16 = i > line.lowerBound ? u[i - 1] : space | |
| 362 | let after: UInt16 = e < line.upperBound ? u[e] : space | |
| 363 | let left = !isBlank(after) && (!isPunctuation(after) || isBlank(before) || isPunctuation(before)) | |
| 364 | let right = !isBlank(before) && (!isPunctuation(before) || isBlank(after) || isPunctuation(after)) | |
| 365 | let canOpen = c == underscore ? left && (!right || isPunctuation(before)) : left | |
| 366 | let canClose = c == underscore ? right && (!left || isPunctuation(after)) : right | |
| 367 | if c != tilde || e - i <= 2 { | |
| 368 | delimiters.append(Delimiter(position: i, char: c, count: e - i, canOpen: canOpen, canClose: canClose)) | |
| 369 | } | |
| 370 | i = e | |
| 371 | } | |
| 372 | guard delimiters.count > 1 else { return } | |
| 373 | for closer in delimiters.indices where delimiters[closer].canClose { | |
| 374 | while delimiters[closer].count > 0 { | |
| 375 | guard let opener = delimiters[..<closer].lastIndex(where: { | |
| 376 | $0.count > 0 && $0.canOpen && $0.char == delimiters[closer].char | |
| 377 | && ($0.char != tilde || $0.count == delimiters[closer].count) | |
| 378 | }) else { break } | |
| 379 | let char = delimiters[closer].char | |
| 380 | let use = char == tilde ? delimiters[closer].count : (delimiters[opener].count >= 2 && delimiters[closer].count >= 2 ? 2 : 1) | |
| 381 | let openEnd = delimiters[opener].position + delimiters[opener].count | |
| 382 | let closeStart = delimiters[closer].position | |
| 383 | let kind: Span.Kind = char == tilde ? .strikeThrough : use == 2 ? .bold : .italic | |
| 384 | spans.append(Span(kind, (openEnd - use)..<(closeStart + use))) | |
| 385 | spans.append(Span(.marker, (openEnd - use)..<openEnd)) | |
| 386 | spans.append(Span(.marker, closeStart..<(closeStart + use))) | |
| 387 | delimiters[opener].count -= use | |
| 388 | delimiters[closer].count -= use | |
| 389 | delimiters[closer].position += use | |
| 390 | for between in (opener + 1)..<closer { delimiters[between].count = 0 } | |
| 391 | } | |
| 392 | } | |
| 393 | } | |
| 394 | } | |
Sources/OrgCore/Markdown/MarkdownStructure.swift added +272 · view
| @@ -0,0 +1,272 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | /// Markdown as far as highlighting, heading folding, the outline and the index need it: front | |
| 4 | /// matter, fenced code and ATX headings line by line, and inline markup within a line. Not a | |
| 5 | /// CommonMark parser: setext headings, indented code blocks, HTML blocks and emphasis across | |
| 6 | /// lines aren't recognised, and fences may be indented by any amount. Offsets are UTF-16. | |
| 7 | public enum Markdown { | |
| 8 | /// Whether `path` names a Markdown file (`.md`, `.markdown`). | |
| 9 | public static func isPath(_ path: String) -> Bool { | |
| 10 | let ext = (path as NSString).pathExtension.lowercased() | |
| 11 | return ext == "md" || ext == "markdown" | |
| 12 | } | |
| 13 | ||
| 14 | /// Whether `path` names a plain text file (`.txt`). | |
| 15 | public static func isPlainTextPath(_ path: String) -> Bool { | |
| 16 | (path as NSString).pathExtension.lowercased() == "txt" | |
| 17 | } | |
| 18 | ||
| 19 | public struct Heading: Sendable, Equatable { | |
| 20 | /// Start of the heading line. | |
| 21 | public let start: Int | |
| 22 | /// Start of the line after it, or the end of the text. | |
| 23 | public let lineEnd: Int | |
| 24 | public let level: Int | |
| 25 | public let title: String | |
| 26 | } | |
| 27 | ||
| 28 | /// A fenced code block, from its opening line to after its closing line; an unclosed one | |
| 29 | /// runs to the end of the text. | |
| 30 | public struct Fence: Sendable, Equatable { | |
| 31 | public let range: Range<Int> | |
| 32 | /// The opening line, with its newline. | |
| 33 | public let opening: Range<Int> | |
| 34 | /// The closing line, with its newline. | |
| 35 | public let closing: Range<Int>? | |
| 36 | /// The first word of the info string. | |
| 37 | public let language: String? | |
| 38 | ||
| 39 | public var body: Range<Int> { opening.upperBound..<(closing?.lowerBound ?? range.upperBound) } | |
| 40 | } | |
| 41 | ||
| 42 | /// YAML front matter between `---` lines, or TOML between `+++` lines, on the first line. | |
| 43 | public struct FrontMatter: Sendable, Equatable { | |
| 44 | public enum Format: String, Sendable { case yaml, toml } | |
| 45 | public let format: Format | |
| 46 | public let range: Range<Int> | |
| 47 | public let opening: Range<Int> | |
| 48 | public let closing: Range<Int> | |
| 49 | ||
| 50 | public var body: Range<Int> { opening.upperBound..<closing.lowerBound } | |
| 51 | } | |
| 52 | ||
| 53 | public struct Structure: Sendable, Equatable { | |
| 54 | public var frontMatter: FrontMatter? | |
| 55 | public var fences: [Fence] = [] | |
| 56 | public var headings: [Heading] = [] | |
| 57 | ||
| 58 | public init() {} | |
| 59 | ||
| 60 | /// The ranges that aren't Markdown text: front matter and fences, in order. | |
| 61 | public var blocks: [Range<Int>] { (frontMatter.map { [$0.range] } ?? []) + fences.map(\.range) } | |
| 62 | } | |
| 63 | ||
| 64 | public static func structure(_ text: String) -> Structure { | |
| 65 | structure(Array(text.utf16)) | |
| 66 | } | |
| 67 | ||
| 68 | public static func structure(_ u: [UInt16]) -> Structure { | |
| 69 | var result = Structure() | |
| 70 | let n = u.count | |
| 71 | var i = 0 | |
| 72 | if let front = frontMatter(u) { | |
| 73 | result.frontMatter = front | |
| 74 | i = front.range.upperBound | |
| 75 | } | |
| 76 | var open: (start: Int, opening: Range<Int>, char: UInt16, count: Int, language: String?)? | |
| 77 | while i < n { | |
| 78 | let end = lineEnd(u, i) | |
| 79 | let next = end < n ? end + 1 : n | |
| 80 | if let fence = open { | |
| 81 | if isClosingFence(u, i, end, char: fence.char, count: fence.count) { | |
| 82 | result.fences.append(Fence(range: fence.start..<next, opening: fence.opening, closing: i..<next, language: fence.language)) | |
| 83 | open = nil | |
| 84 | } | |
| 85 | } else if let fence = openingFence(u, i, end) { | |
| 86 | open = (i, i..<next, fence.char, fence.count, fence.language) | |
| 87 | } else if let heading = atxHeading(u, i, end) { | |
| 88 | result.headings.append(Heading(start: i, lineEnd: next, level: heading.level, title: string(u, heading.title))) | |
| 89 | } | |
| 90 | i = next | |
| 91 | } | |
| 92 | if let fence = open { | |
| 93 | result.fences.append(Fence(range: fence.start..<n, opening: fence.opening, closing: nil, language: fence.language)) | |
| 94 | } | |
| 95 | return result | |
| 96 | } | |
| 97 | ||
| 98 | /// The structure of `new`, which is `old` with `edit` made, from `structure` without reading | |
| 99 | /// the whole text again: offsets after the edit move, and the edited lines are read for | |
| 100 | /// headings. Nil when the edit may start or end front matter or a fence, which needs a | |
| 101 | /// fresh read. | |
| 102 | public static func structure(_ structure: Structure, old: [UInt16], new: [UInt16], after edit: TextEdit) -> Structure? { | |
| 103 | let lower = edit.range.lowerBound | |
| 104 | let upper = edit.range.upperBound | |
| 105 | let delta = new.count - old.count | |
| 106 | var start = lower | |
| 107 | while start > 0, old[start - 1] != newline { start -= 1 } | |
| 108 | let oldEnd = lineEnd(old, upper) | |
| 109 | let newEnd = lineEnd(new, upper + delta) | |
| 110 | func mayFence(_ u: [UInt16], _ range: Range<Int>) -> Bool { | |
| 111 | var run = 0 | |
| 112 | for c in u[range] { | |
| 113 | run = c == backtick || c == tilde ? run + 1 : 0 | |
| 114 | if run >= 3 { return true } | |
| 115 | } | |
| 116 | return false | |
| 117 | } | |
| 118 | if start == 0 || mayFence(old, start..<oldEnd) || mayFence(new, start..<newEnd) { return nil } | |
| 119 | if let front = structure.frontMatter, start < front.range.upperBound { return nil } | |
| 120 | // An unclosed `---` or `+++` first line may be closed by the edit. | |
| 121 | let first = lineEnd(new, 0) | |
| 122 | if structure.frontMatter == nil, isLine(new, 0, first, "---") || isLine(new, 0, first, "+++") { return nil } | |
| 123 | // No front matter or fence line is edited, so their bounds are at or before the edited | |
| 124 | // lines' start, or after their end; an unclosed fence runs on to the end of the text. | |
| 125 | func map(_ offset: Int) -> Int { offset <= start ? offset : offset + delta } | |
| 126 | func map(_ range: Range<Int>) -> Range<Int> { map(range.lowerBound)..<map(range.upperBound) } | |
| 127 | var result = Structure() | |
| 128 | result.frontMatter = structure.frontMatter | |
| 129 | result.fences = structure.fences.map { fence in | |
| 130 | let range = fence.closing == nil ? map(fence.range.lowerBound)..<new.count : map(fence.range) | |
| 131 | return Fence(range: range, opening: map(fence.opening), closing: fence.closing.map(map), language: fence.language) | |
| 132 | } | |
| 133 | let inFence = result.fences.contains { $0.range.lowerBound < start && start < $0.range.upperBound } | |
| 134 | var headings = structure.headings.filter { $0.start < start } | |
| 135 | if !inFence { | |
| 136 | var i = start | |
| 137 | repeat { | |
| 138 | let end = lineEnd(new, i) | |
| 139 | if let heading = atxHeading(new, i, end) { | |
| 140 | headings.append(Heading(start: i, lineEnd: end < new.count ? end + 1 : end, level: heading.level, title: string(new, heading.title))) | |
| 141 | } | |
| 142 | i = end + 1 | |
| 143 | } while i <= newEnd && i < new.count | |
| 144 | } | |
| 145 | for heading in structure.headings where heading.start > oldEnd { | |
| 146 | headings.append(Heading(start: heading.start + delta, lineEnd: heading.lineEnd + delta, level: heading.level, title: heading.title)) | |
| 147 | } | |
| 148 | result.headings = headings | |
| 149 | return result | |
| 150 | } | |
| 151 | ||
| 152 | /// The front matter's `title`, else the first heading's. | |
| 153 | public static func title(_ text: String) -> String? { | |
| 154 | let u = Array(text.utf16) | |
| 155 | return title(u, structure(u)) | |
| 156 | } | |
| 157 | ||
| 158 | public static func title(_ u: [UInt16], _ structure: Structure) -> String? { | |
| 159 | if let front = structure.frontMatter { | |
| 160 | let body = string(u, front.body) | |
| 161 | let pattern = front.format == .yaml ? /(?m)^title[ \t]*:[ \t]*(.*?)[ \t\r]*$/ : /(?m)^title[ \t]*=[ \t]*(.*?)[ \t\r]*$/ | |
| 162 | if let match = body.firstMatch(of: pattern) { | |
| 163 | var value = Substring(match.1) | |
| 164 | if value.count >= 2, let first = value.first, first == "\"" || first == "'", value.last == first { | |
| 165 | value = value.dropFirst().dropLast() | |
| 166 | } | |
| 167 | if !value.isEmpty { return String(value) } | |
| 168 | } | |
| 169 | } | |
| 170 | return structure.headings.first { !$0.title.isEmpty }?.title | |
| 171 | } | |
| 172 | ||
| 173 | // MARK: - Lines | |
| 174 | ||
| 175 | static let newline: UInt16 = 10 | |
| 176 | static let space: UInt16 = 32 | |
| 177 | static let tab: UInt16 = 9 | |
| 178 | static let cr: UInt16 = 13 | |
| 179 | static let hash: UInt16 = 35 | |
| 180 | static let backtick: UInt16 = 96 | |
| 181 | static let tilde: UInt16 = 126 | |
| 182 | ||
| 183 | /// The offset of the newline ending the line at `start`, or the end of the text. | |
| 184 | static func lineEnd(_ u: [UInt16], _ start: Int) -> Int { | |
| 185 | var i = start | |
| 186 | while i < u.count, u[i] != newline { i += 1 } | |
| 187 | return i | |
| 188 | } | |
| 189 | ||
| 190 | static func isBlank(_ c: UInt16) -> Bool { c == space || c == tab || c == cr } | |
| 191 | ||
| 192 | static func string(_ u: [UInt16], _ range: Range<Int>) -> String { | |
| 193 | String(decoding: u[range], as: UTF16.self) | |
| 194 | } | |
| 195 | ||
| 196 | /// The line without trailing spaces, tabs and carriage return. | |
| 197 | static func trimmedEnd(_ u: [UInt16], _ start: Int, _ end: Int) -> Int { | |
| 198 | var e = end | |
| 199 | while e > start, isBlank(u[e - 1]) { e -= 1 } | |
| 200 | return e | |
| 201 | } | |
| 202 | ||
| 203 | static func isLine(_ u: [UInt16], _ start: Int, _ end: Int, _ marker: String) -> Bool { | |
| 204 | let e = trimmedEnd(u, start, end) | |
| 205 | return Array(marker.utf16) == Array(u[start..<e]) | |
| 206 | } | |
| 207 | ||
| 208 | static func frontMatter(_ u: [UInt16]) -> FrontMatter? { | |
| 209 | let end = lineEnd(u, 0) | |
| 210 | let format: FrontMatter.Format | |
| 211 | if isLine(u, 0, end, "---") { format = .yaml } else if isLine(u, 0, end, "+++") { format = .toml } else { return nil } | |
| 212 | guard end < u.count else { return nil } | |
| 213 | let opening = 0..<(end + 1) | |
| 214 | var i = end + 1 | |
| 215 | while i < u.count { | |
| 216 | let e = lineEnd(u, i) | |
| 217 | let next = e < u.count ? e + 1 : e | |
| 218 | if format == .yaml ? (isLine(u, i, e, "---") || isLine(u, i, e, "...")) : isLine(u, i, e, "+++") { | |
| 219 | return FrontMatter(format: format, range: 0..<next, opening: opening, closing: i..<next) | |
| 220 | } | |
| 221 | i = next | |
| 222 | } | |
| 223 | return nil | |
| 224 | } | |
| 225 | ||
| 226 | static func openingFence(_ u: [UInt16], _ start: Int, _ end: Int) -> (char: UInt16, count: Int, language: String?)? { | |
| 227 | var i = start | |
| 228 | while i < end, u[i] == space || u[i] == tab { i += 1 } | |
| 229 | guard i < end, u[i] == backtick || u[i] == tilde else { return nil } | |
| 230 | let char = u[i] | |
| 231 | var count = 0 | |
| 232 | while i < end, u[i] == char { i += 1; count += 1 } | |
| 233 | guard count >= 3 else { return nil } | |
| 234 | let info = i..<trimmedEnd(u, i, end) | |
| 235 | if char == backtick, u[info].contains(backtick) { return nil } | |
| 236 | var word = info.lowerBound | |
| 237 | while word < info.upperBound, isBlank(u[word]) || u[word] == 123 || u[word] == 46 { word += 1 } // `{`, `.` | |
| 238 | var wordEnd = word | |
| 239 | while wordEnd < info.upperBound, !isBlank(u[wordEnd]), u[wordEnd] != 125, u[wordEnd] != 44 { wordEnd += 1 } // `}`, `,` | |
| 240 | return (char, count, wordEnd > word ? string(u, word..<wordEnd) : nil) | |
| 241 | } | |
| 242 | ||
| 243 | static func isClosingFence(_ u: [UInt16], _ start: Int, _ end: Int, char: UInt16, count: Int) -> Bool { | |
| 244 | var i = start | |
| 245 | while i < end, u[i] == space || u[i] == tab { i += 1 } | |
| 246 | var run = 0 | |
| 247 | while i < end, u[i] == char { i += 1; run += 1 } | |
| 248 | return run >= count && trimmedEnd(u, i, end) == i | |
| 249 | } | |
| 250 | ||
| 251 | /// An ATX heading: up to three spaces, one to six `#`, then a space, a tab or the end of | |
| 252 | /// the line. The title leaves out a closing run of `#`. | |
| 253 | static func atxHeading(_ u: [UInt16], _ start: Int, _ end: Int) -> (level: Int, title: Range<Int>)? { | |
| 254 | var i = start | |
| 255 | var indent = 0 | |
| 256 | while i < end, u[i] == space, indent < 4 { i += 1; indent += 1 } | |
| 257 | guard indent < 4, i < end, u[i] == hash else { return nil } | |
| 258 | var level = 0 | |
| 259 | while i < end, u[i] == hash { i += 1; level += 1 } | |
| 260 | guard level <= 6, i == end || isBlank(u[i]) else { return nil } | |
| 261 | while i < end, isBlank(u[i]) { i += 1 } | |
| 262 | var e = trimmedEnd(u, i, end) | |
| 263 | var closing = e | |
| 264 | while closing > i, u[closing - 1] == hash { closing -= 1 } | |
| 265 | if closing == i { | |
| 266 | e = i | |
| 267 | } else if closing < e, isBlank(u[closing - 1]) { | |
| 268 | e = trimmedEnd(u, i, closing) | |
| 269 | } | |
| 270 | return (level, i..<e) | |
| 271 | } | |
| 272 | } | |
Sources/OrgEditorAppKit/Modal.swift +1 −1 · view
| @@ -192,7 +192,7 @@ extension OrgEditor { | ||
| 192 | 192 | } |
| 193 | 193 | |
| 194 | 194 | private func commandApplies(_ id: String, in context: EditContext) -> Bool { |
| 195 | if !isOrg, id.hasPrefix("org.") { return false } | |
| 195 | if refuses(id) { return false } | |
| 196 | 196 | return switch EditorCommands.command(id)?.action { |
| 197 | 197 | case .text(let command): command.applies(in: context) |
| 198 | 198 | default: true |
Sources/OrgEditorAppKit/OrgEditor+Folding.swift +15 −2 · view
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | #if os(macOS) |
| 2 | 2 | import AppKit |
| 3 | 3 | import OrgCore |
| 4 | import OrgDocument | |
| 4 | 5 | import OrgPresentation |
| 5 | 6 | |
| 6 | 7 | extension OrgEditor { |
| @@ -21,7 +22,7 @@ extension OrgEditor { | ||
| 21 | 22 | sparseHidden = nil |
| 22 | 23 | view.folds = state.folds |
| 23 | 24 | view.bodyFolds = state.bodyFolds |
| 24 | view = view.pruned(to: document.tree, wrappers: false) | |
| 25 | view = pruned(view) | |
| 25 | 26 | // Found one by one, or all at once when there are many. |
| 26 | 27 | let found = wrappers ?? (state.wrapperFolds.count > 32 |
| 27 | 28 | ? Wrappers.all(document.tree).filter { state.wrapperFolds.contains($0.start) } |
| @@ -56,7 +57,19 @@ extension OrgEditor { | ||
| 56 | 57 | return |
| 57 | 58 | } |
| 58 | 59 | folded.set(view.folds.union(view.bodyFolds).union(view.wrapperFolds)) |
| 59 | hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds, wrapperRanges: Array(wrapperHidden.values)) + narrowHidden) | |
| 60 | let headings = isMarkdown | |
| 61 | ? Presentation.markdownHiddenRanges(markdown, folds: view.folds, bodyFolds: view.bodyFolds) | |
| 62 | : Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds, wrapperRanges: Array(wrapperHidden.values)) | |
| 63 | hidden.set(headings + narrowHidden) | |
| 64 | } | |
| 65 | ||
| 66 | /// `view` without heading folds that no longer start a heading; drawer and block folds are | |
| 67 | /// left for the caller. Markdown's are checked against its headings, without the fold tree. | |
| 68 | func pruned(_ view: ViewState) -> ViewState { | |
| 69 | guard isMarkdown else { return view.pruned(to: document.tree, wrappers: false) } | |
| 70 | guard !view.folds.isEmpty || !view.bodyFolds.isEmpty else { return view } | |
| 71 | let starts = Set(markdown.structure.headings.map(\.start)) | |
| 72 | return ViewState(selection: view.selection, folds: view.folds.filter(starts.contains), bodyFolds: view.bodyFolds.filter(starts.contains), wrapperFolds: view.wrapperFolds) | |
| 60 | 73 | } |
| 61 | 74 | |
| 62 | 75 | /// `updateHidden`, laying out again only the text that changed between hidden and shown |
Sources/OrgEditorAppKit/OrgEditor+Shrink.swift +6 −6 · view
| @@ -73,10 +73,10 @@ extension OrgEditor { | ||
| 73 | 73 | public func cycleAtCaret() -> Bool { |
| 74 | 74 | leaveSparseTree() |
| 75 | 75 | let caret = textView.selectedRange().location |
| 76 | guard let state = Presentation.cycle(at: caret, in: document.tree, foldState) else { return false } | |
| 76 | guard let state = Presentation.cycle(at: caret, in: foldTree, foldState) else { return false } | |
| 77 | 77 | setFolds(state) |
| 78 | 78 | // Off a closing line that folding hid, to the opening line, as org does. |
| 79 | if let wrapper = Wrappers.toggleable(at: caret, in: document.tree), hidden.containing(caret) != nil { setCaret(wrapper.start) } | |
| 79 | if let wrapper = Wrappers.toggleable(at: caret, in: foldTree), hidden.containing(caret) != nil { setCaret(wrapper.start) } | |
| 80 | 80 | return true |
| 81 | 81 | } |
| 82 | 82 | |
| @@ -85,7 +85,7 @@ extension OrgEditor { | ||
| 85 | 85 | func fold(_ id: String) { |
| 86 | 86 | leaveSparseTree() |
| 87 | 87 | let caret = textView.selectedRange().location |
| 88 | let tree = document.tree | |
| 88 | let tree = foldTree | |
| 89 | 89 | let next: FoldState? |
| 90 | 90 | if id == "org.fold.close" || id == "org.fold.open-subtree" { |
| 91 | 91 | next = Presentation.outline(tree).last { $0.start <= caret && (caret < $0.end || $0.end == utf16Length) } |
| @@ -108,7 +108,7 @@ extension OrgEditor { | ||
| 108 | 108 | /// Shift-TAB: overview, contents, show all. |
| 109 | 109 | public func cycleGlobal() { |
| 110 | 110 | leaveSparseTree() |
| 111 | let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: view.wrapperFolds) | |
| 111 | let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: foldTree, wrapperFolds: view.wrapperFolds) | |
| 112 | 112 | globalVisibility = visibility |
| 113 | 113 | setFolds(state) |
| 114 | 114 | } |
| @@ -126,11 +126,11 @@ extension OrgEditor { | ||
| 126 | 126 | func unfold(around offset: Int) { |
| 127 | 127 | leaveSparseTree() |
| 128 | 128 | var state = foldState |
| 129 | for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end { | |
| 129 | for entry in Presentation.outline(foldTree) where entry.start < offset && offset < entry.end { | |
| 130 | 130 | state.folds.remove(entry.start) |
| 131 | 131 | state.bodyFolds.remove(entry.start) |
| 132 | 132 | } |
| 133 | for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true { | |
| 133 | for start in state.wrapperFolds where Wrappers.starting(at: start, in: foldTree)?.hidden.contains(offset) == true { | |
| 134 | 134 | state.wrapperFolds.remove(start) |
| 135 | 135 | } |
| 136 | 136 | guard state != foldState else { return } |
Sources/OrgEditorAppKit/OrgEditor+Styling.swift +8 · view
| @@ -19,6 +19,14 @@ extension OrgEditor { | ||
| 19 | 19 | guard !range.isEmpty else { return } |
| 20 | 20 | let whole = NSRange(range) |
| 21 | 21 | storage.setAttributes(theme.base, range: whole) |
| 22 | if isMarkdown { | |
| 23 | for run in Presentation.markdownStyles(markdown, in: range, highlighter: highlighter) { | |
| 24 | guard let clipped = clip(run.range, to: range) else { continue } | |
| 25 | theme.apply(run.role, to: storage, range: clipped) | |
| 26 | } | |
| 27 | applyHighlights(range, in: storage) | |
| 28 | return | |
| 29 | } | |
| 22 | 30 | guard isOrg else { |
| 23 | 31 | for run in plainRuns() where run.range.overlaps(range) { |
| 24 | 32 | guard let clipped = clip(run.range, to: range) else { continue } |
Sources/OrgEditorAppKit/OrgEditor.swift +45 −9 · view
| @@ -72,14 +72,19 @@ public final class OrgEditor: NSObject { | ||
| 72 | 72 | /// Highlights code in src blocks; nil leaves code plain. |
| 73 | 73 | public let highlighter: (any CodeHighlighter)? |
| 74 | 74 | |
| 75 | /// What the file is: org, or plain text, highlighted as code when the language is known. | |
| 75 | /// What the file is: org, Markdown, or plain text, highlighted as code when the language | |
| 76 | /// is known. | |
| 76 | 77 | public enum Mode: Equatable, Sendable { |
| 77 | 78 | case org |
| 79 | case markdown | |
| 78 | 80 | case plain(language: String?) |
| 79 | 81 | } |
| 80 | 82 | |
| 81 | 83 | public let mode: Mode |
| 82 | 84 | public var isOrg: Bool { mode == .org } |
| 85 | public var isMarkdown: Bool { mode == .markdown } | |
| 86 | /// A Markdown file's structure, for the revision it was read at. | |
| 87 | var markdownCache: (revision: Int, document: MarkdownDocument)? | |
| 83 | 88 | /// The text as shown for accessibility, and the storage generation it's for. |
| 84 | 89 | var accessibleCache: (storage: Int, text: AccessibleText)? |
| 85 | 90 | /// Bumped on every character or attribute change to the storage. |
| @@ -275,6 +280,7 @@ public final class OrgEditor: NSObject { | ||
| 275 | 280 | isLoading = true |
| 276 | 281 | textView.textStorage?.setAttributedString(NSAttributedString(string: text, attributes: theme.base)) |
| 277 | 282 | isLoading = false |
| 283 | if isMarkdown { shaded.set(markdown.structure.blocks) } | |
| 278 | 284 | lines.reset(text as NSString) |
| 279 | 285 | for view in orgTextViews { |
| 280 | 286 | view.lineIndex = lines |
| @@ -596,18 +602,35 @@ public final class OrgEditor: NSObject { | ||
| 596 | 602 | } |
| 597 | 603 | |
| 598 | 604 | private func applies(_ id: String, in context: EditContext) -> Bool { |
| 599 | if !isOrg, id.hasPrefix("org.") { return false } | |
| 605 | if refuses(id) { return false } | |
| 600 | 606 | return switch EditorCommands.command(id)?.action { |
| 601 | 607 | case .text(let command): command.applies(in: context) |
| 602 | 608 | case .view where id.hasPrefix("org.table."): KeyContext.holds("table", in: context) |
| 603 | 609 | case .view where id.hasPrefix("org.snippet."): snippetSession != nil |
| 604 | case .view: id != "org.cycle" || Presentation.heading(containing: context.caret, in: context.tree) != nil | |
| 605 | || Wrappers.toggleable(at: context.caret, in: context.tree) != nil | |
| 610 | case .view: id != "org.cycle" || Presentation.heading(containing: context.caret, in: foldTree) != nil | |
| 611 | || Wrappers.toggleable(at: context.caret, in: foldTree) != nil | |
| 606 | 612 | case .edit, .mark, .app, .find: true |
| 607 | 613 | case nil: true |
| 608 | 614 | } |
| 609 | 615 | } |
| 610 | 616 | |
| 617 | /// Whether `id` is refused because the file isn't org: in Markdown only the fold commands | |
| 618 | /// of org's run, so none writes org into the file. | |
| 619 | func refuses(_ id: String) -> Bool { | |
| 620 | !isOrg && OrgOnlyCommands.refuses(id, markdown: isMarkdown) | |
| 621 | } | |
| 622 | ||
| 623 | /// The file's structure for folding: the org tree, or for Markdown a tree of its headings. | |
| 624 | var foldTree: OrgTree { isMarkdown ? markdown.foldTree : document.tree } | |
| 625 | ||
| 626 | /// The Markdown file's structure now. | |
| 627 | var markdown: MarkdownDocument { | |
| 628 | if let markdownCache, markdownCache.revision == document.revision { return markdownCache.document } | |
| 629 | let made = MarkdownDocument(document.text) | |
| 630 | markdownCache = (document.revision, made) | |
| 631 | return made | |
| 632 | } | |
| 633 | ||
| 611 | 634 | /// The last command run and the revision it left, for `last-command`. |
| 612 | 635 | var lastCommand: (id: String, revision: Int)? |
| 613 | 636 | |
| @@ -622,7 +645,7 @@ public final class OrgEditor: NSObject { | ||
| 622 | 645 | fail("Unknown command \(id)") |
| 623 | 646 | return |
| 624 | 647 | } |
| 625 | if !isOrg, id.hasPrefix("org.") { | |
| 648 | if refuses(id) { | |
| 626 | 649 | fail("Not an org file") |
| 627 | 650 | return |
| 628 | 651 | } |
| @@ -819,8 +842,8 @@ public final class OrgEditor: NSObject { | ||
| 819 | 842 | |
| 820 | 843 | func settleBlocks() { |
| 821 | 844 | blockCheck?.cancel() |
| 822 | guard isOrg else { return } | |
| 823 | let blocks = Presentation.shadedBlocks(document.tree) | |
| 845 | guard isOrg || isMarkdown else { return } | |
| 846 | let blocks = isMarkdown ? markdown.structure.blocks : Presentation.shadedBlocks(document.tree) | |
| 824 | 847 | guard blocks != shaded.all else { return } |
| 825 | 848 | let old = shaded.all |
| 826 | 849 | shaded.set(blocks) |
| @@ -838,8 +861,10 @@ public final class OrgEditor: NSObject { | ||
| 838 | 861 | let newText = storage.string as NSString |
| 839 | 862 | let newEnd = edit.range.lowerBound + replacement.utf16.count |
| 840 | 863 | let oldTree = document.tree |
| 864 | let oldMarkdown = isMarkdown ? markdown : nil | |
| 841 | 865 | do { |
| 842 | 866 | try document.apply([edit], baseRevision: document.revision) |
| 867 | if let oldMarkdown { markdownCache = (document.revision, oldMarkdown.applying(edit)) } | |
| 843 | 868 | } catch { |
| 844 | 869 | assertionFailure("text view and document disagree: \(error)") |
| 845 | 870 | return |
| @@ -848,8 +873,17 @@ public final class OrgEditor: NSObject { | ||
| 848 | 873 | // edited line when the edit reaches into unstyled text. |
| 849 | 874 | styled.map(through: edit, in: newText) |
| 850 | 875 | let oldHidden = hidden.all |
| 851 | let affected = Presentation.restyleRange(for: edit, old: (oldTree, oldText), new: (document.tree, newText)) | |
| 852 | view = view.mapped(through: [edit]).pruned(to: document.tree, wrappers: false) | |
| 876 | var affected = isMarkdown | |
| 877 | ? Presentation.markdownRestyleRange(for: edit, oldBlocks: oldMarkdown?.structure.blocks ?? [], new: markdown, newText: newText) | |
| 878 | : Presentation.restyleRange(for: edit, old: (oldTree, oldText), new: (document.tree, newText)) | |
| 879 | // A fence opened or closed far up restyles what follows in the background passes. | |
| 880 | if isMarkdown, affected.count > Self.styleChunk { | |
| 881 | let lines = newText.lineRange(for: NSRange(location: edit.range.lowerBound, length: newEnd - edit.range.lowerBound)) | |
| 882 | styled.unstyle(from: NSMaxRange(lines)) | |
| 883 | affected = affected.lowerBound..<NSMaxRange(lines) | |
| 884 | scheduleStyling() | |
| 885 | } | |
| 886 | view = pruned(view.mapped(through: [edit])) | |
| 853 | 887 | mapWrapperFolds(through: edit, near: affected) |
| 854 | 888 | if let narrowed { self.narrowed = ViewState(selection: [narrowed]).mapped(through: [edit]).selection[0] } |
| 855 | 889 | mapVimPositions(through: edit) |
| @@ -875,6 +909,8 @@ public final class OrgEditor: NSObject { | ||
| 875 | 909 | shaded.set(oldShaded.map { mapRange($0, through: edit) }) |
| 876 | 910 | } |
| 877 | 911 | scheduleBlockCheck() |
| 912 | } else if isMarkdown { | |
| 913 | shaded.set(markdown.structure.blocks) | |
| 878 | 914 | } |
| 879 | 915 | invalidateLayout(from: oldHidden.map { mapRange($0, through: edit) }, to: hidden.all) |
| 880 | 916 | invalidateLayout(from: oldShaded.map { mapRange($0, through: edit) }, to: shaded.all) |
Sources/OrgEditorAppKit/ViewToggles.swift +12 −1 · view
| @@ -25,7 +25,7 @@ extension OrgEditor { | ||
| 25 | 25 | /// Ranges spell-fu skips in Org, for this revision of the text. |
| 26 | 26 | func spellSkipped() -> [Range<Int>] { |
| 27 | 27 | if let cached = spellSkipCache, cached.text == document.text { return cached.ranges } |
| 28 | let ranges = isOrg ? SpellCheck.skipped(document.tree) : [] | |
| 28 | let ranges = isOrg ? SpellCheck.skipped(document.tree) : isMarkdown ? markdown.structure.blocks : [] | |
| 29 | 29 | spellSkipCache = (document.text, ranges) |
| 30 | 30 | return ranges |
| 31 | 31 | } |
| @@ -69,6 +69,17 @@ extension OrgEditor { | ||
| 69 | 69 | |
| 70 | 70 | /// A click on a heading's stars cycles it; a click on a checkbox toggles it. |
| 71 | 71 | func click(at offset: Int) -> Bool { |
| 72 | if isMarkdown { | |
| 73 | // A Markdown heading's `#`s cycle it, as a heading's stars do. | |
| 74 | let u = markdown.units | |
| 75 | guard let heading = markdown.structure.headings.last(where: { $0.start <= offset }), offset < heading.lineEnd else { return false } | |
| 76 | var hashes = heading.start | |
| 77 | while hashes < u.count, u[hashes] == 32 { hashes += 1 } | |
| 78 | guard offset <= hashes + heading.level else { return false } | |
| 79 | setCaret(heading.start) | |
| 80 | _ = cycleAtCaret() | |
| 81 | return true | |
| 82 | } | |
| 72 | 83 | guard isOrg else { return false } |
| 73 | 84 | var node = document.tree.root |
| 74 | 85 | while let child = node.child(containing: offset) ?? node.child(containing: offset - 1) { |
Sources/OrgIndex/FileRecord.swift +37 · view
| @@ -7,6 +7,9 @@ public enum FileKind: String, Sendable { | ||
| 7 | 7 | case archive |
| 8 | 8 | /// A Syncthing conflict copy: listed, never indexed for search, agenda or IDs. |
| 9 | 9 | case conflict |
| 10 | /// Markdown or plain text: searched, titled by its front matter or first heading; | |
| 11 | /// never read for the agenda, IDs or links. | |
| 12 | case text | |
| 10 | 13 | /// Any other file: listed and openable, never read by the index. |
| 11 | 14 | case other |
| 12 | 15 | } |
| @@ -133,6 +136,15 @@ public struct FileRecord: Sendable, Equatable { | ||
| 133 | 136 | self.mtime = mtime |
| 134 | 137 | self.hash = Self.hash(bytes) |
| 135 | 138 | let source = SourceText(bytes: bytes) |
| 139 | if kind == .text { | |
| 140 | settingsVersion = settings.version | |
| 141 | links = [] | |
| 142 | fileID = nil | |
| 143 | fileTags = [] | |
| 144 | fileRoam = RoamProperties() | |
| 145 | (headings, title, preamble) = Self.textRows(source.text, path: path) | |
| 146 | return | |
| 147 | } | |
| 136 | 148 | var resolved = settings |
| 137 | 149 | resolved.org = settings.org.resolvingSetupFiles(in: source.text, path: path, read: OrgSettings.readFile) |
| 138 | 150 | self.settingsVersion = Self.settingsVersion(settings, text: source.text, setupKeywords: resolved.org.setupKeywords) |
| @@ -140,6 +152,31 @@ public struct FileRecord: Sendable, Equatable { | ||
| 140 | 152 | ? ([], [], nil, nil, "", [], RoamProperties()) : Self.rows(source.text, settings: resolved) |
| 141 | 153 | } |
| 142 | 154 | |
| 155 | /// A Markdown file's headings, with their own text as bodies, its title and the text | |
| 156 | /// before its first heading; a plain text file's text, untitled. | |
| 157 | static func textRows(_ text: String, path: String) -> (headings: [HeadingRecord], title: String?, preamble: String) { | |
| 158 | guard Markdown.isPath(path) else { return ([], nil, text) } | |
| 159 | let u = Array(text.utf16) | |
| 160 | let structure = Markdown.structure(u) | |
| 161 | let headings = structure.headings | |
| 162 | func slice(_ range: Range<Int>) -> String { String(decoding: u[range], as: UTF16.self) } | |
| 163 | var records: [HeadingRecord] = [] | |
| 164 | var open: [Int] = [] | |
| 165 | for (index, heading) in headings.enumerated() { | |
| 166 | while let last = open.last, headings[last].level >= heading.level { open.removeLast() } | |
| 167 | let end = headings[(index + 1)...].first { $0.level <= heading.level }?.start ?? u.count | |
| 168 | let bodyEnd = index + 1 < headings.count ? min(headings[index + 1].start, end) : end | |
| 169 | records.append(HeadingRecord( | |
| 170 | ordinal: index, parent: open.last, start: heading.start, end: end, level: heading.level, | |
| 171 | todo: nil, isDone: false, priority: nil, title: heading.title, | |
| 172 | outlinePath: open.map { headings[$0].title } + [heading.title], orgID: nil, archived: false, | |
| 173 | body: slice(heading.lineEnd..<max(heading.lineEnd, bodyEnd)), tags: [], properties: [], timestamps: [], clocks: [], links: [] | |
| 174 | )) | |
| 175 | open.append(index) | |
| 176 | } | |
| 177 | return (records, Markdown.title(u, structure), slice(0..<(headings.first?.start ?? u.count))) | |
| 178 | } | |
| 179 | ||
| 143 | 180 | /// The settings version a file's rows are built under: the index's, with the keywords of |
| 144 | 181 | /// the setup files it names mixed in, so a changed setup file indexes it again. |
| 145 | 182 | public static func settingsVersion(_ settings: IndexSettings, text: String, setupKeywords: String) -> Int { |
Sources/OrgPresentation/MarkdownDisplay.swift added +179 · view
| @@ -0,0 +1,179 @@ | ||
| 1 | import Foundation | |
| 2 | import OrgCore | |
| 3 | ||
| 4 | /// A Markdown file's text and structure at one revision, with what the editors build from | |
| 5 | /// them: the outline, and the tree the fold commands work on. | |
| 6 | public final class MarkdownDocument: @unchecked Sendable { | |
| 7 | public let units: [UInt16] | |
| 8 | public let structure: Markdown.Structure | |
| 9 | ||
| 10 | public init(_ text: String) { | |
| 11 | units = Array(text.utf16) | |
| 12 | structure = Markdown.structure(units) | |
| 13 | } | |
| 14 | ||
| 15 | init(units: [UInt16], structure: Markdown.Structure) { | |
| 16 | self.units = units | |
| 17 | self.structure = structure | |
| 18 | } | |
| 19 | ||
| 20 | /// The document after `edit`, read again only where the edit needs it. | |
| 21 | public func applying(_ edit: TextEdit) -> MarkdownDocument { | |
| 22 | var new = units | |
| 23 | new.replaceSubrange(edit.range, with: Array(edit.replacement.utf16)) | |
| 24 | return MarkdownDocument(units: new, structure: Markdown.structure(structure, old: units, new: new, after: edit) ?? Markdown.structure(new)) | |
| 25 | } | |
| 26 | ||
| 27 | public private(set) lazy var outline: [OutlineEntry] = Presentation.markdownOutline(structure, length: units.count) | |
| 28 | ||
| 29 | /// An org tree whose headings are the Markdown headings, at the same offsets: the text with | |
| 30 | /// each heading's `#`s as stars and everything else but newlines as spaces. The org fold | |
| 31 | /// code (cycling, hidden ranges, Doom's fold keys) works on it unchanged. | |
| 32 | public private(set) lazy var foldTree: OrgTree = { | |
| 33 | var skeleton = units.map { $0 == 10 ? UInt16(10) : UInt16(32) } | |
| 34 | for heading in structure.headings { | |
| 35 | for k in 0..<heading.level { skeleton[heading.start + k] = 42 } | |
| 36 | } | |
| 37 | return OrgParser.parse(String(decoding: skeleton, as: UTF16.self)) | |
| 38 | }() | |
| 39 | } | |
| 40 | ||
| 41 | extension Presentation { | |
| 42 | /// Every Markdown heading in document order: a section runs to the next heading of its | |
| 43 | /// level or higher. | |
| 44 | public static func markdownOutline(_ structure: Markdown.Structure, length: Int) -> [OutlineEntry] { | |
| 45 | let headings = structure.headings | |
| 46 | var entries: [OutlineEntry] = [] | |
| 47 | var open: [Int] = [] | |
| 48 | for (index, heading) in headings.enumerated() { | |
| 49 | while let last = open.last, headings[last].level >= heading.level { open.removeLast() } | |
| 50 | let end = headings[(index + 1)...].first { $0.level <= heading.level }?.start ?? length | |
| 51 | entries.append(OutlineEntry(start: heading.start, level: heading.level, title: heading.title, end: end, parent: open.last, isTopLevel: open.isEmpty)) | |
| 52 | open.append(index) | |
| 53 | } | |
| 54 | return entries | |
| 55 | } | |
| 56 | ||
| 57 | /// What folding the Markdown headings at `folds` (whole sections) and `bodyFolds` (their | |
| 58 | /// text before the first subheading) hides, as `hiddenRanges` does for org headings. | |
| 59 | public static func markdownHiddenRanges(_ document: MarkdownDocument, folds: Set<Int>, bodyFolds: Set<Int>) -> [Range<Int>] { | |
| 60 | guard !folds.isEmpty || !bodyFolds.isEmpty else { return [] } | |
| 61 | let outline = document.outline | |
| 62 | let headings = document.structure.headings | |
| 63 | var ranges: [Range<Int>] = [] | |
| 64 | var hiddenUntil = 0 | |
| 65 | for (index, entry) in outline.enumerated() where entry.start >= hiddenUntil { | |
| 66 | let lineEnd = headings[index].lineEnd | |
| 67 | if folds.contains(entry.start) { | |
| 68 | if lineEnd < entry.end { ranges.append(lineEnd..<entry.end) } | |
| 69 | hiddenUntil = entry.end | |
| 70 | } else if bodyFolds.contains(entry.start) { | |
| 71 | let bodyEnd = index + 1 < outline.count && outline[index + 1].parent == index ? outline[index + 1].start : entry.end | |
| 72 | if lineEnd < bodyEnd { ranges.append(lineEnd..<bodyEnd) } | |
| 73 | } | |
| 74 | } | |
| 75 | return ranges | |
| 76 | } | |
| 77 | ||
| 78 | /// The display a file that isn't org opens with: nothing folded, indented or shown inline. | |
| 79 | public static func textStartupDisplay(options: EditingOptions) -> StartupDisplay { | |
| 80 | StartupDisplay(folds: FoldState(), wrappers: [], indented: false, hideStars: false, inlineImages: false, alignTables: false, truncated: options.startupTruncated) | |
| 81 | } | |
| 82 | ||
| 83 | /// Style runs for the Markdown lines overlapping `range`: front matter and fences as | |
| 84 | /// blocks, highlighted as YAML, TOML or the fence's language; other lines by their | |
| 85 | /// markup. Outer runs come before the runs inside them. | |
| 86 | public static func markdownStyles(_ document: MarkdownDocument, in range: Range<Int>, highlighter: (any CodeHighlighter)? = nil) -> [StyleRun] { | |
| 87 | let u = document.units | |
| 88 | let structure = document.structure | |
| 89 | guard !range.isEmpty, range.lowerBound < u.count else { return [] } | |
| 90 | var runs: [StyleRun] = [] | |
| 91 | func code(_ language: String?, _ body: Range<Int>) { | |
| 92 | guard let highlighter, let language, !body.isEmpty else { return } | |
| 93 | let text = String(decoding: u[body], as: UTF16.self) | |
| 94 | for run in highlighter.highlights(language: language, code: text) { | |
| 95 | runs.append(StyleRun(range: (run.range.lowerBound + body.lowerBound)..<(run.range.upperBound + body.lowerBound), role: .syntax(run.category))) | |
| 96 | } | |
| 97 | } | |
| 98 | if let front = structure.frontMatter, front.range.overlaps(range) { | |
| 99 | runs.append(StyleRun(range: front.opening, role: .blockDelimiter)) | |
| 100 | if !front.body.isEmpty { runs.append(StyleRun(range: front.body, role: .metadata)) } | |
| 101 | code(front.format.rawValue, front.body) | |
| 102 | runs.append(StyleRun(range: front.closing, role: .blockDelimiter)) | |
| 103 | } | |
| 104 | let fences = structure.fences | |
| 105 | var first = firstIndex(fences) { $0.range.upperBound > range.lowerBound } | |
| 106 | while first < fences.count, fences[first].range.lowerBound < range.upperBound { | |
| 107 | let fence = fences[first] | |
| 108 | runs.append(StyleRun(range: fence.opening, role: .blockDelimiter)) | |
| 109 | if !fence.body.isEmpty { runs.append(StyleRun(range: fence.body, role: .block)) } | |
| 110 | code(fence.language, fence.body) | |
| 111 | if let closing = fence.closing { runs.append(StyleRun(range: closing, role: .blockDelimiter)) } | |
| 112 | first += 1 | |
| 113 | } | |
| 114 | let blocks = structure.blocks | |
| 115 | var block = firstIndex(blocks) { $0.upperBound > range.lowerBound } | |
| 116 | var i = range.lowerBound | |
| 117 | while i > 0, u[i - 1] != 10 { i -= 1 } | |
| 118 | let upper = min(range.upperBound, u.count) | |
| 119 | while i < upper { | |
| 120 | if block < blocks.count, blocks[block].lowerBound <= i { | |
| 121 | i = max(i, blocks[block].upperBound) | |
| 122 | block += 1 | |
| 123 | continue | |
| 124 | } | |
| 125 | var end = i | |
| 126 | while end < u.count, u[end] != 10 { end += 1 } | |
| 127 | for span in Markdown.lineSpans(u, i, end) { runs.append(StyleRun(range: span.range, role: role(span.kind))) } | |
| 128 | i = end + 1 | |
| 129 | } | |
| 130 | return runs | |
| 131 | } | |
| 132 | ||
| 133 | /// The first index whose element satisfies `test`, which holds from some index to the end. | |
| 134 | static func firstIndex<T>(_ items: [T], where test: (T) -> Bool) -> Int { | |
| 135 | var low = 0 | |
| 136 | var high = items.count | |
| 137 | while low < high { | |
| 138 | let mid = (low + high) / 2 | |
| 139 | if test(items[mid]) { high = mid } else { low = mid + 1 } | |
| 140 | } | |
| 141 | return low | |
| 142 | } | |
| 143 | ||
| 144 | static func role(_ kind: Markdown.Span.Kind) -> StyleRole { | |
| 145 | switch kind { | |
| 146 | case .heading(let level): .heading(level: level) | |
| 147 | case .code: .code | |
| 148 | case .bold: .bold | |
| 149 | case .italic, .quote: .italic | |
| 150 | case .strikeThrough: .strikeThrough | |
| 151 | case .marker: .markup | |
| 152 | case .link: .link | |
| 153 | case .linkMarkup: .linkMarkup | |
| 154 | case .comment: .comment | |
| 155 | case .rule: .rule | |
| 156 | case .table: .table | |
| 157 | case .checkbox: .cookie | |
| 158 | } | |
| 159 | } | |
| 160 | ||
| 161 | /// The lines an edit to a Markdown file restyles: the edited lines, and every front matter | |
| 162 | /// or fence that the edit made, unmade or moved the end of. | |
| 163 | public static func markdownRestyleRange(for edit: TextEdit, oldBlocks: [Range<Int>], new document: MarkdownDocument, newText: NSString) -> Range<Int> { | |
| 164 | let newEnd = edit.range.lowerBound + edit.replacement.utf16.count | |
| 165 | let lines = newText.lineRange(for: NSRange(location: edit.range.lowerBound, length: newEnd - edit.range.lowerBound)) | |
| 166 | var lower = lines.location | |
| 167 | var upper = NSMaxRange(lines) | |
| 168 | let delta = newEnd - edit.range.upperBound | |
| 169 | func map(_ offset: Int) -> Int { | |
| 170 | offset < edit.range.lowerBound ? offset : offset >= edit.range.upperBound ? offset + delta : newEnd | |
| 171 | } | |
| 172 | let mapped = Set(oldBlocks.map { map($0.lowerBound)..<map($0.upperBound) }) | |
| 173 | for changed in mapped.symmetricDifference(document.structure.blocks) { | |
| 174 | lower = min(lower, changed.lowerBound) | |
| 175 | upper = max(upper, changed.upperBound) | |
| 176 | } | |
| 177 | return lower..<min(upper, newText.length) | |
| 178 | } | |
| 179 | } | |
Sources/OrgPresentation/Restyling.swift +3 · view
| @@ -10,6 +10,9 @@ public struct StyledExtent: Sendable, Equatable { | ||
| 10 | 10 | |
| 11 | 11 | public mutating func reset() { end = 0 } |
| 12 | 12 | |
| 13 | /// Counts the text from `offset` on as unstyled again. | |
| 14 | public mutating func unstyle(from offset: Int) { end = min(end, offset) } | |
| 15 | ||
| 13 | 16 | /// The whole lines from `end`, about `size` units, now counted as styled; nil when all are. |
| 14 | 17 | public mutating func next(_ size: Int, in text: NSString) -> Range<Int>? { |
| 15 | 18 | guard end < text.length else { return nil } |
Sources/OrgWorkspace/Discovery.swift +3 −1 · view
| @@ -69,7 +69,8 @@ public struct ScanRules: Sendable, Equatable { | ||
| 69 | 69 | public enum WorkspaceScanner { |
| 70 | 70 | /// What a file name means to the workspace. Syncthing temp files, our own temp and backup |
| 71 | 71 | /// files, Emacs backups, auto-saves and lock files, and Finder's files are ignored, and |
| 72 | /// other dotfiles unless `rules` takes them in; files that aren't org files are `.other`. | |
| 72 | /// other dotfiles unless `rules` takes them in; Markdown and `.txt` files are `.text`, other | |
| 73 | /// files that aren't org files `.other`. | |
| 73 | 74 | public static func classify(_ name: String, rules: ScanRules = ScanRules()) -> FileClassification { |
| 74 | 75 | if name.hasPrefix(".") { |
| 75 | 76 | if name.hasSuffix(".icloud") { |
| @@ -86,6 +87,7 @@ public enum WorkspaceScanner { | ||
| 86 | 87 | let conflict = name.contains(".sync-conflict-") |
| 87 | 88 | if name.hasSuffix(".org") { return .file(conflict ? .conflict : .org) } |
| 88 | 89 | if name.hasSuffix(".org_archive") { return .file(conflict ? .conflict : .archive) } |
| 90 | if Markdown.isPath(name) || Markdown.isPlainTextPath(name) { return .file(conflict ? .conflict : .text) } | |
| 89 | 91 | return .file(.other) |
| 90 | 92 | } |
| 91 | 93 | |
Sources/Orgstar/ContentView.swift +3 −4 · view
| @@ -177,11 +177,11 @@ struct ContentView: View { | ||
| 177 | 177 | /// Whether the outline pane shows: remembered for org files, hidden by default for |
| 178 | 178 | /// other files, and always shown while search results are up. |
| 179 | 179 | private var outlineShown: Bool { |
| 180 | !query.isEmpty || (previewPath == nil && (session.isOrg ? orgOutlineShown : plainOutlineShown)) | |
| 180 | !query.isEmpty || (previewPath == nil && (session.isOrg || session.isMarkdown ? orgOutlineShown : plainOutlineShown)) | |
| 181 | 181 | } |
| 182 | 182 | |
| 183 | 183 | private func toggleOutline() { |
| 184 | if session.isOrg { orgOutlineShown.toggle() } else { plainOutlineShown.toggle() } | |
| 184 | if session.isOrg || session.isMarkdown { orgOutlineShown.toggle() } else { plainOutlineShown.toggle() } | |
| 185 | 185 | } |
| 186 | 186 | |
| 187 | 187 | @ViewBuilder |
| @@ -1390,8 +1390,7 @@ struct ContentView: View { | ||
| 1390 | 1390 | return commands.show(Self.unavailable(EditorCommands.all.first { $0.id == id }?.title ?? id)) |
| 1391 | 1391 | } |
| 1392 | 1392 | if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return } |
| 1393 | let orgOnly = ["app.refile", "app.refile.copy", "app.archive", "app.clock.in", "app.clock.default", "app.copy-rich-text", "app.export-subtree", "app.export-body-only", "app.share-subtree"].contains(id) || Printing.commands.contains(id) || (id.hasPrefix("app.export.") && !id.hasPrefix("app.export.icalendar-")) || id.hasPrefix("org.") | |
| 1394 | if orgOnly, !session.isOrg { | |
| 1393 | if !session.isOrg, Printing.commands.contains(id) || OrgOnlyCommands.refuses(id, markdown: session.isMarkdown) { | |
| 1395 | 1394 | commands.show(String(localized: "Not an org file")) |
| 1396 | 1395 | return |
| 1397 | 1396 | } |
Sources/Orgstar/PaneView.swift +1 −1 · view
| @@ -86,7 +86,7 @@ struct PaneView: NSViewRepresentable { | ||
| 86 | 86 | private func makeEditor(_ path: String, _ container: NSView) -> OrgEditor? { |
| 87 | 87 | guard let entry = session.openDocuments.first(where: { $0.path == path }) else { return nil } |
| 88 | 88 | let document = entry.document |
| 89 | let mode: OrgEditor.Mode = DocumentSession.isOrgPath(path) ? .org : .plain(language: FileTypes.language(path)) | |
| 89 | let mode: OrgEditor.Mode = DocumentSession.isOrgPath(path) ? .org : Markdown.isPath(path) ? .markdown : .plain(language: FileTypes.language(path)) | |
| 90 | 90 | let editor = OrgEditor(document: document, frame: container.bounds, editable: document.isEditable, highlighter: Self.highlighter, mode: mode, options: settings.options) |
| 91 | 91 | let store = commands.store |
| 92 | 92 | editor.onChange = { [weak session] in session?.bufferChanged(path) } |
Sources/Orgstar/Sidebar.swift +3 −2 · view
| @@ -143,6 +143,7 @@ struct Sidebar: View { | ||
| 143 | 143 | case .org: return "doc.text" |
| 144 | 144 | case .archive: return "archivebox" |
| 145 | 145 | case .conflict: return "exclamationmark.triangle" |
| 146 | case .text: return "doc.plaintext" | |
| 146 | 147 | case .other: |
| 147 | 148 | guard let type = UTType(filenameExtension: (file.path as NSString).pathExtension) else { return "doc" } |
| 148 | 149 | if type.conforms(to: .image) { return "photo" } |
| @@ -208,8 +209,8 @@ struct OutlineColumn: View { | ||
| 208 | 209 | } |
| 209 | 210 | .themedListBackground(theme.color("sidebar-background", in: colorScheme)) |
| 210 | 211 | .overlay { |
| 211 | if session.path != nil, !session.isOrg { | |
| 212 | ContentUnavailableView("No Outline", systemImage: "doc.plaintext", description: Text("Only org files have an outline.")) | |
| 212 | if session.path != nil, !session.isOrg, !session.isMarkdown { | |
| 213 | ContentUnavailableView("No Outline", systemImage: "doc.plaintext", description: Text("Only org and Markdown files have an outline.")) | |
| 213 | 214 | } else if session.path != nil, session.outline.isEmpty { |
| 214 | 215 | ContentUnavailableView("No Headings", systemImage: "list.bullet.indent") |
| 215 | 216 | } |
Sources/OrgstarMobile/EditorScreen.swift +3 −2 · view
| @@ -193,7 +193,7 @@ struct EditorScreen: View { | ||
| 193 | 193 | editor?.run("edit.undo") |
| 194 | 194 | } |
| 195 | 195 | // On iPhone, Export is in Commands, so the file name has room. |
| 196 | if sizeClass == .regular, let tree = session.document(of: path)?.tree { | |
| 196 | if sizeClass == .regular, DocumentSession.isOrgPath(path), let tree = session.document(of: path)?.tree { | |
| 197 | 197 | ExportMenu(path: path, tree: tree, report: { message = $0 }, exportSubtree: exportSubtree) |
| 198 | 198 | } |
| 199 | 199 | Button("Commands", systemImage: "command") { sheet = .palette } |
| @@ -473,7 +473,8 @@ struct EditorScreen: View { | ||
| 473 | 473 | guard let document = session.document(of: path) else { return nil } |
| 474 | 474 | let editor = MobileEditor( |
| 475 | 475 | document: document, editable: document.isEditable, options: editorOptions, theme: model.theme, |
| 476 | showMarkup: model.showMarkup, baseDirectory: URL(fileURLWithPath: path).deletingLastPathComponent() | |
| 476 | showMarkup: model.showMarkup, baseDirectory: URL(fileURLWithPath: path).deletingLastPathComponent(), | |
| 477 | mode: DocumentSession.isOrgPath(path) ? .org : Markdown.isPath(path) ? .markdown : .plain | |
| 477 | 478 | ) |
| 478 | 479 | let path = path |
| 479 | 480 | editor.fileName = path |
Sources/OrgstarMobile/FoldersScreen.swift +2 −2 · view
| @@ -333,7 +333,7 @@ private struct FolderContents: View { | ||
| 333 | 333 | } |
| 334 | 334 | |
| 335 | 335 | var body: some View { |
| 336 | let files = workspace.files.filter { $0.root == root && ($0.kind == .org || DocumentSession.isEncryptedOrgFile($0.path)) && $0.relativePath.hasPrefix(prefix) } | |
| 336 | let files = workspace.files.filter { $0.root == root && ($0.kind == .org || $0.kind == .text || DocumentSession.isEncryptedOrgFile($0.path)) && $0.relativePath.hasPrefix(prefix) } | |
| 337 | 337 | let pending = below(workspace.downloading.filter { $0.hasPrefix(root + "/") }.map { String($0.dropFirst(root.count + 1)) }) |
| 338 | 338 | let empty = Set(emptySubfolders()) |
| 339 | 339 | let subfolders = Set((below(files.map(\.relativePath)) + pending).compactMap { path in |
| @@ -357,7 +357,7 @@ private struct FolderContents: View { | ||
| 357 | 357 | } |
| 358 | 358 | ForEach(files.filter { !$0.relativePath.dropFirst(prefix.count).contains("/") }) { file in |
| 359 | 359 | NavigationLink(value: ReaderRoute.file(file.path)) { |
| 360 | Label(file.name, systemImage: "doc.text") | |
| 360 | Label(file.name, systemImage: file.kind == .text ? "doc.plaintext" : "doc.text") | |
| 361 | 361 | } |
| 362 | 362 | .swipeActions(edge: .trailing) { |
| 363 | 363 | Button("Delete", systemImage: "trash") { deleting = file.path }.tint(.red) |
Sources/OrgstarMobile/MobileEditor+Display.swift +8 −6 · view
| @@ -182,7 +182,9 @@ extension MobileEditor { | ||
| 182 | 182 | let before = hidden.folded |
| 183 | 183 | let oldHidden = hidden.all |
| 184 | 184 | hidden.set( |
| 185 | Presentation.hiddenRanges(tree, folds: fold.folds, bodyFolds: fold.bodyFolds, wrapperRanges: wrappers), | |
| 185 | isMarkdown | |
| 186 | ? Presentation.markdownHiddenRanges(markdown, folds: fold.folds, bodyFolds: fold.bodyFolds) | |
| 187 | : Presentation.hiddenRanges(tree, folds: fold.folds, bodyFolds: fold.bodyFolds, wrapperRanges: wrappers), | |
| 186 | 188 | folded: fold.folds.union(fold.bodyFolds).union(fold.wrapperFolds) |
| 187 | 189 | ) |
| 188 | 190 | // Lines that gain or lose their `…` are made again: TextKit keeps a shown line's fragment. |
| @@ -201,14 +203,14 @@ extension MobileEditor { | ||
| 201 | 203 | /// TAB at the caret: a heading cycles, a drawer or block opens or closes. |
| 202 | 204 | @discardableResult |
| 203 | 205 | func cycleAtCaret() -> Bool { |
| 204 | guard let next = Presentation.cycle(at: textView.selectedRange.location, in: document.tree, fold) else { return false } | |
| 206 | guard let next = Presentation.cycle(at: textView.selectedRange.location, in: foldTree, fold) else { return false } | |
| 205 | 207 | setFolds(next) |
| 206 | 208 | return true |
| 207 | 209 | } |
| 208 | 210 | |
| 209 | 211 | /// Shift-TAB: overview, contents, show all. |
| 210 | 212 | func cycleGlobal() { |
| 211 | let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: fold.wrapperFolds) | |
| 213 | let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: foldTree, wrapperFolds: fold.wrapperFolds) | |
| 212 | 214 | globalVisibility = visibility |
| 213 | 215 | setFolds(state) |
| 214 | 216 | } |
| @@ -217,7 +219,7 @@ extension MobileEditor { | ||
| 217 | 219 | /// `zM`, `zr` and `zm` for the whole buffer. |
| 218 | 220 | func foldCommand(_ id: String) { |
| 219 | 221 | let caret = textView.selectedRange.location |
| 220 | let tree = document.tree | |
| 222 | let tree = foldTree | |
| 221 | 223 | let length = (document.text as NSString).length |
| 222 | 224 | let next: FoldState? |
| 223 | 225 | if id == "org.fold.close" || id == "org.fold.open-subtree" { |
| @@ -241,11 +243,11 @@ extension MobileEditor { | ||
| 241 | 243 | /// Opens the folds hiding `offset`. |
| 242 | 244 | func unfold(around offset: Int) { |
| 243 | 245 | var state = fold |
| 244 | for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end { | |
| 246 | for entry in Presentation.outline(foldTree) where entry.start < offset && offset < entry.end { | |
| 245 | 247 | state.folds.remove(entry.start) |
| 246 | 248 | state.bodyFolds.remove(entry.start) |
| 247 | 249 | } |
| 248 | for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true { | |
| 250 | for start in state.wrapperFolds where Wrappers.starting(at: start, in: foldTree)?.hidden.contains(offset) == true { | |
| 249 | 251 | state.wrapperFolds.remove(start) |
| 250 | 252 | } |
| 251 | 253 | if state != fold { setFolds(state) } |
Sources/OrgstarMobile/MobileEditor+Snippets.swift +1 −1 · view
| @@ -9,7 +9,7 @@ import UIKit | ||
| 9 | 9 | extension MobileEditor { |
| 10 | 10 | /// TAB with no binding that runs here: expands the trigger before the caret, if any. |
| 11 | 11 | func snippetTab(_ chord: KeyChord) -> Bool { |
| 12 | guard chord == KeyChord("TAB"), textView.markedTextRange == nil else { return false } | |
| 12 | guard isOrg, chord == KeyChord("TAB"), textView.markedTextRange == nil else { return false } | |
| 13 | 13 | let expand = ExpandSnippet() |
| 14 | 14 | guard expand.applies(in: editContext()) else { return false } |
| 15 | 15 | _ = perform(expand) |
Sources/OrgstarMobile/MobileEditor+Spelling.swift +1 −1 · view
| @@ -52,7 +52,7 @@ extension MobileEditor { | ||
| 52 | 52 | /// The skipped ranges for the buffer's current text, kept until it changes. |
| 53 | 53 | func spellSkipped() -> [Range<Int>] { |
| 54 | 54 | if let cached = spellSkipCache, cached.revision == document.revision { return cached.ranges } |
| 55 | let ranges = SpellCheck.skipped(document.tree) | |
| 55 | let ranges = isOrg ? SpellCheck.skipped(document.tree) : isMarkdown ? markdown.structure.blocks : [] | |
| 56 | 56 | spellSkipCache = (document.revision, ranges) |
| 57 | 57 | return ranges |
| 58 | 58 | } |
Sources/OrgstarMobile/MobileEditor+Styling.swift +15 −4 · view
| @@ -13,7 +13,7 @@ extension MobileEditor { | ||
| 13 | 13 | loading = true |
| 14 | 14 | textView.textStorage.setAttributedString(NSAttributedString(string: text, attributes: theme.base)) |
| 15 | 15 | loading = false |
| 16 | shaded.set(Presentation.shadedBlocks(document.tree), folded: []) | |
| 16 | shaded.set(isMarkdown ? markdown.structure.blocks : isOrg ? Presentation.shadedBlocks(document.tree) : [], folded: []) | |
| 17 | 17 | restartStyling() |
| 18 | 18 | textView.typingAttributes = theme.base |
| 19 | 19 | } |
| @@ -37,7 +37,7 @@ extension MobileEditor { | ||
| 37 | 37 | restyle(range) |
| 38 | 38 | } |
| 39 | 39 | |
| 40 | private func scheduleStyling() { | |
| 40 | func scheduleStyling() { | |
| 41 | 41 | guard !stylingScheduled, styled.end < textView.textStorage.length else { return } |
| 42 | 42 | stylingScheduled = true |
| 43 | 43 | DispatchQueue.main.async { [weak self] in |
| @@ -195,7 +195,7 @@ extension MobileEditor { | ||
| 195 | 195 | self.restyleScheduled = nil |
| 196 | 196 | if self.blocksMayChange { |
| 197 | 197 | self.blocksMayChange = false |
| 198 | self.shaded.set(Presentation.shadedBlocks(self.document.tree), folded: []) | |
| 198 | if self.isOrg { self.shaded.set(Presentation.shadedBlocks(self.document.tree), folded: []) } | |
| 199 | 199 | } |
| 200 | 200 | self.restyle(range) |
| 201 | 201 | self.updateHidden() |
| @@ -220,6 +220,17 @@ extension MobileEditor { | ||
| 220 | 220 | let whole = lines.location..<NSMaxRange(lines) |
| 221 | 221 | storage.beginEditing() |
| 222 | 222 | storage.setAttributes(theme.base, range: lines) |
| 223 | guard isOrg else { | |
| 224 | if isMarkdown { | |
| 225 | for run in Presentation.markdownStyles(markdown, in: whole, highlighter: Self.highlighter) { | |
| 226 | let clipped = run.range.clamped(to: whole) | |
| 227 | if !clipped.isEmpty { theme.apply(run.role, to: storage, range: NSRange(clipped)) } | |
| 228 | } | |
| 229 | } | |
| 230 | if options.spellCheck { markMisspellings(in: whole, storage: storage) } | |
| 231 | storage.endEditing() | |
| 232 | return | |
| 233 | } | |
| 223 | 234 | let revealed = caretLine |
| 224 | 235 | let (changes, scriptExclusions) = Presentation.styleChanges( |
| 225 | 236 | document.tree, in: whole, highlighter: Self.highlighter, indented: indented, hideStars: hideStars, |
| @@ -345,7 +356,7 @@ extension MobileEditor { | ||
| 345 | 356 | /// Moving to another line shows its markup and hides the last one's. |
| 346 | 357 | func revealCaretLine() { |
| 347 | 358 | // LaTeX previews and images show their source on the caret's line whether or not markup shows. |
| 348 | guard !showMarkup || showsLatex || showsImages else { return } | |
| 359 | guard !showMarkup || showsLatex || showsImages, isOrg else { return } | |
| 349 | 360 | let line = caretLine |
| 350 | 361 | guard line != revealedLine else { return } |
| 351 | 362 | let text = textView.textStorage.string as NSString |
Sources/OrgstarMobile/MobileEditor.swift +56 −13 · view
| @@ -90,6 +90,30 @@ final class MobileEditor: NSObject, DocumentBuffer { | ||
| 90 | 90 | static var lastSubstitute: (pattern: String, replacement: String, flags: String)? |
| 91 | 91 | /// The file's path, for the `%` register. |
| 92 | 92 | var fileName: String? |
| 93 | /// What the file is: org, Markdown, or plain text, which only Markdown styles and folds. | |
| 94 | enum Mode { case org, markdown, plain } | |
| 95 | let mode: Mode | |
| 96 | var isOrg: Bool { mode == .org } | |
| 97 | var isMarkdown: Bool { mode == .markdown } | |
| 98 | /// A Markdown file's structure, for the revision it was read at. | |
| 99 | var markdownCache: (revision: Int, document: MarkdownDocument)? | |
| 100 | ||
| 101 | /// The Markdown file's structure now. | |
| 102 | var markdown: MarkdownDocument { | |
| 103 | if let markdownCache, markdownCache.revision == document.revision { return markdownCache.document } | |
| 104 | let made = MarkdownDocument(document.text) | |
| 105 | markdownCache = (document.revision, made) | |
| 106 | return made | |
| 107 | } | |
| 108 | ||
| 109 | /// The file's structure for folding: the org tree, or for Markdown a tree of its headings. | |
| 110 | var foldTree: OrgTree { isMarkdown ? markdown.foldTree : document.tree } | |
| 111 | ||
| 112 | /// Whether `id` is refused because the file isn't org: in Markdown only the fold commands | |
| 113 | /// of org's run, so none writes org into the file. | |
| 114 | func refuses(_ id: String) -> Bool { | |
| 115 | !isOrg && OrgOnlyCommands.refuses(id, markdown: isMarkdown) | |
| 116 | } | |
| 93 | 117 | var onChange: (() -> Void)? |
| 94 | 118 | var onMessage: ((String) -> Void)? |
| 95 | 119 | var onPrompt: ((Prompt, @escaping (String?) -> Void) -> Void)? |
| @@ -197,9 +221,10 @@ final class MobileEditor: NSObject, DocumentBuffer { | ||
| 197 | 221 | |
| 198 | 222 | init( |
| 199 | 223 | document: DocumentState, editable: Bool, options: EditingOptions = .org, theme spec: ThemeSpec = .default, |
| 200 | showMarkup: Bool = true, baseDirectory: URL? = nil | |
| 224 | showMarkup: Bool = true, baseDirectory: URL? = nil, mode: Mode = .org | |
| 201 | 225 | ) { |
| 202 | 226 | self.document = document |
| 227 | self.mode = mode | |
| 203 | 228 | self.options = options |
| 204 | 229 | self.showMarkup = showMarkup |
| 205 | 230 | self.baseDirectory = baseDirectory |
| @@ -211,12 +236,12 @@ final class MobileEditor: NSObject, DocumentBuffer { | ||
| 211 | 236 | configure(keyed, editable: editable) |
| 212 | 237 | textView.textStorage.delegate = self |
| 213 | 238 | (textView.textLayoutManager?.textContentManager as? NSTextContentStorage)?.delegate = self |
| 214 | let startup = Presentation.startupDisplay(document.tree, options: options) | |
| 239 | let startup = mode == .org ? Presentation.startupDisplay(document.tree, options: options) : Presentation.textStartupDisplay(options: options) | |
| 215 | 240 | indented = startup.indented |
| 216 | 241 | hideStars = startup.hideStars |
| 217 | 242 | showsImages = startup.inlineImages |
| 218 | 243 | showsLatex = startup.latexPreview |
| 219 | shrunk = ShrunkColumns.startup(document.tree) | |
| 244 | if mode == .org { shrunk = ShrunkColumns.startup(document.tree) } | |
| 220 | 245 | applyThemeToView() |
| 221 | 246 | load(document.text) |
| 222 | 247 | setFolds(startup.folds) |
| @@ -238,13 +263,13 @@ final class MobileEditor: NSObject, DocumentBuffer { | ||
| 238 | 263 | view.find = find |
| 239 | 264 | view.addInteraction(UIFindInteraction(sessionDelegate: find)) |
| 240 | 265 | view.onFiles = { [weak self, weak view] files in |
| 241 | guard let self, let onFiles else { return false } | |
| 266 | guard let self, let onFiles, isOrg else { return false } | |
| 242 | 267 | if let view { focus(view) } |
| 243 | 268 | onFiles(files) |
| 244 | 269 | return true |
| 245 | 270 | } |
| 246 | 271 | view.onImage = { [weak self, weak view] data, ext in |
| 247 | guard let self, let onImage else { return false } | |
| 272 | guard let self, let onImage, isOrg else { return false } | |
| 248 | 273 | if let view { focus(view) } |
| 249 | 274 | onImage(data, ext) |
| 250 | 275 | return true |
| @@ -438,6 +463,10 @@ final class MobileEditor: NSObject, DocumentBuffer { | ||
| 438 | 463 | } |
| 439 | 464 | |
| 440 | 465 | func run(_ id: String) { |
| 466 | if refuses(id) { | |
| 467 | fail("Not an org file") | |
| 468 | return | |
| 469 | } | |
| 441 | 470 | if let snippet = Snippets.command(id) { |
| 442 | 471 | _ = perform(snippet) |
| 443 | 472 | return |
| @@ -486,11 +515,12 @@ final class MobileEditor: NSObject, DocumentBuffer { | ||
| 486 | 515 | static let linkCommands: Set<String> = ["org.link.store", "org.id.store-link", "org.link.insert"] |
| 487 | 516 | |
| 488 | 517 | func applies(_ id: String, in context: EditContext) -> Bool { |
| 518 | if refuses(id) { return false } | |
| 489 | 519 | if let command = Commands.command(id) ?? Snippets.command(id) { return command.applies(in: context) } |
| 490 | 520 | switch id { |
| 491 | 521 | case "org.snippet.next-field", "org.snippet.previous-field": return snippetSession != nil |
| 492 | 522 | case "org.cycle": |
| 493 | return Presentation.heading(containing: context.caret, in: context.tree) != nil || Wrappers.toggleable(at: context.caret, in: context.tree) != nil | |
| 523 | return Presentation.heading(containing: context.caret, in: foldTree) != nil || Wrappers.toggleable(at: context.caret, in: foldTree) != nil | |
| 494 | 524 | case _ where id.hasPrefix("org.fold."): return true |
| 495 | 525 | case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "org.toggle-inline-images-linked", "org.latex-preview", "editor.toggle-truncate-lines", |
| 496 | 526 | "editor.toggle-auto-fill", "edit.isearch-forward", "edit.isearch-backward", "editor.complete", "editor.dabbrev-expand", |
| @@ -672,8 +702,10 @@ final class MobileEditor: NSObject, DocumentBuffer { | ||
| 672 | 702 | snippetEdited(edit) |
| 673 | 703 | let oldTree = document.tree |
| 674 | 704 | let oldText = document.text as NSString |
| 705 | let oldMarkdown = isMarkdown ? markdown : nil | |
| 675 | 706 | do { |
| 676 | 707 | try document.apply([edit], baseRevision: document.revision) |
| 708 | if let oldMarkdown { markdownCache = (document.revision, oldMarkdown.applying(edit)) } | |
| 677 | 709 | } catch { |
| 678 | 710 | // Out of step: the view's text wins. |
| 679 | 711 | shrunk = ShrunkColumns() |
| @@ -682,12 +714,23 @@ final class MobileEditor: NSObject, DocumentBuffer { | ||
| 682 | 714 | } |
| 683 | 715 | let newText = textView.textStorage.string as NSString |
| 684 | 716 | styled.map(through: edit, in: newText) |
| 685 | let affected = Presentation.restyleRange(for: edit, old: (oldTree, oldText), new: (document.tree, newText)) | |
| 717 | let newEnd = edit.range.lowerBound + (replacement as NSString).length | |
| 718 | var affected = isMarkdown | |
| 719 | ? Presentation.markdownRestyleRange(for: edit, oldBlocks: oldMarkdown?.structure.blocks ?? [], new: markdown, newText: newText) | |
| 720 | : Presentation.restyleRange(for: edit, old: (oldTree, oldText), new: (document.tree, newText)) | |
| 721 | // A fence opened or closed far up restyles what follows in the background passes. | |
| 722 | if isMarkdown, affected.count > Self.styleChunk { | |
| 723 | let lines = newText.lineRange(for: NSRange(location: edit.range.lowerBound, length: newEnd - edit.range.lowerBound)) | |
| 724 | styled.unstyle(from: NSMaxRange(lines)) | |
| 725 | affected = affected.lowerBound..<NSMaxRange(lines) | |
| 726 | scheduleStyling() | |
| 727 | } | |
| 686 | 728 | vim.changed(edit) |
| 687 | 729 | // Walking the tree for blocks costs more than typing; only an edit on a line that could |
| 688 | 730 | // start or end one needs it, others move the ranges. |
| 689 | let newEnd = edit.range.lowerBound + (replacement as NSString).length | |
| 690 | if Presentation.mayChangeBlocks(oldText, edit.range) || Presentation.mayChangeBlocks(newText, edit.range.lowerBound..<newEnd) { | |
| 731 | if isMarkdown { | |
| 732 | shaded.set(markdown.structure.blocks, folded: []) | |
| 733 | } else if isOrg, Presentation.mayChangeBlocks(oldText, edit.range) || Presentation.mayChangeBlocks(newText, edit.range.lowerBound..<newEnd) { | |
| 691 | 734 | blocksMayChange = true |
| 692 | 735 | } else { |
| 693 | 736 | shaded.set(ViewState(selection: shaded.all).mapped(through: [edit]).selection, folded: []) |
| @@ -719,7 +762,7 @@ extension MobileEditor: UITextViewDelegate { | ||
| 719 | 762 | /// Another view's caret moves with edits made in this one; only the focused view's |
| 720 | 763 | /// selection drives the display. |
| 721 | 764 | func textView(_ textView: UITextView, editMenuForTextIn range: NSRange, suggestedActions: [UIMenuElement]) -> UIMenu? { |
| 722 | let suggested = range.length > 0 && textView.isEditable ? suggestedActions + [formatMenu] : suggestedActions | |
| 765 | let suggested = range.length > 0 && textView.isEditable && isOrg ? suggestedActions + [formatMenu] : suggestedActions | |
| 723 | 766 | if options.spellCheck, let menu = spellingMenu(for: range, in: textView, suggested: suggested) { return menu } |
| 724 | 767 | return suggested.count == suggestedActions.count ? nil : UIMenu(children: suggested) |
| 725 | 768 | } |
| @@ -752,11 +795,11 @@ extension MobileEditor: UITextViewDelegate { | ||
| 752 | 795 | return false |
| 753 | 796 | } |
| 754 | 797 | if !applyingEdits { typedOutsideInsert() } |
| 755 | if autoFills, !applyingEdits, textView.markedTextRange == nil, text == " ", range == textView.selectedRange { | |
| 798 | if autoFills, isOrg, !applyingEdits, textView.markedTextRange == nil, text == " ", range == textView.selectedRange { | |
| 756 | 799 | _ = perform(AutoFillSpace()) |
| 757 | 800 | return false |
| 758 | 801 | } |
| 759 | guard options.electricPair, !applyingEdits, textView.markedTextRange == nil else { return true } | |
| 802 | guard options.electricPair, isOrg, !applyingEdits, textView.markedTextRange == nil else { return true } | |
| 760 | 803 | let selected = textView.selectedRange |
| 761 | 804 | let key: String |
| 762 | 805 | if text.isEmpty, selected.length == 0, range.length == 1, NSMaxRange(range) == selected.location { |
| @@ -796,7 +839,7 @@ extension MobileEditor: UIGestureRecognizerDelegate { | ||
| 796 | 839 | @objc fileprivate func tappedFold(_ tap: UITapGestureRecognizer) { |
| 797 | 840 | if let view = tap.view as? UITextView { focus(view) } |
| 798 | 841 | guard let start = foldToggle(at: tap.location(in: textView)), |
| 799 | let next = Presentation.cycle(at: start, in: document.tree, fold) else { return } | |
| 842 | let next = Presentation.cycle(at: start, in: foldTree, fold) else { return } | |
| 800 | 843 | setFolds(next) |
| 801 | 844 | } |
| 802 | 845 | |
Sources/OrgstarMobile/OrgstarMobileApp.swift +11 −2 · view
| @@ -115,10 +115,19 @@ extension AppTab { | ||
| 115 | 115 | } |
| 116 | 116 | |
| 117 | 117 | extension View { |
| 118 | /// Readers pushed for `ReaderRoute`s. | |
| 118 | /// Readers pushed for `ReaderRoute`s; Markdown and other text files open in the editor. | |
| 119 | 119 | func readerDestination(workspace: WorkspaceModel, session: DocumentSession) -> some View { |
| 120 | 120 | navigationDestination(for: ReaderRoute.self) { route in |
| 121 | ReaderScreen(route: route, workspace: workspace, session: session) | |
| 121 | switch route { | |
| 122 | case .file(let path) where !DocumentSession.isOrgPath(path): | |
| 123 | EditorSplitScreen(path: path, offset: nil, workspace: workspace, session: session) | |
| 124 | case .offset(let path, let offset) where !DocumentSession.isOrgPath(path): | |
| 125 | EditorSplitScreen(path: path, offset: offset, workspace: workspace, session: session) | |
| 126 | case .heading(let location) where !DocumentSession.isOrgPath(location.path): | |
| 127 | EditorSplitScreen(path: location.path, offset: location.start, workspace: workspace, session: session) | |
| 128 | default: | |
| 129 | ReaderScreen(route: route, workspace: workspace, session: session) | |
| 130 | } | |
| 122 | 131 | } |
| 123 | 132 | .navigationDestination(for: EditorRoute.self) { route in |
| 124 | 133 | EditorSplitScreen(path: route.path, offset: route.offset, workspace: workspace, session: session) |
Sources/OrgstarMobile/SearchScreen.swift +2 −2 · view
| @@ -14,12 +14,12 @@ struct SearchScreen: View { | ||
| 14 | 14 | let trimmed = query.trimmingCharacters(in: .whitespaces) |
| 15 | 15 | List { |
| 16 | 16 | if !trimmed.isEmpty { |
| 17 | let files = FuzzyMatch.rank(trimmed, workspace.files.filter { $0.kind == .org }, limit: 8) | |
| 17 | let files = FuzzyMatch.rank(trimmed, workspace.files.filter { $0.kind == .org || $0.kind == .text }, limit: 8) | |
| 18 | 18 | if !files.isEmpty { |
| 19 | 19 | Section("Files") { |
| 20 | 20 | ForEach(files) { file in |
| 21 | 21 | NavigationLink(value: ReaderRoute.file(file.path)) { |
| 22 | Label(file.relativePath, systemImage: "doc.text") | |
| 22 | Label(file.relativePath, systemImage: file.kind == .text ? "doc.plaintext" : "doc.text") | |
| 23 | 23 | } |
| 24 | 24 | } |
| 25 | 25 | } |
Tests/OrgAppTests/AppTests.swift +14 · view
| @@ -263,6 +263,20 @@ struct DocumentSessionTests { | ||
| 263 | 263 | #expect(session.revealRequest?.offset == 12) |
| 264 | 264 | } |
| 265 | 265 | |
| 266 | /// Markdown files have an outline of their headings; plain text files have none. | |
| 267 | @Test func markdownOutline() throws { | |
| 268 | let notes = try Folder() | |
| 269 | let markdown = try notes.write("a.md", "* list item\n# One\n```\n# code\n```\n## Two\n") | |
| 270 | let text = try notes.write("b.txt", "# Not a heading\n") | |
| 271 | let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) | |
| 272 | session.open(markdown.path) | |
| 273 | #expect(session.isMarkdown && !session.isOrg) | |
| 274 | #expect(session.outline.map(\.title) == ["One", "Two"]) | |
| 275 | #expect(session.outline.map(\.level) == [1, 2]) | |
| 276 | session.open(text.path) | |
| 277 | #expect(!session.isMarkdown && session.outline.isEmpty) | |
| 278 | } | |
| 279 | ||
| 266 | 280 | /// A change that can't be read is reported, and the buffer keeps its text. |
| 267 | 281 | @Test func unreadableChangeIsReported() throws { |
| 268 | 282 | let notes = try Folder() |
Tests/OrgCoreTests/MarkdownTests.swift added +134 · view
| @@ -0,0 +1,134 @@ | ||
| 1 | import Foundation | |
| 2 | import OrgCore | |
| 3 | import Testing | |
| 4 | ||
| 5 | struct MarkdownStructureTests { | |
| 6 | @Test func headingsSkipFencesAndFrontMatter() { | |
| 7 | let text = "---\ntitle: Notes\n# not a heading\n---\n# One\n```swift\n# comment\n```\n## Two ##\n####### seven\n#tag\n ### Three\n" | |
| 8 | let structure = Markdown.structure(text) | |
| 9 | #expect(structure.frontMatter?.format == .yaml) | |
| 10 | #expect(structure.frontMatter?.range == 0..<37) | |
| 11 | #expect(structure.fences.count == 1) | |
| 12 | #expect(structure.fences[0].language == "swift") | |
| 13 | #expect(structure.headings.map(\.title) == ["One", "Two", "Three"]) | |
| 14 | #expect(structure.headings.map(\.level) == [1, 2, 3]) | |
| 15 | #expect(structure.headings[0].start == 37) | |
| 16 | #expect(structure.headings[0].lineEnd == 43) | |
| 17 | } | |
| 18 | ||
| 19 | @Test func fences() { | |
| 20 | let structure = Markdown.structure("~~~ {.python}\nx\n```\n~~~~\nafter\n````\nopen to the end\n```\n") | |
| 21 | #expect(structure.fences.count == 2) | |
| 22 | #expect(structure.fences[0].language == "python") | |
| 23 | #expect(structure.fences[0].range == 0..<25) | |
| 24 | #expect(structure.fences[0].body == 14..<20) | |
| 25 | // Unclosed, and a shorter run doesn't close it. | |
| 26 | #expect(structure.fences[1].closing == nil) | |
| 27 | #expect(structure.fences[1].range.upperBound == 56) | |
| 28 | // Backticks in a backtick fence's info string make it inline code. | |
| 29 | #expect(Markdown.structure("``` a`b\n").fences.isEmpty) | |
| 30 | } | |
| 31 | ||
| 32 | @Test func closingHashesAndEmptyHeadings() { | |
| 33 | let headings = Markdown.structure("# a # b ##\n#\n## #\n# c#\n").headings | |
| 34 | #expect(headings.map(\.title) == ["a # b", "", "", "c#"]) | |
| 35 | } | |
| 36 | ||
| 37 | @Test func titles() { | |
| 38 | #expect(Markdown.title("---\ntitle: \"A note\"\n---\n# Heading\n") == "A note") | |
| 39 | #expect(Markdown.title("+++\ntitle = 'TOML note'\n+++\n") == "TOML note") | |
| 40 | #expect(Markdown.title("Intro\n\n## First\n") == "First") | |
| 41 | #expect(Markdown.title("---\ndate: 2026\n---\n# From the heading\n") == "From the heading") | |
| 42 | #expect(Markdown.title("no headings") == nil) | |
| 43 | // A `---` line alone isn't front matter. | |
| 44 | #expect(Markdown.structure("---\ntext\n").frontMatter == nil) | |
| 45 | } | |
| 46 | ||
| 47 | /// Updating the structure through an edit gives what reading the new text does. | |
| 48 | @Test func editsMatchAFreshRead() { | |
| 49 | let pieces = ["# A\n", "## B\n", "text\n", "```\n", "~~~ py\n", "# in fence?\n", "---\n", "+++\n", "\n", "#", "x", "`", " ", "\n"] | |
| 50 | var generator = SeededGenerator(state: testSeed(159)) | |
| 51 | var text = "Intro\n# One\nbody\n```\n# code\n```\n## Two\nmore\n" | |
| 52 | var structure = Markdown.structure(text) | |
| 53 | for _ in 0..<2_000 { | |
| 54 | let old = Array(text.utf16) | |
| 55 | let lower = Int.random(in: 0...old.count, using: &generator) | |
| 56 | let upper = min(old.count, lower + Int.random(in: 0...6, using: &generator)) | |
| 57 | let replacement = Int.random(in: 0...2, using: &generator) == 0 ? "" : pieces.randomElement(using: &generator)! | |
| 58 | var new = old | |
| 59 | new.replaceSubrange(lower..<upper, with: Array(replacement.utf16)) | |
| 60 | let edit = TextEdit(range: lower..<upper, replacement: replacement) | |
| 61 | structure = Markdown.structure(structure, old: old, new: new, after: edit) ?? Markdown.structure(new) | |
| 62 | text = String(decoding: new, as: UTF16.self) | |
| 63 | #expect(structure == Markdown.structure(new), "\(text.debugDescription) after \(edit)") | |
| 64 | if structure != Markdown.structure(new) { return } | |
| 65 | } | |
| 66 | } | |
| 67 | ||
| 68 | @Test func paths() { | |
| 69 | #expect(Markdown.isPath("/a/b.md") && Markdown.isPath("x.MARKDOWN") && !Markdown.isPath("x.org")) | |
| 70 | #expect(Markdown.isPlainTextPath("notes.txt") && !Markdown.isPlainTextPath("notes.md")) | |
| 71 | } | |
| 72 | } | |
| 73 | ||
| 74 | struct MarkdownSpanTests { | |
| 75 | func spans(_ line: String) -> [String] { | |
| 76 | let u = Array(line.utf16) | |
| 77 | return Markdown.lineSpans(u, 0, u.count).map { span in | |
| 78 | "\(span.kind):" + String(decoding: u[span.range], as: UTF16.self) | |
| 79 | } | |
| 80 | } | |
| 81 | ||
| 82 | @Test func emphasis() { | |
| 83 | #expect(spans("a **b** _c_ ~~d~~") == [ | |
| 84 | "bold:**b**", "marker:**", "marker:**", "italic:_c_", "marker:_", "marker:_", "strikeThrough:~~d~~", "marker:~~", "marker:~~", | |
| 85 | ]) | |
| 86 | #expect(spans("***both***") == ["italic:***both***", "marker:*", "bold:**both**", "marker:**", "marker:**", "marker:*"]) | |
| 87 | // Intraword underscores and spaced stars aren't emphasis. | |
| 88 | #expect(spans("snake_case_name and 2 * 3 * 4").isEmpty) | |
| 89 | } | |
| 90 | ||
| 91 | @Test func codeHidesMarkup() { | |
| 92 | #expect(spans("`*not*` and ``a ` b``") == ["code:`*not*`", "marker:`", "marker:`", "code:``a ` b``", "marker:``", "marker:``"]) | |
| 93 | #expect(spans("an `unclosed *span*").contains("italic:*span*")) | |
| 94 | } | |
| 95 | ||
| 96 | @Test func links() { | |
| 97 | #expect(spans("[a *b*](http://x.y/(z)) ") == [ | |
| 98 | "linkMarkup:[", "link:a *b*", "italic:*b*", "marker:*", "marker:*", "linkMarkup:](http://x.y/(z))", | |
| 99 | "linkMarkup:", | |
| 100 | ]) | |
| 101 | #expect(spans("<https://example.com> and https://a.b/c_d_e.") == [ | |
| 102 | "linkMarkup:<", "link:https://example.com", "linkMarkup:>", "link:https://a.b/c_d_e", | |
| 103 | ]) | |
| 104 | #expect(spans("[ref]: https://example.com \"Title\"") == ["linkMarkup:[ref]: ", "link:https://example.com"]) | |
| 105 | #expect(spans("[text][ref]") == ["linkMarkup:[", "link:text", "linkMarkup:][ref]"]) | |
| 106 | } | |
| 107 | ||
| 108 | @Test func lines() { | |
| 109 | #expect(spans("## Title with `code`") == ["heading(level: 2):## Title with `code`", "code:`code`", "marker:`", "marker:`"]) | |
| 110 | #expect(spans("- [x] done") == ["marker:-", "checkbox:[x]"]) | |
| 111 | #expect(spans(" 12. item") == ["marker:12."]) | |
| 112 | #expect(spans("> > quoted *text*") == ["marker:>", "marker:>", "quote:quoted *text*", "italic:*text*", "marker:*", "marker:*"]) | |
| 113 | #expect(spans("* * *") == ["rule:* * *"]) | |
| 114 | #expect(spans("| a | b |") == ["table:| a | b |"]) | |
| 115 | #expect(spans("<!-- note --> after") == ["comment:<!-- note -->"]) | |
| 116 | } | |
| 117 | } | |
| 118 | ||
| 119 | struct OrgOnlyCommandTests { | |
| 120 | @Test func refusedOutsideOrg() { | |
| 121 | for id in ["org.todo.cycle", "org.meta-return", "org.link.insert", "app.refile", "app.archive", "app.attach.attach", "app.export.html", | |
| 122 | "app.table-import", "app.clock.in", "app.node.insert", "app.crypt.encrypt-entry", "app.export-dialog"] { | |
| 123 | #expect(OrgOnlyCommands.refuses(id, markdown: true), "\(id)") | |
| 124 | #expect(OrgOnlyCommands.refuses(id, markdown: false), "\(id)") | |
| 125 | } | |
| 126 | for id in ["org.cycle", "org.cycle-global", "org.fold.toggle", "org.fold.close-all"] { | |
| 127 | #expect(!OrgOnlyCommands.refuses(id, markdown: true), "\(id)") | |
| 128 | #expect(OrgOnlyCommands.refuses(id, markdown: false), "\(id)") | |
| 129 | } | |
| 130 | for id in ["app.save", "app.agenda", "app.capture", "app.search", "app.word-count", "app.export.icalendar-agenda", "edit.undo", "editor.toggle-truncate-lines"] { | |
| 131 | #expect(!OrgOnlyCommands.refuses(id, markdown: true), "\(id)") | |
| 132 | } | |
| 133 | } | |
| 134 | } | |
Tests/OrgEditorAppKitTests/GateTests.swift +22 −2 · view
| @@ -65,6 +65,20 @@ struct GateTests { | ||
| 65 | 65 | return text |
| 66 | 66 | }() |
| 67 | 67 | |
| 68 | /// About 1 MB of Markdown: front matter, headings, paragraphs with emphasis, code and | |
| 69 | /// links, lists, block quotes and fenced code. | |
| 70 | static let markdown: String = { | |
| 71 | var text = "---\ntitle: Gate\n---\n" | |
| 72 | var n = 0 | |
| 73 | while text.utf8.count < 1_000_000 { | |
| 74 | text += "## Section \(n)\n\nParagraph \(n) with **bold**, *italic*, `code`, a [link](https://example.com/\(n)) and https://example.com.\n" | |
| 75 | text += "It continues on a second line with ~~struck~~ and _more_.\n\n" | |
| 76 | text += "- item \(n)\n - [ ] nested task\n\n> quoted \(n)\n\n```swift\nlet n = \(n)\n```\n\n" | |
| 77 | n += 1 | |
| 78 | } | |
| 79 | return text | |
| 80 | }() | |
| 81 | ||
| 68 | 82 | struct Result: CustomStringConvertible { |
| 69 | 83 | var name: String |
| 70 | 84 | var bytes: Int |
| @@ -85,13 +99,13 @@ struct GateTests { | ||
| 85 | 99 | return Int(stats.size_in_use) |
| 86 | 100 | } |
| 87 | 101 | |
| 88 | func measure(_ name: String, _ text: String) -> Result { | |
| 102 | func measure(_ name: String, _ text: String, mode: OrgEditor.Mode = .org) -> Result { | |
| 89 | 103 | let clock = ContinuousClock() |
| 90 | 104 | let bytes = Array(text.utf8) |
| 91 | 105 | let before = Self.heapBytes() |
| 92 | 106 | var harness: Harness! |
| 93 | 107 | let open = clock.measure { |
| 94 | harness = Harness(DocumentState(bytes: bytes), layout: false) | |
| 108 | harness = Harness(DocumentState(bytes: bytes), layout: false, mode: mode) | |
| 95 | 109 | } |
| 96 | 110 | harness.drainStyling() |
| 97 | 111 | let memoryRatio = Double(Self.heapBytes() - before) / Double(bytes.count) |
| @@ -140,6 +154,12 @@ struct GateTests { | ||
| 140 | 154 | print("GATE \(name) (\(text.utf8.count / 1000) kB): lint \(lint)") |
| 141 | 155 | #expect(lint < .milliseconds(500) * max(1, Double(text.utf8.count) / 1_000_000), "\(name): lint") |
| 142 | 156 | } |
| 157 | let markdown = measure("1 MB Markdown", Self.markdown, mode: .markdown) | |
| 158 | print("GATE \(markdown)") | |
| 159 | #expect(markdown.open < .milliseconds(100) * max(1, Double(markdown.bytes) / 1_000_000), "Markdown: open") | |
| 160 | #expect(markdown.typingP95 < .milliseconds(16), "Markdown: typing") | |
| 161 | #expect(markdown.newlineP95 < .milliseconds(16), "Markdown: blank line") | |
| 162 | #expect(markdown.memoryRatio < 45, "Markdown: memory") | |
| 143 | 163 | let large = measure("10 MB mixed document", Self.tenMegabytes) |
| 144 | 164 | print("GATE \(large)") |
| 145 | 165 | #expect(large.open < .milliseconds(1_500), "10 MB: open") |
Tests/OrgEditorAppKitTests/MarkdownModeTests.swift added +113 · view
| @@ -0,0 +1,113 @@ | ||
| 1 | import AppKit | |
| 2 | import OrgCore | |
| 3 | import OrgDocument | |
| 4 | import OrgPresentation | |
| 5 | import Testing | |
| 6 | @testable import OrgEditorAppKit | |
| 7 | ||
| 8 | /// Markdown files: highlighted, folded by heading, and closed to org's commands. | |
| 9 | @MainActor | |
| 10 | struct MarkdownModeTests { | |
| 11 | func markdown(_ text: String) -> Harness { | |
| 12 | let h = Harness(DocumentState(bytes: Array(text.utf8)), mode: .markdown) | |
| 13 | h.drainStyling() | |
| 14 | h.layout() | |
| 15 | return h | |
| 16 | } | |
| 17 | ||
| 18 | func font(_ h: Harness, at offset: Int) -> NSFont? { | |
| 19 | h.textView.textStorage!.attribute(.font, at: offset, effectiveRange: nil) as? NSFont | |
| 20 | } | |
| 21 | ||
| 22 | @Test func highlighting() { | |
| 23 | let text = "# Title\nplain **bold** and `code`\n* item\n" | |
| 24 | let h = markdown(text) | |
| 25 | let theme = h.editor.theme | |
| 26 | #expect(font(h, at: 2)?.fontDescriptor.symbolicTraits.contains(.bold) == true) | |
| 27 | #expect(font(h, at: 10) == theme.font) | |
| 28 | #expect(font(h, at: 17)?.fontDescriptor.symbolicTraits.contains(.bold) == true) | |
| 29 | let storage = h.textView.textStorage! | |
| 30 | let code = (text as NSString).range(of: "code").location | |
| 31 | #expect(storage.attribute(.foregroundColor, at: code, effectiveRange: nil) as? NSColor == theme.color("code")) | |
| 32 | // `* item` is a list item, not an org heading. | |
| 33 | let item = (text as NSString).range(of: "item").location | |
| 34 | #expect(font(h, at: item) == theme.font) | |
| 35 | } | |
| 36 | ||
| 37 | @Test func typingKeepsHighlightingInStep() { | |
| 38 | let h = markdown("a\n```\n# code\n```\n# Heading\n") | |
| 39 | let heading = h.offset(of: "# Heading") + 2 | |
| 40 | #expect(font(h, at: heading)?.fontDescriptor.symbolicTraits.contains(.bold) == true) | |
| 41 | // Removing the closing fence makes the heading code. | |
| 42 | let closing = h.offset(of: "```\n# Heading") | |
| 43 | h.textView.setSelectedRange(NSRange(location: closing, length: 4)) | |
| 44 | h.textView.insertText("", replacementRange: h.textView.selectedRange()) | |
| 45 | #expect(font(h, at: h.offset(of: "# Heading") + 2) == h.editor.theme.font) | |
| 46 | #expect(h.editor.document.text == "a\n```\n# code\n# Heading\n") | |
| 47 | } | |
| 48 | ||
| 49 | @Test func tabFoldsHeadings() { | |
| 50 | let h = markdown("# A\nbody\n## B\nmore\n# C\ntext\n") | |
| 51 | h.caret(at: 1) | |
| 52 | h.editor.run("org.cycle") | |
| 53 | #expect(h.visibleLines == ["# A\n", "# C\n", "text\n"]) | |
| 54 | h.editor.run("org.cycle") | |
| 55 | #expect(h.visibleLines == ["# A\n", "body\n", "## B\n", "# C\n", "text\n"]) | |
| 56 | h.editor.run("org.cycle-global") | |
| 57 | #expect(h.visibleLines == ["# A\n", "# C\n"]) | |
| 58 | h.editor.reveal(h.offset(of: "more")) | |
| 59 | #expect(h.visibleLines.contains("more\n")) | |
| 60 | // Folds stay on their headings as text is typed above them. | |
| 61 | h.editor.run("org.cycle-global") | |
| 62 | h.caret(at: 0) | |
| 63 | h.textView.insertText("x", replacementRange: h.textView.selectedRange()) | |
| 64 | let folded = h.editor.foldState.folds.union(h.editor.foldState.bodyFolds) | |
| 65 | #expect(folded == Set(h.editor.markdown.outline.map(\.start))) | |
| 66 | } | |
| 67 | ||
| 68 | @Test func clickingHashesCycles() { | |
| 69 | let h = markdown("## A\nbody\n- [ ] task\n") | |
| 70 | #expect(!h.editor.click(at: 4)) | |
| 71 | #expect(h.editor.click(at: 1)) | |
| 72 | #expect(h.visibleLines == ["## A\n"]) | |
| 73 | // A task box isn't toggled: that would be org's checkbox command. | |
| 74 | _ = h.editor.click(at: 1) | |
| 75 | #expect(!h.editor.click(at: h.offset(of: "[ ]") + 1)) | |
| 76 | #expect(h.editor.document.text == "## A\nbody\n- [ ] task\n") | |
| 77 | } | |
| 78 | ||
| 79 | @Test func orgCommandsAreRefused() { | |
| 80 | let text = "# Heading\n- item\n| a |\n" | |
| 81 | let h = markdown(text) | |
| 82 | var messages: [String] = [] | |
| 83 | var appCommands: [String] = [] | |
| 84 | h.editor.onMessage = { messages.append($0) } | |
| 85 | h.editor.onAppCommand = { appCommands.append($0) } | |
| 86 | for id in ["org.todo.cycle", "org.item.insert", "org.heading.insert", "org.timestamp.inactive", "org.link.insert", "org.emphasize.bold", | |
| 87 | "org.table.align", "org.tags.set", "org.schedule", "org.priority.up", "app.refile", "app.archive", "app.attach.attach", | |
| 88 | "app.table-import", "app.export.html", "app.clock.in"] { | |
| 89 | h.caret(at: 3) | |
| 90 | h.editor.run(id) | |
| 91 | #expect(h.editor.document.text == text, "\(id)") | |
| 92 | } | |
| 93 | #expect(appCommands.isEmpty) | |
| 94 | #expect(messages == Array(repeating: "Not an org file", count: 16)) | |
| 95 | // Typing doesn't continue lists or fill as org would. | |
| 96 | h.caret(at: 16) | |
| 97 | h.textView.insertNewline(nil) | |
| 98 | #expect(h.editor.document.text == "# Heading\n- item\n\n| a |\n") | |
| 99 | // App commands that aren't about the file's entries still reach the app. | |
| 100 | h.editor.run("app.save") | |
| 101 | #expect(appCommands == ["app.save"]) | |
| 102 | } | |
| 103 | ||
| 104 | @Test func plainTextDoesNotFold() { | |
| 105 | let h = Harness(DocumentState(bytes: Array("# A\nbody\n".utf8)), mode: .plain(language: nil)) | |
| 106 | var messages: [String] = [] | |
| 107 | h.editor.onMessage = { messages.append($0) } | |
| 108 | h.caret(at: 1) | |
| 109 | h.editor.run("org.cycle") | |
| 110 | #expect(h.visibleLines == ["# A\n", "body\n"]) | |
| 111 | #expect(messages == ["Not an org file"]) | |
| 112 | } | |
| 113 | } | |
Tests/OrgIndexTests/TextFileRecordTests.swift added +43 · view
| @@ -0,0 +1,43 @@ | ||
| 1 | import Foundation | |
| 2 | import OrgCore | |
| 3 | import Testing | |
| 4 | @testable import OrgIndex | |
| 5 | ||
| 6 | /// Markdown and plain text files in the index: searched, titled, never org. | |
| 7 | struct TextFileRecordTests { | |
| 8 | @Test func markdownHeadingsAndTitle() { | |
| 9 | let text = "---\ntitle: Field notes\n---\nThe heron came back.\n# Birds\nherons\n## Waders\n* TODO not org\n```\n# not a heading\n```\n# Fish\n" | |
| 10 | let file = record("/notes/a.md", text, kind: .text) | |
| 11 | #expect(file.title == "Field notes") | |
| 12 | #expect(file.preamble == "---\ntitle: Field notes\n---\nThe heron came back.\n") | |
| 13 | #expect(file.headings.map(\.title) == ["Birds", "Waders", "Fish"]) | |
| 14 | #expect(file.headings.map(\.level) == [1, 2, 1]) | |
| 15 | #expect(file.headings.map(\.parent) == [nil, 0, nil]) | |
| 16 | #expect(file.headings[1].outlinePath == ["Birds", "Waders"]) | |
| 17 | #expect(file.headings[0].body == "herons\n") | |
| 18 | #expect(file.headings[1].body == "* TODO not org\n```\n# not a heading\n```\n") | |
| 19 | #expect(file.headings.allSatisfy { $0.todo == nil && $0.tags.isEmpty && $0.timestamps.isEmpty && $0.links.isEmpty }) | |
| 20 | #expect(file.fileID == nil && file.links.isEmpty) | |
| 21 | #expect(record("/notes/b.md", "Intro\n## First\n", kind: .text).title == "First") | |
| 22 | } | |
| 23 | ||
| 24 | @Test func plainTextIsOneBody() { | |
| 25 | let file = record("/notes/a.txt", "* not a heading\n#+title: not a title\n", kind: .text) | |
| 26 | #expect(file.headings.isEmpty && file.title == nil) | |
| 27 | #expect(file.preamble == "* not a heading\n#+title: not a title\n") | |
| 28 | } | |
| 29 | ||
| 30 | @Test func searchFindsTextFiles() throws { | |
| 31 | let store = try IndexStore() | |
| 32 | try store.write(record("/notes/a.md", "---\ntitle: Pond\n---\nOtters swim.\n# Herons\nThey wade.\n", kind: .text)) | |
| 33 | try store.write(record("/notes/b.txt", "A list of kingfishers.\n", kind: .text)) | |
| 34 | #expect(try store.search("otters").map(\.title) == ["Pond"]) | |
| 35 | let heading = try store.search("wade") | |
| 36 | #expect(heading.map(\.title) == ["Herons"]) | |
| 37 | #expect(heading.first?.start == 33) | |
| 38 | #expect(try store.search("kingfish").map(\.title) == ["b.txt"]) | |
| 39 | // Not org: no outline, nodes or link targets. | |
| 40 | #expect(try store.outline(maxLevel: 3).isEmpty) | |
| 41 | #expect(try store.linkTargets().isEmpty) | |
| 42 | } | |
| 43 | } | |
Tests/OrgPresentationTests/MarkdownDisplayTests.swift added +87 · view
| @@ -0,0 +1,87 @@ | ||
| 1 | import Foundation | |
| 2 | import OrgCore | |
| 3 | import OrgPresentation | |
| 4 | import Testing | |
| 5 | ||
| 6 | /// Highlights `yaml` and `swift` code as one keyword run over the whole code. | |
| 7 | struct WholeCodeHighlighter: CodeHighlighter { | |
| 8 | func highlights(language: String, code: String) -> [(range: Range<Int>, category: SyntaxCategory)] { | |
| 9 | ["yaml", "swift"].contains(language) ? [(0..<code.utf16.count, .keyword)] : [] | |
| 10 | } | |
| 11 | } | |
| 12 | ||
| 13 | struct MarkdownDisplayTests { | |
| 14 | let text = "Intro\n# A\nbody\n## B\nmore\n```\n# not\n```\n# C\ntext\n" | |
| 15 | ||
| 16 | @Test func outline() { | |
| 17 | let document = MarkdownDocument(text) | |
| 18 | let outline = document.outline | |
| 19 | #expect(outline.map(\.title) == ["A", "B", "C"]) | |
| 20 | #expect(outline.map(\.start) == [6, 15, 39]) | |
| 21 | #expect(outline.map(\.end) == [39, 39, 48]) | |
| 22 | #expect(outline.map(\.parent) == [nil, 0, nil]) | |
| 23 | #expect(outline.map(\.isTopLevel) == [true, false, true]) | |
| 24 | } | |
| 25 | ||
| 26 | @Test func foldsByHeading() { | |
| 27 | let document = MarkdownDocument(text) | |
| 28 | let tree = document.foldTree | |
| 29 | #expect(tree.text.utf16.count == text.utf16.count) | |
| 30 | #expect(Presentation.outline(tree).map(\.start) == document.outline.map(\.start)) | |
| 31 | #expect(Presentation.hiddenRanges(tree, folds: [6]) == [10..<39]) | |
| 32 | #expect(Presentation.hiddenRanges(tree, folds: [15]) == [20..<39]) | |
| 33 | // TAB on a heading: folded, children, subtree. | |
| 34 | let folded = Presentation.cycle(6, in: tree, FoldState()) | |
| 35 | #expect(folded.folds == [6]) | |
| 36 | let children = Presentation.cycle(6, in: tree, folded) | |
| 37 | #expect(children.folds == [15]) | |
| 38 | // Without the tree, the same ranges as org's for the tree. | |
| 39 | for (folds, bodyFolds) in [([6], []), ([15], []), ([6, 15], []), ([], [6]), ([39], [6]), ([], [6, 15, 39]), ([6], [15])] as [(Set<Int>, Set<Int>)] { | |
| 40 | #expect(Presentation.markdownHiddenRanges(document, folds: folds, bodyFolds: bodyFolds) | |
| 41 | == Presentation.hiddenRanges(tree, folds: folds, bodyFolds: bodyFolds), "\(folds) \(bodyFolds)") | |
| 42 | } | |
| 43 | // The `#` line in a fence isn't a heading. | |
| 44 | #expect(Presentation.heading(containing: 31, in: tree) == nil) | |
| 45 | #expect(Presentation.heading(containing: 40, in: tree) == 39) | |
| 46 | } | |
| 47 | ||
| 48 | func roles(_ text: String, highlighter: (any CodeHighlighter)? = nil) -> [String] { | |
| 49 | let document = MarkdownDocument(text) | |
| 50 | let ns = text as NSString | |
| 51 | return Presentation.markdownStyles(document, in: 0..<ns.length, highlighter: highlighter).map { | |
| 52 | "\($0.role) " + ns.substring(with: NSRange($0.range)).replacingOccurrences(of: "\n", with: "⏎") | |
| 53 | } | |
| 54 | } | |
| 55 | ||
| 56 | @Test func styles() { | |
| 57 | #expect(roles("---\nk: v\n---\n# H *e*\n```swift\nlet\n```\n> q\n", highlighter: WholeCodeHighlighter()) == [ | |
| 58 | "blockDelimiter ---⏎", "metadata k: v⏎", "syntax(OrgPresentation.SyntaxCategory.keyword) k: v⏎", "blockDelimiter ---⏎", | |
| 59 | "blockDelimiter ```swift⏎", "block let⏎", "syntax(OrgPresentation.SyntaxCategory.keyword) let⏎", "blockDelimiter ```⏎", | |
| 60 | "heading(level: 1) # H *e*", "italic *e*", "markup *", "markup *", | |
| 61 | "markup >", "italic q", | |
| 62 | ]) | |
| 63 | } | |
| 64 | ||
| 65 | @Test func stylesOnlyTheLinesAsked() { | |
| 66 | let text = "# A\n**b**\n```\n# c\n" | |
| 67 | let document = MarkdownDocument(text) | |
| 68 | let runs = Presentation.markdownStyles(document, in: 5..<6) | |
| 69 | #expect(runs.map(\.role) == [.bold, .markup, .markup]) | |
| 70 | // Inside an unclosed fence, nothing is a heading. | |
| 71 | #expect(Presentation.markdownStyles(document, in: 14..<17).map(\.role) == [.blockDelimiter, .block]) | |
| 72 | } | |
| 73 | ||
| 74 | @Test func restyleRangeFollowsFences() { | |
| 75 | let old = "a\n```\ncode\n```\nb\n# h\n" | |
| 76 | let oldBlocks = MarkdownDocument(old).structure.blocks | |
| 77 | // Deleting the closing fence opens the block to the end of the text. | |
| 78 | let edit = TextEdit(range: 11..<15, replacement: "") | |
| 79 | let new = "a\n```\ncode\nb\n# h\n" | |
| 80 | let range = Presentation.markdownRestyleRange(for: edit, oldBlocks: oldBlocks, new: MarkdownDocument(new), newText: new as NSString) | |
| 81 | #expect(range == 2..<(new as NSString).length) | |
| 82 | // Typing inside a paragraph restyles its line. | |
| 83 | let typed = TextEdit(range: 1..<1, replacement: "x") | |
| 84 | let after = "ax\n```\ncode\n```\nb\n# h\n" | |
| 85 | #expect(Presentation.markdownRestyleRange(for: typed, oldBlocks: oldBlocks, new: MarkdownDocument(after), newText: after as NSString) == 0..<3) | |
| 86 | } | |
| 87 | } | |
Tests/OrgWorkspaceTests/DiscoveryTests.swift +6 −2 · view
| @@ -13,7 +13,11 @@ struct ClassificationTests { | ||
| 13 | 13 | (".a.org.orgstar-1234", .ignored), |
| 14 | 14 | ("a.org~", .ignored), |
| 15 | 15 | ("#a.org#", .ignored), |
| 16 | ("a.md", .file(.other)), | |
| 16 | ("a.md", .file(.text)), | |
| 17 | ("a.markdown", .file(.text)), | |
| 18 | ("a.txt", .file(.text)), | |
| 19 | ("a.sync-conflict-20261004-120000-ABCDEFG.md", .file(.conflict)), | |
| 20 | (".a.md.icloud", .placeholder("a.md")), | |
| 17 | 21 | ("photo.jpg", .file(.other)), |
| 18 | 22 | (".hidden.org", .file(.org)), |
| 19 | 23 | (".zshrc", .file(.other)), |
| @@ -50,7 +54,7 @@ struct ScanTests { | ||
| 50 | 54 | try folder.write("node_modules/x/index.js", "") |
| 51 | 55 | let discovery = try WorkspaceScanner.scan(folder.url) |
| 52 | 56 | #expect(discovery.files.map(\.url.lastPathComponent) == ["app.toml", ".notes.org", "a.org", "notes.txt", "b.org_archive"]) |
| 53 | #expect(discovery.files.map(\.kind) == [.other, .org, .org, .other, .archive]) | |
| 57 | #expect(discovery.files.map(\.kind) == [.other, .org, .org, .text, .archive]) | |
| 54 | 58 | let visible = try WorkspaceScanner.scan(folder.url, rules: ScanRules(hiddenFiles: false)) |
| 55 | 59 | #expect(visible.files.map(\.url.lastPathComponent) == ["a.org", "notes.txt", "b.org_archive"]) |
| 56 | 60 | #expect(discovery.placeholders.map(\.lastPathComponent) == ["e.org"]) |
Tests/OrgWorkspaceTests/ReconcileTests.swift +1 −1 · view
| @@ -67,7 +67,7 @@ struct ReconcileTests { | ||
| 67 | 67 | let folder = try Folder() |
| 68 | 68 | let index = try IndexStore() |
| 69 | 69 | let reconciler = Reconciler(index: index, settings: IndexSettings()) |
| 70 | let notes = try folder.write("notes.md", "* Alpha\n") | |
| 70 | let notes = try folder.write("notes.html", "* Alpha\n") | |
| 71 | 71 | try folder.write(".git/HEAD", "ref: refs/heads/main\n") |
| 72 | 72 | _ = try reconciler.reconcile(root: folder.url) |
| 73 | 73 | #expect(try index.files().map(\.kind) == [.other]) |
docs/manual/guide/01-files-and-folders.org +26 −6 · view
| @@ -95,7 +95,7 @@ show-hidden-files = true | ||
| 95 | 95 | ignored-folders = ".git .hg node_modules build" |
| 96 | 96 | #+END_SRC |
| 97 | 97 | |
| 98 | Only org files (=.org= and =.org_archive=) are read by the index. Other files are listed and can be opened, but their contents are not searched. | |
| 98 | Org files (=.org= and =.org_archive=), Markdown files (=.md=, =.markdown=) and =.txt= files are read by the index. Only org files feed the agenda, IDs and links; Markdown and text files are searched. Other files are listed and can be opened, but their contents are not searched. | |
| 99 | 99 | |
| 100 | 100 | ** Creating, renaming and trashing files |
| 101 | 101 | |
| @@ -128,11 +128,31 @@ orgstar has no Open Recent menu. Instead, it reopens the buffers that were open | ||
| 128 | 128 | How a file opens depends on what it is: |
| 129 | 129 | |
| 130 | 130 | - *Org files* (=.org=, =.org_archive=) open in the editor with org editing. |
| 131 | - *Text files* open in the same editor as plain text. A file counts as text when macOS knows its type as text, or, for unknown types, when its first 8 KB are valid UTF-8 with no NUL bytes. Org commands report =Not an org file=, and the outline pane shows "No outline" when you turn it on. Files in these languages get syntax highlighting: shell (=.sh=, =.bash=, =.zsh=, =.zshrc=, =.bashrc=, =.profile=), Python, Emacs Lisp, C, C++, R, JavaScript, Java, Scheme, Clojure, Haskell, Rust, Go, Ruby, JSON, YAML, TOML and Lua. | |
| 131 | - *Markdown files* (=.md=, =.markdown=) open in the editor with Markdown highlighting, heading folds and an outline; see /Markdown/ below. | |
| 132 | - *Text files* open in the same editor as plain text. A file counts as text when macOS knows its type as text, or, for unknown types, when its first 8 KB are valid UTF-8 with no NUL bytes. Org commands, folding included, report =Not an org file=, and the outline pane shows "No outline" when you turn it on. Files in these languages get syntax highlighting: shell (=.sh=, =.bash=, =.zsh=, =.zshrc=, =.bashrc=, =.profile=), Python, Emacs Lisp, C, C++, R, JavaScript, Java, Scheme, Clojure, Haskell, Rust, Go, Ruby, JSON, YAML, TOML and Lua. | |
| 132 | 133 | - *Everything else* (images, PDFs, audio, video, archives, binary files) shows a Quick Look preview in place of the editor, with =Open with Default App= and =Show in Finder= buttons below it. The preview is not a buffer. |
| 133 | 134 | |
| 134 | 135 | Text files from Finder use orgstar only if you choose it with Open With, since orgstar is not their default app. |
| 135 | 136 | |
| 137 | ** Markdown | |
| 138 | ||
| 139 | Markdown and plain text are a fallback, for notes kept in those formats next to org files, such as Denote's Markdown notes. orgstar edits them as text and doesn't convert them. | |
| 140 | ||
| 141 | In a Markdown file the editor styles: | |
| 142 | ||
| 143 | - ATX headings (=#= to =######=), in the theme's heading colours and sizes; | |
| 144 | - =**bold**=, =__bold__=, =*italic*=, =_italic_=, =~~strike-through~~= and =`code`=, with their markers in the markup colour; | |
| 145 | - links (=[text](url)=, =[text][label]=, =<url>=, bare =http://= and =https://= addresses, images and =[label]: url= definitions); | |
| 146 | - list bullets and numbers, task boxes (=[ ]=, =[x]=), block quotes, tables, rules (=---=, =***=, =___=) and =<!-- comments -->=; | |
| 147 | - fenced code (=```= or =~~~=) on the block band, highlighted when the fence names one of the languages above; | |
| 148 | - YAML (=---=) or TOML (=+++=) front matter at the top of the file, highlighted as YAML or TOML. | |
| 149 | ||
| 150 | Headings fold with the fold commands of /Folding/ in [[file:02-the-editor.org][The editor]]: =TAB= on a heading line, =S-TAB=, Doom's =z= keys, and a click on a heading's =#=s. A section runs to the next heading of the same or a higher level; a =#= line inside fenced code or front matter is not a heading. The outline pane lists the headings, and search finds them (see /Searching your notes/ below). | |
| 151 | ||
| 152 | Other org commands report =Not an org file= and change nothing, so none of them writes org syntax into the file. Among them: heading and list structure commands, TODO keywords, priorities, tags, properties, dates, tables, links and Insert Link, emphasis, checkbox toggling, clocking, refiling, archiving, attachments, encryption, Share Subtree, Copy as Rich Text and every export. Lint File says it works on Org files. Typing doesn't continue lists, pair brackets or fill paragraphs as it does in org files, dropped files aren't attached, and snippets don't expand. Commands that don't act on the file's own entries, such as the agenda, capture, search and Save, work as usual. | |
| 153 | ||
| 154 | Not supported in Markdown files: setext headings (a line underlined with === or ---), indented code blocks, HTML blocks, emphasis that spans lines, footnotes, a rendered preview, and Markdown versions of org's structure editing, agenda, capture and export. | |
| 155 | ||
| 136 | 156 | * Buffers |
| 137 | 157 | |
| 138 | 158 | Each open file is a buffer, as in Emacs. A buffer keeps its text, caret, folds, undo history and unsaved edits while another buffer is showing. Opening a file that already has a buffer shows that buffer. Two paths to the same file (through a symbolic link, for example) share one buffer, as =find-buffer-visiting= does. |
| @@ -180,13 +200,13 @@ View ▸ Show Tab Bar shows a row of tabs above each pane, one per buffer that p | ||
| 180 | 200 | |
| 181 | 201 | * Searching your notes |
| 182 | 202 | |
| 183 | The search field in the toolbar searches every org file in your folders. Click it or choose Edit ▸ Search Notes (=⇧⌘F=; =SPC /= or =SPC s p= in Doom normal state) and type. | |
| 203 | The search field in the toolbar searches every org, Markdown and =.txt= file in your folders. Click it or choose Edit ▸ Search Notes (=⇧⌘F=; =SPC /= or =SPC s p= in Doom normal state) and type. | |
| 184 | 204 | |
| 185 | 205 | While the field holds text, the outline pane shows the results in place of the outline. Each result is a heading, or a file when the match is in the text before its first heading, titled by its =#+TITLE= or its name. Under the title is the passage the words were found in, with them in bold, then the file's name. Click a result to open the file at that heading. Clear the field to get the outline back. |
| 186 | 206 | |
| 187 | 207 | How matching works: |
| 188 | 208 | |
| 189 | - orgstar searches heading titles, the text under each heading and the text before a file's first heading, in =.org= and =.org_archive= files. Files that aren't org are not searched. Syncthing conflict copies are not searched. | |
| 209 | - orgstar searches heading titles, the text under each heading and the text before a file's first heading, in =.org= and =.org_archive= files, and in Markdown files by their =#= headings. A Markdown file's result for the text before its first heading is titled by the =title= in its front matter, else its first heading. A =.txt= file is searched as a whole and titled by its name. Other files are not searched. Syncthing conflict copies are not searched. | |
| 190 | 210 | - Each word you type matches words that start with it, ignoring case and accents: =proj= finds =project= and =projection=. |
| 191 | 211 | - Every word must match within the same heading, or within the text before the first heading. |
| 192 | 212 | - Up to 50 results show, best matches first. |
| @@ -196,7 +216,7 @@ To find text inside the open file, use Edit ▸ Find (see [[file:02-the-editor.o | ||
| 196 | 216 | |
| 197 | 217 | * The outline pane |
| 198 | 218 | |
| 199 | The outline pane lists the headings of the open org file, indented by level. Headings without a title show as =(untitled)=. Click a heading to move the caret to it; folded headings around it unfold. A file without headings shows "No headings"; a file that isn't org shows "No outline". | |
| 219 | The outline pane lists the headings of the open org or Markdown file, indented by level. Headings without a title show as =(untitled)=. Click a heading to move the caret to it; folded headings around it unfold. A file without headings shows "No headings"; a file that is neither org nor Markdown shows "No outline". | |
| 200 | 220 | |
| 201 | 221 | The outline follows your edits after a short pause in typing. |
| 202 | 222 | |
| @@ -438,4 +458,4 @@ orgstar does not convert between encodings or line endings. | ||
| 438 | 458 | |
| 439 | 459 | * On iOS |
| 440 | 460 | |
| 441 | The iOS app adds folders from its Folders screen and lists only org files there. Conflicts, Syncthing copies and recovery versions are in the editor's menu; the iOS app doesn't list git commits, and commits, pulls and pushes a git folder through the Working Copy app. Files are watched through file presenters rather than FSEvents. See [[file:14-ios.org][iOS]]. | |
| 461 | The iOS app adds folders from its Folders screen and lists only org, Markdown and =.txt= files there. Conflicts, Syncthing copies and recovery versions are in the editor's menu; the iOS app doesn't list git commits, and commits, pulls and pushes a git folder through the Working Copy app. Files are watched through file presenters rather than FSEvents. See [[file:14-ios.org][iOS]]. | |
docs/manual/guide/02-the-editor.org +4 · view
| @@ -6,6 +6,8 @@ | ||
| 6 | 6 | |
| 7 | 7 | The editor holds the file's text exactly as it is on disk. Styling, hidden markup, indentation and images are display only; none of them change the file. |
| 8 | 8 | |
| 9 | This chapter describes org files. Markdown files get their own highlighting and heading folds, and other text files plain text or code highlighting; see /Files that aren't org/ in [[file:01-files-and-folders.org][Files and folders]]. | |
| 10 | ||
| 9 | 11 | Org files open with the caret at the start of the file, as in Emacs. Buffers you had open when you quit reopen with the caret where you left it. |
| 10 | 12 | |
| 11 | 13 | ** Markup |
| @@ -137,6 +139,8 @@ Overview and contents also fold drawers before the first heading. | ||
| 137 | 139 | |
| 138 | 140 | Clicking a heading's stars cycles that heading, as =TAB= does on it. |
| 139 | 141 | |
| 142 | In Markdown files these commands fold =#= headings the same way, and a click on a heading's =#=s cycles it; there are no drawers or blocks to fold. Other files don't fold. See /Markdown/ in [[file:01-files-and-folders.org][Files and folders]]. | |
| 143 | ||
| 140 | 144 | The caret can't rest in folded text: moving forward into a fold jumps past it, and moving back into one goes to the end of the heading line. Going to a location from the outline pane, search, a link or the agenda opens whatever folds hide it. |
| 141 | 145 | |
| 142 | 146 | ** Folding when a file opens |
docs/manual/guide/14-ios.org +8 −3 · view
| @@ -23,7 +23,7 @@ orgstar on iOS works on folders you choose, in iCloud Drive or in another app's | ||
| 23 | 23 | 1. Open the Folders tab and tap Add Folder (the folder icon with a plus). |
| 24 | 24 | 2. Choose a folder in the picker. |
| 25 | 25 | |
| 26 | orgstar keeps access to the folder across launches. Each folder appears as a section listing its =.org= files by their path inside the folder. To stop using a folder, tap the ⋯ button beside its name, or touch and hold the name, and choose Remove from orgstar…; orgstar asks first. The folder and its files stay where they are. An added folder that is empty also has Delete Folder…, which deletes it from disk too. | |
| 26 | orgstar keeps access to the folder across launches. Each folder appears as a section listing its =.org=, Markdown (=.md=, =.markdown=) and =.txt= files by their path inside the folder. To stop using a folder, tap the ⋯ button beside its name, or touch and hold the name, and choose Remove from orgstar…; orgstar asks first. The folder and its files stay where they are. An added folder that is empty also has Delete Folder…, which deletes it from disk too. | |
| 27 | 27 | |
| 28 | 28 | Swipe left on a file, or touch and hold it, to delete it. orgstar asks first. A file in iCloud Drive goes to Recently Deleted in the Files app; elsewhere it is removed. New File… and New Folder… under + at the top right make one in the folder shown, or with several added folders, in the one you pick; a file name without an extension gets =.org=. New File from Template… there asks for a template from =snippets.toml= in the configuration folder and a name, then opens the new file in the editor with the template expanded; see [[*Snippets][Snippets]]. Empty folders are listed too and delete the same way; a folder with anything in it other than hidden files can't be deleted from orgstar. |
| 29 | 29 | |
| @@ -35,7 +35,7 @@ There is no way to open a single file from the Files app. Add the folder that co | ||
| 35 | 35 | |
| 36 | 36 | * The reader |
| 37 | 37 | |
| 38 | Tap a file in Folders or Search, or Open in File in an agenda entry's sheet, to read it. | |
| 38 | Tap a file in Folders or Search, or Open in File in an agenda entry's sheet, to read it. Markdown and =.txt= files open in the editor instead (see /Markdown and text files/ below). | |
| 39 | 39 | |
| 40 | 40 | - Tap a heading to fold or unfold it, as =TAB= cycles it on the Mac. A chevron marks headings with content. |
| 41 | 41 | - The file opens with the visibility its =#+STARTUP= line asks for, then each heading's =VISIBILITY= property when =#+STARTUP= sets a visibility. Drawers and blocks are folded as =org-cycle-hide-drawer-startup= and =org-cycle-hide-block-startup= say, or as the file's =#+STARTUP= says (=hidedrawers=, =nohideblocks= and the like). Tap a folded drawer's first line or its =…= to open it, and the first line again to fold it. |
| @@ -68,6 +68,10 @@ The key bar holds what you repeat at the caret while typing, the toolbar what ac | ||
| 68 | 68 | |
| 69 | 69 | Messages from commands show at the top of the editor and the column view, and at the bottom of the reader, the agenda and the board, for a few seconds; tap one to dismiss it. VoiceOver reads each message as it appears. An error opening, saving or reading a file shows what failed on its first line, such as =Couldn't Save File=. |
| 70 | 70 | |
| 71 | ** Markdown and text files | |
| 72 | ||
| 73 | Markdown files (=.md=, =.markdown=) open straight in the editor, highlighted as on the Mac: headings, emphasis, code, links, lists, block quotes, fenced code and front matter. Fold and open headings with Cycle Visibility and Cycle Global Visibility in Commands, or =TAB= and =S-TAB= with a hardware keyboard; tap a fold's =…= to open it. =.txt= files open as plain text. In both, org's other commands report =Not an org file= and change nothing, the Format menu, Export and dropped attachments are not offered, and typing doesn't pair brackets or fill paragraphs. There is no outline for them on iOS, since the outline is the reader's. See /Markdown/ in [[file:01-files-and-folders.org][Files and folders]] for what is styled and what isn't supported. | |
| 74 | ||
| 71 | 75 | ** Panes and windows on iPad |
| 72 | 76 | |
| 73 | 77 | On iPad, the editor can show a file in several panes, as a Mac window does (see [[file:01-files-and-folders.org][Files and folders]]): |
| @@ -256,7 +260,7 @@ Snippets come from =snippets.toml= in the configuration folder, the same file as | ||
| 256 | 260 | |
| 257 | 261 | Search finds: |
| 258 | 262 | |
| 259 | - Files :: up to eight org files whose path matches what you type, ranked as Quick Open ranks them on the Mac. | |
| 263 | - Files :: up to eight org, Markdown or =.txt= files whose path matches what you type, ranked as Quick Open ranks them on the Mac. | |
| 260 | 264 | - Notes :: headings whose title or text contains your words, and files whose text before the first heading does, including unsaved edits in the open file. Under each is the passage the words were found in, with them in bold. |
| 261 | 265 | |
| 262 | 266 | Tap a result to open it in the reader. A heading result opens at that heading. |
| @@ -566,6 +570,7 @@ Quick Look in the Files app shows org files as the HTML export renders them. | ||
| 566 | 570 | - The inspector, and the buffer list and tab bar. The board and column view are there (see [[file:07-agenda.org][The agenda]] and [[file:04-outlines.org][Outlines]]). |
| 567 | 571 | - The global capture hotkey and the Settings window. |
| 568 | 572 | - Replace in Files; the rename commands are on iOS. |
| 573 | - The outline of a Markdown file, which opens in the editor rather than the reader. | |
| 569 | 574 | - Explicit saving. |
| 570 | 575 | |
| 571 | 576 | Commands the iOS app can't carry out show a message instead: "/Command/ isn't available on iPhone and iPad. It runs on the Mac." Only tables that need Emacs say that Emacs is needed. Commands that only appear on the Mac aren't listed in Commands. Refile… in Commands (or =C-c C-w= with a hardware keyboard) refiles the entry at the caret, choosing the target as the agenda's Refile… does. |
l10n/Localizable.xcstrings +34 · view
| @@ -32576,6 +32576,40 @@ | ||
| 32576 | 32576 | } |
| 32577 | 32577 | } |
| 32578 | 32578 | }, |
| 32579 | "Only org and Markdown files have an outline.": { | |
| 32580 | "localizations": { | |
| 32581 | "de": { | |
| 32582 | "stringUnit": { | |
| 32583 | "state": "translated", | |
| 32584 | "value": "Nur Org- und Markdown-Dateien haben eine Gliederung." | |
| 32585 | } | |
| 32586 | }, | |
| 32587 | "es": { | |
| 32588 | "stringUnit": { | |
| 32589 | "state": "translated", | |
| 32590 | "value": "Solo los archivos Org y Markdown tienen esquema." | |
| 32591 | } | |
| 32592 | }, | |
| 32593 | "fr": { | |
| 32594 | "stringUnit": { | |
| 32595 | "state": "translated", | |
| 32596 | "value": "Seuls les fichiers Org et Markdown ont une structure." | |
| 32597 | } | |
| 32598 | }, | |
| 32599 | "ja": { | |
| 32600 | "stringUnit": { | |
| 32601 | "state": "translated", | |
| 32602 | "value": "アウトラインがあるのはOrgファイルとMarkdownファイルだけです。" | |
| 32603 | } | |
| 32604 | }, | |
| 32605 | "pt-BR": { | |
| 32606 | "stringUnit": { | |
| 32607 | "state": "translated", | |
| 32608 | "value": "Somente arquivos Org e Markdown têm estrutura." | |
| 32609 | } | |
| 32610 | } | |
| 32611 | } | |
| 32612 | }, | |
| 32579 | 32613 | "Only org files have an outline.": { |
| 32580 | 32614 | "localizations": { |
| 32581 | 32615 | "de": { |