Sources/OrgCore/Commands/Fill.swift
681 lines · 31478 bytes
32 symbols in this file
ElementelementelementcontentsEnditemBodyColumnorgAdaptiveFillPrefixpostAffiliatedmatchAdaptivePrefixskipLineStartMarkupcontextPrefixfillNoBreakmoveToBreakPointskipBackwardcanonicallySpacefillRegionAsParagraphfillParagraphfillParagraphsparagraphBackwardStopfillRegionparagraphContentsBeginFillParagraphappliesrunFillRegionappliesrunautoFillcommentLineBreakdeleteBlanksAroundAutoFillSpaceappliesrun
1import Foundation
2
3// M-q: `org-fill-paragraph` (Org 9.8.7) over Emacs's `fill-region-as-paragraph` (fill.el), for
4// paragraphs, comments and comment blocks, with `sentence-end-double-space` nil,
5// `colon-double-space` nil, `left-margin` 0 and left justification.
6
7extension EmacsBuffer {
8 /// `org-element-paragraph-separate`, which org uses as `paragraph-start`.
9 var paragraphStartPattern: String {
10 let letters = options.listAllowAlphabetical ? "|[A-Za-z]" : ""
11 return "(?:\\*+ |\\[fn:[-_\\w]+\\]|%%\\(|[ \\t]*(?:$|\\||\\+(?:-+\\+)+[ \\t]*$|#(?: |$|\\+(?:BEGIN_\\S+|\\S+(?:\\[.*\\])?:[ \\t]*))|:(?: |$|[-_\\w]+:[ \\t]*$)|-{5,}[ \\t]*$|\\\\begin\\{([A-Za-z0-9*]+)\\}|(?:[-+*]|(?:[0-9]+\(letters))[.)])(?:[ \\t]|$)))"
12 }
13
14 static let adaptiveFillPattern = "[-–!|#%;>*·•‣⁃◦ \\t]*"
15 static let sentenceEndPattern = "([.?!…‽][\\]\"'”’)}»›]*($|[\\t \\u00A0])|[。.?!]+)[ \\u00A0\\t\\n]*"
16
17 /// An element as `org-element-at-point` sees it, with offsets in the buffer.
18 struct Element {
19 let kind: SyntaxKind
20 let range: Range<Int>
21 /// The enclosing element, for paragraphs in items.
22 let parentKind: SyntaxKind?
23 let parentStart: Int?
24 /// For blocks: the word after `#+begin_`, lowercased.
25 let blockType: String?
26 /// For plain lists: the first item's start.
27 let firstItem: Int?
28 }
29
30 static let elementKinds: Set<SyntaxKind> = [.paragraph, .comment, .block, .table, .tableRow, .item, .plainList, .heading,
31 .keyword, .fixedWidth, .drawer, .propertyDrawer, .planning, .dynamicBlock,
32 .footnoteDefinition, .horizontalRule, .clock, .nodeProperty]
33
34 /// The innermost element (not object) holding `offset`, as `org-element-at-point`. Greater
35 /// blocks (quote, center, special) are parsed into their elements.
36 func element(at offset: Int) -> Element? {
37 // Elements never cross a heading, so the section around `offset` is enough to parse.
38 let lineBegin = lineStart(offset)
39 let from = headingLevel(atLine: lineBegin) != nil ? lineBegin : (previousHeadingStart(before: lineBegin) ?? 0)
40 let to = nextHeadingStart(after: lineBegin) ?? length
41 return element(at: offset, in: substring(from, to), base: from)
42 }
43
44 private func element(at offset: Int, in text: String, base: Int) -> Element? {
45 let tree = OrgParser.parse(text, defaults: settings)
46 let local = offset - base
47 var node = tree.root
48 var found: SyntaxNode?
49 while true {
50 let child = node.child(containing: local) ?? (local == node.range.upperBound ? node.children.last : nil)
51 guard let child, Self.elementKinds.contains(child.kind) || child.kind == .section || child.kind == .zerothSection else { break }
52 if Self.elementKinds.contains(child.kind) { found = child }
53 if [.heading, .paragraph, .comment, .tableRow, .block].contains(child.kind) { break }
54 node = child
55 }
56 guard let found else { return nil }
57 let range = (found.range.lowerBound + base)..<(found.range.upperBound + base)
58 var blockType: String?
59 if found.kind == .block {
60 let first = found.text.prefix { $0 != "\n" }.lowercased()
61 blockType = first.firstMatch(of: /#\+begin_(\S+)/).map { String($0.1) }
62 if let type = blockType, !["src", "example", "export", "comment", "verse"].contains(type) {
63 let contentsStart = lineEnd(range.lowerBound) + 1
64 let closing = saveExcursion { () -> Int in
65 point = range.upperBound
66 skipBackward(Self.whitespace)
67 return lineStart(point)
68 }
69 if offset >= contentsStart, offset < closing, contentsStart < closing {
70 return element(at: offset, in: substring(contentsStart, closing), base: contentsStart)
71 }
72 }
73 }
74 let parent = found.parent.flatMap { Self.elementKinds.contains($0.kind) ? $0 : nil }
75 return Element(
76 kind: found.kind, range: range, parentKind: parent?.kind, parentStart: parent.map { $0.range.lowerBound + base },
77 blockType: blockType, firstItem: found.children.first { $0.kind == .item }.map { $0.range.lowerBound + base }
78 )
79 }
80
81 /// Where an element's contents end: after its last non-blank line.
82 func contentsEnd(_ node: Element) -> Int {
83 saveExcursion {
84 point = node.range.upperBound
85 skipBackward(Self.whitespace)
86 return min(lineEnd(point) + 1, length)
87 }
88 }
89
90 /// `org-list-item-body-column`.
91 func itemBodyColumn(_ item: Int) -> Int {
92 saveExcursion {
93 point = item
94 let match = looking("[ \\t]*(\\S+)", setsMatch: false)!
95 point = match[1]!.upperBound
96 return currentColumn + 1
97 }
98 }
99
100 /// `org-adaptive-fill-function` at point's line.
101 func orgAdaptiveFillPrefix() -> String? {
102 saveExcursion {
103 guard !atHeading else { return nil }
104 let lineBegin = lineStart(point)
105 guard let element = element(at: lineBegin) else { return nil }
106 switch element.kind {
107 case .comment:
108 point = lineBegin
109 let indent = substring(lineBegin, lineBegin + (looking("[ \\t]*", setsMatch: false).map { $0[0]!.count } ?? 0))
110 return indent + "# "
111 case .item, .plainList:
112 let item = element.kind == .item ? element.range.lowerBound : (element.firstItem ?? element.range.lowerBound)
113 return String(repeating: " ", count: itemBodyColumn(item))
114 case .block where element.blockType == "comment":
115 let begin = lineEnd(element.range.lowerBound) + 1
116 let end = saveExcursion { () -> Int in
117 point = element.range.upperBound
118 skipBackward(Self.whitespace)
119 return lineStart(point)
120 }
121 guard lineBegin >= begin, lineBegin < end else { return nil }
122 point = lineBegin
123 return looking("[ \\t]+", setsMatch: false).map { substring($0[0]!.lowerBound, $0[0]!.upperBound) } ?? ""
124 case .paragraph:
125 point = lineBegin
126 if element.parentKind == .item, let parent = element.parentStart {
127 return String(repeating: " ", count: itemBodyColumn(parent))
128 }
129 if let prefix = contextPrefix(from: postAffiliated(element), to: element.range.upperBound, paragraphOnly: true) {
130 return prefix
131 }
132 return looking("[ \\t]+", setsMatch: false).map { substring($0[0]!.lowerBound, $0[0]!.upperBound) } ?? ""
133 default:
134 return nil
135 }
136 }
137 }
138
139 /// Start of an element after its affiliated keywords.
140 func postAffiliated(_ node: Element) -> Int {
141 saveExcursion {
142 point = node.range.lowerBound
143 while looking("[ \\t]*#\\+(?:CAPTION|DATA|HEADERS?|LABEL|NAME|PLOT|RESNAME|RESULTS?|SOURCE|SRCNAME|TBLNAME|ATTR_[-_\\w]+)(?:\\[.*\\])?:", setsMatch: false) != nil {
144 if forwardLine(1) != 0 { break }
145 }
146 return point
147 }
148 }
149
150 /// `fill-match-adaptive-prefix`, with org's function or, in paragraphs, the regexp after
151 /// any markup at the line start.
152 func matchAdaptivePrefix(paragraphOnly: Bool) -> String? {
153 let prefix: String?
154 if paragraphOnly {
155 let start = point
156 prefix = saveExcursion {
157 skipLineStartMarkup()
158 return looking(Self.adaptiveFillPattern, setsMatch: false).map { substring($0[0]!.lowerBound, $0[0]!.upperBound) }
159 }
160 point = start
161 } else {
162 prefix = orgAdaptiveFillPrefix() ?? looking(Self.adaptiveFillPattern, setsMatch: false).map { substring($0[0]!.lowerBound, $0[0]!.upperBound) }
163 }
164 guard let prefix else { return nil }
165 return (prefix as NSString).length >= options.fillColumn ? nil : prefix
166 }
167
168 /// Moves past the opening markup of an object that starts at point, as
169 /// `org-adaptive-fill-paragraph-function` does.
170 private func skipLineStartMarkup() {
171 let line = substring(point, lineEnd(point)) + "\n"
172 let tree = OrgParser.parse(line, defaults: settings)
173 var node: SyntaxNode? = tree.root
174 while let current = node, let child = current.child(containing: 0), child.range.lowerBound == 0 {
175 if [.bold, .italic, .underline, .strikeThrough].contains(child.kind) {
176 point += 1
177 return
178 }
179 if child.kind == .link, let description = child.firstChild(.linkDescription) {
180 point += description.range.lowerBound
181 return
182 }
183 node = child
184 }
185 }
186
187 /// `fill-context-prefix`.
188 func contextPrefix(from: Int, to: Int, paragraphOnly: Bool = false) -> String? {
189 saveExcursion {
190 point = from
191 if eolp { forwardLine(1) }
192 point = lineStart(point)
193 var first = matchAdaptivePrefix(paragraphOnly: paragraphOnly)
194 forwardLine(1)
195 if point < to {
196 point = lineStart(point)
197 let second: String? = looking(paragraphStartPattern, setsMatch: false) != nil ? nil : matchAdaptivePrefix(paragraphOnly: paragraphOnly)
198 if let second {
199 if first == nil { first = "" }
200 var pattern = "^"
201 var rest = Substring(second)
202 while let match = rest.firstMatch(of: /^[ \t]*([^ \t]+)/) {
203 pattern += ".*" + NSRegularExpression.escapedPattern(for: String(match.1))
204 rest = rest[match.range.upperBound...]
205 }
206 if first!.range(of: pattern, options: .regularExpression) != nil { return second }
207 let common = zip(first!, second).prefix { $0 == $1 }.count
208 return common == 0 ? nil : String(first!.prefix(common))
209 }
210 }
211 guard let firstPrefix = first else { return nil }
212 let keep = firstPrefix.allSatisfy({ $0 == " " || $0 == "\t" }) || firstPrefix.range(of: "^\\s*#( |$)", options: .regularExpression) != nil
213 let result = keep ? firstPrefix : String(repeating: " ", count: displayWidth(firstPrefix))
214 let probe = result + "a"
215 let regex = Self.regex(paragraphStartPattern, caseInsensitive: false)
216 if let match = regex.firstMatch(in: probe, options: [.anchored], range: NSRange(location: 0, length: (probe as NSString).length)), match.range.location == 0 {
217 return nil
218 }
219 return result
220 }
221 }
222
223 /// `fill-nobreak-p` with org's predicates.
224 func fillNoBreak() -> Bool {
225 if bolp { return false }
226 let startsParagraph = saveExcursion { () -> Bool in
227 skipForward(Self.blanks)
228 return !eolp && looking(paragraphStartPattern, setsMatch: false) != nil
229 }
230 if startsParagraph { return true }
231 let lineBreak = saveExcursion { () -> Bool in
232 skipBackward(Self.blanks)
233 skipBackward([92])
234 return looking("\\\\\\\\($|[^\\\\])", setsMatch: false) != nil
235 }
236 if lineBreak { return true }
237 if looking("[ \\t]*\\{\\{\\{n(?:\\([^\\n)]*\\))?\\}\\}\\}[.)](?:$| )", setsMatch: false) != nil { return true }
238 let saved = lastMatch
239 defer { lastMatch = saved }
240 if atTimestamp() != nil, looking("[\\[<](" + Self.timestampCore + ")[^\\]>\\n]*[\\]>]", setsMatch: false) == nil { return true }
241 return false
242 }
243
244 /// `fill-move-to-break-point` for text without CJK characters.
245 func moveToBreakPoint(_ lineBegin: Int) {
246 if lineBegin > point { point = lineBegin }
247 while true {
248 guard let match = searchBackward("[ \\t]", bound: lineBegin, caseInsensitive: false) else {
249 point = lineBegin
250 break
251 }
252 point = match[0]!.lowerBound + 1
253 if fillNoBreak() {
254 skipBackward(Self.blanks, bound: lineBegin)
255 } else {
256 break
257 }
258 }
259 skipBackward(Self.blanks)
260 if lineBegin >= point {
261 let end = lineEnd(point)
262 var first = true
263 point = lineBegin
264 while point < end, first || fillNoBreak() {
265 skipForward(Self.blanks)
266 while point < length, let c = character(at: point), c != 32, c != 10, c != 9 { point += 1 }
267 first = false
268 }
269 }
270 }
271
272 /// `skip-chars-backward` stopping at `bound`.
273 func skipBackward(_ set: Set<unichar>, bound: Int) {
274 while point > bound, let c = character(at: point - 1), set.contains(c) { point -= 1 }
275 }
276
277 /// `canonically-space-region` with single spaces after sentences.
278 func canonicallySpace(_ begin: Int, _ endOffset: Int) {
279 saveExcursion {
280 let end = marker(endOffset, advances: true)
281 defer { release(end) }
282 for offset in begin..<end.position where character(at: offset) == 9 { replace(offset..<(offset + 1), with: " ") }
283 point = begin
284 let pattern = "(" + Self.sentenceEndPattern + ") *| +"
285 while point < end.position, let match = searchForward(pattern, bound: end.position, caseInsensitive: false) {
286 let matchEnd = match[0]!.upperBound
287 let start: Int
288 if let sentence = match[1], matchEnd > sentence.upperBound {
289 start = sentence.upperBound
290 } else if match[1] != nil {
291 let lastNonSpace = saveExcursion { () -> Int in point = matchEnd; skipBackward([32]); return point }
292 start = min(matchEnd, lastNonSpace + 1)
293 } else {
294 let before = saveExcursion { () -> unichar? in
295 point = match[0]!.lowerBound
296 skipBackward(Set(" ]})\"'".utf16))
297 return character(at: point - 1)
298 }
299 start = match[0]!.lowerBound + (before == 10 ? 0 : 1)
300 }
301 if start < matchEnd { deleteRegion(start, matchEnd) }
302 }
303 }
304 }
305
306 /// `fill-region-as-paragraph` with left justification and adaptive fill. With `nosqueeze`,
307 /// spaces between words and at the end stay.
308 func fillRegionAsParagraph(_ fromOffset: Int, _ toOffset: Int, prefix fixedPrefix: String? = nil, nosqueeze: Bool = false) {
309 point = min(fromOffset, toOffset)
310 let to = max(fromOffset, toOffset)
311 skipForward(Self.whitespace)
312 let fromPlusIndent = point
313 point = lineStart(point)
314 var from = max(point, fromOffset)
315 point = to
316 var oneLeft = false
317 while point > from, character(at: point - 1) == 10 {
318 if oneLeft {
319 deleteRegion(point - 1, point)
320 } else {
321 point -= 1
322 oneLeft = true
323 }
324 }
325 let toMarker = marker(point, advances: true)
326 defer { release(toMarker) }
327 point = fromPlusIndent
328 guard toMarker.position > point else { return }
329 var prefix = fixedPrefix
330 if prefix == nil || prefix == "" { prefix = contextPrefix(from: from, to: toMarker.position) }
331 point = lineStart(from)
332 // `fill-delete-prefix`.
333 let prefixPattern: String
334 if let prefix, !prefix.allSatisfy({ $0 == " " || $0 == "\t" }) {
335 prefixPattern = "[ \\t]*(" + NSRegularExpression.escapedPattern(for: prefix).replacingOccurrences(of: "[ \\t]+", with: "[ \\t]*", options: .regularExpression) + ")?[ \\t]*"
336 } else {
337 prefixPattern = "[ \\t]*"
338 }
339 point = from
340 forwardLine(1)
341 while point < toMarker.position {
342 if let match = looking(prefixPattern, setsMatch: false) { deleteRegion(point, match[0]!.upperBound) }
343 if forwardLine(1) != 0 { break }
344 }
345 point = from
346 if let match = looking(prefixPattern, setsMatch: false) { point = match[0]!.upperBound }
347 from = point
348 // `fill-delete-newlines`.
349 var at = from
350 while at < toMarker.position {
351 if character(at: at) == 10 { replace(at..<(at + 1), with: " ") }
352 at += 1
353 }
354 if !nosqueeze {
355 point = from
356 skipForward(Self.blanks)
357 canonicallySpace(point, toMarker.position)
358 point = toMarker.position
359 let end = point
360 skipBackward(Self.blanks)
361 if point < end { deleteRegion(point, end) }
362 }
363 point = from
364 while point < toMarker.position {
365 let lineBegin = point
366 moveToColumn(options.fillColumn)
367 var breaks = false
368 if point < toMarker.position, lineBegin < toMarker.position {
369 if currentColumn <= options.fillColumn { point += 1 }
370 moveToBreakPoint(lineBegin)
371 skipForward(Self.blanks)
372 breaks = point < toMarker.position
373 }
374 guard breaks else {
375 point = toMarker.position
376 break
377 }
378 // `fill-newline`.
379 skipBackward(Self.blanks)
380 insert("\n")
381 indentLineTo(0)
382 if let prefix, !prefix.isEmpty { insertBeforeMarkers(prefix) }
383 }
384 point = toMarker.position
385 if !eobp { point += 1 }
386 }
387
388 /// `org-fill-paragraph` without a region or justification.
389 func fillParagraph() {
390 saveExcursion {
391 if lookingAt("^[ \\t]*$") != nil || saveExcursion({ beginningOfLine(); return lookingAt("[ \\t]*$") != nil }) {
392 skipForward(Self.whitespace)
393 }
394 let eol = lineEnd(point)
395 guard let element = element(at: eol) else { return }
396 switch element.kind {
397 case .paragraph:
398 let begin = paragraphContentsBegin(element)
399 var end = contentsEnd(element)
400 guard lineEnd(point) >= begin else { return }
401 var cuts = [begin]
402 saveExcursion {
403 point = begin
404 while let match = searchForward("\\\\\\\\[ \\t]*\\n", bound: end, caseInsensitive: false) {
405 cuts.insert(match[0]!.upperBound, at: 0)
406 }
407 }
408 for cut in cuts where cut != end {
409 fillRegionAsParagraph(cut, end)
410 end = cut
411 }
412 case .comment:
413 let begin = postAffiliated(element)
414 let elementEnd = element.range.upperBound
415 guard point >= begin, point <= elementEnd else { return }
416 let from = saveExcursion { () -> Int in
417 endOfLine()
418 if searchBackward("^[ \\t]*#[ \\t]*$", bound: begin, caseInsensitive: false) != nil {
419 forwardLine(1)
420 return point
421 }
422 return begin
423 }
424 let to = saveExcursion { () -> Int in
425 endOfLine()
426 if searchForward("^[ \\t]*#[ \\t]*$", bound: elementEnd, caseInsensitive: false) != nil {
427 return lineStart(point) - 1
428 }
429 point = elementEnd
430 skipBackward(Self.whitespace)
431 return lineEnd(point)
432 }
433 guard to > from else { return }
434 let prefix = saveExcursion { () -> String in
435 beginningOfLine()
436 let comment = looking("[ \\t]*#", setsMatch: false)!
437 point = comment[0]!.upperBound
438 let marker = substring(comment[0]!.lowerBound, comment[0]!.upperBound)
439 if let rest = looking(Self.adaptiveFillPattern, setsMatch: false) {
440 return marker + substring(rest[0]!.lowerBound, rest[0]!.upperBound)
441 }
442 return marker + " "
443 }
444 saveExcursion { fillRegionAsParagraph(from, to, prefix: prefix) }
445 case .block where element.blockType == "comment":
446 let begin = saveExcursion { () -> Int in
447 point = element.range.lowerBound
448 forwardLine(1)
449 return point
450 }
451 let end = saveExcursion { () -> Int in
452 point = element.range.upperBound
453 skipBackward(Self.whitespace)
454 return lineStart(point)
455 }
456 guard point >= begin, point <= end else { return }
457 let from = saveExcursion { () -> Int in
458 endOfLine()
459 if searchBackward("^[ \\t]*$", bound: begin, caseInsensitive: false) == nil { point = begin }
460 return lineStart(point)
461 }
462 let to = saveExcursion { () -> Int in
463 beginningOfLine()
464 if searchForward("^[ \\t]*$", bound: end, caseInsensitive: false) == nil { point = end }
465 return lineStart(point)
466 }
467 fillRegionAsParagraph(from, to)
468 default:
469 return
470 }
471 }
472 }
473
474 /// `org-fill-paragraph` with an active region: from the region's end back to `start`, M-q at
475 /// the end of each paragraph's text, moving back a paragraph at a time.
476 func fillParagraphs(_ start: Int, _ end: Int) {
477 saveExcursion {
478 point = end
479 skipBackward(Self.whitespace)
480 while point > start {
481 let before = point
482 fillParagraph()
483 point = paragraphBackwardStop()
484 skipBackward(Self.whitespace)
485 if point >= before { break }
486 }
487 }
488 }
489
490 /// Where `org--backward-paragraph-once` goes from the end of a line's text.
491 private func paragraphBackwardStop() -> Int {
492 guard let element = element(at: point) else { return lineStart(point) }
493 switch element.kind {
494 case .block where ["comment", "example", "export", "src", "verse"].contains(element.blockType ?? ""):
495 // Between empty lines in the block.
496 let contentsStart = lineEnd(element.range.lowerBound) + 1
497 guard point > contentsStart else { return element.range.lowerBound }
498 let contentsEnd = saveExcursion { () -> Int in
499 point = element.range.upperBound
500 skipBackward(Self.whitespace)
501 return lineStart(point)
502 }
503 if point > contentsEnd { return contentsEnd }
504 return saveExcursion {
505 skipBackward(Self.whitespace, bound: element.range.lowerBound)
506 return searchBackward("^[ \t]*\n", bound: contentsStart, caseInsensitive: false)?[0]!.lowerBound ?? contentsStart
507 }
508 case .block, .drawer, .propertyDrawer, .dynamicBlock:
509 // On the closing line: inside, to the contents' end.
510 return lineStart(point) > element.range.lowerBound ? lineStart(point) : element.range.lowerBound
511 default:
512 return lineStart(element.range.lowerBound)
513 }
514 }
515
516 /// `fill-region` over whole lines: each paragraph's part of `from..<to` filled as a
517 /// paragraph. Other elements stay.
518 func fillRegion(_ from: Int, _ to: Int, nosqueeze: Bool = false) {
519 var spans: [Range<Int>] = []
520 var line = lineStart(from)
521 while line < to, line < length {
522 var next = lineEnd(line) + 1
523 let blank = substring(line, lineEnd(line)).allSatisfy { $0 == " " || $0 == "\t" }
524 if !blank, let element = element(at: lineEnd(line)) {
525 if element.kind == .paragraph {
526 let span = max(paragraphContentsBegin(element), from)..<min(contentsEnd(element), to)
527 if !span.isEmpty { spans.append(span) }
528 }
529 next = max(next, lineStart(min(length, max(element.range.lowerBound, contentsEnd(element)))))
530 if next <= line { next = lineEnd(line) + 1 }
531 }
532 line = next
533 }
534 // Back to front, so the spans before stay where they are.
535 for span in spans.reversed() { fillRegionAsParagraph(span.lowerBound, span.upperBound, nosqueeze: nosqueeze) }
536 }
537
538 /// Where a paragraph's text starts: past affiliated keywords, and for a paragraph that
539 /// opens an item, past the bullet.
540 func paragraphContentsBegin(_ node: Element) -> Int {
541 max(postAffiliated(node), node.range.lowerBound)
542 }
543}
544
545/// M-q: `org-fill-paragraph`. With a selection, as with an active region, every paragraph
546/// in it; `point` is where the caret is in it, and stays.
547public struct FillParagraph: OrgCommand {
548 public let point: Int?
549
550 public init(point: Int? = nil) { self.point = point }
551 public var id: String { "org.fill-paragraph" }
552 public var title: String { "Fill Paragraph" }
553 public func applies(in context: EditContext) -> Bool { true }
554 public func run(in context: EditContext) -> CommandStep {
555 commitBuffer(context) { buffer in
556 if let selection = context.selection.first, !selection.isEmpty {
557 if let point { buffer.point = point }
558 buffer.fillParagraphs(selection.lowerBound, selection.upperBound)
559 } else {
560 buffer.fillParagraph()
561 }
562 }
563 }
564}
565
566/// evil's `gq` and `gw` operators: the paragraphs in `range`'s lines filled, as `fill-region`.
567/// With `keep` (`gw`) the caret stays there; without (`gq`) it goes to the first non-blank
568/// of the range's last line. Spaces are not squeezed, as Doom's `+evil--no-squeeze-on-fill-a`
569/// has it.
570public struct FillRegion: OrgCommand {
571 public let range: Range<Int>
572 public let keep: Int?
573
574 public init(range: Range<Int>, keep: Int?) {
575 self.range = range
576 self.keep = keep
577 }
578
579 public var id: String { "org.fill-region" }
580 public var title: String { "Fill Region" }
581 public func applies(in context: EditContext) -> Bool { true }
582 public func run(in context: EditContext) -> CommandStep {
583 commitBuffer(context) { buffer in
584 let target = buffer.marker(keep ?? max(range.lowerBound, range.upperBound - 1))
585 defer { buffer.release(target) }
586 buffer.fillRegion(range.lowerBound, range.upperBound, nosqueeze: true)
587 buffer.point = target.position
588 if keep == nil {
589 buffer.beginningOfLine()
590 buffer.skipForward(EmacsBuffer.blanks)
591 }
592 }
593 }
594}
595
596// `auto-fill-mode` in Org: `org-auto-fill-function`, which runs `do-auto-fill` with
597// `org-adaptive-fill-function`'s prefix and breaks lines with `org-comment-line-break-function`.
598extension EmacsBuffer {
599 /// After typing a space, point after it: the line broken before `fill-column` as often as it
600 /// takes, each new line starting with the fill prefix.
601 func autoFill() {
602 let fillColumn = options.fillColumn
603 guard currentColumn > fillColumn, let prefix = orgAdaptiveFillPrefix() else { return }
604 var giveUp = false
605 while !giveUp, currentColumn > fillColumn {
606 let fillPoint = saveExcursion { () -> Int in
607 beginningOfLine()
608 moveToColumn(cellWidth(prefix))
609 let afterPrefix = point
610 moveToColumn(fillColumn + 1)
611 moveToBreakPoint(afterPrefix)
612 return point
613 }
614 let useless = saveExcursion { () -> Bool in
615 point = fillPoint
616 if bolp || lookingAt(" *$") != nil { return true }
617 // Right after a comment starter, which would only start another comment.
618 let limit = point
619 beginningOfLine()
620 return searchForward("^[ \\t]*#(?: |$)", bound: limit, caseInsensitive: false).map { $0[0]!.upperBound == limit } ?? false
621 }
622 if useless { break }
623 let previousColumn = currentColumn
624 let atFillPoint = saveExcursion { () -> Bool in
625 skipBackward(Self.blanks)
626 return point == fillPoint
627 }
628 if atFillPoint {
629 commentLineBreak()
630 } else {
631 saveExcursion {
632 point = fillPoint
633 commentLineBreak()
634 }
635 }
636 if currentColumn >= previousColumn { giveUp = true }
637 }
638 }
639
640 /// `org-comment-line-break-function` with SOFT: a newline at point, the space around it
641 /// gone, and the next line started with the fill prefix.
642 func commentLineBreak() {
643 let prefix = orgAdaptiveFillPrefix()
644 insert("\n")
645 saveExcursion {
646 point -= 1
647 deleteBlanksAround()
648 }
649 deleteBlanksAround()
650 if let prefix { insert(prefix) }
651 }
652
653 /// `delete-horizontal-space`.
654 private func deleteBlanksAround() {
655 var start = point
656 while start > 0, let c = character(at: start - 1), c == 32 || c == 9 { start -= 1 }
657 var end = point
658 while let c = character(at: end), c == 32 || c == 9 { end += 1 }
659 deleteRegion(start, end)
660 point = start
661 }
662}
663
664/// SPC with `auto-fill-mode`: the space typed, then the line filled as Org's auto-fill does.
665public struct AutoFillSpace: OrgCommand {
666 public init() {}
667 public var id: String { "org.auto-fill-space" }
668 public var title: String { "Type Space and Auto-Fill" }
669 public func applies(in context: EditContext) -> Bool { true }
670 public func run(in context: EditContext) -> CommandStep {
671 let selection = context.selection.first ?? context.caret..<context.caret
672 let typed = TextEdit(range: selection, replacement: " ").apply(to: context.text)
673 let caret = selection.lowerBound + 1
674 let inserted = EditContext(revision: context.revision, text: typed, tree: OrgParser.parse(typed, defaults: context.tree.settings),
675 selection: [caret..<caret], now: context.now, calendar: context.calendar, options: context.options)
676 let filled = commitBuffer(inserted) { $0.autoFill() }
677 guard case .commit(let result) = filled else { return filled }
678 let text = result.edits.sorted { $0.range.lowerBound > $1.range.lowerBound }.reduce(typed) { $1.apply(to: $0) }
679 return .commit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, text), selection: result.selection))
680 }
681}