Sources/OrgCore/Lint/LintCheckers.swift

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

585 lines · 33452 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                       folder: (root as NSString).appendingPathComponent(candidate.relative))
230            }
231        }
232    }
233
234    // MARK: - Duplicates
235
236    mutating func duplicateChecks() {
237        func reportDuplicates(_ items: [(offset: Int, key: String)], _ checker: LintChecker, _ message: (String) -> String) {
238            var counts: [String: Int] = [:]
239            for item in items { counts[item.key, default: 0] += 1 }
240            for item in items where counts[item.key]! > 1 { report(checker, at: item.offset, message(item.key)) }
241        }
242        var ids: [(offset: Int, key: String)] = []
243        var customIDs: [(offset: Int, key: String)] = []
244        for drawer in propertyDrawers {
245            for node in drawer.children {
246                guard let property = Property(line: node.text), !property.additive, !property.value.isEmpty else { continue }
247                switch property.key.uppercased() {
248                case "ID": ids.append((node.range.lowerBound, property.value))
249                case "CUSTOM_ID": customIDs.append((node.range.lowerBound, property.value))
250                default: break
251                }
252            }
253        }
254        reportDuplicates(customIDs, .duplicateCustomID) { "Duplicate CUSTOM_ID property \"\($0)\"" }
255        reportDuplicates(names.map { ($0.offset, $0.value) }, .duplicateName) { "Duplicate NAME \"\($0)\"" }
256        reportDuplicates(targets.map { ($0.range.lowerBound, Self.words(String($0.text.dropFirst(2).dropLast(2))).joined(separator: " ")) }, .duplicateTarget) {
257            "Duplicate target <<\($0)>>"
258        }
259        reportDuplicates(footnoteDefinitions.compactMap { node in Self.definitionLabel(node).map { (node.range.lowerBound, $0) } }, .duplicateFootnoteDefinition) {
260            "Duplicate footnote definition \"\($0)\""
261        }
262        var counts: [String: Int] = [:]
263        for id in ids { counts[id.key, default: 0] += 1 }
264        var elsewhere: [String: [String]] = [:]
265        for id in ids where elsewhere[id.key] == nil {
266            elsewhere[id.key] = (env.idFiles?(id.key) ?? []).filter { $0 != path }.map { ($0 as NSString).lastPathComponent }
267        }
268        for id in ids {
269            let others = Array(Set(elsewhere[id.key]!)).sorted()
270            guard counts[id.key]! > 1 || !others.isEmpty else { continue }
271            report(.duplicateID, at: id.offset, "Duplicate ID \"\(id.key)\"" + (others.isEmpty ? "" : ", also in \(others.joined(separator: ", "))"))
272        }
273    }
274
275    // MARK: - Drawers and blocks
276
277    mutating func drawerChecks() {
278        var drawerEnds: [Int: Int] = [:]
279        for node in drawers + propertyDrawers {
280            drawerEnds[lineIndex(node.range.lowerBound)] = lineIndex(node.range.upperBound - 1)
281        }
282        let pattern = "^[ \\t]*:((?:\\w|[-_])+):[ \\t]*$"
283        let lines = matches(pattern).map { lineIndex($0.range.location) }
284        var skipUntil = -1
285        var k = 0
286        while k < lines.count {
287            let line = lines[k]
288            k += 1
289            guard line > skipUntil else { continue }
290            switch lineTags[line] {
291            case .drawer where drawerEnds[line] != nil:
292                let end = drawerEnds[line]!
293                while k < lines.count, lines[k] < end {
294                    report(.incompleteDrawer, at: lineStarts[lines[k]], "Possible misleading drawer entry \"\(self.line(lines[k]).trimmingCharacters(in: .whitespaces))\"")
295                    k += 1
296                }
297                skipUntil = end
298            case .propertyDrawer where drawerEnds[line] != nil:
299                skipUntil = drawerEnds[line]!
300            case .verbatimBlock:
301                break
302            default:
303                report(.incompleteDrawer, at: lineStarts[line], "Possible incomplete drawer \"\(self.line(line).trimmingCharacters(in: .whitespaces))\"")
304            }
305        }
306
307        for node in drawers where line(lineIndex(node.range.lowerBound)).trimmingCharacters(in: .whitespaces) == ":PROPERTIES:" {
308            report(.obsoletePropertiesDrawer, at: node.range.lowerBound, "Incorrect location for PROPERTIES drawer")
309        }
310        // `org-property-drawer-re`: only `:KEY:` lines between the first and the last.
311        for node in propertyDrawers {
312            let first = lineIndex(node.range.lowerBound), last = lineIndex(node.range.upperBound - 1)
313            if (first + 1..<last).contains(where: { !Self.isPropertyLine(line($0)) }) {
314                report(.obsoletePropertiesDrawer, at: node.range.lowerBound, "Incorrect contents for PROPERTIES drawer")
315            }
316        }
317    }
318
319    /// `[ \t]*:\S+:([ \t].*)?`, a line `org-property-drawer-re` allows: the first run of
320    /// non-blanks after the colon is at least two long and ends in a colon.
321    static func isPropertyLine(_ line: String) -> Bool {
322        let rest = line.drop { $0 == " " || $0 == "\t" }
323        guard rest.first == ":" else { return false }
324        let run = rest.dropFirst().prefix { !$0.isWhitespace }
325        return run.count >= 2 && run.last == ":"
326    }
327
328    static let deprecatedExportBlocks: Set<String> = ["ASCII", "BEAMER", "HTML", "LATEX", "MAN", "MARKDOWN", "MD", "ODT", "ORG", "TEXINFO"]
329
330    mutating func blockChecks() {
331        for m in matches("^[ \\t]*#\\+(BEGIN|END)(?::|_\\S*)?[ \\t]*", caseInsensitive: true) {
332            let index = lineIndex(m.range.location)
333            let name = line(index).trimmingCharacters(in: .whitespaces)
334            let lineEnd = lineStarts[index] + (line(index) as NSString).length
335            if group(m, 1)!.uppercased() == "END", NSMaxRange(m.range) < lineEnd {
336                report(.invalidBlock, at: lineStarts[index], "Invalid block closing line \"\(name)\"")
337            } else if ![.block, .verbatimBlock, .dynamicBlock].contains(lineTags[index]) {
338                report(.invalidBlock, at: lineStarts[index], "Possible incomplete block \"\(name)\"")
339            }
340        }
341        for node in blocks {
342            let name = Self.blockName(node)
343            let first = node.text.prefix { $0 != "\n" && $0 != "\r" }.drop { $0 == " " || $0 == "\t" }
344            let parameters = first.dropFirst("#+begin_".count + name.count).trimmingCharacters(in: .whitespaces)
345            switch name.lowercased() {
346            case "src":
347                if parameters.isEmpty || parameters.hasPrefix(":") || parameters.hasPrefix("-") || parameters.hasPrefix("+") {
348                    report(.missingLanguageInSrcBlock, at: node.range.lowerBound, "Missing language in source block")
349                }
350            case "export":
351                if parameters.isEmpty { report(.missingBackendInExportBlock, at: node.range.lowerBound, "Missing backend in export block") }
352            case let lower where Self.deprecatedExportBlocks.contains(lower.uppercased()):
353                report(.deprecatedExportBlocks, at: node.range.lowerBound, "Deprecated syntax for export block.  Use \"BEGIN_EXPORT \(name)\" instead")
354            default:
355                break
356            }
357        }
358    }
359
360    // MARK: - Lines org-lint searches for
361
362    mutating func lineChecks() {
363        for m in matches("^[ \\t]*(?:CLOSED|DEADLINE|SCHEDULED):", caseInsensitive: true) {
364            let index = lineIndex(m.range.location)
365            if ![.planning, .verbatimBlock].contains(lineTags[index]) {
366                report(.misplacedPlanningInfo, at: lineStarts[index], "Misplaced planning info line")
367            }
368        }
369        for m in matches("^[ \\t]+%%\\(") {
370            let index = lineIndex(m.range.location)
371            if lineTags[index] != .verbatimBlock { report(.indentedDiarySexp, at: lineStarts[index], "Possible indented diary-sexp") }
372        }
373        let dual = try! NSRegularExpression(pattern: "^[ \\t]*#\\+(?:CAPTION|RESULTS)(\\[.*\\])?:(?: |$)", options: .caseInsensitive)
374        for m in matches("^[ \\t]*#\\+([^\\s:]*)(?: |$)") {
375            let name = group(m, 1)!
376            let upper = name.uppercased()
377            if upper.hasPrefix("BEGIN") || upper.hasPrefix("END") { continue }
378            let index = lineIndex(m.range.location)
379            let content = line(index)
380            if dual.firstMatch(in: content, range: NSRange(location: 0, length: (content as NSString).length)) != nil { continue }
381            report(.invalidKeywordSyntax, at: m.range.location, "Possible missing colon in keyword \"\(name)\"")
382        }
383        for m in matches("[^*\\n\\r ,]\\*{2,} ", anchorsMatchLines: false) {
384            let index = lineIndex(NSMaxRange(m.range))
385            if [.paragraph, .heading].contains(lineTags[index]) { report(.misplacedHeading, at: m.range.location, "Possibly misplaced heading line") }
386        }
387    }
388
389    // MARK: - Headings
390
391    /// Keywords common in Org configurations: a heading starting with one the file doesn't
392    /// define is likely meant as a TODO entry.
393    static let commonKeywords: Set<String> = [
394        "TODO", "DONE", "NEXT", "WAIT", "WAITING", "HOLD", "STARTED", "STRT", "SOMEDAY", "MAYBE", "CANCELLED", "CANCELED", "CANCEL",
395        "CNCL", "KILL", "PROJ", "PROJECT", "LOOP", "IDEA", "DELEGATED", "INPROGRESS", "IN-PROGRESS", "DOING", "BLOCKED", "REVIEW",
396    ]
397
398    /// The edit distance of two words, a swap of neighbours counting one.
399    static func distance(_ a: [Character], _ b: [Character]) -> Int {
400        guard !a.isEmpty, !b.isEmpty else { return max(a.count, b.count) }
401        var d = Array(repeating: Array(repeating: 0, count: b.count + 1), count: a.count + 1)
402        for i in 0...a.count { d[i][0] = i }
403        for j in 0...b.count { d[0][j] = j }
404        for i in 1...a.count {
405            for j in 1...b.count {
406                let cost = a[i - 1] == b[j - 1] ? 0 : 1
407                d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost)
408                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) }
409            }
410        }
411        return d[a.count][b.count]
412    }
413
414    mutating func headingChecks() {
415        let known = tree.settings.todoKeywordNames
416        let priorities = tree.settings.priorities
417        for heading in model.headings {
418            let at = heading.headingRange.lowerBound
419            let title = heading.title
420            var uncommented = title
421            if uncommented == "COMMENT" { uncommented = "" } else if uncommented.hasPrefix("COMMENT ") { uncommented = String(uncommented.dropFirst(8)) }
422            if uncommented.hasPrefix("QUOTE ") { report(.quoteSection, at: at, "Deprecated QUOTE section") }
423            let words = Self.words(title)
424            if let last = words.last, last.hasPrefix(":"), last.contains("::"), last.wholeMatch(of: /:[\p{L}\p{N}_@#%:]+:/) != nil {
425                report(.spuriousColons, at: at, "Tags contain a spurious colon")
426            }
427            if let value = heading.priority {
428                // `org-priority-value-regexp` reads 0 to 64 without leading zeros; other numbers aren't a priority.
429                if let n = Int(value), String(n) != value || n > 64 {
430                    report(.priority, at: at, "Invalid priority '\(value)'")
431                } else if !Self.validPriority(value, priorities) {
432                    report(.priority, at: at, "Out-of-bounds priority '\(value)'")
433                }
434            } else if title.hasPrefix("[#"), let m = title.prefixMatch(of: /\[#([^\[\]]*)(\]*)/) {
435                // Org reads `[#a]` as a priority, case-folded, but not a valid one, and reports nothing.
436                let lowerLetter = m.1.count == 1 && m.1.first!.isASCII && m.1.first!.isLowercase && !m.2.isEmpty
437                if !lowerLetter { report(.priority, at: at, m.2.isEmpty ? "Malformed priority '\(m.0)'" : "Invalid priority '\(m.1)'") }
438            }
439            if heading.todo == nil, let word = words.first, let first = word.first, first.isASCII, first.isUppercase, word.count >= 2,
440               word.wholeMatch(of: /[A-Z][A-Z0-9_-]*[A-Z0-9]/) != nil, !known.contains(word), word != "COMMENT",
441               Self.commonKeywords.contains(word) || known.contains(where: { $0.count >= 4 && Self.distance(Array($0), Array(word)) == 1 }) {
442                report(.unknownTodoKeyword, at: at, "Unknown TODO keyword \"\(word)\"")
443            }
444        }
445    }
446
447    static func validPriority(_ value: String, _ priorities: Priorities) -> Bool {
448        if let n = Int(value), let high = Int(priorities.highest), let low = Int(priorities.lowest) { return (min(high, low)...max(high, low)).contains(n) }
449        guard Int(value) == nil, Int(priorities.highest) == nil, Int(priorities.lowest) == nil else { return false }
450        return priorities.highest <= value && value <= priorities.lowest
451    }
452
453    // MARK: - Properties
454
455    /// `org-special-properties`.
456    static let specialProperties: Set<String> = ["ALLTAGS", "BLOCKED", "CLOCKSUM", "CLOCKSUM_T", "CLOSED", "DEADLINE", "FILE", "ITEM", "PRIORITY", "SCHEDULED", "TAGS", "TIMESTAMP", "TIMESTAMP_IA", "TODO"]
457
458    /// `org-duration-p`.
459    static func isDuration(_ s: String) -> Bool {
460        ColumnView.minutes(s) != nil && s.trimmingCharacters(in: .whitespaces).wholeMatch(of: /[0-9]+(?:\.[0-9]*)?/) == nil
461    }
462
463    mutating func propertyChecks() {
464        for drawer in propertyDrawers {
465            for node in drawer.children where node.kind == .nodeProperty {
466                guard let property = Property(line: node.text) else { continue }
467                let at = node.range.lowerBound
468                if Self.specialProperties.contains(property.key.uppercased()) {
469                    report(.specialPropertyInPropertiesDrawer, at: at, "Special property \"\(property.key)\" found in a properties drawer")
470                }
471                if property.key == "EFFORT", !property.additive, !property.value.isEmpty, !Self.isDuration(property.value) {
472                    report(.invalidEffortProperty, at: at, "Invalid effort duration format: \"\(property.value)\"")
473                }
474                if property.key == "ID", property.value.contains("::") {
475                    report(.invalidIDProperty, at: at, "IDs should not include \"::\": \"\(property.value)\"")
476                }
477            }
478        }
479    }
480
481    // MARK: - Timestamps
482
483    mutating func timestampChecks() {
484        for node in timestamps {
485            let stamp = node.text
486            guard !stamp.contains("%%("), let canonical = LintTimestamp.canonical(stamp), canonical != stamp else { continue }
487            report(.timestampSyntax, at: node.range.lowerBound, "Potentially malformed timestamp \(stamp).  Parsed as: \(canonical)")
488        }
489        for node in clocks {
490            let actual = node.text.trimmingCharacters(in: .whitespacesAndNewlines)
491            guard let canonical = LintTimestamp.canonicalClock(actual), canonical != actual else { continue }
492            report(.clockSyntax, at: node.range.lowerBound, "Potentially malformed CLOCK: line \(actual).  Parsed as: \(canonical)")
493        }
494        for node in plannings {
495            // Each timestamp belongs to the keyword just before it.
496            var stamps: [String: Timestamp] = [:]
497            for child in node.children where child.kind == .timestamp {
498                let before = ns.substring(with: NSRange(location: node.range.lowerBound, length: child.range.lowerBound - node.range.lowerBound))
499                    .trimmingCharacters(in: .whitespaces)
500                guard let keyword = ["SCHEDULED", "DEADLINE", "CLOSED"].first(where: { before.hasSuffix($0 + ":") }), stamps[keyword] == nil,
501                      let stamp = Timestamp.parse(child.text) else { continue }
502                stamps[keyword] = stamp
503            }
504            let at = node.range.lowerBound
505            if let scheduled = stamps["SCHEDULED"], !scheduled.active {
506                report(.planningInactive, at: at, "Inactive timestamp in SCHEDULED will not appear in agenda.")
507            } else if let deadline = stamps["DEADLINE"], !deadline.active {
508                report(.planningInactive, at: at, "Inactive timestamp in DEADLINE will not appear in agenda.")
509            }
510            if let s = stamps["SCHEDULED"]?.repeater, let d = stamps["DEADLINE"]?.repeater,
511               s.kind != .restart, d.kind != .restart, s.interval.value > 0, d.interval.value > 0,
512               s.kind != d.kind || s.interval != d.interval {
513                report(.mismatchedPlanningRepeaters, at: at, "Different repeaters in SCHEDULED and DEADLINE timestamps.")
514            }
515        }
516    }
517
518    // MARK: - Footnotes
519
520    /// A definition's label, from its `[fn:LABEL]`.
521    static func definitionLabel(_ node: SyntaxNode) -> String? {
522        guard let marker = node.tokens.first(where: { $0.kind == .marker }) else { return nil }
523        let label = String(marker.text.dropFirst(4).dropLast())
524        return label.isEmpty ? nil : label
525    }
526
527    /// A reference's label, nil for an anonymous one, and whether it defines the footnote too.
528    static func referenceLabel(_ node: SyntaxNode) -> (label: String?, inline: Bool) {
529        let inside = node.text.dropFirst(4).dropLast()
530        guard let colon = inside.firstIndex(of: ":") else { return (String(inside), false) }
531        let label = inside[..<colon]
532        return (label.isEmpty ? nil : String(label), true)
533    }
534
535    mutating func footnoteChecks() {
536        let references = footnoteReferences.map { (node: $0, reference: Self.referenceLabel($0)) }
537        let definitions = footnoteDefinitions.compactMap { node in Self.definitionLabel(node).map { (node: node, label: $0) } }
538        let defined = Set(definitions.map(\.label) + references.filter(\.reference.inline).compactMap(\.reference.label))
539        let referenced = Set(references.compactMap(\.reference.label))
540        for (node, reference) in references where !reference.inline {
541            if let label = reference.label, !defined.contains(label) {
542                report(.undefinedFootnoteReference, at: node.range.lowerBound, "Missing definition for footnote [\(label)]")
543            }
544        }
545        for (node, label) in definitions where !referenced.contains(label) {
546            report(.unreferencedFootnoteDefinition, at: node.range.lowerBound, "No reference for footnote definition [\(label)]")
547        }
548    }
549}
550
551/// The targets a `file:…::search` link can reach in an Org file, as `Links.search` finds them.
552struct SearchIndex {
553    let tree: OrgTree
554    let text: String
555    let customIDs: Set<String>
556    let targets: Set<[String]>
557    let names: Set<[String]>
558    let headings: Set<[String]>
559
560    init(_ tree: OrgTree) {
561        self.tree = tree
562        text = tree.text
563        let model = DocumentModel(tree: tree)
564        customIDs = Set(model.headings.flatMap { $0.properties.filter { $0.key.uppercased() == "CUSTOM_ID" }.map(\.value) })
565        headings = Set(model.headings.map { Links.normalizedTitle($0.title).split(whereSeparator: \.isWhitespace).map { $0.uppercased() } })
566        let ns = text as NSString
567        targets = Set(try! NSRegularExpression(pattern: "(?<!<)<<([^<>\\n]+)>>(?!>)").matches(in: text, range: NSRange(location: 0, length: ns.length)).map {
568            Linter.words(ns.substring(with: $0.range(at: 1))).map { $0.uppercased() }
569        })
570        names = Set(text.matches(of: /(?m)^[ \t]*#\+(?i:name): +(.*?)[ \t]*$/).map { Linter.words(String($0.1)).map { $0.uppercased() } })
571    }
572
573    func finds(_ s: String) -> Bool {
574        let normalized = s.replacingOccurrences(of: "\\n[ \\t]*", with: " ", options: .regularExpression)
575        if normalized.hasPrefix("#") { return customIDs.contains(String(normalized.dropFirst())) }
576        if (normalized.hasPrefix("(") && normalized.hasSuffix(")")) || (normalized.count >= 2 && normalized.hasPrefix("/") && normalized.hasSuffix("/")) {
577            if case .failed = Links.search(s, text: text, tree: tree) { return false }
578            return true
579        }
580        let starred = normalized.hasPrefix("*")
581        let words = Linter.words(starred ? String(s.dropFirst()) : s).map { $0.uppercased() }
582        if !starred, targets.contains(words) || names.contains(words) { return true }
583        return headings.contains(words)
584    }
585}
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