summaryrefslogtreecommitdiff
path: root/scalatexApi/src/main/scala/scalatex/stages/Trim.scala
blob: 02d9cc480a6964edd334204714b1696c464a9fd1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package scalatex.stages

/**
 * Preprocesses the input string to normalize things related to whitespace
 *
 * Find the "first" non-whitespace-line of the text and remove the front
 * of every line to align that first line with the left margin.
 *
 * Remove all trailing whitespace from each line.
 */
object Trim extends (String => String){
  def apply(str: String) = {
    val lines = str.split("\n")
    val offset = lines.iterator
                      .filter(_.length > 0)
                      .next()
                      .takeWhile(_ == ' ')
                      .length
    lines.iterator
         .map(_.drop(offset).replaceFirst("\\s+$", ""))
         .mkString("\n")
  }
}