-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathCommentWrapper.swift
More file actions
89 lines (73 loc) · 2.67 KB
/
CommentWrapper.swift
File metadata and controls
89 lines (73 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//
// CommentWrapper.swift
// CommentWrapperExt
//
// Created by Steve Barnegren on 06/04/2018.
// Copyright © 2018 Steve Barnegren. All rights reserved.
//
import Foundation
class CommentWrapper {
static func wrap(string: String, lineLength: Int) -> String {
let prefix = string.commentPrefix()
let unprefixedString = string.lines()
.map { $0.removing(prefix: prefix) }
.map { $0.removing(prefix: prefix.trimmingTrailingWhitespace()) }
.joined(separator: "\n")
let items = Itemizer.itemize(string: unprefixedString)
let adjustedLineLength: Int
switch Settings.lineLength {
case .absolute:
adjustedLineLength = lineLength - prefix.count
default:
adjustedLineLength = lineLength
}
let wrappedString = wrap(items: items, lineLength: adjustedLineLength)
let wrappedWithPrefix = wrappedString
.lines()
.map { prefix.appending($0) }
.map { $0.trimmingTrailingWhitespace() }
.joined(separator: "\n")
return wrappedWithPrefix
}
private static func wrap(items: [StringItem], lineLength: Int) -> String {
var lines = [String]()
var currentLine = String()
var whiteSpace = String()
func appendCurrentLine() {
if currentLine.isEmpty == false {
lines.append(currentLine)
currentLine = ""
}
}
var reversed = Array(items.reversed())
while let next = reversed.popLast() {
// next.debug_print()
switch next {
case .word(let word):
if currentLine.count + whiteSpace.count + word.count > lineLength {
appendCurrentLine()
whiteSpace = ""
}
currentLine.append(contentsOf: whiteSpace)
currentLine.append(contentsOf: word)
whiteSpace = ""
case .space:
whiteSpace.append(" ")
case .newline:
if currentLine.isEmpty {
lines.append("")
} else {
appendCurrentLine()
}
case .bullet:
whiteSpace = ""
currentLine.append("-")
case .code(let value), .markdownReferenceLink(let value):
whiteSpace = ""
currentLine.append(contentsOf: value)
}
}
appendCurrentLine()
return lines.joined(separator: "\n")
}
}