...
Tawesoft Logo

Source file src/tawesoft.co.uk/go/dialog/wrap.go

Documentation: src/tawesoft.co.uk/go/dialog/wrap.go

     1  package dialog // import "tawesoft.co.uk/go/dialog"
     2  
     3  import (
     4      "strings"
     5  )
     6  
     7  // quickly wraps a message for error output
     8  func wrap(message string, length int) string {
     9      var atoms = strings.Fields(strings.TrimSpace(message))
    10      var results = make([]string, 0, 16)
    11      var currentLength int
    12  
    13      for _, atom := range atoms {
    14          // special case for an atom longer than a whole line
    15          if (currentLength == 0) && (len(atom) >= length) {
    16              results = append(results, atom)
    17              results = append(results, "\n")
    18              currentLength = 0
    19              continue
    20          }
    21  
    22          // will overflow?
    23          if currentLength + len(atom) + 1 > length {
    24              results = append(results, "\n")
    25              currentLength = 0
    26          }
    27  
    28          // mid-line?
    29          if currentLength > 0 {
    30              results = append(results, " ")
    31              currentLength += 1
    32          }
    33  
    34          results = append(results, atom)
    35          currentLength += len(atom)
    36      }
    37  
    38      return strings.TrimSpace(strings.Join(results, ""))
    39  }
    40  

View as plain text