in Sources/Markdown/Walker/Walkers/MarkupFormatter.swift [533:590]
mutating func softWrapPrint(_ string: String, for element: InlineMarkup) {
guard let lineLimit = formattingOptions.preferredLineLimit else {
print(string, for: element)
return
}
// Headings may not have soft breaks.
guard element.firstAncestor(where: { $0 is Heading }) == nil else {
print(string, for: element)
return
}
let words = string.components(separatedBy: CharacterSet(charactersIn: " \t"))[...]
/// Hard line breaks in Markdown require two spaces before the newline; soft breaks require none.
let breakSuffix: String
switch lineLimit.lineSplittingElement {
case .hardBreak:
breakSuffix = " "
case .softBreak:
breakSuffix = ""
}
var wordsThisLine = 0
for index in words.indices {
let word = words[index]
if index == words.startIndex && wordsThisLine == 0 {
// Always print the first word if it's at the start of a line.
// A break won't help here and could actually hurt by
// unintentionally starting a new paragraph.
// However, there is one exception:
// we might already be right at the edge of a line when
// this method was called.
if state.lastLineLength + word.count >= lineLimit.maxLength {
queueNewline()
}
print(word, for: element)
wordsThisLine += 1
continue
}
if state.lastLineLength + word.count + breakSuffix.count + 1 >= lineLimit.maxLength {
print(breakSuffix, for: element)
queueNewline()
wordsThisLine = 0
}
// Insert a space between words.
if wordsThisLine > 0 {
print(" ", for: element)
}
// Finally, print the word.
print(word, for: element)
wordsThisLine += 1
}
}