| @@ -1,12 +1,12 @@ |
| 1 | import Foundation |
1 | import Foundation |
| 2 | |
2 | |
| 3 | // Clock tables (org-clock.el, Org 9.8.7): the `clocktable` dynamic block written by |
3 | // Clock tables (org-clock.el, Org 9.8.7): the `clocktable` dynamic block written by |
| 4 | // `org-clocktable-write-default` from `org-clock-sum`, updated by `org-update-dblock` (C-c C-c |
4 | // `org-clocktable-write-default` from `org-clock-get-table-data` and `org-clock-sum`, updated |
| 5 | // on its #+BEGIN line, C-c C-x C-u) and inserted by `org-clock-report` (C-c C-x C-r), with |
5 | // by `org-update-dblock` (C-c C-c on its #+BEGIN line, C-c C-x C-u) and inserted by |
| 6 | // `org-clocktable-defaults` and `org-duration-format` ((\"d\" . nil) (special . h:mm)). |
6 | // `org-clock-report` (C-c C-x C-r), with `org-clocktable-defaults` and `org-duration-format` |
| 7 | // Scopes within the file (file, subtree, tree, treeN); `:link` links within the file, as |
7 | // ((\"d\" . nil) (special . h:mm)). Scopes within the file (file, subtree, tree, treeN), the |
| 8 | // Emacs does in a buffer without a file. `:match`, `:step`, `:formatter` and scopes over |
8 | // agenda files, archives and lists of files, `:match`, and `:step`. Other files are read from |
| 9 | // other files aren't supported. |
9 | // disk. `:formatter` and scopes given as functions aren't supported. |
| 10 | |
10 | |
| 11 | enum ClockTable { |
11 | enum ClockTable { |
| 12 | struct Params { |
12 | struct Params { |
| @@ -131,42 +131,68 @@ enum ClockTable { |
| 131 | options: .anchorsMatchLines) |
131 | options: .anchorsMatchLines) |
| 132 | static let nakedClock = try! NSRegularExpression(pattern: "^[ \\t]*CLOCK:[ \\t]*=>[ \\t]+([0-9]+):([0-9]+)", options: .anchorsMatchLines) |
132 | static let nakedClock = try! NSRegularExpression(pattern: "^[ \\t]*CLOCK:[ \\t]*=>[ \\t]+([0-9]+):([0-9]+)", options: .anchorsMatchLines) |
| 133 | |
133 | |
| 134 | /// `org-clock-sum` over `region`: each heading's minutes with its subtree's, and the total. |
134 | /// `org-clock-sum` over `region`: the minutes of each heading with its subtree's, and the |
| 135 | static func sum(_ text: String, region: Range<Int>, tstart: Double?, tend: Double?, calendar: Calendar) -> (rows: [(start: Int, level: Int, minutes: Int)], total: Int) { |
135 | /// total. With `include`, headings it rejects add none of their own time, though their |
| |
136 | /// ancestors still show the time of included descendants. |
| |
137 | static func sum(_ text: String, region: Range<Int>, tstart: Double?, tend: Double?, calendar: Calendar, |
| |
138 | include: ((Int) -> Bool)? = nil) -> (rows: [(start: Int, level: Int, minutes: Int)], total: Int) { |
| 136 | let ns = text as NSString |
139 | let ns = text as NSString |
| 137 | let range = NSRange(region) |
140 | let range = NSRange(region) |
| 138 | var own: [Int: Int] = [:] // heading start → minutes |
| |
| 139 | let headings = (try! NSRegularExpression(pattern: "^(\\*+)[ \\t]", options: .anchorsMatchLines)).matches(in: text, range: range) |
| |
| 140 | .map { (start: $0.range.location, level: $0.range(at: 1).length) } |
| |
| 141 | func owner(_ offset: Int) -> Int? { headings.last { $0.start <= offset }?.start } |
| |
| 142 | func seconds(_ m: NSTextCheckingResult, _ first: Int) -> Double { |
141 | func seconds(_ m: NSTextCheckingResult, _ first: Int) -> Double { |
| 143 | let parts = (first..<(first + 5)).map { Int(ns.substring(with: m.range(at: $0)))! } |
142 | let parts = (first..<(first + 5)).map { Int(ns.substring(with: m.range(at: $0)))! } |
| 144 | return calendar.date(from: DateComponents(year: parts[0], month: parts[1], day: parts[2], hour: parts[3], minute: parts[4]))!.timeIntervalSince1970 |
143 | return calendar.date(from: DateComponents(year: parts[0], month: parts[1], day: parts[2], hour: parts[3], minute: parts[4]))!.timeIntervalSince1970 |
| 145 | } |
144 | } |
| |
145 | // Clock lines and headings, scanned from the end as Org does. |
| |
146 | enum Mark { case heading(level: Int), clock(Int) } |
| |
147 | var marks: [(offset: Int, mark: Mark)] = [] |
| |
148 | for m in headingLine.matches(in: text, range: range) { marks.append((m.range.location, .heading(level: m.range(at: 1).length))) } |
| 146 | for m in clockRange.matches(in: text, range: range) { |
149 | for m in clockRange.matches(in: text, range: range) { |
| 147 | guard let head = owner(m.range.location) else { continue } |
| |
| 148 | let ts = seconds(m, 1) |
150 | let ts = seconds(m, 1) |
| 149 | let te = seconds(m, 6) |
151 | let te = seconds(m, 6) |
| 150 | let dt = (tend.map { min(te, $0) } ?? te) - (tstart.map { max(ts, $0) } ?? ts) |
152 | let dt = (tend.map { min(te, $0) } ?? te) - (tstart.map { max(ts, $0) } ?? ts) |
| 151 | if dt > 0 { own[head, default: 0] += Int(floor(dt / 60)) } |
153 | marks.append((m.range.location, .clock(dt > 0 ? Int(floor(dt / 60)) : 0))) |
| 152 | } |
154 | } |
| 153 | for m in nakedClock.matches(in: text, range: range) { |
155 | for m in nakedClock.matches(in: text, range: range) { |
| 154 | guard let head = owner(m.range.location) else { continue } |
156 | marks.append((m.range.location, .clock(Int(ns.substring(with: m.range(at: 1)))! * 60 + Int(ns.substring(with: m.range(at: 2)))!))) |
| 155 | own[head, default: 0] += Int(ns.substring(with: m.range(at: 1)))! * 60 + Int(ns.substring(with: m.range(at: 2)))! |
| |
| 156 | } |
157 | } |
| |
158 | marks.sort { $0.offset > $1.offset } |
| |
159 | var ltimes = [Int](repeating: 0, count: 30) |
| |
160 | var t1 = 0 |
| |
161 | var forced: Set<Int> = [] |
| 157 | var rows: [(Int, Int, Int)] = [] |
162 | var rows: [(Int, Int, Int)] = [] |
| 158 | for (i, heading) in headings.enumerated() { |
163 | let ordered: [(start: Int, level: Int)] = marks.reversed().compactMap { mark in |
| 159 | var minutes = own[heading.start] ?? 0 |
164 | if case .heading(let level) = mark.mark { return (mark.offset, level) } |
| 160 | for later in headings[(i + 1)...] { |
165 | return nil |
| 161 | if later.level <= heading.level { break } |
166 | } |
| 162 | minutes += own[later.start] ?? 0 |
167 | for (offset, mark) in marks { |
| |
168 | switch mark { |
| |
169 | case .clock(let minutes): t1 += minutes |
| |
170 | case .heading(let level): |
| |
171 | while level >= ltimes.count { ltimes += [Int](repeating: 0, count: ltimes.count) } |
| |
172 | let included = include?(offset) ?? true |
| |
173 | if t1 > 0 || ltimes[level] > 0 { |
| |
174 | if included || forced.contains(offset) { |
| |
175 | if included { for l in 0...level { ltimes[l] += t1 } } |
| |
176 | rows.append((offset, level, ltimes[level])) |
| |
177 | if include != nil { |
| |
178 | // `org-clock-force-headline-inclusion` on the ancestors. |
| |
179 | var current = level |
| |
180 | for heading in ordered.reversed() where heading.start < offset && heading.level < current { |
| |
181 | forced.insert(heading.start) |
| |
182 | current = heading.level |
| |
183 | } |
| |
184 | } |
| |
185 | } |
| |
186 | t1 = 0 |
| |
187 | for l in level..<ltimes.count { ltimes[l] = 0 } |
| |
188 | } |
| 163 | } |
189 | } |
| 164 | if minutes > 0 { rows.append((heading.start, heading.level, minutes)) } |
| |
| 165 | } |
190 | } |
| 166 | let total = own.values.reduce(0, +) |
191 | return (rows.reversed().map { (start: $0.0, level: $0.1, minutes: $0.2) }, ltimes[0]) |
| 167 | return (rows.map { (start: $0.0, level: $0.1, minutes: $0.2) }, total) |
| |
| 168 | } |
192 | } |
| 169 | |
193 | |
| |
194 | static let headingLine = try! NSRegularExpression(pattern: "^(\\*+)[ \\t]", options: .anchorsMatchLines) |
| |
195 | |
| 170 | /// `org-shorten-string`. |
196 | /// `org-shorten-string`. |
| 171 | static func shorten(_ s: String, _ max: Int) -> String { |
197 | static func shorten(_ s: String, _ max: Int) -> String { |
| 172 | guard s.count > max else { return s } |
198 | guard s.count > max else { return s } |
| @@ -177,43 +203,33 @@ enum ClockTable { |
| 177 | return String(s.prefix(Swift.max(max - 3, 0))) + "..." |
203 | return String(s.prefix(Swift.max(max - 3, 0))) + "..." |
| 178 | } |
204 | } |
| 179 | |
205 | |
| 180 | /// The table `org-clocktable-write-default` writes, without its final newline. |
206 | /// What `org-clock-get-table-data` gives for one file: its name, its total and its rows. |
| 181 | static func write(_ buffer: EmacsBuffer, params: Params, region: Range<Int>, content: String) throws -> String { |
207 | struct FileTable { |
| |
208 | let path: String? |
| |
209 | let total: Int |
| |
210 | let rows: [Row] |
| |
211 | } |
| |
212 | |
| |
213 | /// `org-clock-get-table-data` over `region` of `buffer`, the file at `path`, between |
| |
214 | /// `tstart` and `tend` (seconds). |
| |
215 | static func tableData(_ buffer: EmacsBuffer, path: String?, params: Params, region: Range<Int>, tstart: Double?, tend: Double?) -> FileTable { |
| 182 | let maxlevel = params.int(":maxlevel") ?? 3 |
216 | let maxlevel = params.int(":maxlevel") ?? 3 |
| 183 | let emph = params.flag(":emphasize") |
| |
| 184 | let link = params.flag(":link") |
217 | let link = params.flag(":link") |
| 185 | let compact = params.flag(":compact") |
| |
| 186 | let showLevel = !compact && params.flag(":level") |
| |
| 187 | let showTags = params.flag(":tags") |
218 | let showTags = params.flag(":tags") |
| 188 | let indent = compact || params.flag(":indent") |
| |
| 189 | let percent = params.values[":formula"]?.symbol == "%" |
| |
| 190 | let properties = params.values[":properties"]?.elements?.compactMap(\.string) ?? [] |
219 | let properties = params.values[":properties"]?.elements?.compactMap(\.string) ?? [] |
| 191 | if params.values[":match"].map({ $0.symbol != "nil" }) ?? false { throw EmacsBuffer.UserError(message: "Clock tables with :match aren't supported yet") } |
| |
| 192 | if params.values[":step"].map({ $0.symbol != "nil" }) ?? false { throw EmacsBuffer.UserError(message: "Clock tables with :step aren't supported yet") } |
| |
| 193 | var narrow: Int? |
| |
| 194 | var narrowCut = false |
| |
| 195 | if let value = params.values[":narrow"] { |
| |
| 196 | if let n = value.integer { narrow = n } |
| |
| 197 | else if let s = value.symbol, let m = s.wholeMatch(of: /([0-9]+)!/) { narrow = Int(m.1); narrowCut = true } |
| |
| 198 | else if value.symbol != "nil" { throw EmacsBuffer.UserError(message: "Invalid value \(value.description) of :narrow property in clock table") } |
| |
| 199 | } |
| |
| 200 | if compact, narrow == nil { narrow = 40; narrowCut = true } |
| |
| 201 | if let n = narrow, !narrowCut, link { narrow = n; narrowCut = true } |
| |
| 202 | |
| |
| 203 | var tstart: Double? |
| |
| 204 | var tend: Double? |
| |
| 205 | var rangeText: String? |
| |
| 206 | if let block = params.symbol(":block") ?? params.values[":block"]?.integer.map(String.init), block != "nil" { |
| |
| 207 | let r = try range(block, now: buffer.now, calendar: buffer.calendar, wstart: params.int(":wstart") ?? 1, mstart: params.int(":mstart") ?? 1) |
| |
| 208 | (tstart, tend, rangeText) = (r.0, r.1, r.2) |
| |
| 209 | } else { |
| |
| 210 | if let s = params.values[":tstart"]?.string { tstart = TagsMatcher.matcherTime(s, now: buffer.now, calendar: buffer.calendar) } |
| |
| 211 | if let s = params.values[":tend"]?.string { tend = TagsMatcher.matcherTime(s, now: buffer.now, calendar: buffer.calendar) } |
| |
| 212 | } |
| |
| 213 | let text = buffer.string |
220 | let text = buffer.string |
| 214 | let summed = sum(text, region: region, tstart: tstart, tend: tend, calendar: buffer.calendar) |
221 | // `:match`: a tags/property/TODO match each heading's own time must pass. |
| |
222 | var include: ((Int) -> Bool)? |
| |
223 | if let match = params.values[":match"]?.string { |
| |
224 | let matcher = TagsMatcher(match) |
| |
225 | let source = AgendaSource(path: path ?? "", text: text, defaults: buffer.settings, checksBlocking: false) |
| |
226 | let byStart = Dictionary(source.headings.map { ($0.start, $0) }, uniquingKeysWith: { a, _ in a }) |
| |
227 | let now = buffer.now, calendar = buffer.calendar |
| |
228 | include = { start in byStart[start].map { matcher.matches($0, in: source, now: now, calendar: calendar) } ?? false } |
| |
229 | } |
| |
230 | let summed = sum(text, region: region, tstart: tstart, tend: tend, calendar: buffer.calendar, include: include) |
| 215 | var rows: [Row] = [] |
231 | var rows: [Row] = [] |
| 216 | for entry in summed.rows where entry.level <= maxlevel { |
232 | for entry in summed.rows where entry.minutes > 0 && entry.level <= maxlevel { |
| 217 | buffer.point = entry.start |
233 | buffer.point = entry.start |
| 218 | guard let match = buffer.lookingAt(buffer.complexHeadingPattern) else { continue } |
234 | guard let match = buffer.lookingAt(buffer.complexHeadingPattern) else { continue } |
| 219 | var title = match[4].map { buffer.substring($0.lowerBound, $0.upperBound) } ?? "" |
235 | var title = match[4].map { buffer.substring($0.lowerBound, $0.upperBound) } ?? "" |
| @@ -222,7 +238,7 @@ enum ClockTable { |
| 222 | if link { |
238 | if link { |
| 223 | let search = "*" + Links.normalize(title, context: false) |
239 | let search = "*" + Links.normalize(title, context: false) |
| 224 | let description = Links.displayFormat(title.replacingOccurrences(of: "\\[[0-9]*(?:%|/[0-9]*)\\]", with: "", options: .regularExpression)).trimmingCharacters(in: .whitespaces) |
240 | let description = Links.displayFormat(title.replacingOccurrences(of: "\\[[0-9]*(?:%|/[0-9]*)\\]", with: "", options: .regularExpression)).trimmingCharacters(in: .whitespaces) |
| 225 | headline = Links.makeString(search, description) |
241 | headline = Links.makeString(path.map { "file:\($0)::" + search } ?? search, description) |
| 226 | } |
242 | } |
| 227 | // `org-get-tags`: inherited ones first. |
243 | // `org-get-tags`: inherited ones first. |
| 228 | let own = buffer.tags() |
244 | let own = buffer.tags() |
| @@ -238,23 +254,75 @@ enum ClockTable { |
| 238 | } |
254 | } |
| 239 | rows.append(Row(level: entry.level, headline: headline, tags: tags, minutes: entry.minutes, properties: props)) |
255 | rows.append(Row(level: entry.level, headline: headline, tags: tags, minutes: entry.minutes, properties: props)) |
| 240 | } |
256 | } |
| 241 | let total = summed.total |
257 | return FileTable(path: path, total: summed.total, rows: rows) |
| 242 | let columns = compact || maxlevel < 2 ? 1 : min(maxlevel, params.int(":tcolumns") ?? 100, rows.map(\.level).max() ?? 1) |
258 | } |
| |
259 | |
| |
260 | /// The `:block`, or `:tstart` and `:tend`, as seconds, with the block's caption text. |
| |
261 | static func timeRange(_ params: Params, now: Date, calendar: Calendar) throws -> (start: Double?, end: Double?, text: String?) { |
| |
262 | if let block = params.symbol(":block") ?? params.values[":block"]?.integer.map(String.init), block != "nil" { |
| |
263 | let r = try range(block, now: now, calendar: calendar, wstart: params.int(":wstart") ?? 1, mstart: params.int(":mstart") ?? 1) |
| |
264 | return (r.0, r.1, r.2) |
| |
265 | } |
| |
266 | let start = params.values[":tstart"]?.string.map { TagsMatcher.matcherTime($0, now: now, calendar: calendar) } |
| |
267 | let end = params.values[":tend"]?.string.map { TagsMatcher.matcherTime($0, now: now, calendar: calendar) } |
| |
268 | return (start, end, nil) |
| |
269 | } |
| |
270 | |
| |
271 | /// The table `org-clocktable-write-default` writes for `tables`, without its final |
| |
272 | /// newline. `multifile` adds the File column and a row per file. |
| |
273 | static func write(_ buffer: EmacsBuffer, params: Params, tables: [FileTable], multifile: Bool, rangeText: String?, content: String) throws -> String { |
| |
274 | let maxlevel = params.int(":maxlevel") ?? 3 |
| |
275 | let emph = params.flag(":emphasize") |
| |
276 | let link = params.flag(":link") |
| |
277 | let compact = params.flag(":compact") |
| |
278 | let showLevel = !compact && params.flag(":level") |
| |
279 | let showTags = params.flag(":tags") |
| |
280 | let indent = compact || params.flag(":indent") |
| |
281 | let percent = params.values[":formula"]?.symbol == "%" |
| |
282 | let properties = params.values[":properties"]?.elements?.compactMap(\.string) ?? [] |
| |
283 | var narrow: Int? |
| |
284 | var narrowCut = false |
| |
285 | if let value = params.values[":narrow"] { |
| |
286 | if let n = value.integer { narrow = n } |
| |
287 | else if let s = value.symbol, let m = s.wholeMatch(of: /([0-9]+)!/) { narrow = Int(m.1); narrowCut = true } |
| |
288 | else if value.symbol != "nil" { throw EmacsBuffer.UserError(message: "Invalid value \(value.description) of :narrow property in clock table") } |
| |
289 | } |
| |
290 | if compact, narrow == nil { narrow = 40; narrowCut = true } |
| |
291 | if let n = narrow, !narrowCut, link { narrow = n; narrowCut = true } |
| 243 | |
292 | |
| 244 | let stamp = buffer.formatTimestamp(buffer.calendar.dateComponents([.year, .month, .day, .hour, .minute], from: buffer.now), withTime: true, inactive: true) |
293 | let total = tables.reduce(0) { $0 + $1.total } |
| 245 | var out = "#+CAPTION: Clock summary at \(stamp)\(rangeText.map { ", for \($0)." } ?? "")\n" |
294 | let levels = tables.filter { $0.total != 0 }.flatMap { $0.rows.map(\.level) } |
| |
295 | let columns = compact || maxlevel < 2 ? 1 : min(maxlevel, params.int(":tcolumns") ?? 100, levels.max() ?? 1) |
| |
296 | let file = multifile ? "|" : "" |
| |
297 | |
| |
298 | var out: String |
| |
299 | if let header = params.values[":header"]?.string { |
| |
300 | out = header |
| |
301 | } else { |
| |
302 | let stamp = buffer.formatTimestamp(buffer.calendar.dateComponents([.year, .month, .day, .hour, .minute], from: buffer.now), withTime: true, inactive: true) |
| |
303 | out = "#+CAPTION: Clock summary at \(stamp)\(rangeText.map { ", for \($0)." } ?? "")\n" |
| |
304 | } |
| 246 | if let narrow, !narrowCut { |
305 | if let narrow, !narrowCut { |
| 247 | out += "|" + (showLevel ? "|" : "") + (showTags ? "|" : "") + String(repeating: "|", count: properties.count) + "<\(narrow)>| |\n" |
306 | out += "|" + file + (showLevel ? "|" : "") + (showTags ? "|" : "") + String(repeating: "|", count: properties.count) + "<\(narrow)>| |\n" |
| 248 | } |
307 | } |
| 249 | out += "|" + (showLevel ? "L|" : "") + (showTags ? "Tags |" : "") + properties.map { $0 + "|" }.joined() |
308 | out += "|" + (multifile ? "File|" : "") + (showLevel ? "L|" : "") + (showTags ? "Tags |" : "") + properties.map { $0 + "|" }.joined() |
| 250 | + "Headline|Time|" + String(repeating: "|", count: max(0, columns - 1)) + (percent ? "%|\n" : "\n") |
309 | + "Headline|Time|" + String(repeating: "|", count: max(0, columns - 1)) + (percent ? "%|\n" : "\n") |
| 251 | out += "|-\n|" + (showLevel ? "|" : "") + (showTags ? "|" : "") + String(repeating: "|", count: properties.count) |
310 | out += "|-\n|" + (multifile ? "| ALL " : "") + (showLevel ? "|" : "") + (showTags ? "|" : "") + String(repeating: "|", count: properties.count) |
| 252 | + "*Total time*| *\(duration(total))*|" + String(repeating: "|", count: max(0, columns - 1)) |
311 | + "*Total time*| *\(duration(total))*|" + String(repeating: "|", count: max(0, columns - 1)) |
| 253 | + (percent ? (total == 0 ? "0.0|" : "100.0|") : "") + "\n" |
312 | + (percent ? (total == 0 ? "0.0|" : "100.0|") : "") + "\n" |
| 254 | if total > 0 { |
313 | if total > 0 { |
| 255 | if total > 0 || !params.flag(":fileskip0") { out += "|-\n" } |
314 | for table in tables where table.total > 0 || !params.flag(":fileskip0") { |
| 256 | if maxlevel > 0 { |
315 | out += "|-\n" |
| 257 | for row in rows { |
316 | if multifile { |
| |
317 | let name = table.path.map { path in |
| |
318 | (params.flag(":filetitle") ? Self.title(path) : nil) ?? (path as NSString).lastPathComponent |
| |
319 | } ?? "" |
| |
320 | out += "| \(name) " + (showLevel ? "| " : "") + "| " + (showTags ? "| " : "") + String(repeating: "|", count: properties.count) |
| |
321 | + "*File time* | *\(duration(table.total))*|" + String(repeating: "|", count: max(0, columns - 1)) |
| |
322 | + (percent ? String(format: " %.1f |", 100 * Double(table.total) / Double(total)) : "") + "\n" |
| |
323 | } |
| |
324 | guard maxlevel > 0 else { continue } |
| |
325 | for row in table.rows { |
| 258 | var headline = row.headline |
326 | var headline = row.headline |
| 259 | if narrowCut, let narrow { |
327 | if narrowCut, let narrow { |
| 260 | if let m = headline.wholeMatch(of: /\[\[(.+?)\]\[(.+)\]\]/) { |
328 | if let m = headline.wholeMatch(of: /\[\[(.+?)\]\[(.+)\]\]/) { |
| @@ -267,7 +335,7 @@ enum ClockTable { |
| 267 | guard emph else { return f + " |" } |
335 | guard emph else { return f + " |" } |
| 268 | return row.level == 1 ? "*\(f)* |" : row.level == 2 ? "/\(f)/ |" : f + " |" |
336 | return row.level == 1 ? "*\(f)* |" : row.level == 2 ? "/\(f)/ |" : f + " |" |
| 269 | } |
337 | } |
| 270 | out += "|" + (showLevel ? "\(row.level)|" : "") + (showTags ? row.tags.joined(separator: ", ") + "|" : "") |
338 | out += "|" + file + (showLevel ? "\(row.level)|" : "") + (showTags ? row.tags.joined(separator: ", ") + "|" : "") |
| 271 | + properties.map { (row.properties[$0] ?? "") + "|" }.joined() |
339 | + properties.map { (row.properties[$0] ?? "") + "|" }.joined() |
| 272 | + (indent && row.level > 1 ? "\\_" + String(repeating: " ", count: 2 * (row.level - 1)) : "") |
340 | + (indent && row.level > 1 ? "\\_" + String(repeating: " ", count: 2 * (row.level - 1)) : "") |
| 273 | + field(headline) + String(repeating: "|", count: max(0, min(columns, row.level) - 1)) |
341 | + field(headline) + String(repeating: "|", count: max(0, min(columns, row.level) - 1)) |
| @@ -284,6 +352,16 @@ enum ClockTable { |
| 284 | } |
352 | } |
| 285 | return out |
353 | return out |
| 286 | } |
354 | } |
| |
355 | |
| |
356 | /// `org-get-title` of the file at `path`. |
| |
357 | static func title(_ path: String) -> String? { |
| |
358 | guard let text = try? String(contentsOfFile: path, encoding: .utf8) else { return nil } |
| |
359 | let titles = text.components(separatedBy: "\n").compactMap { line -> String? in |
| |
360 | guard let r = line.range(of: "^#\\+(?i:title):[ \\t]*", options: .regularExpression) else { return nil } |
| |
361 | return String(line[r.upperBound...]).trimmingCharacters(in: .whitespaces) |
| |
362 | } |
| |
363 | return titles.isEmpty ? nil : titles.joined(separator: " ") |
| |
364 | } |
| 287 | } |
365 | } |
| 288 | |
366 | |
| 289 | extension EmacsBuffer { |
367 | extension EmacsBuffer { |
| @@ -322,12 +400,73 @@ extension EmacsBuffer { |
| 322 | } |
400 | } |
| 323 | guard name == "clocktable" else { throw UserError(message: "Dynamic blocks named \(name) aren't supported") } |
401 | guard name == "clocktable" else { throw UserError(message: "Dynamic blocks named \(name) aren't supported") } |
| 324 | let params = try ClockTable.Params(paramText) |
402 | let params = try ClockTable.Params(paramText) |
| 325 | // The scope's text. |
403 | let range = try ClockTable.timeRange(params, now: now, calendar: calendar) |
| |
404 | if let step = params.symbol(":step"), step != "nil" { |
| |
405 | let table = try clockTableSteps(step, params: params, begin: begin, range: range, content: content) |
| |
406 | try replaceDynamicBlockContent(at: begin, with: table, alignAll: true) |
| |
407 | return |
| |
408 | } |
| |
409 | let tables = try clockTables(params, begin: begin, tstart: range.start, tend: range.end) |
| |
410 | let table = try ClockTable.write(self, params: params, tables: tables.tables, multifile: tables.multifile, rangeText: range.text, content: content) |
| |
411 | try replaceDynamicBlockContent(at: begin, with: table) |
| |
412 | } |
| |
413 | |
| |
414 | /// The files `:scope` names and each one's table data, and whether the table gets a File |
| |
415 | /// column, as `org-dblock-write:clocktable` works them out. |
| |
416 | func clockTables(_ params: ClockTable.Params, begin: Int, tstart: Double?, tend: Double?) throws -> (tables: [ClockTable.FileTable], multifile: Bool) { |
| |
417 | let path = options.filePath |
| |
418 | func read(_ file: String) -> String? { |
| |
419 | file == path ? string : (try? String(contentsOfFile: file, encoding: .utf8)) |
| |
420 | } |
| |
421 | let files: [String]? |
| |
422 | let scopeValue = params.values[":scope"] ?? .symbol("file") |
| |
423 | let scope = scopeValue.symbol ?? scopeValue.string ?? "" |
| |
424 | if let list = scopeValue.elements, scopeValue.symbol == nil { |
| |
425 | // A list of files; folders give their org files, as agenda entries do. |
| |
426 | let base = path.map { ($0 as NSString).deletingLastPathComponent } |
| |
427 | var expanded: [String] = [] |
| |
428 | for item in list { |
| |
429 | guard let name = item.string else { throw UserError(message: "Unknown scope: \(scopeValue.description)") } |
| |
430 | var file = (name as NSString).expandingTildeInPath |
| |
431 | if !file.hasPrefix("/"), let base { file = (base as NSString).appendingPathComponent(file) } |
| |
432 | file = (file as NSString).standardizingPath |
| |
433 | var isDirectory: ObjCBool = false |
| |
434 | if FileManager.default.fileExists(atPath: file, isDirectory: &isDirectory), isDirectory.boolValue { |
| |
435 | let names = (try? FileManager.default.contentsOfDirectory(atPath: file)) ?? [] |
| |
436 | expanded += names.sorted().filter { !$0.hasPrefix(".") && $0.hasSuffix(".org") }.map { (file as NSString).appendingPathComponent($0) } |
| |
437 | } else { |
| |
438 | expanded.append(file) |
| |
439 | } |
| |
440 | } |
| |
441 | files = expanded |
| |
442 | } else { |
| |
443 | switch scope { |
| |
444 | case "agenda": files = options.agendaFiles ?? [] |
| |
445 | case "agenda-with-archives": files = Archive.addArchiveFiles(options.agendaFiles ?? [], options: options, read: read) |
| |
446 | case "file-with-archives": files = path.map { Archive.addArchiveFiles([$0], options: options, read: read) } |
| |
447 | case "nil", "file", "subtree", "tree": files = nil |
| |
448 | case let s where s.wholeMatch(of: /tree[0-9]+/) != nil: files = nil |
| |
449 | default: throw UserError(message: "Unknown scope: \(scopeValue.description)") |
| |
450 | } |
| |
451 | } |
| |
452 | if let files, scope != "file-with-archives" || path != nil { |
| |
453 | var tables: [ClockTable.FileTable] = [] |
| |
454 | for file in files { |
| |
455 | guard let text = read(file) else { continue } |
| |
456 | let buffer = file == path ? self : EmacsBuffer(text, point: 0, settings: OrgParser.parse(text).settings, options: options) |
| |
457 | buffer.now = now |
| |
458 | buffer.calendar = calendar |
| |
459 | let saved = point |
| |
460 | tables.append(ClockTable.tableData(buffer, path: file, params: params, region: 0..<buffer.length, tstart: tstart, tend: tend)) |
| |
461 | point = saved |
| |
462 | } |
| |
463 | // `file-with-archives` counts as one extended file. |
| |
464 | return (tables, !params.flag(":hidefiles") && scope != "file-with-archives") |
| |
465 | } |
| |
466 | // The scope's text in this buffer. |
| 326 | point = begin |
467 | point = begin |
| 327 | let region: Range<Int> |
468 | let region: Range<Int> |
| 328 | switch params.symbol(":scope") ?? "file" { |
469 | switch scope { |
| 329 | case "nil", "file": |
| |
| 330 | region = 0..<length |
| |
| 331 | case "subtree": |
470 | case "subtree": |
| 332 | guard !beforeFirstHeading, let r = try? subtreeRange() else { throw UserError(message: "Before first headline") } |
471 | guard !beforeFirstHeading, let r = try? subtreeRange() else { throw UserError(message: "Before first headline") } |
| 333 | region = r |
472 | region = r |
| @@ -339,16 +478,71 @@ extension EmacsBuffer { |
| 339 | if let limit, outlineLevel <= limit { break } |
478 | if let limit, outlineLevel <= limit { break } |
| 340 | } |
479 | } |
| 341 | region = try subtreeRange() |
480 | region = try subtreeRange() |
| 342 | case let scope: |
481 | default: |
| 343 | throw UserError(message: "Clock tables over \(scope) aren't supported yet") |
482 | region = 0..<length |
| 344 | } |
483 | } |
| 345 | let table = try ClockTable.write(self, params: params, region: region, content: content) |
484 | return ([ClockTable.tableData(self, path: path, params: params, region: region, tstart: tstart, tend: tend)], false) |
| 346 | try replaceDynamicBlockContent(at: begin, with: table) |
485 | } |
| |
486 | |
| |
487 | /// `org-clocktable-steps`: a table per day, week, semimonth, month, quarter or year of the |
| |
488 | /// range, each after a line naming its start; with `:stepskip0`, only those with time. |
| |
489 | func clockTableSteps(_ step: String, params: ClockTable.Params, begin: Int, range: (start: Double?, end: Double?, text: String?), content: String) throws -> String { |
| |
490 | let headers = ["day": "Daily report: ", "week": "Weekly report starting on: ", "semimonth": "Semimonthly report starting on: ", |
| |
491 | "month": "Monthly report starting on: ", "year": "Annual report starting on: ", "quarter": "Quarterly report starting on: "] |
| |
492 | guard let stepHeader = headers[step] else { throw UserError(message: "Unknown `:step' specification: \(step)") } |
| |
493 | guard let start = range.start, let end = range.end else { |
| |
494 | throw UserError(message: "Clocktable `:step' can only be used with `:block' or `:tstart', `:tend'") |
| |
495 | } |
| |
496 | let weekStart = params.int(":wstart") ?? 1 |
| |
497 | let monthStart = params.int(":mstart") ?? 1 |
| |
498 | var stepParams = params |
| |
499 | stepParams.values[":header"] = .string("") |
| |
500 | stepParams.values[":step"] = nil |
| |
501 | stepParams.values[":block"] = nil |
| |
502 | // The block's contents as `org-clocktable-steps` builds them after `org-prepare-dblock`'s |
| |
503 | // `open-line`, with point at `p`; `out` ends where the #+END line starts. |
| |
504 | var out = "\n" |
| |
505 | var p = 0 |
| |
506 | var at = Date(timeIntervalSince1970: start) |
| |
507 | let stop = Date(timeIntervalSince1970: end) |
| |
508 | while at < stop { |
| |
509 | let c = calendar.dateComponents([.year, .month, .day, .weekday], from: at) |
| |
510 | let (y, m, d, dow) = (c.year!, c.month!, c.day!, c.weekday! - 1) |
| |
511 | func date(_ year: Int, _ month: Int, _ day: Int) -> Date { |
| |
512 | calendar.date(from: DateComponents(year: year, month: month, day: day))! |
| |
513 | } |
| |
514 | let next: Date = switch step { |
| |
515 | case "day": date(y, m, d + 1) |
| |
516 | case "week": date(y, m, d + (dow == weekStart ? 7 : ((weekStart - dow) % 7 + 7) % 7)) |
| |
517 | case "semimonth": d < 16 ? date(y, m, 16) : date(y, m + 1, 1) |
| |
518 | case "month": date(y, m + 1, monthStart) |
| |
519 | case "quarter": date(y, m + 3, monthStart) |
| |
520 | default: date(y + 1, 1, 1) |
| |
521 | } |
| |
522 | let tables = try clockTables(stepParams, begin: begin, tstart: at.timeIntervalSince1970, tend: min(next, stop).timeIntervalSince1970) |
| |
523 | let total = tables.tables.reduce(0) { $0 + $1.total } |
| |
524 | let stamp = formatTimestamp(calendar.dateComponents([.year, .month, .day], from: at), withTime: false, inactive: true) |
| |
525 | let table = try ClockTable.write(self, params: stepParams, tables: tables.tables, multifile: tables.multifile, rangeText: nil, content: content) |
| |
526 | if p > 0, (out as NSString).character(at: p - 1) != 10 { |
| |
527 | out = (out as NSString).replacingCharacters(in: NSRange(location: p, length: 0), with: "\n") |
| |
528 | p += 1 |
| |
529 | } |
| |
530 | let tableBegin = p + 1 |
| |
531 | out = (out as NSString).replacingCharacters(in: NSRange(location: p, length: 0), with: "\n" + stepHeader + stamp + "\n" + table) |
| |
532 | // An empty table goes, from its header line to the #+END line. |
| |
533 | if params.flag(":stepskip0"), total == 0 { |
| |
534 | out = (out as NSString).substring(to: tableBegin) |
| |
535 | } |
| |
536 | // `(end-of-line 0)` from the #+END line. |
| |
537 | p = max(0, (out as NSString).length - 1) |
| |
538 | at = next |
| |
539 | } |
| |
540 | return String(out.dropLast()) |
| 347 | } |
541 | } |
| 348 | |
542 | |
| 349 | /// Puts `table` between the #+BEGIN and #+END lines of the block at `begin`, indented like |
543 | /// Puts `table` between the #+BEGIN and #+END lines of the block at `begin`, indented like |
| 350 | /// the #+BEGIN line as `org-update-dblock` does, and aligns it. |
544 | /// the #+BEGIN line as `org-update-dblock` does, and aligns it. |
| 351 | func replaceDynamicBlockContent(at begin: Int, with table: String, recalculate: Bool = false) throws { |
545 | func replaceDynamicBlockContent(at begin: Int, with table: String, recalculate: Bool = false, alignAll: Bool = false) throws { |
| 352 | point = begin |
546 | point = begin |
| 353 | guard let start = lookingAt(Self.dblockStart) else { throw UserError(message: "Not at a dynamic block") } |
547 | guard let start = lookingAt(Self.dblockStart) else { throw UserError(message: "Not at a dynamic block") } |
| 354 | let indentation = currentIndentation |
548 | let indentation = currentIndentation |
| @@ -372,7 +566,9 @@ extension EmacsBuffer { |
| 372 | insert(pad) |
566 | insert(pad) |
| 373 | } |
567 | } |
| 374 | point = deleteFrom |
568 | point = deleteFrom |
| 375 | if let bar = searchForward("^[ \\t]*\\|", caseInsensitive: false) { |
569 | let endMark = marker(deleteFrom + (table as NSString).length + 1) |
| |
570 | defer { release(endMark) } |
| |
571 | while let bar = searchForward("^[ \\t]*\\|", bound: endMark.position, caseInsensitive: false) { |
| 376 | point = bar[0]!.upperBound |
572 | point = bar[0]!.upperBound |
| 377 | // A table kept with formulas is recalculated, as the column view writer does. |
573 | // A table kept with formulas is recalculated, as the column view writer does. |
| 378 | if recalculate { |
574 | if recalculate { |
| @@ -383,6 +579,10 @@ extension EmacsBuffer { |
| 383 | } |
579 | } |
| 384 | } |
580 | } |
| 385 | tableAlign() |
581 | tableAlign() |
| |
582 | // `:step` writes a table per step, each aligned. |
| |
583 | guard alignAll else { break } |
| |
584 | point = lineStart(point) |
| |
585 | while lookingAt("^[ \\t]*\\|") != nil, forwardLine(1) == 0 {} |
| 386 | } |
586 | } |
| 387 | point = begin |
587 | point = begin |
| 388 | } |
588 | } |