Sources/OrgCore/Lint/LintCheckers.swift

f24016fbc9384e5bae26abb48db212a9330b488b
orgstar/Sources/OrgCore/Lint/LintCheckers.swift

584 lines · 33358 bytes

  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}
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