-
Notifications
You must be signed in to change notification settings - Fork 169
/
Copy pathString+Simplenote.swift
210 lines (165 loc) · 6.29 KB
/
String+Simplenote.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import Foundation
import AppKit
// MARK: - String Constants
//
extension String {
/// String containing the NSTextAttachment Marker
///
static let attachmentString = String(Character(UnicodeScalar(NSTextAttachment.character)!))
/// Newline
///
static let newline = "\n"
/// Space
///
static let space = " "
/// Tabs
///
static let tab = "\t"
/// All of the supported List Markers
///
static let listMarkers = [ attachmentString, "*", "-", "+", "•" ]
/// Rich List Item: Represented with an Attachment + Space
///
static let richListMarker = .attachmentString + .space
/// Returns the receiver casted as a Foundation String. For convenience
///
var asNSString: NSString {
self as NSString
}
}
// MARK: - Helper API(s)
//
extension String {
/// Returns the Range enclosing all of the receiver's contents
///
var fullRange: Range<String.Index> {
startIndex ..< endIndex
}
/// Returns a copy of the receiver minus its trailing newline (if any)
///
func dropTrailingNewline() -> String {
return last == Character(.newline) ? String(dropLast()) : self
}
/// Truncates the receiver's full words, up to a specified maximum length.
/// - Note: Whenever this is not possible (ie. the receiver doesn't have words), regular truncation will be performed
///
func truncateWords(upTo maximumLength: Int) -> String {
var output = String()
for word in components(separatedBy: .whitespaces) {
if (output.count + word.count) >= maximumLength {
break
}
let prefix = output.isEmpty ? String() : .space
output.append(prefix)
output.append(word)
}
if output.isEmpty {
return prefix(maximumLength).trimmingCharacters(in: .whitespaces)
}
return output
}
/// Returns a new string dropping specified prefix
///
func droppingPrefix(_ prefix: String) -> String {
guard hasPrefix(prefix) else {
return self
}
return String(dropFirst(prefix.count))
}
/// Returns a new string replacing newlines with spaces
///
func replacingNewlinesWithSpaces() -> String {
split(whereSeparator: { $0.isNewline }).joined(separator: " ")
}
func objectFromJSONString() -> Any? {
guard let data = self.data(using: .utf8) else {
return nil
}
return try? JSONSerialization.jsonObject(with: data)
}
}
// MARK: - Searching for the first / last characters
//
extension String {
/// Find and return the location of the first / last character from the specified character set
///
func locationOfFirstCharacter(from searchSet: CharacterSet,
startingFrom startLocation: String.Index,
backwards: Bool = false) -> String.Index? {
guard startLocation <= endIndex else {
return nil
}
let range = backwards ? startIndex..<startLocation : startLocation..<endIndex
let characterRange = rangeOfCharacter(from: searchSet,
options: backwards ? .backwards : [],
range: range)
return characterRange?.lowerBound
}
}
// MARK: - Searching for keywords
//
extension String {
/// Finds keywords in a string and optionally trims around the first match
///
/// - Parameters:
/// - keywords: A list of keywords
/// - range: Range of the string. If nil full range is used
/// - leadingLimit: Limit result string to a certain characters before the first match. Only full words are used. Provide 0 to have no limit.
/// - trailingLimit: Limit result string to a certain characters after the first match. Only full words are used. Provide 0 to have no limit.
///
func contentSlice(matching keywords: [String],
in range: Range<String.Index>? = nil,
leadingLimit: Int = 0,
trailingLimit: Int = 0) -> ContentSlice? {
guard !keywords.isEmpty else {
return nil
}
let range = range ?? startIndex..<endIndex
var leadingWordsRange: [Range<String.Index>] = []
var matchingWordsRange: [Range<String.Index>] = []
var trailingWordsRange: [Range<String.Index>] = []
enumerateSubstrings(in: range, options: [.byWords, .localized, .substringNotRequired]) { (_, wordRange, _, stop) in
if trailingLimit > 0, let firstMatch = matchingWordsRange.first {
if distance(from: firstMatch.upperBound, to: wordRange.upperBound) > trailingLimit {
stop = true
return
}
trailingWordsRange.append(wordRange)
}
for keyword in keywords {
if self.range(of: keyword, options: [.caseInsensitive, .diacriticInsensitive], range: wordRange, locale: Locale.current) != nil {
matchingWordsRange.append(wordRange)
break
}
}
if leadingLimit > 0 && matchingWordsRange.isEmpty {
leadingWordsRange.append(wordRange)
}
}
// No matches => return nil
guard let firstMatch = matchingWordsRange.first, let lastMatch = matchingWordsRange.last else {
return nil
}
let lowerBound: String.Index = {
if leadingLimit == 0 {
return range.lowerBound
}
let upperBound = firstMatch.lowerBound
var lowerBound = upperBound
for range in leadingWordsRange.reversed() {
if distance(from: range.lowerBound, to: upperBound) > leadingLimit {
break
}
lowerBound = range.lowerBound
}
return lowerBound
}()
let upperBound: String.Index = {
if trailingLimit == 0 {
return range.upperBound
}
return trailingWordsRange.last?.upperBound ?? lastMatch.upperBound
}()
return ContentSlice(content: self, range: lowerBound..<upperBound, matches: matchingWordsRange)
}
}