-
Notifications
You must be signed in to change notification settings - Fork 221
/
TrimBehaviour.swift
76 lines (61 loc) · 2.32 KB
/
TrimBehaviour.swift
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
//
// Stencil
// Copyright © 2022 Stencil
// MIT Licence
//
import Foundation
public struct TrimBehaviour: Equatable {
var leading: Trim
var trailing: Trim
public enum Trim {
/// nothing
case nothing
/// tabs and spaces
case whitespace
/// tabs and spaces and a single new line
case whitespaceAndOneNewLine
/// all tabs spaces and newlines
case whitespaceAndNewLines
}
public init(leading: Trim, trailing: Trim) {
self.leading = leading
self.trailing = trailing
}
/// doesn't touch newlines
public static let nothing = TrimBehaviour(leading: .nothing, trailing: .nothing)
/// removes whitespace before a block and whitespace and a single newline after a block
public static let smart = TrimBehaviour(leading: .whitespace, trailing: .whitespaceAndOneNewLine)
/// removes all whitespace and newlines before and after a block
public static let all = TrimBehaviour(leading: .whitespaceAndNewLines, trailing: .whitespaceAndNewLines)
static func leadingRegex(trim: Trim) -> NSRegularExpression {
switch trim {
case .nothing:
fatalError("No RegularExpression for none")
case .whitespace:
return Self.leadingWhitespace
case .whitespaceAndOneNewLine:
return Self.leadingWhitespaceAndOneNewLine
case .whitespaceAndNewLines:
return Self.leadingWhitespaceAndNewlines
}
}
static func trailingRegex(trim: Trim) -> NSRegularExpression {
switch trim {
case .nothing:
fatalError("No RegularExpression for none")
case .whitespace:
return Self.trailingWhitespace
case .whitespaceAndOneNewLine:
return Self.trailingWhitespaceAndOneNewLine
case .whitespaceAndNewLines:
return Self.trailingWhitespaceAndNewLines
}
}
// swiftlint:disable force_try
private static let leadingWhitespaceAndNewlines = try! NSRegularExpression(pattern: "^\\s+")
private static let trailingWhitespaceAndNewLines = try! NSRegularExpression(pattern: "\\s+$")
private static let leadingWhitespaceAndOneNewLine = try! NSRegularExpression(pattern: "^[ \t]*\n")
private static let trailingWhitespaceAndOneNewLine = try! NSRegularExpression(pattern: "\n[ \t]*$")
private static let leadingWhitespace = try! NSRegularExpression(pattern: "^[ \t]*")
private static let trailingWhitespace = try! NSRegularExpression(pattern: "[ \t]*$")
}