Lint File: problems in the current file !488

merged merged by cmc on 2026-11-26 08:33 UTC · krz/orgstar:m5-lint into main

9 files changed, +1598 −2

One commit's changes, read-only. Review comments go on all commits.

Layout: unified · split

Changed files (9)
Sources/OrgCore/Commands/Attach.swift +5 −1 · view
@@ -56,7 +56,11 @@ public enum OrgAttach {
5656 /// `noFSCheck`, when the folder doesn't exist.
5757 public static func directory(tree: OrgTree, at offset: Int, path: String, idDir: String = "data/", inherit: Bool? = nil, noFSCheck: Bool = false, isDirectory: (String) -> Bool) -> String? {
5858 let model = DocumentModel(tree: tree)
59 let heading = entry(model, at: offset)
59 return directory(model: model, heading: entry(model, at: offset), path: path, idDir: idDir, inherit: inherit, noFSCheck: noFSCheck, isDirectory: isDirectory)
60 }
61
62 /// `directory(tree:at:…)` for heading `heading` of `model`, nil for the file's preamble.
63 static func directory(model: DocumentModel, heading: Int?, path: String, idDir: String, inherit: Bool?, noFSCheck: Bool, isDirectory: (String) -> Bool) -> String? {
6064 let folder = (path as NSString).deletingLastPathComponent
6165 func own(_ key: String, _ index: Int) -> String? {
6266 model.headings[index].properties.last { $0.key.uppercased() == key && !$0.additive }?.value
Sources/OrgCore/Links/Links.swift +2 −1 · view
@@ -60,6 +60,7 @@ public enum Links {
6060
6161 /// `org-link-expand-abbrev` for templates with `%s`, `%h`, or a plain prefix.
6262 static func expandAbbreviation(_ link: String, _ abbreviations: [String: String]) -> String {
63 guard !abbreviations.isEmpty else { return link }
6364 let regex = try! NSRegularExpression(pattern: "^([^:]*)(::?(.*))?$")
6465 let ns = link as NSString
6566 guard let m = regex.firstMatch(in: link, range: NSRange(location: 0, length: ns.length)),
@@ -77,7 +78,7 @@ public enum Links {
7778
7879 /// A bracket link's inside (`[[` to `]]` or `][`), as `org-element-link-parser` reads it.
7980 public static func parse(bracket inside: String, abbreviations: [String: String] = [:]) -> OrgLink {
80 let joined = inside.replacingOccurrences(of: "[ \\t]*\\n[ \\t]*", with: " ", options: .regularExpression)
81 let joined = inside.contains("\n") ? inside.replacingOccurrences(of: "[ \\t]*\\n[ \\t]*", with: " ", options: .regularExpression) : inside
8182 let raw = expandAbbreviation(unescape(joined), abbreviations)
8283 let ns = raw as NSString
8384 var type: String
Sources/OrgCore/Lint/Lint.swift added +163 · view
@@ -0,0 +1,163 @@
1import Foundation
2
3/// How sure a checker is that what it reports is a mistake, as org-lint's `:trust`.
4public enum LintTrust: String, Sendable {
5 case high, low
6}
7
8/// The checks Lint File runs. A checker with org-lint's name reports what org-lint's checker of
9/// that name reports (`org-lint.el`, Org 9.8.7), with the same trust; the others are orgstar's.
10public enum LintChecker: String, CaseIterable, Sendable {
11 // Links.
12 case invalidFuzzyLink = "invalid-fuzzy-link"
13 case invalidCustomIDLink = "invalid-custom-id-link"
14 case invalidIDLink = "invalid-id-link"
15 case invalidCoderefLink = "invalid-coderef-link"
16 case linkToLocalFile = "link-to-local-file"
17 case invalidFileSearch = "invalid-file-search"
18 case fileApplication = "file-application"
19 // Attachments.
20 case missingAttachmentFolder = "missing-attachment-folder"
21 case orphanedAttachmentFolder = "orphaned-attachment-folder"
22 // Duplicates.
23 case duplicateID = "duplicate-id"
24 case duplicateCustomID = "duplicate-custom-id"
25 case duplicateName = "duplicate-name"
26 case duplicateTarget = "duplicate-target"
27 case duplicateFootnoteDefinition = "duplicate-footnote-definition"
28 // Structure.
29 case incompleteDrawer = "incomplete-drawer"
30 case invalidBlock = "invalid-block"
31 case misplacedPlanningInfo = "misplaced-planning-info"
32 case obsoletePropertiesDrawer = "obsolete-properties-drawer"
33 case misplacedHeading = "misplaced-heading"
34 case indentedDiarySexp = "indented-diary-sexp"
35 case invalidKeywordSyntax = "invalid-keyword-syntax"
36 case orphanedAffiliatedKeywords = "orphaned-affiliated-keywords"
37 case obsoleteAffiliatedKeywords = "obsolete-affiliated-keywords"
38 case missingLanguageInSrcBlock = "missing-language-in-src-block"
39 case missingBackendInExportBlock = "missing-backend-in-export-block"
40 case deprecatedExportBlocks = "deprecated-export-blocks"
41 case deprecatedCategorySetup = "deprecated-category-setup"
42 case nonExistentSetupfileParameter = "non-existent-setupfile-parameter"
43 // Headings and properties.
44 case unknownTodoKeyword = "unknown-todo-keyword"
45 case priority
46 case spuriousColons = "spurious-colons"
47 case quoteSection = "quote-section"
48 case specialPropertyInPropertiesDrawer = "special-property-in-properties-drawer"
49 case invalidEffortProperty = "invalid-effort-property"
50 case invalidIDProperty = "invalid-id-property"
51 // Timestamps.
52 case timestampSyntax = "timestamp-syntax"
53 case clockSyntax = "clock-syntax"
54 case planningInactive = "planning-inactive"
55 case mismatchedPlanningRepeaters = "mismatched-planning-repeaters"
56 // Footnotes.
57 case undefinedFootnoteReference = "undefined-footnote-reference"
58 case unreferencedFootnoteDefinition = "unreferenced-footnote-definition"
59
60 /// org-lint has a checker by this name.
61 public var isOrgLint: Bool {
62 switch self {
63 case .invalidFileSearch, .missingAttachmentFolder, .orphanedAttachmentFolder, .duplicateID, .unknownTodoKeyword: false
64 default: true
65 }
66 }
67
68 public var trust: LintTrust {
69 switch self {
70 case .linkToLocalFile, .invalidFileSearch, .orphanedAttachmentFolder, .incompleteDrawer, .invalidBlock, .misplacedPlanningInfo,
71 .misplacedHeading, .indentedDiarySexp, .invalidKeywordSyntax, .orphanedAffiliatedKeywords, .deprecatedExportBlocks,
72 .nonExistentSetupfileParameter, .unknownTodoKeyword, .quoteSection, .timestampSyntax, .clockSyntax,
73 .mismatchedPlanningRepeaters:
74 .low
75 default:
76 .high
77 }
78 }
79}
80
81/// One problem in a file.
82public struct LintFinding: Sendable, Equatable, Hashable, Identifiable {
83 /// UTF-16 offset in the file's text.
84 public let offset: Int
85 /// 1-based.
86 public let line: Int
87 public let checker: LintChecker
88 public let message: String
89
90 public init(offset: Int, line: Int, checker: LintChecker, message: String) {
91 self.offset = offset
92 self.line = line
93 self.checker = checker
94 self.message = message
95 }
96
97 public var trust: LintTrust { checker.trust }
98
99 public var id: String { "\(offset) \(checker.rawValue) \(message)" }
100}
101
102/// What the checkers know of the world outside the file: the file system and the workspace's
103/// IDs. The file system's paths are absolute.
104public struct LintEnvironment: Sendable {
105 public var fileExists: @Sendable (String) -> Bool
106 public var isDirectory: @Sendable (String) -> Bool
107 /// The names in a folder.
108 public var contentsOfDirectory: @Sendable (String) -> [String]
109 /// The text of an Org file another file links into.
110 public var readFile: @Sendable (String) -> String?
111 /// The other files whose entries or file property drawers have this ID. Nil without a
112 /// workspace index: IDs then resolve in the file alone, and attachment folders aren't
113 /// checked for entries.
114 public var idFiles: (@Sendable (String) -> [String])?
115 /// `org-attach-id-dir` and `org-attach-use-inheritance`, as `OrgAttach.directory` takes them.
116 public var attachIDDir: String
117 public var attachInherit: Bool?
118 /// `org-crypt-tag-matcher`: entries with this tag and an encrypted body aren't linted inside.
119 public var cryptTag: String
120
121 public init(
122 fileExists: @escaping @Sendable (String) -> Bool, isDirectory: @escaping @Sendable (String) -> Bool,
123 contentsOfDirectory: @escaping @Sendable (String) -> [String], readFile: @escaping @Sendable (String) -> String?,
124 idFiles: (@Sendable (String) -> [String])? = nil, attachIDDir: String = "data/", attachInherit: Bool? = nil, cryptTag: String = "crypt"
125 ) {
126 self.fileExists = fileExists
127 self.isDirectory = isDirectory
128 self.contentsOfDirectory = contentsOfDirectory
129 self.readFile = readFile
130 self.idFiles = idFiles
131 self.attachIDDir = attachIDDir
132 self.attachInherit = attachInherit
133 self.cryptTag = cryptTag
134 }
135
136 /// The local file system, with no workspace index.
137 public static let fileSystem = LintEnvironment(
138 fileExists: { FileManager.default.fileExists(atPath: $0) },
139 isDirectory: { path in
140 var directory: ObjCBool = false
141 return FileManager.default.fileExists(atPath: path, isDirectory: &directory) && directory.boolValue
142 },
143 contentsOfDirectory: { (try? FileManager.default.contentsOfDirectory(atPath: $0)) ?? [] },
144 readFile: { try? String(contentsOfFile: $0, encoding: .utf8) }
145 )
146}
147
148/// Lint File: problems in one Org file, as org-lint reports them. Reports only; nothing is
149/// changed. The file is the whole input, so a command over many files runs this once per file
150/// with one environment.
151public enum OrgLint {
152 /// The findings in `text`, parsed as `tree`, by offset. `path` is where the file is, for
153 /// relative links, setup files and attachments; nil skips those checks.
154 public static func lint(_ text: String, tree: OrgTree, path: String?, environment: LintEnvironment = .fileSystem) -> [LintFinding] {
155 var linter = Linter(text: text, tree: tree, path: path, environment: environment)
156 linter.run()
157 return linter.findings.sorted { ($0.offset, $0.checker.order) < ($1.offset, $1.checker.order) }
158 }
159}
160
161extension LintChecker {
162 var order: Int { Self.allCases.firstIndex(of: self)! }
163}
Sources/OrgCore/Lint/LintCheckers.swift added +584 · view
@@ -0,0 +1,584 @@
1import Foundation
2
3// The checkers. Messages are org-lint's where org-lint has the checker.
4
5extension Linter {
6 // MARK: - Keywords
7
8 /// `org-element-affiliated-keywords`.
9 static let affiliatedKeys: Set<String> = ["CAPTION", "DATA", "HEADER", "HEADERS", "LABEL", "NAME", "PLOT", "RESNAME", "RESULT", "RESULTS", "SOURCE", "SRCNAME", "TBLNAME"]
10 /// `org-element-keyword-translation-alist`, as `org-lint-obsolete-affiliated-keywords` names them.
11 static let obsoleteKeys: [String: String] = ["DATA": "NAME", "LABEL": "NAME", "RESNAME": "NAME", "SOURCE": "NAME", "SRCNAME": "NAME", "TBLNAME": "NAME", "RESULT": "RESULTS", "HEADERS": "HEADER"]
12
13 /// A keyword line's key, upcased and without a dual keyword's `[…]`, and its value.
14 static func keyword(_ node: SyntaxNode) -> (key: String, value: String)? {
15 let line = node.text.prefix { $0 != "\n" && $0 != "\r" }.drop { $0 == " " || $0 == "\t" }
16 guard line.hasPrefix("#+"), let colon = line.firstIndex(of: ":") else { return nil }
17 var key = line[line.index(line.startIndex, offsetBy: 2)..<colon]
18 if let bracket = key.firstIndex(of: "[") { key = key[..<bracket] }
19 return (key.uppercased(), line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces))
20 }
21
22 static func isAffiliated(_ key: String) -> Bool {
23 affiliatedKeys.contains(key) || key.hasPrefix("ATTR_")
24 }
25
26 mutating func keywordChecks() {
27 var categories = 0
28 var run: [(node: SyntaxNode, key: String, value: String, line: Int)] = []
29 func finishRun(_ linter: inout Linter) {
30 guard let last = run.last else { return }
31 let next = last.line + 1
32 let following = next < linter.lineStarts.count ? linter.line(next) : nil
33 let orphaned = following.map { $0.allSatisfy { $0 == " " || $0 == "\t" } || $0.firstMatch(of: #/^\*+ /#) != nil } ?? true
34 if orphaned {
35 for keyword in run where keyword.key != "RESULT" && keyword.key != "RESULTS" {
36 linter.report(.orphanedAffiliatedKeywords, at: keyword.node.range.lowerBound, "Orphaned affiliated keyword: \"\(keyword.key)\"")
37 }
38 } else {
39 for keyword in run {
40 if let new = Linter.obsoleteKeys[keyword.key] {
41 linter.report(.obsoleteAffiliatedKeywords, at: keyword.node.range.lowerBound, "Obsolete affiliated keyword: \"\(keyword.key)\". Use \"\(new)\" instead")
42 }
43 }
44 // The element's name is the last NAME before it.
45 if let name = run.last(where: { $0.key == "NAME" }) { linter.names.append((name.node.range.lowerBound, name.value)) }
46 for keyword in run where keyword.key == "RESULTS" && !keyword.value.isEmpty { linter.resultNames.append(keyword.value) }
47 }
48 run = []
49 }
50 for node in keywords {
51 guard let (key, value) = Self.keyword(node) else { continue }
52 let line = lineIndex(node.range.lowerBound)
53 if let last = run.last, last.line + 1 != line || !Self.isAffiliated(key) { finishRun(&self) }
54 if Self.isAffiliated(key) { run.append((node, key, value, line)) }
55 switch key {
56 case "CATEGORY":
57 categories += 1
58 if categories > 1 { report(.deprecatedCategorySetup, at: node.range.lowerBound, "Spurious CATEGORY keyword. Set :CATEGORY: property instead") }
59 case "SETUPFILE":
60 var file = value
61 if file.count >= 2, file.hasPrefix("\""), file.hasSuffix("\"") { file = String(file.dropFirst().dropLast()) }
62 guard let folder, !file.isEmpty, file.firstMatch(of: /^[A-Za-z][A-Za-z0-9+.-]*:\/\//) == nil, !Self.isRemote(file) else { break }
63 if !env.fileExists(OrgAttach.expand(file, in: folder)) {
64 report(.nonExistentSetupfileParameter, at: node.range.lowerBound, "Non-existent setup file \"\(file)\"")
65 }
66 default:
67 break
68 }
69 }
70 finishRun(&self)
71 }
72
73 // MARK: - Links
74
75 static func isRemote(_ path: String) -> Bool { path.firstMatch(of: /^\/[^\/:]+:/) != nil }
76
77 static func words(_ s: String) -> [String] { s.split(whereSeparator: \.isWhitespace).map(String.init) }
78
79 /// A heading's title as `org-export-search-cells` reads it: without COMMENT, statistics
80 /// cookies as blanks, upcased words.
81 static func headlineKey(_ title: String) -> [String] {
82 var t = title
83 if t == "COMMENT" { t = "" } else if t.hasPrefix("COMMENT ") { t = String(t.dropFirst(8)) }
84 if t.contains("[") { t = t.replacingOccurrences(of: "\\[[0-9]*(?:%|/[0-9]*)\\]", with: " ", options: .regularExpression) }
85 return words(t).map { $0.uppercased() }
86 }
87
88 /// The link a link node is, read as `Links.link(at:)` reads it; nil for a radio link.
89 func link(_ node: SyntaxNode, abbreviations: [String: String]) -> OrgLink? {
90 if let path = node.tokens.first(where: { $0.kind == .linkPath })?.text {
91 return Links.parse(bracket: path.contains("\n") ? node.linkPath! : path, abbreviations: abbreviations)
92 }
93 let whole = node.text
94 if whole.hasPrefix("<"), whole.hasSuffix(">") { return Links.parse(plain: String(whole.dropFirst().dropLast())) }
95 if tree.settings.radioTargets.contains(where: { Links.words($0) == Links.words(whole) }) { return nil }
96 return Links.parse(plain: whole)
97 }
98
99 /// The heading `offset` is under.
100 func headingIndex(at offset: Int) -> Int? {
101 var low = 0, high = model.headings.count
102 while low < high {
103 let mid = (low + high) / 2
104 if model.headings[mid].headingRange.lowerBound <= offset { low = mid + 1 } else { high = mid }
105 }
106 return low == 0 ? nil : low - 1
107 }
108
109 func attachmentDirectory(_ heading: Int?, cache: inout [Int: String?]) -> String? {
110 guard let path else { return nil }
111 let key = heading ?? -1
112 if let cached = cache[key] { return cached }
113 let dir = OrgAttach.directory(model: model, heading: heading, path: path, idDir: env.attachIDDir, inherit: env.attachInherit, noFSCheck: false,
114 isDirectory: env.isDirectory)
115 cache[key] = dir
116 return dir
117 }
118
119 /// Every `:ID:` in the file: entries' and the file's own.
120 var localIDs: Set<String> {
121 Set(propertyDrawers.flatMap(\.children).compactMap { Property(line: $0.text) }.filter { $0.key.uppercased() == "ID" && !$0.value.isEmpty }.map(\.value))
122 }
123
124 mutating func linkChecks() {
125 let abbreviations = Links.abbreviations(in: tree.settings.setupKeywords + text)
126 var headlines = Set<[String]>()
127 var headingIDs = Set<String>()
128 for heading in model.headings {
129 headlines.insert(Self.headlineKey(heading.title))
130 for property in heading.properties where !property.additive && ["ID", "CUSTOM_ID"].contains(property.key.uppercased()) {
131 headingIDs.insert(property.value)
132 }
133 }
134 let targetKeys = Set(targets.map { Self.words(String($0.text.dropFirst(2).dropLast(2))).map { $0.uppercased() } })
135 let nameKeys = Set((names.map(\.value) + resultNames).map(Self.words))
136 let ids = localIDs
137 var attachDirs: [Int: String?] = [:]
138 var searchIndexes: [String: SearchIndex?] = [:]
139
140 for node in links {
141 guard let link = link(node, abbreviations: abbreviations) else { continue }
142 let at = node.range.lowerBound
143 switch link.type {
144 case "fuzzy":
145 let starred = link.path.hasPrefix("*")
146 let words = Self.words(starred ? String(link.path.dropFirst()) : link.path)
147 let upper = words.map { $0.uppercased() }
148 let found = starred ? headlines.contains(upper)
149 : targetKeys.contains(upper) || nameKeys.contains(words) || nameKeys.contains(upper) || headlines.contains(upper)
150 if !found, !words.isEmpty {
151 report(.invalidFuzzyLink, at: at, "Unknown fuzzy location \"\(starred ? String(link.path.dropFirst()) : link.path)\"")
152 }
153 case "custom-id":
154 if !headingIDs.contains(link.path) { report(.invalidCustomIDLink, at: at, "Unknown custom ID \"\(link.path)\"") }
155 case "id":
156 // An ID may hold `::` (invalid-id-property reports it); otherwise what follows is a search.
157 let candidates = [link.path, link.path.components(separatedBy: "::")[0]]
158 if !candidates.contains(where: ids.contains), candidates.allSatisfy({ env.idFiles?($0).isEmpty ?? true }) {
159 report(.invalidIDLink, at: at, "Unknown ID \"\(link.path)\"")
160 }
161 case "coderef":
162 if Coderef.search(link.path, text: text, tree: tree) == nil { report(.invalidCoderefLink, at: at, "Unknown coderef \"\(link.path)\"") }
163 case "file":
164 if link.raw.hasPrefix("file+"), let colon = link.raw.firstIndex(of: ":") {
165 report(.fileApplication, at: at, "Deprecated \"\(link.raw[..<colon])\" link type")
166 }
167 guard let folder, !link.path.isEmpty, !Self.isRemote(link.path) else { continue }
168 let file = OrgAttach.expand(link.path, in: folder)
169 if !env.fileExists(file) {
170 report(.linkToLocalFile, at: at, "Link to non-existent local file \"\(link.path)\"")
171 } else if let search = link.searchOption, !search.isEmpty, search.allSatisfy(\.isWhitespace) == false,
172 Int(search) == nil, file.hasSuffix(".org") || file.hasSuffix(".org_archive") {
173 if searchIndexes[file] == nil {
174 let other = file == path.map({ OrgAttach.expand($0, in: "/") }) ? text : env.readFile(file)
175 searchIndexes[file] = other.map { SearchIndex(OrgParser.parse($0, defaults: tree.settings)) }
176 }
177 if let index = searchIndexes[file] ?? nil, !index.finds(search) {
178 report(.invalidFileSearch, at: at, "Unknown location \"\(search)\" in \"\(link.path)\"")
179 }
180 }
181 case "attachment":
182 guard let folder else { continue }
183 var name = link.path
184 if let range = name.range(of: "::") { name = String(name[..<range.lowerBound]) }
185 let dir = attachmentDirectory(headingIndex(at: at), cache: &attachDirs) ?? folder
186 let file = OrgAttach.expand(name, in: dir)
187 if !env.fileExists(file) { report(.linkToLocalFile, at: at, "Link to non-existent local file \"\(file)\"") }
188 default:
189 break
190 }
191 }
192 }
193
194 // MARK: - Attachments
195
196 mutating func attachmentChecks() {
197 guard let path, let folder else { return }
198 var attachDirs: [Int: String?] = [:]
199 for (index, heading) in model.headings.enumerated() where heading.localTags.contains("ATTACH") {
200 if attachmentDirectory(index, cache: &attachDirs) == nil {
201 report(.missingAttachmentFolder, at: heading.headingRange.lowerBound, "Entry tagged ATTACH has no attachment folder")
202 }
203 }
204 // Folders under the ID folder whose ID no entry has, here or, through the index, elsewhere.
205 guard let idFiles = env.idFiles else { return }
206 let ids = localIDs
207 var roots = [OrgAttach.expand(env.attachIDDir, in: folder)]
208 let fallback = OrgAttach.expand("data/", in: folder)
209 if fallback != roots[0] { roots.append(fallback) }
210 for root in roots where env.isDirectory(root) {
211 func subfolders(_ dir: String) -> [String] {
212 env.contentsOfDirectory(dir).filter { !$0.hasPrefix(".") && env.isDirectory((dir as NSString).appendingPathComponent($0)) }.sorted()
213 }
214 var candidates: [(id: String, relative: String)] = []
215 for first in subfolders(root) {
216 let firstPath = (root as NSString).appendingPathComponent(first)
217 if first == "__" {
218 for letter in subfolders(firstPath) {
219 for id in subfolders((firstPath as NSString).appendingPathComponent(letter)) { candidates.append((id, "\(first)/\(letter)/\(id)")) }
220 }
221 } else if first.count == 2 || first.count == 6 {
222 for rest in subfolders(firstPath) { candidates.append((first + rest, "\(first)/\(rest)")) }
223 }
224 }
225 let shown = root.hasPrefix(folder + "/") ? String(root.dropFirst(folder.count + 1)) : root
226 for candidate in candidates where !ids.contains(candidate.id) && idFiles(candidate.id).filter({ $0 != path }).isEmpty {
227 let folderName = (shown as NSString).appendingPathComponent(candidate.relative)
228 report(.orphanedAttachmentFolder, at: 0, "Attachment folder \"\(folderName)\" belongs to no entry")
229 }
230 }
231 }
232
233 // MARK: - Duplicates
234
235 mutating func duplicateChecks() {
236 func reportDuplicates(_ items: [(offset: Int, key: String)], _ checker: LintChecker, _ message: (String) -> String) {
237 var counts: [String: Int] = [:]
238 for item in items { counts[item.key, default: 0] += 1 }
239 for item in items where counts[item.key]! > 1 { report(checker, at: item.offset, message(item.key)) }
240 }
241 var ids: [(offset: Int, key: String)] = []
242 var customIDs: [(offset: Int, key: String)] = []
243 for drawer in propertyDrawers {
244 for node in drawer.children {
245 guard let property = Property(line: node.text), !property.additive, !property.value.isEmpty else { continue }
246 switch property.key.uppercased() {
247 case "ID": ids.append((node.range.lowerBound, property.value))
248 case "CUSTOM_ID": customIDs.append((node.range.lowerBound, property.value))
249 default: break
250 }
251 }
252 }
253 reportDuplicates(customIDs, .duplicateCustomID) { "Duplicate CUSTOM_ID property \"\($0)\"" }
254 reportDuplicates(names.map { ($0.offset, $0.value) }, .duplicateName) { "Duplicate NAME \"\($0)\"" }
255 reportDuplicates(targets.map { ($0.range.lowerBound, Self.words(String($0.text.dropFirst(2).dropLast(2))).joined(separator: " ")) }, .duplicateTarget) {
256 "Duplicate target <<\($0)>>"
257 }
258 reportDuplicates(footnoteDefinitions.compactMap { node in Self.definitionLabel(node).map { (node.range.lowerBound, $0) } }, .duplicateFootnoteDefinition) {
259 "Duplicate footnote definition \"\($0)\""
260 }
261 var counts: [String: Int] = [:]
262 for id in ids { counts[id.key, default: 0] += 1 }
263 var elsewhere: [String: [String]] = [:]
264 for id in ids where elsewhere[id.key] == nil {
265 elsewhere[id.key] = (env.idFiles?(id.key) ?? []).filter { $0 != path }.map { ($0 as NSString).lastPathComponent }
266 }
267 for id in ids {
268 let others = Array(Set(elsewhere[id.key]!)).sorted()
269 guard counts[id.key]! > 1 || !others.isEmpty else { continue }
270 report(.duplicateID, at: id.offset, "Duplicate ID \"\(id.key)\"" + (others.isEmpty ? "" : ", also in \(others.joined(separator: ", "))"))
271 }
272 }
273
274 // MARK: - Drawers and blocks
275
276 mutating func drawerChecks() {
277 var drawerEnds: [Int: Int] = [:]
278 for node in drawers + propertyDrawers {
279 drawerEnds[lineIndex(node.range.lowerBound)] = lineIndex(node.range.upperBound - 1)
280 }
281 let pattern = "^[ \\t]*:((?:\\w|[-_])+):[ \\t]*$"
282 let lines = matches(pattern).map { lineIndex($0.range.location) }
283 var skipUntil = -1
284 var k = 0
285 while k < lines.count {
286 let line = lines[k]
287 k += 1
288 guard line > skipUntil else { continue }
289 switch lineTags[line] {
290 case .drawer where drawerEnds[line] != nil:
291 let end = drawerEnds[line]!
292 while k < lines.count, lines[k] < end {
293 report(.incompleteDrawer, at: lineStarts[lines[k]], "Possible misleading drawer entry \"\(self.line(lines[k]).trimmingCharacters(in: .whitespaces))\"")
294 k += 1
295 }
296 skipUntil = end
297 case .propertyDrawer where drawerEnds[line] != nil:
298 skipUntil = drawerEnds[line]!
299 case .verbatimBlock:
300 break
301 default:
302 report(.incompleteDrawer, at: lineStarts[line], "Possible incomplete drawer \"\(self.line(line).trimmingCharacters(in: .whitespaces))\"")
303 }
304 }
305
306 for node in drawers where line(lineIndex(node.range.lowerBound)).trimmingCharacters(in: .whitespaces) == ":PROPERTIES:" {
307 report(.obsoletePropertiesDrawer, at: node.range.lowerBound, "Incorrect location for PROPERTIES drawer")
308 }
309 // `org-property-drawer-re`: only `:KEY:` lines between the first and the last.
310 for node in propertyDrawers {
311 let first = lineIndex(node.range.lowerBound), last = lineIndex(node.range.upperBound - 1)
312 if (first + 1..<last).contains(where: { !Self.isPropertyLine(line($0)) }) {
313 report(.obsoletePropertiesDrawer, at: node.range.lowerBound, "Incorrect contents for PROPERTIES drawer")
314 }
315 }
316 }
317
318 /// `[ \t]*:\S+:([ \t].*)?`, a line `org-property-drawer-re` allows: the first run of
319 /// non-blanks after the colon is at least two long and ends in a colon.
320 static func isPropertyLine(_ line: String) -> Bool {
321 let rest = line.drop { $0 == " " || $0 == "\t" }
322 guard rest.first == ":" else { return false }
323 let run = rest.dropFirst().prefix { !$0.isWhitespace }
324 return run.count >= 2 && run.last == ":"
325 }
326
327 static let deprecatedExportBlocks: Set<String> = ["ASCII", "BEAMER", "HTML", "LATEX", "MAN", "MARKDOWN", "MD", "ODT", "ORG", "TEXINFO"]
328
329 mutating func blockChecks() {
330 for m in matches("^[ \\t]*#\\+(BEGIN|END)(?::|_\\S*)?[ \\t]*", caseInsensitive: true) {
331 let index = lineIndex(m.range.location)
332 let name = line(index).trimmingCharacters(in: .whitespaces)
333 let lineEnd = lineStarts[index] + (line(index) as NSString).length
334 if group(m, 1)!.uppercased() == "END", NSMaxRange(m.range) < lineEnd {
335 report(.invalidBlock, at: lineStarts[index], "Invalid block closing line \"\(name)\"")
336 } else if ![.block, .verbatimBlock, .dynamicBlock].contains(lineTags[index]) {
337 report(.invalidBlock, at: lineStarts[index], "Possible incomplete block \"\(name)\"")
338 }
339 }
340 for node in blocks {
341 let name = Self.blockName(node)
342 let first = node.text.prefix { $0 != "\n" && $0 != "\r" }.drop { $0 == " " || $0 == "\t" }
343 let parameters = first.dropFirst("#+begin_".count + name.count).trimmingCharacters(in: .whitespaces)
344 switch name.lowercased() {
345 case "src":
346 if parameters.isEmpty || parameters.hasPrefix(":") || parameters.hasPrefix("-") || parameters.hasPrefix("+") {
347 report(.missingLanguageInSrcBlock, at: node.range.lowerBound, "Missing language in source block")
348 }
349 case "export":
350 if parameters.isEmpty { report(.missingBackendInExportBlock, at: node.range.lowerBound, "Missing backend in export block") }
351 case let lower where Self.deprecatedExportBlocks.contains(lower.uppercased()):
352 report(.deprecatedExportBlocks, at: node.range.lowerBound, "Deprecated syntax for export block. Use \"BEGIN_EXPORT \(name)\" instead")
353 default:
354 break
355 }
356 }
357 }
358
359 // MARK: - Lines org-lint searches for
360
361 mutating func lineChecks() {
362 for m in matches("^[ \\t]*(?:CLOSED|DEADLINE|SCHEDULED):", caseInsensitive: true) {
363 let index = lineIndex(m.range.location)
364 if ![.planning, .verbatimBlock].contains(lineTags[index]) {
365 report(.misplacedPlanningInfo, at: lineStarts[index], "Misplaced planning info line")
366 }
367 }
368 for m in matches("^[ \\t]+%%\\(") {
369 let index = lineIndex(m.range.location)
370 if lineTags[index] != .verbatimBlock { report(.indentedDiarySexp, at: lineStarts[index], "Possible indented diary-sexp") }
371 }
372 let dual = try! NSRegularExpression(pattern: "^[ \\t]*#\\+(?:CAPTION|RESULTS)(\\[.*\\])?:(?: |$)", options: .caseInsensitive)
373 for m in matches("^[ \\t]*#\\+([^\\s:]*)(?: |$)") {
374 let name = group(m, 1)!
375 let upper = name.uppercased()
376 if upper.hasPrefix("BEGIN") || upper.hasPrefix("END") { continue }
377 let index = lineIndex(m.range.location)
378 let content = line(index)
379 if dual.firstMatch(in: content, range: NSRange(location: 0, length: (content as NSString).length)) != nil { continue }
380 report(.invalidKeywordSyntax, at: m.range.location, "Possible missing colon in keyword \"\(name)\"")
381 }
382 for m in matches("[^*\\n\\r ,]\\*{2,} ", anchorsMatchLines: false) {
383 let index = lineIndex(NSMaxRange(m.range))
384 if [.paragraph, .heading].contains(lineTags[index]) { report(.misplacedHeading, at: m.range.location, "Possibly misplaced heading line") }
385 }
386 }
387
388 // MARK: - Headings
389
390 /// Keywords common in Org configurations: a heading starting with one the file doesn't
391 /// define is likely meant as a TODO entry.
392 static let commonKeywords: Set<String> = [
393 "TODO", "DONE", "NEXT", "WAIT", "WAITING", "HOLD", "STARTED", "STRT", "SOMEDAY", "MAYBE", "CANCELLED", "CANCELED", "CANCEL",
394 "CNCL", "KILL", "PROJ", "PROJECT", "LOOP", "IDEA", "DELEGATED", "INPROGRESS", "IN-PROGRESS", "DOING", "BLOCKED", "REVIEW",
395 ]
396
397 /// The edit distance of two words, a swap of neighbours counting one.
398 static func distance(_ a: [Character], _ b: [Character]) -> Int {
399 guard !a.isEmpty, !b.isEmpty else { return max(a.count, b.count) }
400 var d = Array(repeating: Array(repeating: 0, count: b.count + 1), count: a.count + 1)
401 for i in 0...a.count { d[i][0] = i }
402 for j in 0...b.count { d[0][j] = j }
403 for i in 1...a.count {
404 for j in 1...b.count {
405 let cost = a[i - 1] == b[j - 1] ? 0 : 1
406 d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost)
407 if i > 1, j > 1, a[i - 1] == b[j - 2], a[i - 2] == b[j - 1] { d[i][j] = min(d[i][j], d[i - 2][j - 2] + 1) }
408 }
409 }
410 return d[a.count][b.count]
411 }
412
413 mutating func headingChecks() {
414 let known = tree.settings.todoKeywordNames
415 let priorities = tree.settings.priorities
416 for heading in model.headings {
417 let at = heading.headingRange.lowerBound
418 let title = heading.title
419 var uncommented = title
420 if uncommented == "COMMENT" { uncommented = "" } else if uncommented.hasPrefix("COMMENT ") { uncommented = String(uncommented.dropFirst(8)) }
421 if uncommented.hasPrefix("QUOTE ") { report(.quoteSection, at: at, "Deprecated QUOTE section") }
422 let words = Self.words(title)
423 if let last = words.last, last.hasPrefix(":"), last.contains("::"), last.wholeMatch(of: /:[\p{L}\p{N}_@#%:]+:/) != nil {
424 report(.spuriousColons, at: at, "Tags contain a spurious colon")
425 }
426 if let value = heading.priority {
427 // `org-priority-value-regexp` reads 0 to 64 without leading zeros; other numbers aren't a priority.
428 if let n = Int(value), String(n) != value || n > 64 {
429 report(.priority, at: at, "Invalid priority '\(value)'")
430 } else if !Self.validPriority(value, priorities) {
431 report(.priority, at: at, "Out-of-bounds priority '\(value)'")
432 }
433 } else if title.hasPrefix("[#"), let m = title.prefixMatch(of: /\[#([^\[\]]*)(\]*)/) {
434 // Org reads `[#a]` as a priority, case-folded, but not a valid one, and reports nothing.
435 let lowerLetter = m.1.count == 1 && m.1.first!.isASCII && m.1.first!.isLowercase && !m.2.isEmpty
436 if !lowerLetter { report(.priority, at: at, m.2.isEmpty ? "Malformed priority '\(m.0)'" : "Invalid priority '\(m.1)'") }
437 }
438 if heading.todo == nil, let word = words.first, let first = word.first, first.isASCII, first.isUppercase, word.count >= 2,
439 word.wholeMatch(of: /[A-Z][A-Z0-9_-]*[A-Z0-9]/) != nil, !known.contains(word), word != "COMMENT",
440 Self.commonKeywords.contains(word) || known.contains(where: { $0.count >= 4 && Self.distance(Array($0), Array(word)) == 1 }) {
441 report(.unknownTodoKeyword, at: at, "Unknown TODO keyword \"\(word)\"")
442 }
443 }
444 }
445
446 static func validPriority(_ value: String, _ priorities: Priorities) -> Bool {
447 if let n = Int(value), let high = Int(priorities.highest), let low = Int(priorities.lowest) { return (min(high, low)...max(high, low)).contains(n) }
448 guard Int(value) == nil, Int(priorities.highest) == nil, Int(priorities.lowest) == nil else { return false }
449 return priorities.highest <= value && value <= priorities.lowest
450 }
451
452 // MARK: - Properties
453
454 /// `org-special-properties`.
455 static let specialProperties: Set<String> = ["ALLTAGS", "BLOCKED", "CLOCKSUM", "CLOCKSUM_T", "CLOSED", "DEADLINE", "FILE", "ITEM", "PRIORITY", "SCHEDULED", "TAGS", "TIMESTAMP", "TIMESTAMP_IA", "TODO"]
456
457 /// `org-duration-p`.
458 static func isDuration(_ s: String) -> Bool {
459 ColumnView.minutes(s) != nil && s.trimmingCharacters(in: .whitespaces).wholeMatch(of: /[0-9]+(?:\.[0-9]*)?/) == nil
460 }
461
462 mutating func propertyChecks() {
463 for drawer in propertyDrawers {
464 for node in drawer.children where node.kind == .nodeProperty {
465 guard let property = Property(line: node.text) else { continue }
466 let at = node.range.lowerBound
467 if Self.specialProperties.contains(property.key.uppercased()) {
468 report(.specialPropertyInPropertiesDrawer, at: at, "Special property \"\(property.key)\" found in a properties drawer")
469 }
470 if property.key == "EFFORT", !property.additive, !property.value.isEmpty, !Self.isDuration(property.value) {
471 report(.invalidEffortProperty, at: at, "Invalid effort duration format: \"\(property.value)\"")
472 }
473 if property.key == "ID", property.value.contains("::") {
474 report(.invalidIDProperty, at: at, "IDs should not include \"::\": \"\(property.value)\"")
475 }
476 }
477 }
478 }
479
480 // MARK: - Timestamps
481
482 mutating func timestampChecks() {
483 for node in timestamps {
484 let stamp = node.text
485 guard !stamp.contains("%%("), let canonical = LintTimestamp.canonical(stamp), canonical != stamp else { continue }
486 report(.timestampSyntax, at: node.range.lowerBound, "Potentially malformed timestamp \(stamp). Parsed as: \(canonical)")
487 }
488 for node in clocks {
489 let actual = node.text.trimmingCharacters(in: .whitespacesAndNewlines)
490 guard let canonical = LintTimestamp.canonicalClock(actual), canonical != actual else { continue }
491 report(.clockSyntax, at: node.range.lowerBound, "Potentially malformed CLOCK: line \(actual). Parsed as: \(canonical)")
492 }
493 for node in plannings {
494 // Each timestamp belongs to the keyword just before it.
495 var stamps: [String: Timestamp] = [:]
496 for child in node.children where child.kind == .timestamp {
497 let before = ns.substring(with: NSRange(location: node.range.lowerBound, length: child.range.lowerBound - node.range.lowerBound))
498 .trimmingCharacters(in: .whitespaces)
499 guard let keyword = ["SCHEDULED", "DEADLINE", "CLOSED"].first(where: { before.hasSuffix($0 + ":") }), stamps[keyword] == nil,
500 let stamp = Timestamp.parse(child.text) else { continue }
501 stamps[keyword] = stamp
502 }
503 let at = node.range.lowerBound
504 if let scheduled = stamps["SCHEDULED"], !scheduled.active {
505 report(.planningInactive, at: at, "Inactive timestamp in SCHEDULED will not appear in agenda.")
506 } else if let deadline = stamps["DEADLINE"], !deadline.active {
507 report(.planningInactive, at: at, "Inactive timestamp in DEADLINE will not appear in agenda.")
508 }
509 if let s = stamps["SCHEDULED"]?.repeater, let d = stamps["DEADLINE"]?.repeater,
510 s.kind != .restart, d.kind != .restart, s.interval.value > 0, d.interval.value > 0,
511 s.kind != d.kind || s.interval != d.interval {
512 report(.mismatchedPlanningRepeaters, at: at, "Different repeaters in SCHEDULED and DEADLINE timestamps.")
513 }
514 }
515 }
516
517 // MARK: - Footnotes
518
519 /// A definition's label, from its `[fn:LABEL]`.
520 static func definitionLabel(_ node: SyntaxNode) -> String? {
521 guard let marker = node.tokens.first(where: { $0.kind == .marker }) else { return nil }
522 let label = String(marker.text.dropFirst(4).dropLast())
523 return label.isEmpty ? nil : label
524 }
525
526 /// A reference's label, nil for an anonymous one, and whether it defines the footnote too.
527 static func referenceLabel(_ node: SyntaxNode) -> (label: String?, inline: Bool) {
528 let inside = node.text.dropFirst(4).dropLast()
529 guard let colon = inside.firstIndex(of: ":") else { return (String(inside), false) }
530 let label = inside[..<colon]
531 return (label.isEmpty ? nil : String(label), true)
532 }
533
534 mutating func footnoteChecks() {
535 let references = footnoteReferences.map { (node: $0, reference: Self.referenceLabel($0)) }
536 let definitions = footnoteDefinitions.compactMap { node in Self.definitionLabel(node).map { (node: node, label: $0) } }
537 let defined = Set(definitions.map(\.label) + references.filter(\.reference.inline).compactMap(\.reference.label))
538 let referenced = Set(references.compactMap(\.reference.label))
539 for (node, reference) in references where !reference.inline {
540 if let label = reference.label, !defined.contains(label) {
541 report(.undefinedFootnoteReference, at: node.range.lowerBound, "Missing definition for footnote [\(label)]")
542 }
543 }
544 for (node, label) in definitions where !referenced.contains(label) {
545 report(.unreferencedFootnoteDefinition, at: node.range.lowerBound, "No reference for footnote definition [\(label)]")
546 }
547 }
548}
549
550/// The targets a `file:…::search` link can reach in an Org file, as `Links.search` finds them.
551struct SearchIndex {
552 let tree: OrgTree
553 let text: String
554 let customIDs: Set<String>
555 let targets: Set<[String]>
556 let names: Set<[String]>
557 let headings: Set<[String]>
558
559 init(_ tree: OrgTree) {
560 self.tree = tree
561 text = tree.text
562 let model = DocumentModel(tree: tree)
563 customIDs = Set(model.headings.flatMap { $0.properties.filter { $0.key.uppercased() == "CUSTOM_ID" }.map(\.value) })
564 headings = Set(model.headings.map { Links.normalizedTitle($0.title).split(whereSeparator: \.isWhitespace).map { $0.uppercased() } })
565 let ns = text as NSString
566 targets = Set(try! NSRegularExpression(pattern: "(?<!<)<<([^<>\\n]+)>>(?!>)").matches(in: text, range: NSRange(location: 0, length: ns.length)).map {
567 Linter.words(ns.substring(with: $0.range(at: 1))).map { $0.uppercased() }
568 })
569 names = Set(text.matches(of: /(?m)^[ \t]*#\+(?i:name): +(.*?)[ \t]*$/).map { Linter.words(String($0.1)).map { $0.uppercased() } })
570 }
571
572 func finds(_ s: String) -> Bool {
573 let normalized = s.replacingOccurrences(of: "\\n[ \\t]*", with: " ", options: .regularExpression)
574 if normalized.hasPrefix("#") { return customIDs.contains(String(normalized.dropFirst())) }
575 if (normalized.hasPrefix("(") && normalized.hasSuffix(")")) || (normalized.count >= 2 && normalized.hasPrefix("/") && normalized.hasSuffix("/")) {
576 if case .failed = Links.search(s, text: text, tree: tree) { return false }
577 return true
578 }
579 let starred = normalized.hasPrefix("*")
580 let words = Linter.words(starred ? String(s.dropFirst()) : s).map { $0.uppercased() }
581 if !starred, targets.contains(words) || names.contains(words) { return true }
582 return headings.contains(words)
583 }
584}
Sources/OrgCore/Lint/LintTimestamp.swift added +144 · view
@@ -0,0 +1,144 @@
1import Foundation
2
3/// Timestamps and clock lines as Org writes them back after reading them
4/// (`org-element-timestamp-parser` then `org-element-timestamp-interpreter`), which
5/// org-lint's timestamp-syntax and clock-syntax compare with the text.
6enum LintTimestamp {
7 static let dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
8 /// `org-ts-regexp0`, as `org-parse-time-string` reads a date and time.
9 static let dateTime = try! NSRegularExpression(pattern: "([0-9]{4})-([0-9]{2})-([0-9]{2})( +[^\\]+0-9>\\r\\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?")
10 static let rawValue = try! NSRegularExpression(pattern: "^([<\\[].*?)[\\]>](?:--([<\\[][0-9]{4}-[0-9]{2}-[0-9]{2}(?: .*?)?[\\]>]))?$")
11 static let timeRange = try! NSRegularExpression(pattern: "[012]?[0-9]:[0-5][0-9](-([012]?[0-9]):([0-5][0-9]))")
12 static let repeater = try! NSRegularExpression(pattern: "(\\+\\+|\\.\\+|\\+)([0-9]+)([hdwmy])(?:/([0-9]+)([hdwmy]))?")
13 static let warning = try! NSRegularExpression(pattern: "(-)?-([0-9]+)([hdwmy])")
14
15 struct DateTime {
16 var year, month, day: Int
17 var hour, minute: Int?
18 }
19
20 static func groups(_ regex: NSRegularExpression, _ s: String) -> [String?]? {
21 let ns = s as NSString
22 guard let m = regex.firstMatch(in: s, range: NSRange(location: 0, length: ns.length)) else { return nil }
23 return (0..<m.numberOfRanges).map { m.range(at: $0).location == NSNotFound ? nil : ns.substring(with: m.range(at: $0)) }
24 }
25
26 /// `org-parse-time-string` with NODEFAULT.
27 static func parseTime(_ s: String) -> DateTime? {
28 guard let g = groups(dateTime, s), let year = Int(g[1]!), let month = Int(g[2]!), let day = Int(g[3]!) else { return nil }
29 return DateTime(year: year, month: month, day: day, hour: g[6].flatMap { Int($0) }, minute: g[7].flatMap { Int($0) })
30 }
31
32 /// `format-time-string` of `org-time-stamp-format` without brackets, after `encode-time`
33 /// rolls out-of-range values over.
34 static func format(_ t: DateTime, time: Bool) -> String {
35 let minutes = (t.hour ?? 0) * 60 + (t.minute ?? 0)
36 let extraDays = Int((Double(minutes) / 1440).rounded(.down))
37 let absolute = Days.absolute(year: t.year, month: t.month, day: t.day) + extraDays
38 let date = Days.date(absolute)
39 var s = digits(date.year, 4) + "-" + digits(date.month, 2) + "-" + digits(date.day, 2) + " " + dayNames[Days.weekday(absolute)]
40 if time {
41 let inDay = minutes - extraDays * 1440
42 s += " " + digits(inDay / 60, 2) + ":" + digits(inDay % 60, 2)
43 }
44 return s
45 }
46
47 /// `%0Nd`.
48 static func digits(_ n: Int, _ width: Int) -> String {
49 let s = String(n)
50 return s.count >= width ? s : String(repeating: "0", count: width - s.count) + s
51 }
52
53 /// The timestamp as Org writes it back; nil for a diary timestamp or one Org can't read.
54 static func canonical(_ raw: String) -> String? {
55 if let canonical = parsedCanonical(raw) { return canonical }
56 guard !raw.contains("%%"), let g = groups(rawValue, raw), let dateStart = g[1], let start = parseTime(dateStart) else { return nil }
57 let active = raw.hasPrefix("<")
58 let (open, close) = active ? ("<", ">") : ("[", "]")
59 let dateEnd = g[2].flatMap(parseTime)
60 let range = groups(timeRange, dateStart).map { (Int($0[2]!)!, Int($0[3]!)!) }
61
62 var suffix = ""
63 if let r = groups(repeater, raw) {
64 suffix += " " + r[1]! + String(Int(r[2]!)!) + r[3]!
65 if let value = r[4], let unit = r[5] { suffix += "/" + String(Int(value)!) + unit }
66 }
67 if let w = groups(warning, raw) {
68 suffix += " " + (w[1] == nil ? "-" : "--") + String(Int(w[2]!)!) + w[3]!
69 }
70
71 var s = open + format(start, time: start.hour != nil && start.minute != nil)
72 let hourEnd = dateEnd?.hour ?? range?.0 ?? start.hour
73 let minuteEnd = dateEnd?.minute ?? range?.1 ?? start.minute
74 if let dateEnd {
75 var end = dateEnd
76 end.hour = hourEnd
77 end.minute = minuteEnd
78 s += suffix + close + "--" + open + format(end, time: hourEnd != nil && minuteEnd != nil)
79 } else if let hourEnd, let minuteEnd, range != nil {
80 s += String(format: "-%02d:%02d", hourEnd, minuteEnd)
81 }
82 return s + suffix + close
83 }
84
85 /// `canonical` for a timestamp `Timestamp.parse` reads, other than a date range, without
86 /// regular expressions: Org reads those the same way.
87 static func parsedCanonical(_ raw: String) -> String? {
88 if let dashes = raw.range(of: ">--<") ?? raw.range(of: "]--[") {
89 // A date range without repeaters or warnings: each end on its own, the end's time
90 // defaulting to the start's.
91 let first = raw[..<raw.index(after: dashes.lowerBound)], second = raw[raw.index(before: dashes.upperBound)...]
92 guard let a = Timestamp.parse(first), let b = Timestamp.parse(second), a.end == nil, b.end == nil,
93 a.repeater == nil, a.warning == nil, b.repeater == nil, b.warning == nil else { return nil }
94 let (open, close) = a.active ? ("<", ">") : ("[", "]")
95 let start = DateTime(year: a.start.year, month: a.start.month, day: a.start.day, hour: a.start.hour, minute: a.start.minute)
96 let end = DateTime(year: b.start.year, month: b.start.month, day: b.start.day, hour: b.start.hour ?? a.start.hour, minute: b.start.minute ?? a.start.minute)
97 return open + format(start, time: start.hour != nil && start.minute != nil) + close + "--"
98 + open + format(end, time: end.hour != nil && end.minute != nil) + close
99 }
100 guard let stamp = Timestamp.parse(raw) else { return nil }
101 let (open, close) = stamp.active ? ("<", ">") : ("[", "]")
102 let start = DateTime(year: stamp.start.year, month: stamp.start.month, day: stamp.start.day, hour: stamp.start.hour, minute: stamp.start.minute)
103 var s = open + format(start, time: start.hour != nil && start.minute != nil)
104 if let end = stamp.end, let hour = end.hour, let minute = end.minute { s += "-" + digits(hour, 2) + ":" + digits(minute, 2) }
105 if let repeater = stamp.repeater {
106 let kind = switch repeater.kind {
107 case .cumulate: "+"
108 case .catchUp: "++"
109 case .restart: ".+"
110 }
111 s += " " + kind + String(repeater.interval.value) + String(repeater.interval.unit.rawValue)
112 if let deadline = repeater.habitDeadline { s += "/" + String(deadline.value) + String(deadline.unit.rawValue) }
113 }
114 if let warning = stamp.warning {
115 s += " " + (warning.firstOccurrenceOnly ? "--" : "-") + String(warning.interval.value) + String(warning.interval.unit.rawValue)
116 }
117 return s + close
118 }
119
120 /// A clock line, trimmed, as Org writes it back; nil when Org can't read it.
121 static func canonicalClock(_ line: String) -> String? {
122 guard line.hasPrefix("CLOCK:") else { return nil }
123 let rest = line.dropFirst(6).drop { $0 == " " || $0 == "\t" }
124 guard let end = rest.firstIndex(where: { $0 == "]" || $0 == ">" }) else { return nil }
125 var stampEnd = rest.index(after: end)
126 if rest[stampEnd...].hasPrefix("--"), let second = rest[stampEnd...].firstIndex(where: { $0 == "]" || $0 == ">" }) {
127 stampEnd = rest.index(after: second)
128 }
129 guard let stamp = canonical(String(rest[..<stampEnd])) else { return nil }
130 var s = "CLOCK: " + stamp
131 if let arrow = line.range(of: "=> ") {
132 let duration = line[arrow.upperBound...].trimmingCharacters(in: .whitespaces)
133 let parts = duration.split(separator: ":", omittingEmptySubsequences: true)
134 guard !duration.isEmpty, !duration.contains(where: \.isWhitespace), parts.count >= 2 else { return nil }
135 s += " => " + pad(String(parts[0]), 2) + ":" + pad(String(parts[1]), 2)
136 }
137 return s
138 }
139
140 /// `%Ns`: padded with spaces on the left.
141 static func pad(_ s: String, _ width: Int) -> String {
142 String(repeating: " ", count: max(0, width - s.count)) + s
143 }
144}
Sources/OrgCore/Lint/Linter.swift added +209 · view
@@ -0,0 +1,209 @@
1import Foundation
2
3/// One run of the checkers over a file. The tree is walked once to collect what the checkers
4/// read; checkers that org-lint runs as regexp searches over the buffer search the text and ask
5/// the tree which element each line belongs to.
6struct Linter {
7 let text: String
8 let ns: NSString
9 let tree: OrgTree
10 let path: String?
11 let env: LintEnvironment
12 let model: DocumentModel
13 var findings: [LintFinding] = []
14
15 /// UTF-16 offset of each line's first character.
16 let lineStarts: [Int]
17 /// The innermost element each line belongs to.
18 var lineTags: [Tag]
19 /// Encrypted entry bodies, which aren't linted.
20 var excluded: [Range<Int>] = []
21
22 enum Tag: Equatable {
23 case none, other, heading, paragraph, planning, drawer, propertyDrawer, dynamicBlock
24 /// A block whose contents aren't parsed: comment, example, export, src and verse blocks.
25 case verbatimBlock
26 case block
27 }
28
29 var links: [SyntaxNode] = []
30 var footnoteReferences: [SyntaxNode] = []
31 var footnoteDefinitions: [SyntaxNode] = []
32 var targets: [SyntaxNode] = []
33 var keywords: [SyntaxNode] = []
34 var propertyDrawers: [SyntaxNode] = []
35 var drawers: [SyntaxNode] = []
36 var blocks: [SyntaxNode] = []
37 var plannings: [SyntaxNode] = []
38 var clocks: [SyntaxNode] = []
39 var timestamps: [SyntaxNode] = []
40
41 /// `#+NAME` values of elements, and `#+RESULTS` values, for fuzzy links.
42 var names: [(offset: Int, value: String)] = []
43 var resultNames: [String] = []
44
45 init(text: String, tree: OrgTree, path: String?, environment: LintEnvironment) {
46 self.text = text
47 ns = text as NSString
48 self.tree = tree
49 self.path = path
50 env = environment
51 model = DocumentModel(tree: tree)
52 var starts = [0]
53 var offset = 0
54 for unit in text.utf16 {
55 offset += 1
56 if unit == 10 { starts.append(offset) }
57 }
58 if starts.count > 1, starts.last == ns.length { starts.removeLast() }
59 lineStarts = starts
60 lineTags = Array(repeating: .none, count: starts.count)
61 }
62
63 mutating func run() {
64 excluded = encryptedBodies()
65 walk(tree.root)
66 keywordChecks()
67 linkChecks()
68 attachmentChecks()
69 duplicateChecks()
70 drawerChecks()
71 blockChecks()
72 lineChecks()
73 headingChecks()
74 propertyChecks()
75 timestampChecks()
76 footnoteChecks()
77 }
78
79 // MARK: - Lines
80
81 /// 0-based line of a UTF-16 offset.
82 func lineIndex(_ offset: Int) -> Int {
83 var low = 0, high = lineStarts.count - 1
84 while low < high {
85 let mid = (low + high + 1) / 2
86 if lineStarts[mid] <= offset { low = mid } else { high = mid - 1 }
87 }
88 return low
89 }
90
91 /// Line `index`'s text, without its line ending.
92 func line(_ index: Int) -> String {
93 let start = lineStarts[index]
94 let end = index + 1 < lineStarts.count ? lineStarts[index + 1] : ns.length
95 var s = ns.substring(with: NSRange(location: start, length: end - start))
96 while s.hasSuffix("\n") || s.hasSuffix("\r") { s.removeLast() }
97 return s
98 }
99
100 mutating func report(_ checker: LintChecker, at offset: Int, _ message: String) {
101 guard !excluded.contains(where: { $0.contains(offset) }) else { return }
102 findings.append(LintFinding(offset: offset, line: lineIndex(offset) + 1, checker: checker, message: message))
103 }
104
105 func matches(_ pattern: String, caseInsensitive: Bool = false, anchorsMatchLines: Bool = true) -> [NSTextCheckingResult] {
106 var options: NSRegularExpression.Options = []
107 if caseInsensitive { options.insert(.caseInsensitive) }
108 if anchorsMatchLines { options.insert(.anchorsMatchLines) }
109 let regex = try! NSRegularExpression(pattern: pattern, options: options)
110 return regex.matches(in: text, range: NSRange(location: 0, length: ns.length))
111 }
112
113 func group(_ m: NSTextCheckingResult, _ i: Int) -> String? {
114 m.range(at: i).location == NSNotFound ? nil : ns.substring(with: m.range(at: i))
115 }
116
117 var folder: String? { path.map { ($0 as NSString).deletingLastPathComponent } }
118
119 // MARK: - Collecting
120
121 static let verbatimBlocks: Set<String> = ["comment", "example", "export", "src", "verse"]
122
123 /// The name after `#+begin_` on a block's first line, as written.
124 static func blockName(_ node: SyntaxNode) -> String {
125 let first = node.text.prefix { $0 != "\n" && $0 != "\r" }.drop { $0 == " " || $0 == "\t" }
126 return String(first.dropFirst("#+begin_".count).prefix { !$0.isWhitespace })
127 }
128
129 mutating func tag(_ node: SyntaxNode, _ tag: Tag) {
130 let first = lineIndex(node.range.lowerBound)
131 let last = lineIndex(max(node.range.lowerBound, node.range.upperBound - 1))
132 for i in first...last { lineTags[i] = tag }
133 }
134
135 mutating func walk(_ node: SyntaxNode) {
136 for child in node.children {
137 switch child.kind {
138 case .section, .zerothSection, .title, .linkDescription, .itemTag, .tableRow, .tableCell:
139 walk(child)
140 case .heading:
141 tag(child, .heading)
142 walk(child)
143 case .block:
144 tag(child, Self.verbatimBlocks.contains(Self.blockName(child).lowercased()) ? .verbatimBlock : .block)
145 blocks.append(child)
146 case .dynamicBlock:
147 tag(child, .dynamicBlock)
148 case .drawer:
149 tag(child, .drawer)
150 drawers.append(child)
151 walk(child)
152 case .propertyDrawer:
153 tag(child, .propertyDrawer)
154 propertyDrawers.append(child)
155 case .planning:
156 tag(child, .planning)
157 plannings.append(child)
158 case .clock:
159 tag(child, .other)
160 clocks.append(child)
161 case .paragraph:
162 tag(child, .paragraph)
163 walk(child)
164 case .keyword, .affiliatedKeyword:
165 tag(child, .other)
166 keywords.append(child)
167 case .footnoteDefinition:
168 tag(child, .other)
169 footnoteDefinitions.append(child)
170 walk(child)
171 case .link:
172 links.append(child)
173 walk(child)
174 case .footnoteReference:
175 footnoteReferences.append(child)
176 walk(child)
177 case .target:
178 targets.append(child)
179 case .timestamp:
180 timestamps.append(child)
181 case .bold, .italic, .underline, .strikeThrough, .citation, .citationReference, .superscript, .subscript, .radioTarget:
182 walk(child)
183 case .verbatim, .code, .statisticsCookie, .macro, .inlineSourceBlock, .latexFragment, .lineBreak, .entity, .exportSnippet,
184 .inlineBabelCall:
185 break
186 default:
187 tag(child, .other)
188 walk(child)
189 }
190 }
191 }
192
193 /// The bodies of entries tagged with the crypt tag that hold an armored message: from its
194 /// begin line through its end line.
195 func encryptedBodies() -> [Range<Int>] {
196 var ranges: [Range<Int>] = []
197 for (index, heading) in model.headings.enumerated() where heading.localTags.contains(env.cryptTag) {
198 let bodyEnd = model.headings.dropFirst(index + 1).first { $0.parent == index }?.sectionRange.lowerBound ?? heading.sectionRange.upperBound
199 let body = NSRange(location: heading.headingRange.upperBound, length: max(0, bodyEnd - heading.headingRange.upperBound))
200 let begin = ns.range(of: "-----BEGIN PGP MESSAGE-----", range: body)
201 guard begin.location != NSNotFound else { continue }
202 let after = NSRange(location: NSMaxRange(begin), length: NSMaxRange(body) - NSMaxRange(begin))
203 let end = ns.range(of: "-----END PGP MESSAGE-----", range: after)
204 let stop = end.location == NSNotFound ? NSMaxRange(body) : NSMaxRange(ns.lineRange(for: end))
205 ranges.append(ns.lineRange(for: begin).location..<stop)
206 }
207 return ranges
208 }
209}
Tests/OrgCoreTests/LintOracleTests.swift added +86 · view
@@ -0,0 +1,86 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// orgstar's checkers against `org-lint` in Emacs, on the same files: the same lines for every
6/// checker both have.
7struct LintOracleTests {
8 static let enabled = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil && EmacsOracle.isAvailable
9
10 static let script = #"""
11 ;;; -*- lexical-binding: t -*-
12 (require 'org)
13 (require 'org-lint)
14 (require 'json)
15 (setq org-todo-keywords '((sequence "TODO" "DONE"))
16 org-id-locations-file (make-temp-file "orgstar-id-locations"))
17 (let ((results nil))
18 (dolist (file (split-string (getenv "ORACLE_FILES") "\n" t))
19 (with-current-buffer (find-file-noselect file)
20 (org-mode)
21 (let ((lines nil))
22 (dolist (r (org-lint))
23 (let ((v (cadr r)))
24 (push (format "%s %s" (aref v 0) (org-lint-checker-name (aref v 3))) lines)))
25 (push (vconcat (nreverse lines)) results))
26 (kill-buffer)))
27 (let ((coding-system-for-write 'utf-8-unix))
28 (with-temp-file (getenv "ORACLE_OUTPUT")
29 (insert (json-encode (vconcat (nreverse results)))))))
30 """#
31
32 /// `org-lint`'s reports for each file, as "LINE CHECKER".
33 static func orgLint(_ files: [URL]) throws -> [[String]] {
34 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-lint-\(UUID().uuidString)")
35 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
36 defer { try? FileManager.default.removeItem(at: folder) }
37 let scriptURL = folder.appendingPathComponent("lint.el"), output = folder.appendingPathComponent("out.json")
38 try script.write(to: scriptURL, atomically: true, encoding: .utf8)
39 let log = try EmacsOracle.run(["-Q", "--batch", "-l", scriptURL.path],
40 environment: ["ORACLE_FILES": files.map(\.path).joined(separator: "\n"), "ORACLE_OUTPUT": output.path, "TZ": "UTC"])
41 guard let data = try? Data(contentsOf: output) else { throw EmacsOracle.EvaluateError(log: log) }
42 return try JSONDecoder().decode([[String]].self, from: data)
43 }
44
45 /// The checkers both have. Not invalid-id-link: `org-id-find-id-file` falls back to the
46 /// file being linted for an ID it doesn't know, so what org-lint reports depends on org-id's
47 /// saved locations; `idLinksResolveThroughTheIndex` covers orgstar's.
48 static let shared: Set<String> = Set(LintChecker.allCases.filter { $0.isOrgLint && $0 != .invalidIDLink }.map(\.rawValue))
49
50 static func ours(_ url: URL) throws -> [String] {
51 let text = try String(contentsOf: url, encoding: .utf8)
52 return OrgLint.lint(text, tree: OrgParser.parse(text), path: url.path).map { "\($0.line) \($0.checker.rawValue)" }
53 }
54
55 /// Both sides' reports for the checkers both have, sorted.
56 static func compare(_ files: [URL]) throws {
57 let theirs = try orgLint(files)
58 for (file, reports) in zip(files, theirs) {
59 let expected = reports.filter { shared.contains(String($0.split(separator: " ")[1])) }.sorted()
60 let actual = try ours(file).filter { shared.contains(String($0.split(separator: " ")[1])) }.sorted()
61 #expect(actual == expected, "\(file.lastPathComponent)")
62 }
63 }
64
65 static func folder(_ files: [String: String]) throws -> URL {
66 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-lint-\(UUID().uuidString)").resolvingSymlinksInPath()
67 for (name, text) in files {
68 let url = folder.appendingPathComponent(name)
69 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
70 try text.write(to: url, atomically: true, encoding: .utf8)
71 }
72 return folder
73 }
74
75 @Test(.enabled(if: enabled)) func corpusMatchesOrgLint() throws {
76 let folder = try Self.folder(LintTests.corpus.merging(["exists.org": "* Here\n", "data/ab/cdef/photo.png": ""]) { $1 })
77 defer { try? FileManager.default.removeItem(at: folder) }
78 try Self.compare(LintTests.corpus.keys.sorted().map { folder.appendingPathComponent($0) })
79 }
80
81 @Test(.enabled(if: enabled)) func conformanceFilesMatchOrgLint() throws {
82 let folder = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Conformance")
83 let files = try FileManager.default.contentsOfDirectory(atPath: folder.path).filter { $0.hasSuffix(".org") }.sorted()
84 try Self.compare(files.map { folder.appendingPathComponent($0) })
85 }
86}
Tests/OrgCoreTests/LintTests.swift added +396 · view
@@ -0,0 +1,396 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5struct LintTests {
6 /// Files with problems of most kinds, which `LintOracleTests` also runs through org-lint.
7 static let corpus: [String: String] = [
8 "links.org": """
9 #+TITLE: Links
10 * Heading one
11 :PROPERTIES:
12 :CUSTOM_ID: one
13 :ID: abc::def
14 :END:
15 SCHEDULED: <2026-11-26 Thu>
16 Link [[*Missing heading]] and [[*Heading one]] and [[#nope]] and [[#one]].
17 [[id:00000000-dead]] and [[file:nofile.org]] and [[./exists.org]] and [[id:abc::def]].
18 <2026-11-26 Mon> <2026-11-26> <2026-11-26 Thu 9:00> <2026-02-30 Mon> <2026-11-26 Thu 25:00> [2026-11-26 Thu 10:00-11:00]
19 <2026-11-26 Thu 9am> <2026-11-26 Thu 10:00>--<2026-11-27 Fri> <2026-11-26 Thu +1w -2d> <2026-11-26 Thu .+2d/3d>
20 Footnote[fn:1] and [fn:missing] and [fn:: anon] and [fn:named: inline] and [fn:named].
21 * Second
22 :PROPERTIES:
23 :CUSTOM_ID: one
24 :END:
25 #+NAME: tbl
26 | a |
27
28 #+NAME: tbl
29 | b <2026-11-26> |
30 <<target>> <<target>> <<My Target>>
31 [[my target]] [[tbl]] [[TBL]] [[second]] [[*second]] [[Heading one]] [[nowhere]]
32 [[(here)]] [[(nothere)]] [[file+sys:./exists.org]] [[attachment:nothing.png]]
33 #+BEGIN_SRC emacs-lisp
34 (foo) (ref:here)
35 #+END_SRC
36 * COMMENT Commented [1/2]
37 [[Commented]] [[*commented]]
38 * TODO [#A] Task title :tag:
39 [[Task title]] [[*TODO Task title]]
40 [fn:1] Def.
41 [fn:2] Unused.
42 [fn:1] Dup.
43 """,
44 "structure.org": """
45 #+CATEGORY: one
46 #+CATEGORY: two
47 #+SETUPFILE: missing-setup.org
48 #+TITLE no colon
49 #+CAPTION: orphan
50
51 * QUOTE old section
52 * Tags :a::b:
53 * Planning
54 SCHEDULED: <2026-11-26 Thu +1w> DEADLINE: <2026-11-27 Fri +2d>
55 * Inactive
56 SCHEDULED: [2026-11-26 Thu]
57 * Repeaters same
58 SCHEDULED: <2026-11-26 Thu +1w> DEADLINE: <2026-11-27 Fri +1w>
59 * Body
60 Text here
61 :PROPERTIES:
62 :A: b
63 :END:
64 %%(diary-date 1 1 2026) indented
65 #+BEGIN_EXPORT
66 x
67 #+END_EXPORT
68 #+BEGIN_HTML
69 <b>x</b>
70 #+END_HTML
71 :OUTER:
72 :INNER:
73 x
74 :END:
75 #+BEGIN_EXAMPLE
76 x
77 #+END_EXAMPLE trailing
78 Paragraph ** Oops heading
79 #+SRCNAME: old
80 #+BEGIN_SRC sh
81 echo
82 #+END_SRC
83 #+BEGIN_SRC
84 #+END_SRC
85 :PROPERTIES:
86 :EFFORT: abc
87 :END:
88 * Effort
89 :PROPERTIES:
90 :EFFORT: abc
91 :Effort: def
92 :TODO: x
93 :ID:
94 :END:
95 CLOCK: [2026-11-26 Thu 9:00]--[2026-11-26 Thu 10:00] => 1:00
96 CLOCK: [2026-11-26 Thu 09:00]--[2026-11-26 Thu 10:00] => 1:00
97 CLOCK: [2026-11-26 Thu 09:00]--[2026-11-26 Thu 10:00] => 1:00
98 :LOGBOOK:
99 text
100 * [#Z] Priority
101 * [#a] Lower
102 * [#1 Unclosed
103 * TODOX Unknown keyword
104 ** Heading after
105 :drawer:
106 #+BEGIN_SRC sh
107 :inner:
108 #+END_SRC
109 :END:
110 #+BEGIN_QUOTE
111 never closed
112 :END:
113 DEADLINE: <2026-11-26 Thu>
114 """,
115 ]
116
117 static func lint(_ text: String, path: String? = nil, environment: LintEnvironment = .fileSystem, defaults: OrgSettings = .default) -> [LintFinding] {
118 OrgLint.lint(text, tree: OrgParser.parse(text, defaults: defaults), path: path, environment: environment)
119 }
120
121 /// The lines `checker` reports in `text`.
122 static func lines(_ checker: LintChecker, _ text: String, path: String? = nil, environment: LintEnvironment = .fileSystem) -> [Int] {
123 lint(text, path: path, environment: environment).filter { $0.checker == checker }.map(\.line)
124 }
125
126 /// A file system holding only `files` (absolute paths; folders end in `/`).
127 static func environment(_ files: Set<String>, ids: [String: [String]]? = nil) -> LintEnvironment {
128 var idFiles: (@Sendable (String) -> [String])?
129 if let ids { idFiles = { ids[$0] ?? [] } }
130 return LintEnvironment(
131 fileExists: { path in files.contains(path) || files.contains(path + "/") },
132 isDirectory: { files.contains($0 + "/") },
133 contentsOfDirectory: { dir in
134 Array(Set(files.compactMap { file -> String? in
135 guard file.hasPrefix(dir + "/") else { return nil }
136 return file.dropFirst(dir.count + 1).split(separator: "/").first.map(String.init)
137 }))
138 },
139 readFile: { _ in nil },
140 idFiles: idFiles
141 )
142 }
143
144 // MARK: - Links
145
146 @Test func fuzzyLinks() {
147 let text = "* Heading one\n<<Target here>>\n#+NAME: tbl\n| a |\n\n[[*Heading one]] [[heading ONE]] [[target here]] [[tbl]]\n[[*Nope]] [[TBL]] [[*Target here]]\n"
148 #expect(Self.lines(.invalidFuzzyLink, text) == [7, 7, 7])
149 }
150
151 @Test func customIDLinks() {
152 let text = "* A\n:PROPERTIES:\n:CUSTOM_ID: a\n:ID: uuid-1\n:END:\n[[#a]] [[#uuid-1]]\n[[#b]]\n"
153 #expect(Self.lines(.invalidCustomIDLink, text) == [7])
154 }
155
156 @Test func idLinksResolveThroughTheIndex() {
157 let text = ":PROPERTIES:\n:ID: file-id\n:END:\n* A\n:PROPERTIES:\n:ID: here\n:END:\n[[id:here]] [[id:file-id]] [[id:there]]\n[[id:nowhere]]\n"
158 let environment = Self.environment([], ids: ["there": ["/notes/other.org"]])
159 #expect(Self.lines(.invalidIDLink, text, environment: environment) == [9])
160 #expect(Self.lines(.invalidIDLink, text, environment: Self.environment([])) == [8, 9])
161 }
162
163 @Test func coderefLinks() {
164 let text = "#+BEGIN_SRC sh\necho (ref:one)\n#+END_SRC\n[[(one)]]\n[[(two)]]\n"
165 #expect(Self.lines(.invalidCoderefLink, text) == [5])
166 }
167
168 @Test func fileLinks() {
169 let environment = Self.environment(["/notes/a.org", "/notes/sub/"])
170 let text = "[[file:a.org]] [[./sub]] [[file:/ssh:host:/x]]\n[[file:missing.org]] [[~/nowhere-at-all]]\n"
171 #expect(Self.lines(.linkToLocalFile, text, path: "/notes/x.org", environment: environment) == [2, 2])
172 #expect(Self.lines(.linkToLocalFile, text, path: nil, environment: environment).isEmpty)
173 }
174
175 @Test func fileSearchLinks() {
176 var environment = Self.environment(["/notes/a.org"])
177 environment.readFile = { _ in "* Alpha\n:PROPERTIES:\n:CUSTOM_ID: al\n:END:\n<<tgt>>\n" }
178 let text = "[[file:a.org::*Alpha]] [[file:a.org::#al]] [[file:a.org::tgt]] [[file:a.org::12]]\n[[file:a.org::*Beta]] [[file:a.org::#be]]\n"
179 #expect(Self.lines(.invalidFileSearch, text, path: "/notes/x.org", environment: environment) == [2, 2])
180 }
181
182 @Test func fileApplicationLinks() {
183 #expect(Self.lines(.fileApplication, "[[file:a.org]]\n[[file+sys:a.org]] [[file+emacs:b.org]]\n") == [2, 2])
184 }
185
186 @Test func attachmentLinks() {
187 let environment = Self.environment(["/notes/data/ab/cdef/", "/notes/data/ab/cdef/one.png"])
188 let text = "* A :ATTACH:\n:PROPERTIES:\n:ID: abcdef\n:END:\n[[attachment:one.png]]\n[[attachment:two.png]]\n"
189 let findings = Self.lint(text, path: "/notes/x.org", environment: environment).filter { $0.checker == .linkToLocalFile }
190 #expect(findings.map(\.line) == [6])
191 #expect(findings.first?.message == "Link to non-existent local file \"/notes/data/ab/cdef/two.png\"")
192 }
193
194 // MARK: - Attachments
195
196 @Test func attachTagWithoutFolder() {
197 let environment = Self.environment(["/notes/data/ab/cdef/"])
198 let text = "* A :ATTACH:\n:PROPERTIES:\n:ID: abcdef\n:END:\n* B :ATTACH:\n:PROPERTIES:\n:ID: abcxyz\n:END:\n* C :ATTACH:\n"
199 #expect(Self.lines(.missingAttachmentFolder, text, path: "/notes/x.org", environment: environment) == [5, 9])
200 }
201
202 @Test func attachmentFoldersWithoutEntries() {
203 let files: Set<String> = ["/notes/data/", "/notes/data/ab/", "/notes/data/ab/cdef/", "/notes/data/ab/zzzz/", "/notes/data/ab/yyyy/",
204 "/notes/data/__/", "/notes/data/__/q/", "/notes/data/__/q/qq/"]
205 let environment = Self.environment(files, ids: ["abyyyy": ["/notes/other.org"], "abzzzz": ["/notes/x.org"]])
206 let text = "* A\n:PROPERTIES:\n:ID: abcdef\n:END:\n"
207 let findings = Self.lint(text, path: "/notes/x.org", environment: environment).filter { $0.checker == .orphanedAttachmentFolder }
208 #expect(findings.map(\.message) == ["Attachment folder \"data/__/q/qq\" belongs to no entry", "Attachment folder \"data/ab/zzzz\" belongs to no entry"])
209 #expect(findings.allSatisfy { $0.line == 1 })
210 // Without an index there is nothing to tell an orphan from another file's folder.
211 #expect(Self.lines(.orphanedAttachmentFolder, text, path: "/notes/x.org", environment: Self.environment(files)).isEmpty)
212 }
213
214 // MARK: - Duplicates
215
216 @Test func duplicateIDs() {
217 let text = "* A\n:PROPERTIES:\n:ID: one\n:END:\n* B\n:PROPERTIES:\n:ID: one\n:END:\n* C\n:PROPERTIES:\n:ID: two\n:END:\n* D\n:PROPERTIES:\n:ID: three\n:END:\n"
218 let findings = Self.lint(text, path: "/notes/x.org", environment: Self.environment([], ids: ["two": ["/notes/y.org", "/notes/x.org"]]))
219 .filter { $0.checker == .duplicateID }
220 #expect(findings.map(\.line) == [3, 7, 11])
221 #expect(findings.last?.message == "Duplicate ID \"two\", also in y.org")
222 }
223
224 @Test func duplicateCustomIDsNamesTargetsAndFootnotes() {
225 let text = "* A\n:PROPERTIES:\n:CUSTOM_ID: x\n:END:\n* B\n:PROPERTIES:\n:custom_id: x\n:END:\n#+NAME: n\n| 1 |\n\n#+NAME: n\n| 2 |\n\n<<t>> <<u>>\n<<t>>\n[fn:1] a\n[fn:1] b\n[fn:2] c\n"
226 let findings = Self.lint(text)
227 #expect(findings.filter { $0.checker == .duplicateCustomID }.map(\.line) == [3, 7])
228 #expect(findings.filter { $0.checker == .duplicateName }.map(\.line) == [9, 12])
229 #expect(findings.filter { $0.checker == .duplicateTarget }.map(\.line) == [15, 16])
230 #expect(findings.filter { $0.checker == .duplicateFootnoteDefinition }.map(\.line) == [17, 18])
231 }
232
233 // MARK: - Drawers and blocks
234
235 @Test func drawers() {
236 let text = "* A\n:LOGBOOK:\n- a\n:END:\n:NOTES:\nopen\n* B\n:OUTER:\n:INNER:\n:END:\n#+BEGIN_SRC sh\n:SRC:\n#+END_SRC\n"
237 let findings = Self.lint(text).filter { $0.checker == .incompleteDrawer }
238 #expect(findings.map(\.line) == [5, 9])
239 #expect(findings.map(\.message) == ["Possible incomplete drawer \":NOTES:\"", "Possible misleading drawer entry \":INNER:\""])
240 }
241
242 @Test func propertyDrawers() {
243 let text = "* A\n:PROPERTIES:\n:A: 1\n:END:\nText\n:PROPERTIES:\n:B: 2\n:END:\n* B\n:PROPERTIES:\n:C: 3\n\n:END:\n"
244 #expect(Self.lines(.obsoletePropertiesDrawer, text) == [6, 10])
245 }
246
247 @Test func blocks() {
248 let text = "#+BEGIN_SRC sh\nx\n#+END_SRC\n#+BEGIN_QUOTE\nopen\n#+END_SRC trailing\n#+BEGIN: clocktable\n#+END:\n"
249 let findings = Self.lint(text).filter { $0.checker == .invalidBlock }
250 #expect(findings.map(\.line) == [4, 6])
251 #expect(findings.map(\.message) == ["Possible incomplete block \"#+BEGIN_QUOTE\"", "Invalid block closing line \"#+END_SRC trailing\""])
252 }
253
254 @Test func blockLanguagesAndBackends() {
255 let text = "#+BEGIN_SRC python\n#+END_SRC\n#+BEGIN_SRC :results none\n#+END_SRC\n#+BEGIN_EXPORT html\n#+END_EXPORT\n#+BEGIN_EXPORT\n#+END_EXPORT\n#+BEGIN_LATEX\n#+END_LATEX\n#+BEGIN_NOTE\n#+END_NOTE\n"
256 let findings = Self.lint(text)
257 #expect(findings.filter { $0.checker == .missingLanguageInSrcBlock }.map(\.line) == [3])
258 #expect(findings.filter { $0.checker == .missingBackendInExportBlock }.map(\.line) == [7])
259 #expect(findings.filter { $0.checker == .deprecatedExportBlocks }.map(\.line) == [9])
260 }
261
262 @Test func misplacedPlanning() {
263 let text = "* A\nSCHEDULED: <2026-11-26 Thu>\n* B\nText\nDEADLINE: <2026-11-26 Thu>\n#+BEGIN_EXAMPLE\nCLOSED: [2026-11-26 Thu]\n#+END_EXAMPLE\n* C\n:PROPERTIES:\n:A: b\n:END:\nscheduled: later\n"
264 #expect(Self.lines(.misplacedPlanningInfo, text) == [5, 13])
265 }
266
267 @Test func misplacedHeadings() {
268 #expect(Self.lines(.misplacedHeading, "* A\nText** Oops\nText ** fine\n,** escaped\n#+BEGIN_SRC sh\nx** y\n#+END_SRC\n") == [2])
269 }
270
271 @Test func indentedDiarySexps() {
272 #expect(Self.lines(.indentedDiarySexp, "%%(diary-float t 4 2)\n %%(diary-float t 4 2)\n#+BEGIN_SRC sh\n %%(x)\n#+END_SRC\n") == [2])
273 }
274
275 @Test func keywordSyntax() {
276 let text = "#+TITLE: fine\n#+TITLE wrong\n#+CAPTION[short]: long\n#+BEGIN_SRC sh\n#+END_SRC\n#+\n"
277 #expect(Self.lines(.invalidKeywordSyntax, text) == [2, 6])
278 }
279
280 @Test func affiliatedKeywords() {
281 let text = "#+CAPTION: orphan\n\n#+NAME: fine\n#+TBLNAME: old\n| a |\n#+RESULTS:\n\n#+ATTR_HTML: :width 10\n* H\n"
282 let findings = Self.lint(text)
283 #expect(findings.filter { $0.checker == .orphanedAffiliatedKeywords }.map(\.line) == [1, 8])
284 #expect(findings.filter { $0.checker == .obsoleteAffiliatedKeywords }.map(\.message) == ["Obsolete affiliated keyword: \"TBLNAME\". Use \"NAME\" instead"])
285 }
286
287 @Test func categoriesAndSetupFiles() {
288 let environment = Self.environment(["/notes/setup.org"])
289 let text = "#+CATEGORY: a\n#+SETUPFILE: setup.org\n#+SETUPFILE: \"missing.org\"\n#+SETUPFILE: https://example.com/x.org\n#+CATEGORY: b\n"
290 let findings = Self.lint(text, path: "/notes/x.org", environment: environment)
291 #expect(findings.filter { $0.checker == .deprecatedCategorySetup }.map(\.line) == [5])
292 #expect(findings.filter { $0.checker == .nonExistentSetupfileParameter }.map(\.message) == ["Non-existent setup file \"missing.org\""])
293 }
294
295 // MARK: - Headings and properties
296
297 @Test func unknownTodoKeywords() {
298 var defaults = OrgSettings.default
299 defaults.todoSequences = [TodoSequence(kind: .sequence, active: [TodoKeyword(name: "TODO"), TodoKeyword(name: "WAIT")], done: [TodoKeyword(name: "DONE")])]
300 let text = "* TODO Known\n* WAIT From the config\n* NEXT Unknown\n* TODOX Typo\n* FAQ Questions\n* README\n* DONT x\n* COMMENT x\n"
301 let findings = Self.lint(text, defaults: defaults).filter { $0.checker == .unknownTodoKeyword }
302 #expect(findings.map(\.line) == [3, 4, 7])
303 // The file's own keywords count.
304 #expect(Self.lines(.unknownTodoKeyword, "#+TODO: NEXT | DONE\n* NEXT a\n* TODO b\n") == [3])
305 }
306
307 @Test func priorities() {
308 let text = "* [#A] Fine\n* [#Z] Out\n* [#a] Lower\n* [#1 Unclosed\n* TODO [#B] Fine\n* [#AA] Two\n"
309 let findings = Self.lint(text).filter { $0.checker == .priority }
310 #expect(findings.map(\.message) == ["Out-of-bounds priority 'Z'", "Malformed priority '[#1 Unclosed'", "Invalid priority 'AA'"])
311 }
312
313 @Test func headingTags() {
314 let text = "* A :x:y:\n* B :x::y:\n* QUOTE Old\n* COMMENT QUOTE Older\n* QUOTE\n"
315 let findings = Self.lint(text)
316 #expect(findings.filter { $0.checker == .spuriousColons }.map(\.line) == [2])
317 #expect(findings.filter { $0.checker == .quoteSection }.map(\.line) == [3, 4])
318 }
319
320 @Test func properties() {
321 let text = "* A\n:PROPERTIES:\n:EFFORT: 1:30\n:EFFORT: 2h 30min\n:EFFORT: soon\n:EFFORT: 15\n:Effort: soon\n:TODO: x\n:Scheduled: y\n:ID: a::b\n:ID: ab\n:END:\n"
322 let findings = Self.lint(text)
323 #expect(findings.filter { $0.checker == .invalidEffortProperty }.map(\.line) == [5, 6])
324 #expect(findings.filter { $0.checker == .specialPropertyInPropertiesDrawer }.map(\.line) == [8, 9])
325 #expect(findings.filter { $0.checker == .invalidIDProperty }.map(\.line) == [10])
326 }
327
328 // MARK: - Timestamps
329
330 @Test func timestamps() {
331 let fine = ["<2026-11-26 Thu>", "[2026-11-26 Thu 09:00]", "<2026-11-26 Thu 10:00-11:00>", "<2026-11-26 Thu>--<2026-11-27 Fri>",
332 "<2026-11-26 Thu +1w -2d>", "<2026-11-26 Thu .+2d/3d>", "<2026-11-26 Thu ++1m --3d>", "<%%(diary-float t 4 2)>"]
333 for stamp in fine {
334 #expect(Self.lines(.timestampSyntax, "Text \(stamp)\n").isEmpty, "\(stamp)")
335 }
336 let malformed: [(String, String)] = [
337 ("<2026-11-26>", "<2026-11-26 Thu>"), ("<2026-11-26 Mon>", "<2026-11-26 Thu>"), ("<2026-11-26 Thu 9:00>", "<2026-11-26 Thu 09:00>"),
338 ("<2026-02-30 Mon>", "<2026-03-02 Mon>"), ("<2026-11-26 Thu 25:00>", "<2026-11-27 Fri 01:00>"), ("<2026-11-26 Thu 9am>", "<2026-11-26 Thu>"),
339 ("<2026-11-26 Thu 10:00>--<2026-11-27 Fri>", "<2026-11-26 Thu 10:00>--<2026-11-27 Fri 10:00>"),
340 ]
341 for (stamp, parsed) in malformed {
342 let findings = Self.lint("Text \(stamp)\n").filter { $0.checker == .timestampSyntax }
343 #expect(findings.map(\.message) == ["Potentially malformed timestamp \(stamp). Parsed as: \(parsed)"])
344 }
345 // Planning lines are checked by the planning checkers only.
346 #expect(Self.lines(.timestampSyntax, "* A\nSCHEDULED: <2026-11-26>\n").isEmpty)
347 }
348
349 @Test func clocks() {
350 let text = "* A\n:LOGBOOK:\nCLOCK: [2026-11-26 Thu 09:00]--[2026-11-26 Thu 10:00] => 1:00\nCLOCK: [2026-11-26 Thu 09:00]--[2026-11-26 Thu 10:00] => 1:00\nCLOCK: [2026-11-26 Thu 9:00]\nCLOCK: [2026-11-26 Thu 09:00]\n:END:\n"
351 #expect(Self.lines(.clockSyntax, text) == [4, 5])
352 }
353
354 @Test func planning() {
355 let text = "* A\nSCHEDULED: [2026-11-26 Thu]\n* B\nDEADLINE: [2026-11-26 Thu]\n* C\nSCHEDULED: <2026-11-26 Thu +1w> DEADLINE: <2026-11-27 Fri ++2d>\n* D\nSCHEDULED: <2026-11-26 Thu +1w> DEADLINE: <2026-11-27 Fri +1w>\n* E\nSCHEDULED: <2026-11-26 Thu .+1w> DEADLINE: <2026-11-27 Fri +2d>\n"
356 let findings = Self.lint(text)
357 #expect(findings.filter { $0.checker == .planningInactive }.map(\.line) == [2, 4])
358 #expect(findings.filter { $0.checker == .mismatchedPlanningRepeaters }.map(\.line) == [6])
359 }
360
361 // MARK: - Footnotes
362
363 @Test func footnotes() {
364 let text = "Text[fn:1] [fn:2] [fn:in: inline] [fn:in] [fn:: anonymous] [fn:gone]\n\n[fn:1] One.\n[fn:3] Three.\n"
365 let findings = Self.lint(text)
366 #expect(findings.filter { $0.checker == .undefinedFootnoteReference }.map(\.message) == ["Missing definition for footnote [2]", "Missing definition for footnote [gone]"])
367 #expect(findings.filter { $0.checker == .unreferencedFootnoteDefinition }.map(\.line) == [4])
368 }
369
370 // MARK: - Whole file
371
372 @Test func encryptedEntriesAreSkipped() {
373 let text = "* Secret :crypt:\n-----BEGIN PGP MESSAGE-----\n\n#+BEGIN_QUOTE\n:DRAWER:\n-----END PGP MESSAGE-----\n* Open\n#+BEGIN_QUOTE\n"
374 #expect(Self.lint(text).map(\.line) == [8])
375 }
376
377 @Test func findingsAreInFileOrderWithLines() {
378 let text = "[[#b]]\r\n* A\r\n[[#a]]\r\n"
379 let findings = Self.lint(text)
380 #expect(findings.map(\.line) == [1, 3])
381 #expect(findings.map(\.offset) == [0, 13])
382 #expect(findings.allSatisfy { $0.trust == .high })
383 #expect(Self.lint("").isEmpty)
384 }
385
386 /// Entries with planning, properties, logbooks, links and footnotes that are all fine. The
387 /// performance gates time Lint File on 1 MB files.
388 @Test func wellFormedEntries() {
389 var text = "#+TITLE: Large\n"
390 for i in 0..<500 {
391 text += "* TODO Entry \(i) [1/2] :tag:\nSCHEDULED: <2026-11-26 Thu>\n:PROPERTIES:\n:ID: id-\(i)\n:CUSTOM_ID: c\(i)\n:END:\n:LOGBOOK:\nCLOCK: [2026-11-26 Thu 09:00]--[2026-11-26 Thu 10:00] => 1:00\n:END:\n"
392 text += "Body with [[#c\(i)]], [[id:id-\(i)]], [[*Entry \(i)]] and a note[fn:\(i)].\n- item one\n- item two <2026-11-27 Fri>\n\n[fn:\(i)] Note \(i).\n\n"
393 }
394 #expect(Self.lint(text).isEmpty)
395 }
396}
Tests/OrgEditorAppKitTests/GateTests.swift +9 · view
@@ -1,5 +1,6 @@
11import AppKit
22import Foundation
3import OrgCore
34import OrgDocument
45import Testing
56@testable import OrgEditorAppKit
@@ -131,6 +132,14 @@ struct GateTests {
131132 #expect(result.newlineP95 < .milliseconds(16), "\(name): blank line")
132133 #expect(result.memoryRatio < memoryLimit, "\(name): memory")
133134 }
135 // Lint File, which runs off the main thread: the fastest of three runs on a parsed file.
136 for (name, text, _) in inputs {
137 let tree = OrgParser.parse(text)
138 let clock = ContinuousClock()
139 let lint = (0..<3).map { _ in clock.measure { _ = OrgLint.lint(text, tree: tree, path: nil) } }.min()!
140 print("GATE \(name) (\(text.utf8.count / 1000) kB): lint \(lint)")
141 #expect(lint < .milliseconds(500) * max(1, Double(text.utf8.count) / 1_000_000), "\(name): lint")
142 }
134143 let large = measure("10 MB mixed document", Self.tenMegabytes)
135144 print("GATE \(large)")
136145 #expect(large.open < .milliseconds(1_500), "10 MB: open")
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