Lint File: problems in the current file !488
25 files changed, +2421 −5
Changed files (25)
- Sources/OrgApp/CommandRanking.swift +1 −1
- Sources/OrgApp/CommandTitles.swift +1
- Sources/OrgApp/FileLint.swift added +43
- Sources/OrgCore/Commands/Attach.swift +5 −1
- Sources/OrgCore/Links/Links.swift +2 −1
- Sources/OrgCore/Lint/Lint.swift added +163
- Sources/OrgCore/Lint/LintCheckers.swift added +584
- Sources/OrgCore/Lint/LintTimestamp.swift added +144
- Sources/OrgCore/Lint/Linter.swift added +209
- Sources/OrgEditorAppKit/EditorCommands.swift +1
- Sources/Orgstar/ContentView.swift +13
- Sources/Orgstar/LintPane.swift added +85
- Sources/Orgstar/OrgstarApp.swift +2
- Sources/OrgstarMobile/EditorScreen.swift +7 −1
- Sources/OrgstarMobile/LintScreen.swift added +73
- Sources/OrgstarMobile/MobileEditor.swift +1 −1
- Tests/OrgAppTests/FileLintTests.swift added +49
- Tests/OrgCoreTests/LintOracleTests.swift added +86
- Tests/OrgCoreTests/LintTests.swift added +396
- Tests/OrgEditorAppKitTests/GateTests.swift +9
- docs/manual/guide/02-the-editor.org +52
- docs/manual/guide/03-keys.org +1
- docs/manual/guide/14-ios.org +2
- docs/manual/guide/15-alongside-emacs.org +11
- l10n/Localizable.xcstrings +481
Sources/OrgApp/CommandRanking.swift +1 −1 · view
| @@ -94,7 +94,7 @@ public enum CommandGroups { | |||
| 94 | public static let commandList: [Group] = orgMenu + [ | 94 | public static let commandList: [Group] = orgMenu + [ |
| 95 | Group(title: String(localized: "Clock", comment: "Commands list section"), prefixes: ["app.clock."]), | 95 | Group(title: String(localized: "Clock", comment: "Commands list section"), prefixes: ["app.clock."]), |
| 96 | Group(title: String(localized: "Export", comment: "Commands list section"), prefixes: ["app.export", "app.copy-rich-text", "app.publish"]), | 96 | Group(title: String(localized: "Export", comment: "Commands list section"), prefixes: ["app.export", "app.copy-rich-text", "app.publish"]), |
| 97 | Group(title: String(localized: "File", comment: "Commands list section"), prefixes: ["app.save", "app.word-count", "app.recovery", "app.sync-conflicts"]), | 97 | Group(title: String(localized: "File", comment: "Commands list section"), prefixes: ["app.save", "app.word-count", "app.recovery", "app.sync-conflicts", "app.lint"]), |
| 98 | Group(title: String(localized: "Edit", comment: "Commands list section"), prefixes: ["edit.", "macro."]), | 98 | Group(title: String(localized: "Edit", comment: "Commands list section"), prefixes: ["edit.", "macro."]), |
| 99 | Group(title: String(localized: "View", comment: "Commands list section"), prefixes: ["app.toggle-markup", "editor.", "app.split-", "app.pane-"]), | 99 | Group(title: String(localized: "View", comment: "Commands list section"), prefixes: ["app.toggle-markup", "editor.", "app.split-", "app.pane-"]), |
| 100 | ] | 100 | ] |
Sources/OrgApp/CommandTitles.swift +1 · view
| @@ -172,6 +172,7 @@ enum CommandTitles { | |||
| 172 | String(localized: "Kill Word Backward", comment: "Command title"), | 172 | String(localized: "Kill Word Backward", comment: "Command title"), |
| 173 | String(localized: "Last Buffer", comment: "Command title"), | 173 | String(localized: "Last Buffer", comment: "Command title"), |
| 174 | String(localized: "Leave Block", comment: "Command title"), | 174 | String(localized: "Leave Block", comment: "Command title"), |
| 175 | String(localized: "Lint File", comment: "Command title"), | ||
| 175 | String(localized: "Lower Priority", comment: "Command title"), | 176 | String(localized: "Lower Priority", comment: "Command title"), |
| 176 | String(localized: "Mark Subtree", comment: "Command title"), | 177 | String(localized: "Mark Subtree", comment: "Command title"), |
| 177 | String(localized: "Mark as Default Clock Task", comment: "Command title"), | 178 | String(localized: "Mark as Default Clock Task", comment: "Command title"), |
Sources/OrgApp/FileLint.swift added +43 · view
| @@ -0,0 +1,43 @@ | |||
| 1 | import Foundation | ||
| 2 | import OrgCore | ||
| 3 | import OrgIndex | ||
| 4 | |||
| 5 | /// Lint File in the apps: the checkers run over an open file's text off the main actor, with | ||
| 6 | /// the file system and the workspace index for IDs in other files. | ||
| 7 | public enum FileLint { | ||
| 8 | /// The checkers' environment: the file system, IDs through `index` (unsaved buffers' | ||
| 9 | /// from `overlay`), and the attachment and crypt settings. | ||
| 10 | public static func environment(index: IndexStore?, overlay: [String: FileRecord] = [:], defaults: UserDefaults = .standard) -> LintEnvironment { | ||
| 11 | var environment = LintEnvironment.fileSystem | ||
| 12 | environment.attachIDDir = OrgPreferences.attachIDDir(defaults) | ||
| 13 | environment.attachInherit = OrgPreferences.attachUseInheritance(defaults) | ||
| 14 | environment.cryptTag = OrgPreferences.cryptTag(defaults) | ||
| 15 | if let index { | ||
| 16 | environment.idFiles = { id in ((try? index.headings(withID: id, overlay: overlay)) ?? []).map(\.path) } | ||
| 17 | } | ||
| 18 | return environment | ||
| 19 | } | ||
| 20 | |||
| 21 | /// Whether Lint File applies to the file at `path`: Org files, and encrypted ones once | ||
| 22 | /// decrypted in memory. | ||
| 23 | public static func applies(to path: String?) -> Bool { | ||
| 24 | guard let path else { return false } | ||
| 25 | return path.hasSuffix(".org") || path.hasSuffix(".org_archive") || path.hasSuffix(".org.gpg") | ||
| 26 | } | ||
| 27 | |||
| 28 | /// The findings in `text`, off the main actor. | ||
| 29 | @concurrent | ||
| 30 | public static func lint(_ text: String, tree: OrgTree, path: String?, environment: LintEnvironment) async -> [LintFinding] { | ||
| 31 | OrgLint.lint(text, tree: tree, path: path, environment: environment) | ||
| 32 | } | ||
| 33 | |||
| 34 | /// A finding's trust as the panels show it: org-lint's high trust as an error, low as a warning. | ||
| 35 | public static func severity(_ finding: LintFinding) -> String { | ||
| 36 | finding.trust == .high ? String(localized: "Error", comment: "Lint File: a problem org-lint trusts highly") : String(localized: "Warning", comment: "Lint File: a problem that may be intended") | ||
| 37 | } | ||
| 38 | |||
| 39 | /// The panels' summary line. | ||
| 40 | public static func summary(_ findings: [LintFinding]) -> String { | ||
| 41 | findings.isEmpty ? String(localized: "No problems found", comment: "Lint File") : String(localized: "\(findings.count) problems", comment: "Lint File: the number of problems found") | ||
| 42 | } | ||
| 43 | } | ||
Sources/OrgCore/Commands/Attach.swift +5 −1 · view
| @@ -56,7 +56,11 @@ public enum OrgAttach { | |||
| 56 | /// `noFSCheck`, when the folder doesn't exist. | 56 | /// `noFSCheck`, when the folder doesn't exist. |
| 57 | public static func directory(tree: OrgTree, at offset: Int, path: String, idDir: String = "data/", inherit: Bool? = nil, noFSCheck: Bool = false, isDirectory: (String) -> Bool) -> String? { | 57 | public static func directory(tree: OrgTree, at offset: Int, path: String, idDir: String = "data/", inherit: Bool? = nil, noFSCheck: Bool = false, isDirectory: (String) -> Bool) -> String? { |
| 58 | let model = DocumentModel(tree: tree) | 58 | 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? { | ||
| 60 | let folder = (path as NSString).deletingLastPathComponent | 64 | let folder = (path as NSString).deletingLastPathComponent |
| 61 | func own(_ key: String, _ index: Int) -> String? { | 65 | func own(_ key: String, _ index: Int) -> String? { |
| 62 | model.headings[index].properties.last { $0.key.uppercased() == key && !$0.additive }?.value | 66 | 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 { | |||
| 60 | 60 | ||
| 61 | /// `org-link-expand-abbrev` for templates with `%s`, `%h`, or a plain prefix. | 61 | /// `org-link-expand-abbrev` for templates with `%s`, `%h`, or a plain prefix. |
| 62 | static func expandAbbreviation(_ link: String, _ abbreviations: [String: String]) -> String { | 62 | static func expandAbbreviation(_ link: String, _ abbreviations: [String: String]) -> String { |
| 63 | guard !abbreviations.isEmpty else { return link } | ||
| 63 | let regex = try! NSRegularExpression(pattern: "^([^:]*)(::?(.*))?$") | 64 | let regex = try! NSRegularExpression(pattern: "^([^:]*)(::?(.*))?$") |
| 64 | let ns = link as NSString | 65 | let ns = link as NSString |
| 65 | guard let m = regex.firstMatch(in: link, range: NSRange(location: 0, length: ns.length)), | 66 | guard let m = regex.firstMatch(in: link, range: NSRange(location: 0, length: ns.length)), |
| @@ -77,7 +78,7 @@ public enum Links { | |||
| 77 | 78 | ||
| 78 | /// A bracket link's inside (`[[` to `]]` or `][`), as `org-element-link-parser` reads it. | 79 | /// A bracket link's inside (`[[` to `]]` or `][`), as `org-element-link-parser` reads it. |
| 79 | public static func parse(bracket inside: String, abbreviations: [String: String] = [:]) -> OrgLink { | 80 | 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 |
| 81 | let raw = expandAbbreviation(unescape(joined), abbreviations) | 82 | let raw = expandAbbreviation(unescape(joined), abbreviations) |
| 82 | let ns = raw as NSString | 83 | let ns = raw as NSString |
| 83 | var type: String | 84 | var type: String |
Sources/OrgCore/Lint/Lint.swift added +163 · view
| @@ -0,0 +1,163 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | /// How sure a checker is that what it reports is a mistake, as org-lint's `:trust`. | ||
| 4 | public 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. | ||
| 10 | public 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. | ||
| 82 | public 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. | ||
| 104 | public 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. | ||
| 151 | public 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 | |||
| 161 | extension LintChecker { | ||
| 162 | var order: Int { Self.allCases.firstIndex(of: self)! } | ||
| 163 | } | ||
Sources/OrgCore/Lint/LintCheckers.swift added +584 · view
| @@ -0,0 +1,584 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | // The checkers. Messages are org-lint's where org-lint has the checker. | ||
| 4 | |||
| 5 | extension 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. | ||
| 551 | struct 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 @@ | |||
| 1 | import 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. | ||
| 6 | enum 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 @@ | |||
| 1 | import 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. | ||
| 6 | struct 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 | } | ||
Sources/OrgEditorAppKit/EditorCommands.swift +1 · view
| @@ -188,6 +188,7 @@ public enum EditorCommands { | |||
| 188 | EditorCommand(id: "app.sync-conflicts", title: "Resolve Sync Conflicts…", action: .app), | 188 | EditorCommand(id: "app.sync-conflicts", title: "Resolve Sync Conflicts…", action: .app), |
| 189 | EditorCommand(id: "app.revert", title: "Revert to File on Disk", action: .app), | 189 | EditorCommand(id: "app.revert", title: "Revert to File on Disk", action: .app), |
| 190 | EditorCommand(id: "app.recovery", title: "History…", action: .app), | 190 | EditorCommand(id: "app.recovery", title: "History…", action: .app), |
| 191 | EditorCommand(id: "app.lint", title: "Lint File", action: .app), | ||
| 191 | EditorCommand(id: "app.export.html", title: "Export to HTML", action: .app), | 192 | EditorCommand(id: "app.export.html", title: "Export to HTML", action: .app), |
| 192 | EditorCommand(id: "app.export.html-open", title: "Export to HTML and Open", action: .app), | 193 | EditorCommand(id: "app.export.html-open", title: "Export to HTML and Open", action: .app), |
| 193 | EditorCommand(id: "app.export.markdown", title: "Export to Markdown", action: .app), | 194 | EditorCommand(id: "app.export.markdown", title: "Export to Markdown", action: .app), |
Sources/Orgstar/ContentView.swift +13 · view
| @@ -96,6 +96,9 @@ struct ContentView: View { | |||
| 96 | @AppStorage("outlineShown") private var orgOutlineShown = true | 96 | @AppStorage("outlineShown") private var orgOutlineShown = true |
| 97 | @AppStorage("outlineWidth") private var outlineWidth = 220.0 | 97 | @AppStorage("outlineWidth") private var outlineWidth = 220.0 |
| 98 | @AppStorage("backlinksShown") private var backlinksShown = true | 98 | @AppStorage("backlinksShown") private var backlinksShown = true |
| 99 | /// Lint File's panel is open; `lintRun` counts runs of the command. | ||
| 100 | @State private var lintShown = false | ||
| 101 | @State private var lintRun = 0 | ||
| 99 | @AppStorage("inspectorShown") private var inspectorShown = false | 102 | @AppStorage("inspectorShown") private var inspectorShown = false |
| 100 | @AppStorage("showMarkup") private var showMarkup = false | 103 | @AppStorage("showMarkup") private var showMarkup = false |
| 101 | @AppStorage("showLineNumbers") private var showLineNumbers = false | 104 | @AppStorage("showLineNumbers") private var showLineNumbers = false |
| @@ -186,6 +189,11 @@ struct ContentView: View { | |||
| 186 | } | 189 | } |
| 187 | .safeAreaInset(edge: .bottom, spacing: 0) { | 190 | .safeAreaInset(edge: .bottom, spacing: 0) { |
| 188 | VStack(spacing: 0) { | 191 | VStack(spacing: 0) { |
| 192 | if lintShown { | ||
| 193 | LintPane(workspace: workspace, session: session, run: lintRun) { lintShown = false } | ||
| 194 | .frame(height: 190) | ||
| 195 | Divider() | ||
| 196 | } | ||
| 189 | ModeLine(session: session, commands: commands) | 197 | ModeLine(session: session, commands: commands) |
| 190 | EchoArea(commands: commands) | 198 | EchoArea(commands: commands) |
| 191 | } | 199 | } |
| @@ -1489,6 +1497,11 @@ struct ContentView: View { | |||
| 1489 | case "app.recovery": | 1497 | case "app.recovery": |
| 1490 | guard session.path != nil else { return commands.show(String(localized: "No file is open")) } | 1498 | guard session.path != nil else { return commands.show(String(localized: "No file is open")) } |
| 1491 | panel = .recovery(UUID()) | 1499 | panel = .recovery(UUID()) |
| 1500 | case "app.lint": | ||
| 1501 | guard session.path != nil else { return commands.show(String(localized: "No file is open")) } | ||
| 1502 | guard FileLint.applies(to: session.path) else { return commands.show(String(localized: "Lint File works on Org files", comment: "Lint File in a file that isn't Org")) } | ||
| 1503 | lintShown = true | ||
| 1504 | lintRun += 1 | ||
| 1492 | case "app.copy-rich-text": | 1505 | case "app.copy-rich-text": |
| 1493 | copyRichText() | 1506 | copyRichText() |
| 1494 | case "app.export-dialog": | 1507 | case "app.export-dialog": |
Sources/Orgstar/LintPane.swift added +85 · view
| @@ -0,0 +1,85 @@ | |||
| 1 | import OrgApp | ||
| 2 | import OrgCore | ||
| 3 | import SwiftUI | ||
| 4 | |||
| 5 | /// Lint File's panel under the editor: the problems in the open file, by line. Choosing a row | ||
| 6 | /// moves the caret there. The list follows the file as it changes. | ||
| 7 | struct LintPane: View { | ||
| 8 | let workspace: WorkspaceModel | ||
| 9 | let session: DocumentSession | ||
| 10 | /// Raised each time Lint File runs, so running it again lints again. | ||
| 11 | let run: Int | ||
| 12 | let close: () -> Void | ||
| 13 | @State private var findings: [LintFinding]? | ||
| 14 | @State private var linted: Key? | ||
| 15 | @State private var selection: LintFinding.ID? | ||
| 16 | @Environment(\.orgTheme) private var theme | ||
| 17 | @Environment(\.colorScheme) private var colorScheme | ||
| 18 | |||
| 19 | private struct Key: Equatable { | ||
| 20 | var path: String? | ||
| 21 | var revision: Int? | ||
| 22 | var run: Int | ||
| 23 | } | ||
| 24 | |||
| 25 | var body: some View { | ||
| 26 | VStack(spacing: 0) { | ||
| 27 | HStack(spacing: 8) { | ||
| 28 | Text("Lint File").font(.subheadline.weight(.semibold)) | ||
| 29 | if let path = session.path { Text((path as NSString).lastPathComponent).foregroundStyle(.secondary).lineLimit(1) } | ||
| 30 | Spacer() | ||
| 31 | if let findings { Text(FileLint.summary(findings)).foregroundStyle(.secondary) } else { ProgressView().controlSize(.small) } | ||
| 32 | Button("Close", systemImage: "xmark", action: close) | ||
| 33 | .labelStyle(.iconOnly) | ||
| 34 | .buttonStyle(.borderless) | ||
| 35 | .help("Close the Lint File panel") | ||
| 36 | } | ||
| 37 | .padding(.horizontal, 10) | ||
| 38 | .padding(.vertical, 5) | ||
| 39 | Divider() | ||
| 40 | Table(findings ?? [], selection: $selection) { | ||
| 41 | TableColumn("Line") { finding in Text(verbatim: "\(finding.line)").monospacedDigit() } | ||
| 42 | .width(48) | ||
| 43 | TableColumn("Severity") { finding in | ||
| 44 | Label(FileLint.severity(finding), systemImage: finding.trust == .high ? "xmark.octagon.fill" : "exclamationmark.triangle.fill") | ||
| 45 | .foregroundStyle(finding.trust == .high ? Color.red : Color.orange) | ||
| 46 | .labelStyle(.titleAndIcon) | ||
| 47 | } | ||
| 48 | .width(96) | ||
| 49 | TableColumn("Problem") { finding in Text(finding.message).lineLimit(1).help(finding.message) } | ||
| 50 | .width(min: 200, ideal: 360) | ||
| 51 | TableColumn("Checker") { finding in Text(verbatim: finding.checker.rawValue).foregroundStyle(.secondary).lineLimit(1) } | ||
| 52 | .width(min: 120, ideal: 210, max: 260) | ||
| 53 | } | ||
| 54 | .tableStyle(.inset(alternatesRowBackgrounds: true)) | ||
| 55 | .overlay { | ||
| 56 | if findings?.isEmpty == true { Text("No problems found").foregroundStyle(.secondary) } | ||
| 57 | } | ||
| 58 | } | ||
| 59 | .background(theme.color("sidebar-background", in: colorScheme) ?? .clear) | ||
| 60 | .onChange(of: selection) { _, id in | ||
| 61 | guard let id, let finding = findings?.first(where: { $0.id == id }) else { return } | ||
| 62 | session.reveal(finding.offset) | ||
| 63 | } | ||
| 64 | .task(id: Key(path: session.path, revision: session.document?.revision, run: run)) { await refresh() } | ||
| 65 | } | ||
| 66 | |||
| 67 | private func refresh() async { | ||
| 68 | let key = Key(path: session.path, revision: session.document?.revision, run: run) | ||
| 69 | // Typing relints after a pause; a new file or another run of the command at once. | ||
| 70 | if let linted, linted.path == key.path, linted.run == key.run { | ||
| 71 | try? await Task.sleep(for: .milliseconds(500)) | ||
| 72 | guard !Task.isCancelled else { return } | ||
| 73 | } | ||
| 74 | guard let document = session.document, FileLint.applies(to: session.path) else { | ||
| 75 | findings = [] | ||
| 76 | return | ||
| 77 | } | ||
| 78 | let environment = FileLint.environment(index: workspace.index, overlay: workspace.overlay(session.openDocuments)) | ||
| 79 | let found = await FileLint.lint(document.text, tree: document.tree, path: session.path, environment: environment) | ||
| 80 | guard !Task.isCancelled else { return } | ||
| 81 | findings = found | ||
| 82 | linted = key | ||
| 83 | if let selection, !found.contains(where: { $0.id == selection }) { self.selection = nil } | ||
| 84 | } | ||
| 85 | } | ||
Sources/Orgstar/OrgstarApp.swift +2 · view
| @@ -529,6 +529,8 @@ struct OrgstarApp: App { | |||
| 529 | .disabled(session.path == nil) | 529 | .disabled(session.path == nil) |
| 530 | Button("History…") { commands.run("app.recovery") } | 530 | Button("History…") { commands.run("app.recovery") } |
| 531 | .disabled(session.path == nil) | 531 | .disabled(session.path == nil) |
| 532 | Button("Lint File") { commands.run("app.lint") } | ||
| 533 | .disabled(!FileLint.applies(to: session.path)) | ||
| 532 | } | 534 | } |
| 533 | CommandGroup(replacing: .saveItem) { | 535 | CommandGroup(replacing: .saveItem) { |
| 534 | Button("Close Buffer") { | 536 | Button("Close Buffer") { |
Sources/OrgstarMobile/EditorScreen.swift +7 −1 · view
| @@ -94,6 +94,7 @@ struct EditorScreen: View { | |||
| 94 | case graph | 94 | case graph |
| 95 | /// Rename Tag or Rename TODO Keyword, starting from this name. | 95 | /// Rename Tag or Rename TODO Keyword, starting from this name. |
| 96 | case rename(ReplaceKind, String) | 96 | case rename(ReplaceKind, String) |
| 97 | case lint | ||
| 97 | /// The subtree at this offset, to export. | 98 | /// The subtree at this offset, to export. |
| 98 | case exportSubtree(Int) | 99 | case exportSubtree(Int) |
| 99 | 100 | ||
| @@ -112,6 +113,7 @@ struct EditorScreen: View { | |||
| 112 | case .backlinks: "backlinks" | 113 | case .backlinks: "backlinks" |
| 113 | case .graph: "graph" | 114 | case .graph: "graph" |
| 114 | case .rename(let kind, _): kind.rawValue | 115 | case .rename(let kind, _): kind.rawValue |
| 116 | case .lint: "lint" | ||
| 115 | case .exportSubtree: "exportSubtree" | 117 | case .exportSubtree: "exportSubtree" |
| 116 | } | 118 | } |
| 117 | } | 119 | } |
| @@ -243,6 +245,8 @@ struct EditorScreen: View { | |||
| 243 | } | 245 | } |
| 244 | case .rename(let kind, let initial): | 246 | case .rename(let kind, let initial): |
| 245 | RenameScreen(kind: kind, workspace: workspace, session: session, initial: initial) { message = $0 } | 247 | RenameScreen(kind: kind, workspace: workspace, session: session, initial: initial) { message = $0 } |
| 248 | case .lint: | ||
| 249 | LintScreen(workspace: workspace, session: session, path: path) { offset in editor?.reveal(offset) } | ||
| 246 | } | 250 | } |
| 247 | } | 251 | } |
| 248 | .fileImporter(isPresented: $importingTable, allowedContentTypes: [.commaSeparatedText, .tabSeparatedText, .plainText]) { result in | 252 | .fileImporter(isPresented: $importingTable, allowedContentTypes: [.commaSeparatedText, .tabSeparatedText, .plainText]) { result in |
| @@ -511,6 +515,8 @@ struct EditorScreen: View { | |||
| 511 | } else if let kind = ReplaceKind(command: id), kind != .replace { | 515 | } else if let kind = ReplaceKind(command: id), kind != .replace { |
| 512 | let context = self.editor?.editContext() | 516 | let context = self.editor?.editContext() |
| 513 | sheet = .rename(kind, context.map { kind.initial(text: $0.text, caret: $0.caret, keywords: $0.tree.settings.todoKeywordNames) } ?? "") | 517 | sheet = .rename(kind, context.map { kind.initial(text: $0.text, caret: $0.caret, keywords: $0.tree.settings.todoKeywordNames) } ?? "") |
| 518 | } else if id == "app.lint" { | ||
| 519 | if FileLint.applies(to: path) { sheet = .lint } else { message = String(localized: "Lint File works on Org files", comment: "Lint File in a file that isn't Org") } | ||
| 514 | } else if id == "app.toggle-markup" { | 520 | } else if id == "app.toggle-markup" { |
| 515 | model.showMarkup.toggle() | 521 | model.showMarkup.toggle() |
| 516 | } else if MobileEditor.linkCommands.contains(id) { | 522 | } else if MobileEditor.linkCommands.contains(id) { |
| @@ -1048,7 +1054,7 @@ struct CommandPalette: View { | |||
| 1048 | ("app.publish.current-project", "Publish Current Project"), | 1054 | ("app.publish.current-project", "Publish Current Project"), |
| 1049 | ("app.toggle-markup", "Show or Hide Markup"), ("app.word-count", "Word Count"), | 1055 | ("app.toggle-markup", "Show or Hide Markup"), ("app.word-count", "Word Count"), |
| 1050 | ("org.snippet.next-field", "Next Snippet Field"), ("org.snippet.previous-field", "Previous Snippet Field"), | 1056 | ("org.snippet.next-field", "Next Snippet Field"), ("org.snippet.previous-field", "Previous Snippet Field"), |
| 1051 | ("app.recovery", "Recovery Versions…"), ("app.sync-conflicts", "Resolve Sync Conflicts…"), | 1057 | ("app.recovery", "Recovery Versions…"), ("app.sync-conflicts", "Resolve Sync Conflicts…"), ("app.lint", "Lint File"), |
| 1052 | ("org.toggle-inline-images", "Show or Hide Inline Images"), ("org.toggle-inline-images-linked", "Show or Hide Inline Images, Including Described Links"), ("org.latex-preview", "Show or Hide LaTeX Previews"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"), ("editor.toggle-auto-fill", "Turn Auto Fill On or Off"), | 1058 | ("org.toggle-inline-images", "Show or Hide Inline Images"), ("org.toggle-inline-images-linked", "Show or Hide Inline Images, Including Described Links"), ("org.latex-preview", "Show or Hide LaTeX Previews"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"), ("editor.toggle-auto-fill", "Turn Auto Fill On or Off"), |
| 1053 | ("editor.complete", "Complete at Point"), ("editor.dabbrev-expand", "Expand Word"), ("editor.dabbrev-completion", "Complete Word"), | 1059 | ("editor.complete", "Complete at Point"), ("editor.dabbrev-expand", "Expand Word"), ("editor.dabbrev-completion", "Complete Word"), |
| 1054 | ("edit.isearch-forward", "Incremental Search"), ("edit.isearch-backward", "Incremental Search Backward"), | 1060 | ("edit.isearch-forward", "Incremental Search"), ("edit.isearch-backward", "Incremental Search Backward"), |
Sources/OrgstarMobile/LintScreen.swift added +73 · view
| @@ -0,0 +1,73 @@ | |||
| 1 | #if os(iOS) | ||
| 2 | import OrgApp | ||
| 3 | import OrgCore | ||
| 4 | import SwiftUI | ||
| 5 | |||
| 6 | /// Lint File: the problems in the open file, by line, as the Mac's panel lists them. Tapping | ||
| 7 | /// one closes the list and moves the caret to its line. | ||
| 8 | struct LintScreen: View { | ||
| 9 | let workspace: WorkspaceModel | ||
| 10 | let session: DocumentSession | ||
| 11 | let path: String | ||
| 12 | let reveal: (Int) -> Void | ||
| 13 | @State private var findings: [LintFinding]? | ||
| 14 | @Environment(\.dismiss) private var dismiss | ||
| 15 | |||
| 16 | var body: some View { | ||
| 17 | NavigationStack { | ||
| 18 | List { | ||
| 19 | if let findings { | ||
| 20 | Section { | ||
| 21 | ForEach(findings) { finding in | ||
| 22 | Button { | ||
| 23 | dismiss() | ||
| 24 | reveal(finding.offset) | ||
| 25 | } label: { | ||
| 26 | row(finding) | ||
| 27 | } | ||
| 28 | } | ||
| 29 | } header: { | ||
| 30 | Text(FileLint.summary(findings)) | ||
| 31 | } | ||
| 32 | } | ||
| 33 | } | ||
| 34 | .overlay { | ||
| 35 | if findings == nil { | ||
| 36 | ProgressView() | ||
| 37 | } else if findings?.isEmpty == true { | ||
| 38 | ContentUnavailableView("No problems found", systemImage: "checkmark.circle") | ||
| 39 | } | ||
| 40 | } | ||
| 41 | .navigationTitle("Lint File") | ||
| 42 | .navigationBarTitleDisplayMode(.inline) | ||
| 43 | .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } } | ||
| 44 | } | ||
| 45 | .task { await refresh() } | ||
| 46 | } | ||
| 47 | |||
| 48 | private func row(_ finding: LintFinding) -> some View { | ||
| 49 | HStack(alignment: .firstTextBaseline, spacing: 10) { | ||
| 50 | Image(systemName: finding.trust == .high ? "xmark.octagon.fill" : "exclamationmark.triangle.fill") | ||
| 51 | .foregroundStyle(finding.trust == .high ? Color.red : Color.orange) | ||
| 52 | .accessibilityLabel(FileLint.severity(finding)) | ||
| 53 | VStack(alignment: .leading, spacing: 2) { | ||
| 54 | Text(finding.message).foregroundStyle(.primary) | ||
| 55 | Text("Line \(finding.line) · \(finding.checker.rawValue)", comment: "Lint File: a problem's line and checker") | ||
| 56 | .font(.caption) | ||
| 57 | .foregroundStyle(.secondary) | ||
| 58 | } | ||
| 59 | } | ||
| 60 | } | ||
| 61 | |||
| 62 | private func refresh() async { | ||
| 63 | guard let document = session.openDocuments.first(where: { $0.path == path })?.document else { | ||
| 64 | findings = [] | ||
| 65 | return | ||
| 66 | } | ||
| 67 | let environment = FileLint.environment(index: workspace.index, overlay: workspace.overlay(session.openDocuments)) | ||
| 68 | let found = await FileLint.lint(document.text, tree: document.tree, path: path, environment: environment) | ||
| 69 | guard !Task.isCancelled else { return } | ||
| 70 | findings = found | ||
| 71 | } | ||
| 72 | } | ||
| 73 | #endif | ||
Sources/OrgstarMobile/MobileEditor.swift +1 −1 · view
| @@ -505,7 +505,7 @@ final class MobileEditor: NSObject, DocumentBuffer { | |||
| 505 | case "app.crypt.encrypt-entry": return onAppCommand != nil && OrgCrypt.heading(context.text, at: context.caret) != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) == nil | 505 | case "app.crypt.encrypt-entry": return onAppCommand != nil && OrgCrypt.heading(context.text, at: context.caret) != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) == nil |
| 506 | case "app.crypt.open-entry", "app.crypt.decrypt-entry": return onAppCommand != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) != nil | 506 | case "app.crypt.open-entry", "app.crypt.decrypt-entry": return onAppCommand != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) != nil |
| 507 | case "app.table-export", "app.table-export.tsv", "app.plot": return onAppCommand != nil && ImportTable.exportText(context.text, at: context.caret, path: "") != nil | 507 | case "app.table-export", "app.table-export.tsv", "app.plot": return onAppCommand != nil && ImportTable.exportText(context.text, at: context.caret, path: "") != nil |
| 508 | case "app.word-count", "app.recovery", "app.sync-conflicts", "app.attach.photo", "app.attach.camera", "app.attach.scan", | 508 | case "app.word-count", "app.recovery", "app.sync-conflicts", "app.lint", "app.attach.photo", "app.attach.camera", "app.attach.scan", |
| 509 | "app.rename-tag", "app.rename-todo-keyword": return onAppCommand != nil | 509 | "app.rename-tag", "app.rename-todo-keyword": return onAppCommand != nil |
| 510 | case _ where id.hasPrefix(NamedMacros.commandPrefix): return true | 510 | case _ where id.hasPrefix(NamedMacros.commandPrefix): return true |
| 511 | case "app.refile", "app.refile.copy", "app.archive": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil | 511 | case "app.refile", "app.refile.copy", "app.archive": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil |
Tests/OrgAppTests/FileLintTests.swift added +49 · view
| @@ -0,0 +1,49 @@ | |||
| 1 | import Foundation | ||
| 2 | import OrgCore | ||
| 3 | @testable import OrgIndex | ||
| 4 | import Testing | ||
| 5 | @testable import OrgApp | ||
| 6 | |||
| 7 | struct FileLintTests { | ||
| 8 | @Test func idsResolveThroughTheIndexAndItsOverlay() async throws { | ||
| 9 | let store = try IndexStore() | ||
| 10 | try store.write(FileRecord(path: "/notes/a.org", root: "/notes", kind: .org, bytes: Array("* A\n:PROPERTIES:\n:ID: in-a\n:END:\n".utf8), mtime: 1, settings: IndexSettings())) | ||
| 11 | // An unsaved buffer of b.org, in place of what the index has. | ||
| 12 | let overlay = ["/notes/b.org": FileRecord(path: "/notes/b.org", root: "/notes", kind: .org, bytes: Array("* B\n:PROPERTIES:\n:ID: in-b\n:END:\n".utf8), | ||
| 13 | mtime: 2, settings: IndexSettings())] | ||
| 14 | let text = "* Here\n:PROPERTIES:\n:ID: in-a\n:END:\n[[id:in-a]] [[id:in-b]]\n[[id:nowhere]]\n" | ||
| 15 | let environment = FileLint.environment(index: store, overlay: overlay) | ||
| 16 | let findings = await FileLint.lint(text, tree: OrgParser.parse(text), path: "/notes/here.org", environment: environment) | ||
| 17 | #expect(findings.map(\.checker) == [.duplicateID, .invalidIDLink]) | ||
| 18 | #expect(findings.map(\.line) == [3, 6]) | ||
| 19 | #expect(findings.first?.message == "Duplicate ID \"in-a\", also in a.org") | ||
| 20 | } | ||
| 21 | |||
| 22 | @Test func settingsComeFromThePreferences() { | ||
| 23 | let defaults = TestDefaults("FileLintTests") | ||
| 24 | defaults.set("attach/", forKey: "attachIDDir") | ||
| 25 | defaults.set("t", forKey: "attachUseInheritance") | ||
| 26 | defaults.set("secret", forKey: "cryptTagMatcher") | ||
| 27 | let environment = FileLint.environment(index: nil, defaults: defaults) | ||
| 28 | #expect(environment.attachIDDir == "attach/") | ||
| 29 | #expect(environment.attachInherit == true) | ||
| 30 | #expect(environment.cryptTag == "secret") | ||
| 31 | #expect(environment.idFiles == nil) | ||
| 32 | } | ||
| 33 | |||
| 34 | @Test func appliesToOrgFiles() { | ||
| 35 | #expect(FileLint.applies(to: "/n/a.org")) | ||
| 36 | #expect(FileLint.applies(to: "/n/a.org_archive")) | ||
| 37 | #expect(FileLint.applies(to: "/n/a.org.gpg")) | ||
| 38 | #expect(!FileLint.applies(to: "/n/a.md")) | ||
| 39 | #expect(!FileLint.applies(to: nil)) | ||
| 40 | } | ||
| 41 | |||
| 42 | @Test func summaries() { | ||
| 43 | #expect(FileLint.summary([]) == "No problems found") | ||
| 44 | let finding = LintFinding(offset: 0, line: 1, checker: .priority, message: "x") | ||
| 45 | #expect(FileLint.summary([finding, finding]) == "2 problems") | ||
| 46 | #expect(FileLint.severity(finding) == "Error") | ||
| 47 | #expect(FileLint.severity(LintFinding(offset: 0, line: 1, checker: .timestampSyntax, message: "x")) == "Warning") | ||
| 48 | } | ||
| 49 | } | ||
Tests/OrgCoreTests/LintOracleTests.swift added +86 · view
| @@ -0,0 +1,86 @@ | |||
| 1 | import Foundation | ||
| 2 | import 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. | ||
| 7 | struct 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 @@ | |||
| 1 | import Foundation | ||
| 2 | import Testing | ||
| 3 | @testable import OrgCore | ||
| 4 | |||
| 5 | struct 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 @@ | |||
| 1 | import AppKit | 1 | import AppKit |
| 2 | import Foundation | 2 | import Foundation |
| 3 | import OrgCore | ||
| 3 | import OrgDocument | 4 | import OrgDocument |
| 4 | import Testing | 5 | import Testing |
| 5 | @testable import OrgEditorAppKit | 6 | @testable import OrgEditorAppKit |
| @@ -131,6 +132,14 @@ struct GateTests { | |||
| 131 | #expect(result.newlineP95 < .milliseconds(16), "\(name): blank line") | 132 | #expect(result.newlineP95 < .milliseconds(16), "\(name): blank line") |
| 132 | #expect(result.memoryRatio < memoryLimit, "\(name): memory") | 133 | #expect(result.memoryRatio < memoryLimit, "\(name): memory") |
| 133 | } | 134 | } |
| 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 | } | ||
| 134 | let large = measure("10 MB mixed document", Self.tenMegabytes) | 143 | let large = measure("10 MB mixed document", Self.tenMegabytes) |
| 135 | print("GATE \(large)") | 144 | print("GATE \(large)") |
| 136 | #expect(large.open < .milliseconds(1_500), "10 MB: open") | 145 | #expect(large.open < .milliseconds(1_500), "10 MB: open") |
docs/manual/guide/02-the-editor.org +52 · view
| @@ -499,6 +499,58 @@ How each file changes: | |||
| 499 | 499 | ||
| 500 | The echo area then says how many files changed. Org ▸ TODO and Tags has Rename Tag… and Rename TODO Keyword…, which work the same way but change only tags or keywords; see [[file:05-todos-and-tags.org][TODOs and tags]]. | 500 | The echo area then says how many files changed. Org ▸ TODO and Tags has Rename Tag… and Rename TODO Keyword…, which work the same way but change only tags or keywords; see [[file:05-todos-and-tags.org][TODOs and tags]]. |
| 501 | 501 | ||
| 502 | * Lint File | ||
| 503 | |||
| 504 | File ▸ Lint File (=app.lint=, also in the command palette) checks the open Org file for mistakes, as =M-x org-lint= does, and lists them in a panel under the editor: the line, the severity, the problem and the checker that found it. Choosing a row moves the caret to that line. The list follows the file: after an edit it is checked again once you pause typing. Running Lint File again checks at once; the close button hides the panel. Nothing in the file is changed. | ||
| 505 | |||
| 506 | The severity is org-lint's trust in the checker. An error is almost certainly a mistake; a warning may be intended, such as a timestamp written without its day name. Messages are org-lint's own, in English. | ||
| 507 | |||
| 508 | | Checker | Severity | Reports | | ||
| 509 | |-----------------------------------------+----------+--------------------------------------------------------------------------------------------------| | ||
| 510 | | =invalid-fuzzy-link= | Error | =[[*Heading]]= or =[[name]]= with no heading, =<<target>>= or =#+NAME= of that name in the file | | ||
| 511 | | =invalid-custom-id-link= | Error | =[[#id]]= with no heading of that =CUSTOM_ID= or =ID= in the file | | ||
| 512 | | =invalid-id-link= | Error | =[[id:…]]= with no entry of that =ID= in any of your folders | | ||
| 513 | | =invalid-coderef-link= | Error | =[[(label)]]= with no =(ref:label)= in a block of the file | | ||
| 514 | | =link-to-local-file= | Warning | =file:= and =attachment:= links to files that don't exist | | ||
| 515 | | =invalid-file-search= | Warning | =file:other.org::*Heading= (or =::#id=, =::target=) that the other file doesn't have | | ||
| 516 | | =file-application= | Error | =file+sys:= and =file+emacs:= links | | ||
| 517 | | =missing-attachment-folder= | Error | entries tagged =ATTACH= whose attachment folder doesn't exist | | ||
| 518 | | =orphaned-attachment-folder= | Warning | folders under the attachment folder (=data/= by default) whose ID no entry in your folders has | | ||
| 519 | | =duplicate-id= | Error | an =ID= used twice in the file or also in another file | | ||
| 520 | | =duplicate-custom-id= | Error | a =CUSTOM_ID= used twice in the file | | ||
| 521 | | =duplicate-name= | Error | a =#+NAME= used twice in the file | | ||
| 522 | | =duplicate-target= | Error | a =<<target>>= used twice in the file | | ||
| 523 | | =duplicate-footnote-definition= | Error | two definitions of a footnote | | ||
| 524 | | =incomplete-drawer= | Warning | a drawer line with no =:END:=, or one inside another drawer | | ||
| 525 | | =invalid-block= | Warning | a =#+BEGIN_…= with no =#+END_…=, and an end line with text after it | | ||
| 526 | | =misplaced-planning-info= | Warning | a =SCHEDULED:=, =DEADLINE:= or =CLOSED:= line that isn't right under its heading | | ||
| 527 | | =obsolete-properties-drawer= | Error | a =PROPERTIES= drawer away from its heading, or with lines that aren't properties | | ||
| 528 | | =misplaced-heading= | Warning | stars that look like a heading in the middle of a line | | ||
| 529 | | =indented-diary-sexp= | Warning | an indented =%%(…)= line, which isn't a diary sexp | | ||
| 530 | | =invalid-keyword-syntax= | Warning | =#+KEYWORD= without its colon | | ||
| 531 | | =orphaned-affiliated-keywords= | Warning | =#+NAME=, =#+CAPTION=, =#+ATTR_…= and the like with no element after them | | ||
| 532 | | =obsolete-affiliated-keywords= | Error | =#+TBLNAME=, =#+SRCNAME=, =#+RESULT= and the other old names | | ||
| 533 | | =missing-language-in-src-block= | Error | =#+BEGIN_SRC= without a language | | ||
| 534 | | =missing-backend-in-export-block= | Error | =#+BEGIN_EXPORT= without a format | | ||
| 535 | | =deprecated-export-blocks= | Warning | =#+BEGIN_HTML= and the other blocks =#+BEGIN_EXPORT= replaced | | ||
| 536 | | =deprecated-category-setup= | Error | a second =#+CATEGORY= line | | ||
| 537 | | =non-existent-setupfile-parameter= | Warning | a =#+SETUPFILE= that doesn't exist | | ||
| 538 | | =unknown-todo-keyword= | Warning | a heading starting with a word such as =NEXT= or =TODOX= that isn't one of the file's or the configuration's TODO keywords | | ||
| 539 | | =priority= | Error | priorities outside the file's range, and malformed cookies such as =[#AA]= or =[#1= | | ||
| 540 | | =spurious-colons= | Error | tags with an empty tag, such as =:a::b:= | | ||
| 541 | | =quote-section= | Warning | a =QUOTE= heading | | ||
| 542 | | =special-property-in-properties-drawer= | Error | =TODO=, =SCHEDULED= and the other special properties set in a drawer | | ||
| 543 | | =invalid-effort-property= | Error | an =EFFORT= that isn't a duration | | ||
| 544 | | =invalid-id-property= | Error | an =ID= with =::= in it | | ||
| 545 | | =timestamp-syntax= | Warning | a timestamp Org would write differently: no or a wrong day name, =9:00= for =09:00=, a date that doesn't exist | | ||
| 546 | | =clock-syntax= | Warning | the same for =CLOCK:= lines | | ||
| 547 | | =planning-inactive= | Error | an inactive timestamp after =SCHEDULED:= or =DEADLINE:=, which the agenda doesn't show | | ||
| 548 | | =mismatched-planning-repeaters= | Warning | =SCHEDULED= and =DEADLINE= with different repeaters | | ||
| 549 | | =undefined-footnote-reference= | Error | =[fn:label]= with no definition | | ||
| 550 | | =unreferenced-footnote-definition= | Error | a footnote definition nothing refers to | | ||
| 551 | |||
| 552 | IDs are looked up in the index of all your folders, so a link to an entry in another file counts, and an ID used in two files is a duplicate in each. The attachment folders checked are the ones next to the file; each file in that folder lists the same folders. Links, setup files and attachments in a file that hasn't been saved yet aren't checked. The text of an encrypted entry (=:crypt:=) isn't checked; an encrypted file is checked as it is in the editor, decrypted, and nothing is written. For the differences from =org-lint=, see [[file:15-alongside-emacs.org][Working alongside Emacs]]. On iOS, Lint File is in Commands; see [[file:14-ios.org][iPhone and iPad]]. | ||
| 553 | |||
| 502 | * Accessibility | 554 | * Accessibility |
| 503 | 555 | ||
| 504 | The editor works with VoiceOver. VoiceOver reads the text as it is shown rather than as stored: hidden link brackets and targets, hidden emphasis markers and hidden stars are skipped, entities are read as the characters drawn for them, and narrowed table columns are read as drawn. Folded text is still read, so the whole file is available. Lines, the caret position and the selection are reported in terms of the shown text. | 556 | The editor works with VoiceOver. VoiceOver reads the text as it is shown rather than as stored: hidden link brackets and targets, hidden emphasis markers and hidden stars are skipped, entities are read as the characters drawn for them, and narrowed table columns are read as drawn. Folded text is still read, so the whole file is available. Lines, the caret position and the selection are reported in terms of the shown text. |
docs/manual/guide/03-keys.org +1 · view
| @@ -1198,6 +1198,7 @@ No preset binds these. Run them from the palette or a menu, or bind them in =key | |||
| 1198 | | Revert to File on Disk (=app.revert=) | Replaces the buffer with the file on disk; unsaved changes go to recovery (=revert-buffer=). | | 1198 | | Revert to File on Disk (=app.revert=) | Replaces the buffer with the file on disk; unsaved changes go to recovery (=revert-buffer=). | |
| 1199 | | Run Macro… (=macro.run=) | Asks for a named keyboard macro and plays it. Edit ▸ Macros ▸ Run Macro…. | | 1199 | | Run Macro… (=macro.run=) | Asks for a named keyboard macro and plays it. Edit ▸ Macros ▸ Run Macro…. | |
| 1200 | | History… (=app.recovery=) | Shows the file's recovery versions and, in the download version, its git commits. Recovery Versions… on iOS. | | 1200 | | History… (=app.recovery=) | Shows the file's recovery versions and, in the download version, its git commits. Recovery Versions… on iOS. | |
| 1201 | | Lint File (=app.lint=) | Lists the problems in the file in a panel under the editor (=org-lint=). File ▸ Lint File. See [[file:02-the-editor.org][The editor]]. | | ||
| 1201 | | Resolve Sync Conflicts… (=app.sync-conflicts=) | Shows the file's sync conflict copies to resolve them. | | 1202 | | Resolve Sync Conflicts… (=app.sync-conflicts=) | Shows the file's sync conflict copies to resolve them. | |
| 1202 | | Import Table from File… (=app.table-import=) | Asks for a CSV, TSV or space-separated file and inserts it as a table (=org-table-import=). | | 1203 | | Import Table from File… (=app.table-import=) | Asks for a CSV, TSV or space-separated file and inserts it as a table (=org-table-import=). | |
| 1203 | | Export Table to File… (=app.table-export=) | Writes the table at point to a CSV or TSV file (=org-table-export=). | | 1204 | | Export Table to File… (=app.table-export=) | Writes the table at point to a CSV or TSV file (=org-table-export=). | |
docs/manual/guide/14-ios.org +2 · view
| @@ -198,6 +198,8 @@ The org-timer commands are in Commands; a running timer shows above the text. Se | |||
| 198 | 198 | ||
| 199 | Commands has the org-attach commands, and Attach Photo or Video…, Take Photo… and Scan Document…, which insert the link to the photo, or to the scanned pages as one PDF, at the caret; files shared to orgstar can be attached to an entry. Pasting an image and dropping files on the editor attach them and link them at the caret. Attachments are copied or moved: iOS doesn't let orgstar link a file from another app's storage, so the keys for attaching by hard link or symbolic link say "Attachments can't be linked on iPhone and iPad; Attach File… copies the file." See [[file:04-outlines.org][Outlines]] and [[file:09-links.org][Links]]. | 199 | Commands has the org-attach commands, and Attach Photo or Video…, Take Photo… and Scan Document…, which insert the link to the photo, or to the scanned pages as one PDF, at the caret; files shared to orgstar can be attached to an entry. Pasting an image and dropping files on the editor attach them and link them at the caret. Attachments are copied or moved: iOS doesn't let orgstar link a file from another app's storage, so the keys for attaching by hard link or symbolic link say "Attachments can't be linked on iPhone and iPad; Attach File… copies the file." See [[file:04-outlines.org][Outlines]] and [[file:09-links.org][Links]]. |
| 200 | 200 | ||
| 201 | Lint File, under File in Commands, lists the problems in the open file with their lines, as the Mac's Lint File panel does; tap one to close the list and move the caret to its line. The checks are the Mac's; see [[file:02-the-editor.org][The editor]]. Run it again after editing to check again. | ||
| 202 | |||
| 201 | Archive Subtree in Commands (or =C-c C-x C-s= with a hardware keyboard) archives the entry at the caret where =org-archive-location= says, as on the Mac. | 203 | Archive Subtree in Commands (or =C-c C-x C-s= with a hardware keyboard) archives the entry at the caret where =org-archive-location= says, as on the Mac. |
| 202 | 204 | ||
| 203 | Commands has the org-crypt commands; see [[file:04-outlines.org][Outlines]]. A remembered passphrase is used after Face ID, Touch ID or the device passcode. | 205 | Commands has the org-crypt commands; see [[file:04-outlines.org][Outlines]]. A remembered passphrase is used after Face ID, Touch ID or the device passcode. |
docs/manual/guide/15-alongside-emacs.org +11 · view
| @@ -234,6 +234,17 @@ Completion follows Emacs's =completion-at-point= with corfu's list (see [[file:0 | |||
| 234 | - =[[id:= completes every heading in your folders, as =org-roam-node-insert= completes nodes, but a heading without an =ID= gets one when chosen, which org-roam leaves to =org-id-get-create=. The description is the heading's title as written. org-roam's =roam:= links aren't completed. | 234 | - =[[id:= completes every heading in your folders, as =org-roam-node-insert= completes nodes, but a heading without an =ID= gets one when chosen, which org-roam leaves to =org-id-get-create=. The description is the heading's title as written. org-roam's =roam:= links aren't completed. |
| 235 | - Property values come from the index as well as the buffer; Org's =org-read-property-value= offers only the buffer's. | 235 | - Property values come from the index as well as the buffer; Org's =org-read-property-value= offers only the buffer's. |
| 236 | 236 | ||
| 237 | ** Lint File and org-lint | ||
| 238 | |||
| 239 | Lint File (see [[file:02-the-editor.org][The editor]]) runs the checkers of =org-lint= that have the same meaning in orgstar, with org-lint's names, trust and messages, and finds the same lines; the tests compare the two on the same files. It differs in these ways: | ||
| 240 | |||
| 241 | - It checks the current file only; there is no command to check every file yet. | ||
| 242 | - IDs are found through orgstar's index of all your folders, not =org-id-locations=. org-lint finds an unknown ID only when =org-id-locations= is loaded and doesn't have it; Lint File always reports one. | ||
| 243 | - orgstar's own checkers, which org-lint doesn't have: =duplicate-id= (across your folders), =unknown-todo-keyword=, =missing-attachment-folder=, =orphaned-attachment-folder= and =invalid-file-search=. =unknown-todo-keyword= reports a heading starting with a keyword common in Org configurations (=NEXT=, =WAIT=, =HOLD=, …) or one letter away from a keyword of the file (=TODOX=), when the file and the configuration don't define it. | ||
| 244 | - Not checked: Babel header arguments and values and source block languages (=wrong-header-argument=, =wrong-header-value=, =empty-header-argument=, =deprecated-header-syntax=, =named-result=, =invalid-babel-call-block=, =suspicious-language-in-src-block=), which depend on the languages loaded in Emacs; export options, macros and =#+INCLUDE= (=unknown-options-item=, =misspelled-export-option=, =invalid-macro-argument-and-template=, =wrong-include-link-parameter=, =obsolete-include-markup=, =beamer-frame=), which depend on the export back-ends loaded; citations (=non-existent-bibliography=, =missing-print-bibliography=, =invalid-cite-export-declaration=, =incomplete-citation=); =item-number=, =LaTeX-$=, =trailing-bracket-after-link=, =unclosed-brackets-in-link-description=, =percent-encoding-link-escape=, =extraneous-element-in-footnote-section=, =invalid-image-alignment= and =combining-keywords-with-affiliated=, where orgstar's reading of lists, LaTeX fragments and links differs from Org's in details these checks depend on. | ||
| 245 | - Timestamps are checked against English day names, as Emacs writes them with the C locale. | ||
| 246 | - The panel lists everything; org-lint's =h= and =i= (hide or ignore a checker) and its prefix arguments (one category or one checker) aren't there. | ||
| 247 | |||
| 237 | ** Known differences from Emacs Org | 248 | ** Known differences from Emacs Org |
| 238 | 249 | ||
| 239 | orgstar refuses some things with a message rather than doing something different from Emacs. These are the ones found in the current version. | 250 | orgstar refuses some things with a message rather than doing something different from Emacs. These are the ones found in the current version. |
l10n/Localizable.xcstrings +481 · view
| @@ -2196,6 +2196,107 @@ | |||
| 2196 | } | 2196 | } |
| 2197 | } | 2197 | } |
| 2198 | }, | 2198 | }, |
| 2199 | "%lld problems": { | ||
| 2200 | "comment": "Lint File: the number of problems found", | ||
| 2201 | "localizations": { | ||
| 2202 | "de": { | ||
| 2203 | "variations": { | ||
| 2204 | "plural": { | ||
| 2205 | "one": { | ||
| 2206 | "stringUnit": { | ||
| 2207 | "state": "translated", | ||
| 2208 | "value": "%lld Problem" | ||
| 2209 | } | ||
| 2210 | }, | ||
| 2211 | "other": { | ||
| 2212 | "stringUnit": { | ||
| 2213 | "state": "translated", | ||
| 2214 | "value": "%lld Probleme" | ||
| 2215 | } | ||
| 2216 | } | ||
| 2217 | } | ||
| 2218 | } | ||
| 2219 | }, | ||
| 2220 | "en": { | ||
| 2221 | "variations": { | ||
| 2222 | "plural": { | ||
| 2223 | "one": { | ||
| 2224 | "stringUnit": { | ||
| 2225 | "state": "translated", | ||
| 2226 | "value": "%lld problem" | ||
| 2227 | } | ||
| 2228 | }, | ||
| 2229 | "other": { | ||
| 2230 | "stringUnit": { | ||
| 2231 | "state": "translated", | ||
| 2232 | "value": "%lld problems" | ||
| 2233 | } | ||
| 2234 | } | ||
| 2235 | } | ||
| 2236 | } | ||
| 2237 | }, | ||
| 2238 | "es": { | ||
| 2239 | "variations": { | ||
| 2240 | "plural": { | ||
| 2241 | "one": { | ||
| 2242 | "stringUnit": { | ||
| 2243 | "state": "translated", | ||
| 2244 | "value": "%lld problema" | ||
| 2245 | } | ||
| 2246 | }, | ||
| 2247 | "other": { | ||
| 2248 | "stringUnit": { | ||
| 2249 | "state": "translated", | ||
| 2250 | "value": "%lld problemas" | ||
| 2251 | } | ||
| 2252 | } | ||
| 2253 | } | ||
| 2254 | } | ||
| 2255 | }, | ||
| 2256 | "fr": { | ||
| 2257 | "variations": { | ||
| 2258 | "plural": { | ||
| 2259 | "one": { | ||
| 2260 | "stringUnit": { | ||
| 2261 | "state": "translated", | ||
| 2262 | "value": "%lld problème" | ||
| 2263 | } | ||
| 2264 | }, | ||
| 2265 | "other": { | ||
| 2266 | "stringUnit": { | ||
| 2267 | "state": "translated", | ||
| 2268 | "value": "%lld problèmes" | ||
| 2269 | } | ||
| 2270 | } | ||
| 2271 | } | ||
| 2272 | } | ||
| 2273 | }, | ||
| 2274 | "ja": { | ||
| 2275 | "stringUnit": { | ||
| 2276 | "state": "translated", | ||
| 2277 | "value": "%lld件の問題" | ||
| 2278 | } | ||
| 2279 | }, | ||
| 2280 | "pt-BR": { | ||
| 2281 | "variations": { | ||
| 2282 | "plural": { | ||
| 2283 | "one": { | ||
| 2284 | "stringUnit": { | ||
| 2285 | "state": "translated", | ||
| 2286 | "value": "%lld problema" | ||
| 2287 | } | ||
| 2288 | }, | ||
| 2289 | "other": { | ||
| 2290 | "stringUnit": { | ||
| 2291 | "state": "translated", | ||
| 2292 | "value": "%lld problemas" | ||
| 2293 | } | ||
| 2294 | } | ||
| 2295 | } | ||
| 2296 | } | ||
| 2297 | } | ||
| 2298 | } | ||
| 2299 | }, | ||
| 2199 | "%lld selected": { | 2300 | "%lld selected": { |
| 2200 | "localizations": { | 2301 | "localizations": { |
| 2201 | "de": { | 2302 | "de": { |
| @@ -8391,6 +8492,40 @@ | |||
| 8391 | } | 8492 | } |
| 8392 | } | 8493 | } |
| 8393 | }, | 8494 | }, |
| 8495 | "Checker": { | ||
| 8496 | "localizations": { | ||
| 8497 | "de": { | ||
| 8498 | "stringUnit": { | ||
| 8499 | "state": "translated", | ||
| 8500 | "value": "Prüfung" | ||
| 8501 | } | ||
| 8502 | }, | ||
| 8503 | "es": { | ||
| 8504 | "stringUnit": { | ||
| 8505 | "state": "translated", | ||
| 8506 | "value": "Comprobación" | ||
| 8507 | } | ||
| 8508 | }, | ||
| 8509 | "fr": { | ||
| 8510 | "stringUnit": { | ||
| 8511 | "state": "translated", | ||
| 8512 | "value": "Vérification" | ||
| 8513 | } | ||
| 8514 | }, | ||
| 8515 | "ja": { | ||
| 8516 | "stringUnit": { | ||
| 8517 | "state": "translated", | ||
| 8518 | "value": "チェック" | ||
| 8519 | } | ||
| 8520 | }, | ||
| 8521 | "pt-BR": { | ||
| 8522 | "stringUnit": { | ||
| 8523 | "state": "translated", | ||
| 8524 | "value": "Verificação" | ||
| 8525 | } | ||
| 8526 | } | ||
| 8527 | } | ||
| 8528 | }, | ||
| 8394 | "Choice %lld of %lld": { | 8529 | "Choice %lld of %lld": { |
| 8395 | "comment": "VoiceOver label for the echo area's count of matching choices", | 8530 | "comment": "VoiceOver label for the echo area's count of matching choices", |
| 8396 | "localizations": { | 8531 | "localizations": { |
| @@ -10050,6 +10185,40 @@ | |||
| 10050 | } | 10185 | } |
| 10051 | } | 10186 | } |
| 10052 | }, | 10187 | }, |
| 10188 | "Close the Lint File panel": { | ||
| 10189 | "localizations": { | ||
| 10190 | "de": { | ||
| 10191 | "stringUnit": { | ||
| 10192 | "state": "translated", | ||
| 10193 | "value": "Bereich „Datei prüfen“ schließen" | ||
| 10194 | } | ||
| 10195 | }, | ||
| 10196 | "es": { | ||
| 10197 | "stringUnit": { | ||
| 10198 | "state": "translated", | ||
| 10199 | "value": "Cerrar el panel Revisar archivo" | ||
| 10200 | } | ||
| 10201 | }, | ||
| 10202 | "fr": { | ||
| 10203 | "stringUnit": { | ||
| 10204 | "state": "translated", | ||
| 10205 | "value": "Fermer le panneau Vérifier le fichier" | ||
| 10206 | } | ||
| 10207 | }, | ||
| 10208 | "ja": { | ||
| 10209 | "stringUnit": { | ||
| 10210 | "state": "translated", | ||
| 10211 | "value": "「ファイルをチェック」パネルを閉じる" | ||
| 10212 | } | ||
| 10213 | }, | ||
| 10214 | "pt-BR": { | ||
| 10215 | "stringUnit": { | ||
| 10216 | "state": "translated", | ||
| 10217 | "value": "Fechar o painel Verificar Arquivo" | ||
| 10218 | } | ||
| 10219 | } | ||
| 10220 | } | ||
| 10221 | }, | ||
| 10053 | "Closed": { | 10222 | "Closed": { |
| 10054 | "localizations": { | 10223 | "localizations": { |
| 10055 | "de": { | 10224 | "de": { |
| @@ -15191,6 +15360,41 @@ | |||
| 15191 | } | 15360 | } |
| 15192 | } | 15361 | } |
| 15193 | }, | 15362 | }, |
| 15363 | "Error": { | ||
| 15364 | "comment": "Lint File: a problem org-lint trusts highly", | ||
| 15365 | "localizations": { | ||
| 15366 | "de": { | ||
| 15367 | "stringUnit": { | ||
| 15368 | "state": "translated", | ||
| 15369 | "value": "Fehler" | ||
| 15370 | } | ||
| 15371 | }, | ||
| 15372 | "es": { | ||
| 15373 | "stringUnit": { | ||
| 15374 | "state": "translated", | ||
| 15375 | "value": "Error" | ||
| 15376 | } | ||
| 15377 | }, | ||
| 15378 | "fr": { | ||
| 15379 | "stringUnit": { | ||
| 15380 | "state": "translated", | ||
| 15381 | "value": "Erreur" | ||
| 15382 | } | ||
| 15383 | }, | ||
| 15384 | "ja": { | ||
| 15385 | "stringUnit": { | ||
| 15386 | "state": "translated", | ||
| 15387 | "value": "エラー" | ||
| 15388 | } | ||
| 15389 | }, | ||
| 15390 | "pt-BR": { | ||
| 15391 | "stringUnit": { | ||
| 15392 | "state": "translated", | ||
| 15393 | "value": "Erro" | ||
| 15394 | } | ||
| 15395 | } | ||
| 15396 | } | ||
| 15397 | }, | ||
| 15194 | "Evaluate Time Range": { | 15398 | "Evaluate Time Range": { |
| 15195 | "comment": "Command title", | 15399 | "comment": "Command title", |
| 15196 | "localizations": { | 15400 | "localizations": { |
| @@ -22472,6 +22676,75 @@ | |||
| 22472 | } | 22676 | } |
| 22473 | } | 22677 | } |
| 22474 | }, | 22678 | }, |
| 22679 | "Line": { | ||
| 22680 | "localizations": { | ||
| 22681 | "de": { | ||
| 22682 | "stringUnit": { | ||
| 22683 | "state": "translated", | ||
| 22684 | "value": "Zeile" | ||
| 22685 | } | ||
| 22686 | }, | ||
| 22687 | "es": { | ||
| 22688 | "stringUnit": { | ||
| 22689 | "state": "translated", | ||
| 22690 | "value": "Línea" | ||
| 22691 | } | ||
| 22692 | }, | ||
| 22693 | "fr": { | ||
| 22694 | "stringUnit": { | ||
| 22695 | "state": "translated", | ||
| 22696 | "value": "Ligne" | ||
| 22697 | } | ||
| 22698 | }, | ||
| 22699 | "ja": { | ||
| 22700 | "stringUnit": { | ||
| 22701 | "state": "translated", | ||
| 22702 | "value": "行" | ||
| 22703 | } | ||
| 22704 | }, | ||
| 22705 | "pt-BR": { | ||
| 22706 | "stringUnit": { | ||
| 22707 | "state": "translated", | ||
| 22708 | "value": "Linha" | ||
| 22709 | } | ||
| 22710 | } | ||
| 22711 | } | ||
| 22712 | }, | ||
| 22713 | "Line %lld · %@": { | ||
| 22714 | "comment": "Lint File: a problem's line and checker", | ||
| 22715 | "localizations": { | ||
| 22716 | "de": { | ||
| 22717 | "stringUnit": { | ||
| 22718 | "state": "translated", | ||
| 22719 | "value": "Zeile %lld · %@" | ||
| 22720 | } | ||
| 22721 | }, | ||
| 22722 | "es": { | ||
| 22723 | "stringUnit": { | ||
| 22724 | "state": "translated", | ||
| 22725 | "value": "Línea %lld · %@" | ||
| 22726 | } | ||
| 22727 | }, | ||
| 22728 | "fr": { | ||
| 22729 | "stringUnit": { | ||
| 22730 | "state": "translated", | ||
| 22731 | "value": "Ligne %lld · %@" | ||
| 22732 | } | ||
| 22733 | }, | ||
| 22734 | "ja": { | ||
| 22735 | "stringUnit": { | ||
| 22736 | "state": "translated", | ||
| 22737 | "value": "%lld行 · %@" | ||
| 22738 | } | ||
| 22739 | }, | ||
| 22740 | "pt-BR": { | ||
| 22741 | "stringUnit": { | ||
| 22742 | "state": "translated", | ||
| 22743 | "value": "Linha %lld · %@" | ||
| 22744 | } | ||
| 22745 | } | ||
| 22746 | } | ||
| 22747 | }, | ||
| 22475 | "Line %lld, column %lld": { | 22748 | "Line %lld, column %lld": { |
| 22476 | "localizations": { | 22749 | "localizations": { |
| 22477 | "de": { | 22750 | "de": { |
| @@ -22854,6 +23127,76 @@ | |||
| 22854 | } | 23127 | } |
| 22855 | } | 23128 | } |
| 22856 | }, | 23129 | }, |
| 23130 | "Lint File": { | ||
| 23131 | "comment": "Command title", | ||
| 23132 | "localizations": { | ||
| 23133 | "de": { | ||
| 23134 | "stringUnit": { | ||
| 23135 | "state": "translated", | ||
| 23136 | "value": "Datei prüfen" | ||
| 23137 | } | ||
| 23138 | }, | ||
| 23139 | "es": { | ||
| 23140 | "stringUnit": { | ||
| 23141 | "state": "translated", | ||
| 23142 | "value": "Revisar archivo" | ||
| 23143 | } | ||
| 23144 | }, | ||
| 23145 | "fr": { | ||
| 23146 | "stringUnit": { | ||
| 23147 | "state": "translated", | ||
| 23148 | "value": "Vérifier le fichier" | ||
| 23149 | } | ||
| 23150 | }, | ||
| 23151 | "ja": { | ||
| 23152 | "stringUnit": { | ||
| 23153 | "state": "translated", | ||
| 23154 | "value": "ファイルをチェック" | ||
| 23155 | } | ||
| 23156 | }, | ||
| 23157 | "pt-BR": { | ||
| 23158 | "stringUnit": { | ||
| 23159 | "state": "translated", | ||
| 23160 | "value": "Verificar Arquivo" | ||
| 23161 | } | ||
| 23162 | } | ||
| 23163 | } | ||
| 23164 | }, | ||
| 23165 | "Lint File works on Org files": { | ||
| 23166 | "comment": "Lint File in a file that isn't Org", | ||
| 23167 | "localizations": { | ||
| 23168 | "de": { | ||
| 23169 | "stringUnit": { | ||
| 23170 | "state": "translated", | ||
| 23171 | "value": "„Datei prüfen“ funktioniert nur mit Org-Dateien" | ||
| 23172 | } | ||
| 23173 | }, | ||
| 23174 | "es": { | ||
| 23175 | "stringUnit": { | ||
| 23176 | "state": "translated", | ||
| 23177 | "value": "Revisar archivo funciona con archivos Org" | ||
| 23178 | } | ||
| 23179 | }, | ||
| 23180 | "fr": { | ||
| 23181 | "stringUnit": { | ||
| 23182 | "state": "translated", | ||
| 23183 | "value": "Vérifier le fichier fonctionne avec les fichiers Org" | ||
| 23184 | } | ||
| 23185 | }, | ||
| 23186 | "ja": { | ||
| 23187 | "stringUnit": { | ||
| 23188 | "state": "translated", | ||
| 23189 | "value": "「ファイルをチェック」はOrgファイルで使えます" | ||
| 23190 | } | ||
| 23191 | }, | ||
| 23192 | "pt-BR": { | ||
| 23193 | "stringUnit": { | ||
| 23194 | "state": "translated", | ||
| 23195 | "value": "Verificar Arquivo funciona com arquivos Org" | ||
| 23196 | } | ||
| 23197 | } | ||
| 23198 | } | ||
| 23199 | }, | ||
| 22857 | "Lisp %@": { | 23200 | "Lisp %@": { |
| 22858 | "comment": "Why a table needs Emacs: something its Lisp formula does", | 23201 | "comment": "Why a table needs Emacs: something its Lisp formula does", |
| 22859 | "localizations": { | 23202 | "localizations": { |
| @@ -27364,6 +27707,41 @@ | |||
| 27364 | } | 27707 | } |
| 27365 | } | 27708 | } |
| 27366 | }, | 27709 | }, |
| 27710 | "No problems found": { | ||
| 27711 | "comment": "Lint File", | ||
| 27712 | "localizations": { | ||
| 27713 | "de": { | ||
| 27714 | "stringUnit": { | ||
| 27715 | "state": "translated", | ||
| 27716 | "value": "Keine Probleme gefunden" | ||
| 27717 | } | ||
| 27718 | }, | ||
| 27719 | "es": { | ||
| 27720 | "stringUnit": { | ||
| 27721 | "state": "translated", | ||
| 27722 | "value": "No se encontraron problemas" | ||
| 27723 | } | ||
| 27724 | }, | ||
| 27725 | "fr": { | ||
| 27726 | "stringUnit": { | ||
| 27727 | "state": "translated", | ||
| 27728 | "value": "Aucun problème trouvé" | ||
| 27729 | } | ||
| 27730 | }, | ||
| 27731 | "ja": { | ||
| 27732 | "stringUnit": { | ||
| 27733 | "state": "translated", | ||
| 27734 | "value": "問題は見つかりませんでした" | ||
| 27735 | } | ||
| 27736 | }, | ||
| 27737 | "pt-BR": { | ||
| 27738 | "stringUnit": { | ||
| 27739 | "state": "translated", | ||
| 27740 | "value": "Nenhum problema encontrado" | ||
| 27741 | } | ||
| 27742 | } | ||
| 27743 | } | ||
| 27744 | }, | ||
| 27367 | "No recent clock": { | 27745 | "No recent clock": { |
| 27368 | "localizations": { | 27746 | "localizations": { |
| 27369 | "de": { | 27747 | "de": { |
| @@ -31587,6 +31965,40 @@ | |||
| 31587 | } | 31965 | } |
| 31588 | } | 31966 | } |
| 31589 | }, | 31967 | }, |
| 31968 | "Problem": { | ||
| 31969 | "localizations": { | ||
| 31970 | "de": { | ||
| 31971 | "stringUnit": { | ||
| 31972 | "state": "translated", | ||
| 31973 | "value": "Problem" | ||
| 31974 | } | ||
| 31975 | }, | ||
| 31976 | "es": { | ||
| 31977 | "stringUnit": { | ||
| 31978 | "state": "translated", | ||
| 31979 | "value": "Problema" | ||
| 31980 | } | ||
| 31981 | }, | ||
| 31982 | "fr": { | ||
| 31983 | "stringUnit": { | ||
| 31984 | "state": "translated", | ||
| 31985 | "value": "Problème" | ||
| 31986 | } | ||
| 31987 | }, | ||
| 31988 | "ja": { | ||
| 31989 | "stringUnit": { | ||
| 31990 | "state": "translated", | ||
| 31991 | "value": "問題" | ||
| 31992 | } | ||
| 31993 | }, | ||
| 31994 | "pt-BR": { | ||
| 31995 | "stringUnit": { | ||
| 31996 | "state": "translated", | ||
| 31997 | "value": "Problema" | ||
| 31998 | } | ||
| 31999 | } | ||
| 32000 | } | ||
| 32001 | }, | ||
| 31590 | "Promote": { | 32002 | "Promote": { |
| 31591 | "comment": "Key bar button", | 32003 | "comment": "Key bar button", |
| 31592 | "localizations": { | 32004 | "localizations": { |
| @@ -37199,6 +37611,40 @@ | |||
| 37199 | } | 37611 | } |
| 37200 | } | 37612 | } |
| 37201 | }, | 37613 | }, |
| 37614 | "Severity": { | ||
| 37615 | "localizations": { | ||
| 37616 | "de": { | ||
| 37617 | "stringUnit": { | ||
| 37618 | "state": "translated", | ||
| 37619 | "value": "Schwere" | ||
| 37620 | } | ||
| 37621 | }, | ||
| 37622 | "es": { | ||
| 37623 | "stringUnit": { | ||
| 37624 | "state": "translated", | ||
| 37625 | "value": "Gravedad" | ||
| 37626 | } | ||
| 37627 | }, | ||
| 37628 | "fr": { | ||
| 37629 | "stringUnit": { | ||
| 37630 | "state": "translated", | ||
| 37631 | "value": "Gravité" | ||
| 37632 | } | ||
| 37633 | }, | ||
| 37634 | "ja": { | ||
| 37635 | "stringUnit": { | ||
| 37636 | "state": "translated", | ||
| 37637 | "value": "重要度" | ||
| 37638 | } | ||
| 37639 | }, | ||
| 37640 | "pt-BR": { | ||
| 37641 | "stringUnit": { | ||
| 37642 | "state": "translated", | ||
| 37643 | "value": "Gravidade" | ||
| 37644 | } | ||
| 37645 | } | ||
| 37646 | } | ||
| 37647 | }, | ||
| 37202 | "Shift Timer Values in Region…": { | 37648 | "Shift Timer Values in Region…": { |
| 37203 | "comment": "Command title", | 37649 | "comment": "Command title", |
| 37204 | "localizations": { | 37650 | "localizations": { |
| @@ -44914,6 +45360,41 @@ | |||
| 44914 | } | 45360 | } |
| 44915 | } | 45361 | } |
| 44916 | }, | 45362 | }, |
| 45363 | "Warning": { | ||
| 45364 | "comment": "Lint File: a problem that may be intended", | ||
| 45365 | "localizations": { | ||
| 45366 | "de": { | ||
| 45367 | "stringUnit": { | ||
| 45368 | "state": "translated", | ||
| 45369 | "value": "Warnung" | ||
| 45370 | } | ||
| 45371 | }, | ||
| 45372 | "es": { | ||
| 45373 | "stringUnit": { | ||
| 45374 | "state": "translated", | ||
| 45375 | "value": "Advertencia" | ||
| 45376 | } | ||
| 45377 | }, | ||
| 45378 | "fr": { | ||
| 45379 | "stringUnit": { | ||
| 45380 | "state": "translated", | ||
| 45381 | "value": "Avertissement" | ||
| 45382 | } | ||
| 45383 | }, | ||
| 45384 | "ja": { | ||
| 45385 | "stringUnit": { | ||
| 45386 | "state": "translated", | ||
| 45387 | "value": "警告" | ||
| 45388 | } | ||
| 45389 | }, | ||
| 45390 | "pt-BR": { | ||
| 45391 | "stringUnit": { | ||
| 45392 | "state": "translated", | ||
| 45393 | "value": "Aviso" | ||
| 45394 | } | ||
| 45395 | } | ||
| 45396 | } | ||
| 45397 | }, | ||
| 44917 | "Was \"%@\"": { | 45398 | "Was \"%@\"": { |
| 44918 | "comment": "Rename: the config.toml setting before the change", | 45399 | "comment": "Rename: the config.toml setting before the change", |
| 44919 | "localizations": { | 45400 | "localizations": { |