Commit 0dc8dea033

0dc8dea033dd64cad6c9b4130124d1c229454342

parent: 9300add1d8

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-26 11:37 UTC

Lint All Folders

File ▸ Lint All Folders runs the Lint File checkers over every indexed
Org file and archive off the main actor, several files at a time, with
progress and Stop, and lists the problems grouped by file in a window;
a row opens its file at the line. On iOS it is a list from Commands.
Open files are checked as their buffers are. Encrypted files are left
out and encrypted entries' bodies aren't checked. An orphaned
attachment folder is reported once, by the first file beside it.

Gates: 1,000 notes under 2 s, 10,000 under 15 s.

Closes #152

Layout: unified · split

Changed files (19)
Sources/OrgApp/CommandTitles.swift +1 · view
@@ -172,6 +172,7 @@ enum CommandTitles {
172172 String(localized: "Kill Word Backward", comment: "Command title"),
173173 String(localized: "Last Buffer", comment: "Command title"),
174174 String(localized: "Leave Block", comment: "Command title"),
175 String(localized: "Lint All Folders", comment: "Command title"),
175176 String(localized: "Lint File", comment: "Command title"),
176177 String(localized: "Lower Priority", comment: "Command title"),
177178 String(localized: "Mark Subtree", comment: "Command title"),
Sources/OrgApp/FileLint.swift +132 · view
@@ -1,5 +1,6 @@
11import Foundation
22import OrgCore
3import OrgDocument
34import OrgIndex
45
56/// Lint File in the apps: the checkers run over an open file's text off the main actor, with
@@ -31,6 +32,74 @@ public enum FileLint {
3132 OrgLint.lint(text, tree: tree, path: path, environment: environment)
3233 }
3334
35 /// One file's findings in Lint All Folders.
36 public struct FileFindings: Sendable, Identifiable {
37 public let path: String
38 public let findings: [LintFinding]
39 public var id: String { path }
40 }
41
42 /// The files Lint All Folders checks: the indexed Org files and archives. Encrypted files
43 /// (`.org.gpg`) are left out.
44 public static func folderPaths(_ files: [FileEntry]) -> [String] {
45 files.filter { ($0.kind == .org || $0.kind == .archive) && applies(to: $0.path) && !CryptVault.isEncryptedFile($0.path) }.map(\.path).sorted()
46 }
47
48 /// How Lint All Folders names each file: its path below its folder, after the folder's name
49 /// when there are several folders.
50 public static func names(_ files: [FileEntry]) -> [String: String] {
51 let several = Set(files.map(\.root)).count > 1
52 return Dictionary(files.map { ($0.path, several ? "\(($0.root as NSString).lastPathComponent)/\($0.relativePath)" : $0.relativePath) },
53 uniquingKeysWith: { first, _ in first })
54 }
55
56 /// Lint All Folders: the findings in each of `paths`, read from disk or, for an open file,
57 /// from `texts`, off the main actor and several files at a time. Files with none are left
58 /// out. An orphaned attachment folder is reported once, by the first file that finds it.
59 /// `progress` is told the number of files checked so far. Throws `CancellationError` when
60 /// the task is cancelled.
61 @concurrent
62 public static func lint(
63 paths: [String], texts: [String: String], defaults: OrgSettings = .default, environment: LintEnvironment,
64 progress: @escaping @Sendable (Int) async -> Void = { _ in }
65 ) async throws -> [FileFindings] {
66 let chunk = 32
67 let chunks = stride(from: 0, to: paths.count, by: chunk).map { Array(paths[$0..<min($0 + chunk, paths.count)]) }
68 var results = [[FileFindings]](repeating: [], count: chunks.count)
69 try await withThrowingTaskGroup(of: (Int, [FileFindings]).self) { group in
70 var next = 0
71 func add() {
72 guard next < chunks.count else { return }
73 let index = next, paths = chunks[index]
74 next += 1
75 group.addTask {
76 var found: [FileFindings] = []
77 for path in paths {
78 try Task.checkCancellation()
79 guard let text = texts[path] ?? (try? String(contentsOfFile: path, encoding: .utf8)) else { continue }
80 let findings = OrgLint.lint(text, tree: OrgParser.parse(text, defaults: defaults), path: path, environment: environment)
81 if !findings.isEmpty { found.append(FileFindings(path: path, findings: findings)) }
82 }
83 return (index, found)
84 }
85 }
86 for _ in 0..<max(1, ProcessInfo.processInfo.activeProcessorCount) { add() }
87 var done = 0
88 while let (index, found) = try await group.next() {
89 results[index] = found
90 done += chunks[index].count
91 await progress(done)
92 try Task.checkCancellation()
93 add()
94 }
95 }
96 var folders: Set<String> = []
97 return results.joined().compactMap { file in
98 let findings = file.findings.filter { $0.folder.map { folders.insert($0).inserted } ?? true }
99 return findings.isEmpty ? nil : FileFindings(path: file.path, findings: findings)
100 }
101 }
102
34103 /// A finding's trust as the panels show it: org-lint's high trust as an error, low as a warning.
35104 public static func severity(_ finding: LintFinding) -> String {
36105 finding.trust == .high ? String(localized: "Error", comment: "Lint File: a problem org-lint trusts highly") : String(localized: "Warning", comment: "Lint File: a problem that may be intended")
@@ -41,3 +110,66 @@ public enum FileLint {
41110 findings.isEmpty ? String(localized: "No problems found", comment: "Lint File") : String(localized: "\(findings.count) problems", comment: "Lint File: the number of problems found")
42111 }
43112}
113
114/// Lint All Folders as the panels run it: every indexed Org file checked off the main actor,
115/// with progress, until it finishes or is stopped.
116@MainActor
117@Observable
118public final class FolderLint {
119 /// The files with findings, by path; nil until a run finishes.
120 public private(set) var files: [FileLint.FileFindings]?
121 public private(set) var checked = 0
122 public private(set) var total = 0
123 public private(set) var isRunning = false
124 @ObservationIgnored private var task: Task<Void, Never>?
125 /// Counts runs, so a stopped run's last progress doesn't show in the next.
126 @ObservationIgnored private var run = 0
127
128 public init() {}
129
130 /// Checks every indexed file again; open files as their buffers have them.
131 public func run(workspace: WorkspaceModel, session: DocumentSession) {
132 task?.cancel()
133 let paths = FileLint.folderPaths(workspace.files)
134 let open = session.openDocuments
135 let texts = Dictionary(open.map { ($0.path, $0.document.text) }, uniquingKeysWith: { first, _ in first })
136 let environment = FileLint.environment(index: workspace.index, overlay: workspace.overlay(open))
137 let defaults = session.defaults
138 files = nil
139 checked = 0
140 total = paths.count
141 isRunning = true
142 run += 1
143 let run = run
144 task = Task { [weak self] in
145 let found = try? await FileLint.lint(paths: paths, texts: texts, defaults: defaults, environment: environment) { [weak self] checked in
146 await self?.progressed(checked, run: run)
147 }
148 guard let self, let found, !Task.isCancelled else { return }
149 files = found
150 isRunning = false
151 }
152 }
153
154 public func stop() {
155 task?.cancel()
156 task = nil
157 isRunning = false
158 }
159
160 private func progressed(_ count: Int, run: Int) {
161 if run == self.run { checked = count }
162 }
163
164 /// The panels' summary line.
165 public var summary: String {
166 guard let files else {
167 return isRunning
168 ? String(localized: "Checked \(checked) of \(total) files", comment: "Lint All Folders: progress")
169 : String(localized: "Stopped after \(checked) of \(total) files", comment: "Lint All Folders: stopped before the end")
170 }
171 let findings = files.flatMap(\.findings)
172 if findings.isEmpty { return String(localized: "No problems found in \(total) files", comment: "Lint All Folders") }
173 return String(localized: "\(FileLint.summary(findings)) in \(files.count) of \(total) files", comment: "Lint All Folders: the number of problems, files with problems, files checked")
174 }
175}
Sources/OrgCore/Lint/Lint.swift +4 −1 · view
@@ -86,12 +86,15 @@ public struct LintFinding: Sendable, Equatable, Hashable, Identifiable {
8686 public let line: Int
8787 public let checker: LintChecker
8888 public let message: String
89 /// For an orphaned attachment folder, its path, which every file beside it reports.
90 public let folder: String?
8991
90 public init(offset: Int, line: Int, checker: LintChecker, message: String) {
92 public init(offset: Int, line: Int, checker: LintChecker, message: String, folder: String? = nil) {
9193 self.offset = offset
9294 self.line = line
9395 self.checker = checker
9496 self.message = message
97 self.folder = folder
9598 }
9699
97100 public var trust: LintTrust { checker.trust }
Sources/OrgCore/Lint/LintCheckers.swift +2 −1 · view
@@ -225,7 +225,8 @@ extension Linter {
225225 let shown = root.hasPrefix(folder + "/") ? String(root.dropFirst(folder.count + 1)) : root
226226 for candidate in candidates where !ids.contains(candidate.id) && idFiles(candidate.id).filter({ $0 != path }).isEmpty {
227227 let folderName = (shown as NSString).appendingPathComponent(candidate.relative)
228 report(.orphanedAttachmentFolder, at: 0, "Attachment folder \"\(folderName)\" belongs to no entry")
228 report(.orphanedAttachmentFolder, at: 0, "Attachment folder \"\(folderName)\" belongs to no entry",
229 folder: (root as NSString).appendingPathComponent(candidate.relative))
229230 }
230231 }
231232 }
Sources/OrgCore/Lint/Linter.swift +2 −2 · view
@@ -97,9 +97,9 @@ struct Linter {
9797 return s
9898 }
9999
100 mutating func report(_ checker: LintChecker, at offset: Int, _ message: String) {
100 mutating func report(_ checker: LintChecker, at offset: Int, _ message: String, folder: String? = nil) {
101101 guard !excluded.contains(where: { $0.contains(offset) }) else { return }
102 findings.append(LintFinding(offset: offset, line: lineIndex(offset) + 1, checker: checker, message: message))
102 findings.append(LintFinding(offset: offset, line: lineIndex(offset) + 1, checker: checker, message: message, folder: folder))
103103 }
104104
105105 func matches(_ pattern: String, caseInsensitive: Bool = false, anchorsMatchLines: Bool = true) -> [NSTextCheckingResult] {
Sources/OrgEditorAppKit/EditorCommands.swift +1 · view
@@ -190,6 +190,7 @@ public enum EditorCommands {
190190 EditorCommand(id: "app.revert", title: "Revert to File on Disk", action: .app),
191191 EditorCommand(id: "app.recovery", title: "History…", action: .app),
192192 EditorCommand(id: "app.lint", title: "Lint File", action: .app),
193 EditorCommand(id: "app.lint-folders", title: "Lint All Folders", action: .app),
193194 EditorCommand(id: "app.export.html", title: "Export to HTML", action: .app),
194195 EditorCommand(id: "app.export.html-open", title: "Export to HTML and Open", action: .app),
195196 EditorCommand(id: "app.export.markdown", title: "Export to Markdown", action: .app),
Sources/Orgstar/ContentView.swift +3 · view
@@ -1534,6 +1534,9 @@ struct ContentView: View {
15341534 guard FileLint.applies(to: session.path) else { return commands.show(String(localized: "Lint File works on Org files", comment: "Lint File in a file that isn't Org")) }
15351535 lintShown = true
15361536 lintRun += 1
1537 case "app.lint-folders":
1538 commands.folderLint.run(workspace: workspace, session: session)
1539 openWindow(id: "lint-folders")
15371540 case "app.copy-rich-text":
15381541 copyRichText()
15391542 case "app.share-subtree":
Sources/Orgstar/FolderLintWindow.swift added +86 · view
@@ -0,0 +1,86 @@
1import OrgApp
2import OrgCore
3import SwiftUI
4
5/// Lint All Folders: the problems in every indexed Org file, grouped by file. Choosing a row
6/// opens the file in the main window at that line.
7struct FolderLintWindow: View {
8 let workspace: WorkspaceModel
9 let session: DocumentSession
10 let commands: AppCommands
11 @State private var selection: String?
12 @Environment(\.openWindow) private var openWindow
13
14 private var lint: FolderLint { commands.folderLint }
15
16 var body: some View {
17 let names = FileLint.names(workspace.files)
18 return VStack(spacing: 0) {
19 HStack(spacing: 8) {
20 if lint.isRunning {
21 ProgressView(value: Double(lint.checked), total: Double(max(1, lint.total)))
22 .frame(width: 120)
23 }
24 Text(lint.summary).foregroundStyle(.secondary).lineLimit(1)
25 Spacer()
26 if lint.isRunning {
27 Button("Stop") { lint.stop() }
28 } else {
29 Button("Check Again") { lint.run(workspace: workspace, session: session) }
30 }
31 }
32 .padding(.horizontal, 10)
33 .padding(.vertical, 6)
34 Divider()
35 List(selection: $selection) {
36 ForEach(lint.files ?? []) { file in
37 Section {
38 ForEach(file.findings) { finding in
39 row(finding).tag(Self.tag(file.path, finding))
40 }
41 } header: {
42 HStack {
43 Text(verbatim: names[file.path] ?? file.path).lineLimit(1).truncationMode(.middle)
44 Spacer()
45 Text(verbatim: "\(file.findings.count)").monospacedDigit().foregroundStyle(.secondary)
46 }
47 .help(file.path)
48 }
49 }
50 }
51 .overlay {
52 if lint.files?.isEmpty == true { Text("No problems found").foregroundStyle(.secondary) }
53 }
54 }
55 .frame(minWidth: 520, minHeight: 300)
56 .navigationTitle("Lint All Folders")
57 .onAppear { if lint.files == nil, !lint.isRunning { lint.run(workspace: workspace, session: session) } }
58 .onChange(of: selection) { _, tag in
59 guard let tag, let (path, finding) = find(tag) else { return }
60 if !commands.mainWindowOpen { openWindow(id: "main") }
61 commands.jump(path: path, offset: finding.offset)
62 }
63 }
64
65 private func row(_ finding: LintFinding) -> some View {
66 HStack(alignment: .firstTextBaseline, spacing: 8) {
67 Text(verbatim: "\(finding.line)").monospacedDigit().foregroundStyle(.secondary).frame(width: 44, alignment: .trailing)
68 Image(systemName: finding.trust == .high ? "xmark.octagon.fill" : "exclamationmark.triangle.fill")
69 .foregroundStyle(finding.trust == .high ? Color.red : Color.orange)
70 .help(FileLint.severity(finding))
71 .accessibilityLabel(FileLint.severity(finding))
72 Text(finding.message).lineLimit(1).help(finding.message)
73 Spacer()
74 Text(verbatim: finding.checker.rawValue).foregroundStyle(.secondary).lineLimit(1)
75 }
76 }
77
78 private static func tag(_ path: String, _ finding: LintFinding) -> String { path + "\n" + finding.id }
79
80 private func find(_ tag: String) -> (String, LintFinding)? {
81 for file in lint.files ?? [] {
82 if let finding = file.findings.first(where: { Self.tag(file.path, $0) == tag }) { return (file.path, finding) }
83 }
84 return nil
85 }
86}
Sources/Orgstar/OrgstarApp.swift +10 · view
@@ -27,6 +27,8 @@ final class AppCommands {
2727 var showingMessages = false
2828 /// The main window's outline pane is shown, for View ▸ Show Outline.
2929 var outlineShown = false
30 /// Lint All Folders' last run, which its window shows.
31 let folderLint = FolderLint()
3032 /// A location another window asked the main window to show.
3133 private(set) var jumpRequest: (path: String, offset: Int, id: Int)?
3234 private var jumpID = 0
@@ -566,6 +568,13 @@ struct OrgstarApp: App {
566568 }
567569 }
568570 .defaultSize(width: 900, height: 700)
571 Window("Lint All Folders", id: "lint-folders") {
572 if case .success(let model) = workspace {
573 FolderLintWindow(workspace: model, session: session, commands: commands)
574 .tint(ConfigSync.shared.theme.color("accent"))
575 }
576 }
577 .defaultSize(width: 760, height: 520)
569578 Window("Clock Report", id: "clock-report") {
570579 if case .success(let model) = workspace {
571580 ClockReportView(workspace: model, session: session)
@@ -615,6 +624,7 @@ struct OrgstarApp: App {
615624 .disabled(session.path == nil)
616625 Button("Lint File") { commands.run("app.lint") }
617626 .disabled(!FileLint.applies(to: session.path))
627 Button("Lint All Folders") { commands.run("app.lint-folders") }
618628 }
619629 CommandGroup(replacing: .saveItem) {
620630 Button("Close Buffer") {
Sources/OrgstarMobile/EditorScreen.swift +9 −1 · view
@@ -95,6 +95,7 @@ struct EditorScreen: View {
9595 /// Rename Tag or Rename TODO Keyword, starting from this name.
9696 case rename(ReplaceKind, String)
9797 case lint
98 case lintFolders
9899 case shareSubtree(SubtreeShare)
99100 /// The subtree at this offset, to export.
100101 case exportSubtree(Int)
@@ -115,6 +116,7 @@ struct EditorScreen: View {
115116 case .graph: "graph"
116117 case .rename(let kind, _): kind.rawValue
117118 case .lint: "lint"
119 case .lintFolders: "lintFolders"
118120 case .shareSubtree(let share): share.id.uuidString
119121 case .exportSubtree: "exportSubtree"
120122 }
@@ -275,6 +277,10 @@ struct EditorScreen: View {
275277 RenameScreen(kind: kind, workspace: workspace, session: session, initial: initial) { message = $0 }
276278 case .lint:
277279 LintScreen(workspace: workspace, session: session, path: path) { offset in editor?.reveal(offset) }
280 case .lintFolders:
281 FolderLintScreen(workspace: workspace, session: session) { file, offset in
282 if file == path { editor?.reveal(offset) } else { model.openRequest = .offset(file, offset) }
283 }
278284 case .shareSubtree(let share):
279285 SubtreeShareScreen(share: share) { message = $0 }
280286 }
@@ -561,6 +567,8 @@ struct EditorScreen: View {
561567 } else if let kind = ReplaceKind(command: id), kind != .replace {
562568 let context = self.editor?.editContext()
563569 sheet = .rename(kind, context.map { kind.initial(text: $0.text, caret: $0.caret, keywords: $0.tree.settings.todoKeywordNames) } ?? "")
570 } else if id == "app.lint-folders" {
571 sheet = .lintFolders
564572 } else if id == "app.lint" {
565573 if FileLint.applies(to: path) { sheet = .lint } else { message = String(localized: "Lint File works on Org files", comment: "Lint File in a file that isn't Org") }
566574 } else if id == "app.working-copy.sync" {
@@ -1108,7 +1116,7 @@ struct CommandPalette: View {
11081116 ("app.publish.current-project", "Publish Current Project"),
11091117 ("app.toggle-markup", "Show or Hide Markup"), ("app.word-count", "Word Count"),
11101118 ("org.snippet.next-field", "Next Snippet Field"), ("org.snippet.previous-field", "Previous Snippet Field"),
1111 ("app.recovery", "Recovery Versions…"), ("app.sync-conflicts", "Resolve Sync Conflicts…"), ("app.lint", "Lint File"),
1119 ("app.recovery", "Recovery Versions…"), ("app.sync-conflicts", "Resolve Sync Conflicts…"), ("app.lint", "Lint File"), ("app.lint-folders", "Lint All Folders"),
11121120 ("app.working-copy.sync", "Sync with Working Copy"),
11131121 ("org.toggle-inline-images", "Show or Hide Inline Images"), ("org.toggle-inline-images-linked", "Show or Hide Inline Images, Including Described Links"), ("org.latex-preview", "Show or Hide LaTeX Previews"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"), ("editor.toggle-auto-fill", "Turn Auto Fill On or Off"),
11141122 ("editor.complete", "Complete at Point"), ("editor.dabbrev-expand", "Expand Word"), ("editor.dabbrev-completion", "Complete Word"),
Sources/OrgstarMobile/FolderLintScreen.swift added +74 · view
@@ -0,0 +1,74 @@
1#if os(iOS)
2import OrgApp
3import OrgCore
4import SwiftUI
5
6/// Lint All Folders: the problems in every indexed Org file, grouped by file. Tapping one closes
7/// the list and opens its file at that line. Closing the list stops a run.
8struct FolderLintScreen: View {
9 let workspace: WorkspaceModel
10 let session: DocumentSession
11 let open: (String, Int) -> Void
12 @State private var lint = FolderLint()
13 @Environment(\.dismiss) private var dismiss
14
15 var body: some View {
16 let names = FileLint.names(workspace.files)
17 return NavigationStack {
18 List {
19 Section {
20 VStack(alignment: .leading, spacing: 6) {
21 Text(lint.summary).foregroundStyle(.secondary)
22 if lint.isRunning { ProgressView(value: Double(lint.checked), total: Double(max(1, lint.total))) }
23 }
24 }
25 ForEach(lint.files ?? []) { file in
26 Section {
27 ForEach(file.findings) { finding in
28 Button {
29 dismiss()
30 open(file.path, finding.offset)
31 } label: {
32 row(finding)
33 }
34 }
35 } header: {
36 Text(verbatim: names[file.path] ?? file.path)
37 }
38 }
39 }
40 .overlay {
41 if lint.files?.isEmpty == true { ContentUnavailableView("No problems found", systemImage: "checkmark.circle") }
42 }
43 .navigationTitle("Lint All Folders")
44 .navigationBarTitleDisplayMode(.inline)
45 .toolbar {
46 ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } }
47 ToolbarItem(placement: .cancellationAction) {
48 if lint.isRunning {
49 Button("Stop") { lint.stop() }
50 } else {
51 Button("Check Again") { lint.run(workspace: workspace, session: session) }
52 }
53 }
54 }
55 }
56 .onAppear { lint.run(workspace: workspace, session: session) }
57 .onDisappear { lint.stop() }
58 }
59
60 private func row(_ finding: LintFinding) -> some View {
61 HStack(alignment: .firstTextBaseline, spacing: 10) {
62 Image(systemName: finding.trust == .high ? "xmark.octagon.fill" : "exclamationmark.triangle.fill")
63 .foregroundStyle(finding.trust == .high ? Color.red : Color.orange)
64 .accessibilityLabel(FileLint.severity(finding))
65 VStack(alignment: .leading, spacing: 2) {
66 Text(finding.message).foregroundStyle(Color.primary)
67 Text("Line \(finding.line) · \(finding.checker.rawValue)", comment: "Lint File: a problem's line and checker")
68 .font(.caption)
69 .foregroundStyle(Color.secondary)
70 }
71 }
72 }
73}
74#endif
Sources/OrgstarMobile/MobileEditor.swift +1 −1 · view
@@ -507,7 +507,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
507507 case "app.crypt.encrypt-entry": return onAppCommand != nil && OrgCrypt.heading(context.text, at: context.caret) != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) == nil
508508 case "app.crypt.open-entry", "app.crypt.decrypt-entry": return onAppCommand != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
509509 case "app.table-export", "app.table-export.tsv", "app.plot": return onAppCommand != nil && ImportTable.exportText(context.text, at: context.caret, path: "") != nil
510 case "app.word-count", "app.recovery", "app.sync-conflicts", "app.lint", "app.attach.photo", "app.attach.camera", "app.attach.scan",
510 case "app.word-count", "app.recovery", "app.sync-conflicts", "app.lint", "app.lint-folders", "app.attach.photo", "app.attach.camera", "app.attach.scan",
511511 "app.rename-tag", "app.rename-todo-keyword": return onAppCommand != nil
512512 case _ where id.hasPrefix(NamedMacros.commandPrefix): return true
513513 case "app.refile", "app.refile.copy", "app.archive": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil
Tests/OrgAppTests/FileLintTests.swift +77 · view
@@ -46,4 +46,81 @@ struct FileLintTests {
4646 #expect(FileLint.severity(finding) == "Error")
4747 #expect(FileLint.severity(LintFinding(offset: 0, line: 1, checker: .timestampSyntax, message: "x")) == "Warning")
4848 }
49
50 @Test func allFoldersGroupsByFileAndUsesOpenBuffers() async throws {
51 let notes = try Folder()
52 let a = try notes.write("a.org", "* A\n[[*Nowhere]]\n")
53 let b = try notes.write("b.org", "* B\n")
54 let c = try notes.write("sub/c.org", "* C\n[fn:1] unused\n")
55 let paths = [a.path, b.path, c.path]
56 let files = try await FileLint.lint(paths: paths, texts: [b.path: "* B\n#+BEGIN_SRC\n#+END_SRC\n"], environment: FileLint.environment(index: nil))
57 #expect(files.map(\.path) == paths)
58 #expect(files.map { $0.findings.map(\.checker) } == [[.invalidFuzzyLink], [.missingLanguageInSrcBlock], [.unreferencedFootnoteDefinition]])
59 #expect(files[0].findings.first?.line == 2)
60 }
61
62 @Test func orphanedAttachmentFoldersAreReportedOnce() async throws {
63 let notes = try Folder()
64 let store = try IndexStore()
65 var paths: [String] = []
66 for name in ["a.org", "b.org", "c.org"] {
67 let url = try notes.write(name, "* \(name)\n")
68 try store.write(FileRecord(path: url.path, root: notes.url.path, kind: .org, bytes: Array("* \(name)\n".utf8), mtime: 1, settings: IndexSettings()))
69 paths.append(url.path)
70 }
71 try FileManager.default.createDirectory(at: notes.url.appendingPathComponent("data/ab/cdef"), withIntermediateDirectories: true)
72 try FileManager.default.createDirectory(at: notes.url.appendingPathComponent("data/12/3456"), withIntermediateDirectories: true)
73 // Each file alone lists both folders.
74 let one = await FileLint.lint("* a\n", tree: OrgParser.parse("* a\n"), path: paths[1], environment: FileLint.environment(index: store))
75 #expect(one.filter { $0.checker == .orphanedAttachmentFolder }.count == 2)
76 let files = try await FileLint.lint(paths: paths, texts: [:], environment: FileLint.environment(index: store))
77 #expect(files.map(\.path) == [paths[0]])
78 #expect(files[0].findings.map(\.message) == ["Attachment folder \"data/12/3456\" belongs to no entry", "Attachment folder \"data/ab/cdef\" belongs to no entry"])
79 }
80
81 @Test func allFoldersLeavesOutEncryptedFiles() {
82 let files = [
83 FileEntry(path: "/n/b.org", root: "/n", kind: .org), FileEntry(path: "/n/a.org.gpg", root: "/n", kind: .org),
84 FileEntry(path: "/n/a.org", root: "/n", kind: .org), FileEntry(path: "/n/old.org_archive", root: "/n", kind: .archive),
85 FileEntry(path: "/n/a.sync-conflict-1.org", root: "/n", kind: .conflict), FileEntry(path: "/n/x.md", root: "/n", kind: .org),
86 FileEntry(path: "/n/p.png", root: "/n", kind: .other)
87 ]
88 #expect(FileLint.folderPaths(files) == ["/n/a.org", "/n/b.org", "/n/old.org_archive"])
89 }
90
91 @Test func allFoldersNamesFilesBelowTheirFolder() {
92 let one = [FileEntry(path: "/n/a.org", root: "/n", kind: .org), FileEntry(path: "/n/sub/b.org", root: "/n", kind: .org)]
93 #expect(FileLint.names(one) == ["/n/a.org": "a.org", "/n/sub/b.org": "sub/b.org"])
94 let two = one + [FileEntry(path: "/m/a.org", root: "/m", kind: .org)]
95 #expect(FileLint.names(two) == ["/n/a.org": "n/a.org", "/n/sub/b.org": "n/sub/b.org", "/m/a.org": "m/a.org"])
96 }
97
98 @Test func allFoldersSkipsEncryptedEntries() async throws {
99 let notes = try Folder()
100 let text = "* Secret :crypt:\n-----BEGIN PGP MESSAGE-----\n\n[[*Nowhere]]\n-----END PGP MESSAGE-----\n* Open\n[[*Nowhere]]\n"
101 let a = try notes.write("a.org", text)
102 let files = try await FileLint.lint(paths: [a.path], texts: [:], environment: FileLint.environment(index: nil))
103 #expect(files.first?.findings.map(\.line) == [7])
104 }
105
106 @Test func allFoldersStopsWhenCancelled() async throws {
107 let notes = try Folder()
108 let paths = try (0..<100).map { try notes.write("n\($0).org", "* N\n[[*Nowhere]]\n").path }
109 let reports = Counter()
110 let task = Task {
111 try await FileLint.lint(paths: paths, texts: [:], environment: FileLint.environment(index: nil)) { _ in
112 await reports.add()
113 try? await Task.sleep(for: .seconds(30))
114 }
115 }
116 try await Task.sleep(for: .milliseconds(100))
117 task.cancel()
118 await #expect(throws: CancellationError.self) { try await task.value }
119 #expect(await reports.count <= 1)
120 }
121}
122
123private actor Counter {
124 var count = 0
125 func add() { count += 1 }
49126}
Tests/OrgEditorAppKitTests/WorkspaceGateTests.swift +20 −4 · view
@@ -3,8 +3,9 @@ import OrgApp
33import OrgCore
44import Testing
55
6/// Gates for a large workspace: the first index build, the agenda refresh and the backlinks of
7/// a file and a heading. In `GateTests` so they run one at a time with the editor gates.
6/// Gates for a large workspace: the first index build, the agenda refresh, the backlinks of a
7/// file and a heading, and Lint All Folders. In `GateTests` so they run one at a time with the
8/// editor gates.
89extension GateTests {
910 /// Writes `count` notes of eight headings each, about 2 kB a note. Every heading has an ID
1011 /// and a paragraph; the first `fiveLinks` notes have five links and the rest four. A third of
@@ -44,6 +45,17 @@ extension GateTests {
4445 return (model, ContinuousClock.now - start)
4546 }
4647
48 /// One run of Lint All Folders over the workspace, and how many files had findings.
49 static func lintAll(_ model: WorkspaceModel) async throws -> (files: Int, time: Duration) {
50 let paths = FileLint.folderPaths(model.files)
51 let environment = FileLint.environment(index: model.index)
52 var files = 0
53 let time = try await ContinuousClock().measure {
54 files = try await FileLint.lint(paths: paths, texts: [:], environment: environment).count
55 }
56 return (files, time)
57 }
58
4759 static func scratch() throws -> URL {
4860 let url = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-gates-\(UUID().uuidString)")
4961 try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
@@ -80,11 +92,13 @@ extension GateTests {
8092
8193 let (found, backlinks) = try Self.backlinks(model)
8294 #expect(found > 0)
83 print("GATE 10,000 notes: index build \(build), agenda refresh cold \(cold) / warm \(warm) (\(items) items), backlinks over 49,400 links \(backlinks)")
95 let lint = try await Self.lintAll(model)
96 print("GATE 10,000 notes: index build \(build), agenda refresh cold \(cold) / warm \(warm) (\(items) items), backlinks over 49,400 links \(backlinks), lint all folders \(lint.time) (\(lint.files) files with findings)")
8497 #expect(build < .seconds(15), "index build")
8598 #expect(cold < .seconds(10), "agenda refresh, cold")
8699 #expect(warm < .seconds(2), "agenda refresh, warm")
87100 #expect(backlinks < .milliseconds(1_500), "backlinks, 49,400 links")
101 #expect(lint.time < .seconds(15), "lint all folders, 10,000 notes")
88102 }
89103
90104 /// 1,000 notes, 5,000 links.
@@ -94,7 +108,9 @@ extension GateTests {
94108 let (model, _) = try await Self.workspace(1_000, fiveLinks: 1_000, in: scratch)
95109 let (found, time) = try Self.backlinks(model)
96110 #expect(found > 0)
97 print("GATE 1,000 notes: backlinks over 5,000 links \(time)")
111 let lint = try await Self.lintAll(model)
112 print("GATE 1,000 notes: backlinks over 5,000 links \(time), lint all folders \(lint.time) (\(lint.files) files with findings)")
98113 #expect(time < .milliseconds(150), "backlinks, 5,000 links")
114 #expect(lint.time < .seconds(2), "lint all folders, 1,000 notes")
99115 }
100116}
docs/manual/guide/02-the-editor.org +2 · view
@@ -551,6 +551,8 @@ The severity is org-lint's trust in the checker. An error is almost certainly a
551551
552552IDs are looked up in the index of all your folders, so a link to an entry in another file counts, and an ID used in two files is a duplicate in each. The attachment folders checked are the ones next to the file; each file in that folder lists the same folders. Links, setup files and attachments in a file that hasn't been saved yet aren't checked. The text of an encrypted entry (=:crypt:=) isn't checked; an encrypted file is checked as it is in the editor, decrypted, and nothing is written. For the differences from =org-lint=, see [[file:15-alongside-emacs.org][Working alongside Emacs]]. On iOS, Lint File is in Commands; see [[file:14-ios.org][iPhone and iPad]].
553553
554File ▸ Lint All Folders (=app.lint-folders=) runs the same checks over every Org file and archive in your folders and lists the problems in a window, grouped by file. Choosing a row opens the file at that line. The files are checked in the background, several at a time; the window shows how many have been checked, and Stop ends the run. Check Again runs it again. Open files are checked as their buffers are, unsaved edits included; the rest as they are on disk. Encrypted files (=.org.gpg=) are left out, and the text of encrypted entries isn't checked. An attachment folder that belongs to no entry is listed once, under the first file beside it, not under every file in that folder. Ten thousand notes take several seconds on a recent Mac.
555
554556* Accessibility
555557
556558The editor works with VoiceOver. VoiceOver reads the text as it is shown rather than as stored: hidden link brackets and targets, hidden emphasis markers and hidden stars are skipped, entities are read as the characters drawn for them, and narrowed table columns are read as drawn. Folded text is still read, so the whole file is available. Lines, the caret position and the selection are reported in terms of the shown text.
docs/manual/guide/03-keys.org +1 · view
@@ -1199,6 +1199,7 @@ No preset binds these. Run them from the palette or a menu, or bind them in =key
11991199| Run Macro… (=macro.run=) | Asks for a named keyboard macro and plays it. Edit ▸ Macros ▸ Run Macro…. |
12001200| History… (=app.recovery=) | Shows the file's recovery versions and, in the download version, its git commits. Recovery Versions… on iOS. |
12011201| Lint File (=app.lint=) | Lists the problems in the file in a panel under the editor (=org-lint=). File ▸ Lint File. See [[file:02-the-editor.org][The editor]]. |
1202| Lint All Folders (=app.lint-folders=) | Lists the problems in every Org file in your folders, grouped by file. File ▸ Lint All Folders. See [[file:02-the-editor.org][The editor]]. |
12021203| Resolve Sync Conflicts… (=app.sync-conflicts=) | Shows the file's sync conflict copies to resolve them. |
12031204| Share Subtree… (=app.share-subtree=) | Shares the entry at the caret as an org file, with its attachments if chosen, or as text. File ▸ Share Subtree…. See [[file:01-files-and-folders.org][Files and folders]]. |
12041205| Import Table from File… (=app.table-import=) | Asks for a CSV, TSV or space-separated file and inserts it as a table (=org-table-import=). |
docs/manual/guide/14-ios.org +1 −1 · view
@@ -198,7 +198,7 @@ The org-timer commands are in Commands; a running timer shows above the text. Se
198198
199199Commands has the org-attach commands, and Attach Photo or Video…, Take Photo… and Scan Document…, which insert the link to the photo, or to the scanned pages as one PDF, at the caret; files shared to orgstar can be attached to an entry. Pasting an image and dropping files on the editor attach them and link them at the caret. Attachments are copied or moved: iOS doesn't let orgstar link a file from another app's storage, so the keys for attaching by hard link or symbolic link say "Attachments can't be linked on iPhone and iPad; Attach File… copies the file." See [[file:04-outlines.org][Outlines]] and [[file:09-links.org][Links]].
200200
201Lint File, under File in Commands, lists the problems in the open file with their lines, as the Mac's Lint File panel does; tap one to close the list and move the caret to its line. The checks are the Mac's; see [[file:02-the-editor.org][The editor]]. Run it again after editing to check again.
201Lint File, under File in Commands, lists the problems in the open file with their lines, as the Mac's Lint File panel does; tap one to close the list and move the caret to its line. The checks are the Mac's; see [[file:02-the-editor.org][The editor]]. Run it again after editing to check again. Lint All Folders, also under File in Commands, checks every Org file in your folders and lists the problems grouped by file, with progress while it runs and Stop to end it; tap one to open its file at that line. Encrypted files are left out.
202202
203203Sync with Working Copy, under File in Commands, syncs the folder of the open file through Working Copy; see Git folders through Working Copy below.
204204
docs/manual/guide/15-alongside-emacs.org +1 −1 · view
@@ -238,7 +238,7 @@ Completion follows Emacs's =completion-at-point= with corfu's list (see [[file:0
238238
239239Lint File (see [[file:02-the-editor.org][The editor]]) runs the checkers of =org-lint= that have the same meaning in orgstar, with org-lint's names, trust and messages, and finds the same lines; the tests compare the two on the same files. It differs in these ways:
240240
241- It checks the current file only; there is no command to check every file yet.
241- Lint All Folders checks every file in your folders, which org-lint doesn't do; an orphaned attachment folder is listed once there, not once for each file beside it.
242242- IDs are found through orgstar's index of all your folders, not =org-id-locations=. org-lint finds an unknown ID only when =org-id-locations= is loaded and doesn't have it; Lint File always reports one.
243243- orgstar's own checkers, which org-lint doesn't have: =duplicate-id= (across your folders), =unknown-todo-keyword=, =missing-attachment-folder=, =orphaned-attachment-folder= and =invalid-file-search=. =unknown-todo-keyword= reports a heading starting with a keyword common in Org configurations (=NEXT=, =WAIT=, =HOLD=, …) or one letter away from a keyword of the file (=TODOX=), when the file and the configuration don't define it.
244244- Not checked: Babel header arguments and values and source block languages (=wrong-header-argument=, =wrong-header-value=, =empty-header-argument=, =deprecated-header-syntax=, =named-result=, =invalid-babel-call-block=, =suspicious-language-in-src-block=), which depend on the languages loaded in Emacs; export options, macros and =#+INCLUDE= (=unknown-options-item=, =misspelled-export-option=, =invalid-macro-argument-and-template=, =wrong-include-link-parameter=, =obsolete-include-markup=, =beamer-frame=), which depend on the export back-ends loaded; citations (=non-existent-bibliography=, =missing-print-bibliography=, =invalid-cite-export-declaration=, =incomplete-citation=); =item-number=, =LaTeX-$=, =trailing-bracket-after-link=, =unclosed-brackets-in-link-description=, =percent-encoding-link-escape=, =extraneous-element-in-footnote-section=, =invalid-image-alignment= and =combining-keywords-with-affiliated=, where orgstar's reading of lists, LaTeX fragments and links differs from Org's in details these checks depend on.
l10n/Localizable.xcstrings +210 · view
@@ -573,6 +573,41 @@
573573 }
574574 }
575575 },
576 "%@ in %lld of %lld files": {
577 "comment": "Lint All Folders: the number of problems, files with problems, files checked",
578 "localizations": {
579 "de": {
580 "stringUnit": {
581 "state": "translated",
582 "value": "%@ in %lld von %lld Dateien"
583 }
584 },
585 "es": {
586 "stringUnit": {
587 "state": "translated",
588 "value": "%@ en %lld de %lld archivos"
589 }
590 },
591 "fr": {
592 "stringUnit": {
593 "state": "translated",
594 "value": "%@ dans %lld fichiers sur %lld"
595 }
596 },
597 "ja": {
598 "stringUnit": {
599 "state": "translated",
600 "value": "%@(%lld / %lld ファイル)"
601 }
602 },
603 "pt-BR": {
604 "stringUnit": {
605 "state": "translated",
606 "value": "%@ em %lld de %lld arquivos"
607 }
608 }
609 }
610 },
576611 "%@ in a buffer": {
577612 "localizations": {
578613 "de": {
@@ -9280,6 +9315,41 @@
92809315 }
92819316 }
92829317 },
9318 "Check Again": {
9319 "comment": "Lint All Folders: runs the checks again",
9320 "localizations": {
9321 "de": {
9322 "stringUnit": {
9323 "state": "translated",
9324 "value": "Erneut prüfen"
9325 }
9326 },
9327 "es": {
9328 "stringUnit": {
9329 "state": "translated",
9330 "value": "Revisar de nuevo"
9331 }
9332 },
9333 "fr": {
9334 "stringUnit": {
9335 "state": "translated",
9336 "value": "Vérifier à nouveau"
9337 }
9338 },
9339 "ja": {
9340 "stringUnit": {
9341 "state": "translated",
9342 "value": "再チェック"
9343 }
9344 },
9345 "pt-BR": {
9346 "stringUnit": {
9347 "state": "translated",
9348 "value": "Verificar Novamente"
9349 }
9350 }
9351 }
9352 },
92839353 "Check Spelling While Typing": {
92849354 "comment": "Command title",
92859355 "localizations": {
@@ -9349,6 +9419,41 @@
93499419 }
93509420 }
93519421 },
9422 "Checked %lld of %lld files": {
9423 "comment": "Lint All Folders: progress",
9424 "localizations": {
9425 "de": {
9426 "stringUnit": {
9427 "state": "translated",
9428 "value": "%lld von %lld Dateien geprüft"
9429 }
9430 },
9431 "es": {
9432 "stringUnit": {
9433 "state": "translated",
9434 "value": "%lld de %lld archivos revisados"
9435 }
9436 },
9437 "fr": {
9438 "stringUnit": {
9439 "state": "translated",
9440 "value": "%lld fichiers sur %lld vérifiés"
9441 }
9442 },
9443 "ja": {
9444 "stringUnit": {
9445 "state": "translated",
9446 "value": "%lld / %lld ファイルをチェック済み"
9447 }
9448 },
9449 "pt-BR": {
9450 "stringUnit": {
9451 "state": "translated",
9452 "value": "%lld de %lld arquivos verificados"
9453 }
9454 }
9455 }
9456 },
93529457 "Checker": {
93539458 "localizations": {
93549459 "de": {
@@ -24493,6 +24598,41 @@
2449324598 }
2449424599 }
2449524600 },
24601 "Lint All Folders": {
24602 "comment": "Command title",
24603 "localizations": {
24604 "de": {
24605 "stringUnit": {
24606 "state": "translated",
24607 "value": "Alle Ordner prüfen"
24608 }
24609 },
24610 "es": {
24611 "stringUnit": {
24612 "state": "translated",
24613 "value": "Revisar todas las carpetas"
24614 }
24615 },
24616 "fr": {
24617 "stringUnit": {
24618 "state": "translated",
24619 "value": "Vérifier tous les dossiers"
24620 }
24621 },
24622 "ja": {
24623 "stringUnit": {
24624 "state": "translated",
24625 "value": "すべてのフォルダをチェック"
24626 }
24627 },
24628 "pt-BR": {
24629 "stringUnit": {
24630 "state": "translated",
24631 "value": "Verificar Todas as Pastas"
24632 }
24633 }
24634 }
24635 },
2449624636 "Lint File": {
2449724637 "comment": "Command title",
2449824638 "localizations": {
@@ -29108,6 +29248,41 @@
2910829248 }
2910929249 }
2911029250 },
29251 "No problems found in %lld files": {
29252 "comment": "Lint All Folders",
29253 "localizations": {
29254 "de": {
29255 "stringUnit": {
29256 "state": "translated",
29257 "value": "Keine Probleme in %lld Dateien gefunden"
29258 }
29259 },
29260 "es": {
29261 "stringUnit": {
29262 "state": "translated",
29263 "value": "No se encontraron problemas en %lld archivos"
29264 }
29265 },
29266 "fr": {
29267 "stringUnit": {
29268 "state": "translated",
29269 "value": "Aucun problème trouvé dans %lld fichiers"
29270 }
29271 },
29272 "ja": {
29273 "stringUnit": {
29274 "state": "translated",
29275 "value": "%lld ファイルに問題はありません"
29276 }
29277 },
29278 "pt-BR": {
29279 "stringUnit": {
29280 "state": "translated",
29281 "value": "Nenhum problema encontrado em %lld arquivos"
29282 }
29283 }
29284 }
29285 },
2911129286 "No recent clock": {
2911229287 "localizations": {
2911329288 "de": {
@@ -42214,6 +42389,41 @@
4221442389 }
4221542390 }
4221642391 },
42392 "Stopped after %lld of %lld files": {
42393 "comment": "Lint All Folders: stopped before the end",
42394 "localizations": {
42395 "de": {
42396 "stringUnit": {
42397 "state": "translated",
42398 "value": "Nach %lld von %lld Dateien angehalten"
42399 }
42400 },
42401 "es": {
42402 "stringUnit": {
42403 "state": "translated",
42404 "value": "Detenido tras %lld de %lld archivos"
42405 }
42406 },
42407 "fr": {
42408 "stringUnit": {
42409 "state": "translated",
42410 "value": "Arrêté après %lld fichiers sur %lld"
42411 }
42412 },
42413 "ja": {
42414 "stringUnit": {
42415 "state": "translated",
42416 "value": "%lld / %lld ファイルで停止"
42417 }
42418 },
42419 "pt-BR": {
42420 "stringUnit": {
42421 "state": "translated",
42422 "value": "Interrompido após %lld de %lld arquivos"
42423 }
42424 }
42425 }
42426 },
4221742427 "Stops the running clock.": {
4221842428 "localizations": {
4221942429 "de": {
Keyboard shortcuts

Global

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

Repository & editor

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