src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

wrap.go (465B)


      1 package text
      2 
      3 import "strings"
      4 
      5 func Wrap(text string, width int) string {
      6 	if width < 0 {
      7 		return text
      8 	}
      9 
     10 	var words = strings.Fields(text)
     11 	if len(words) == 0 {
     12 		return ""
     13 	}
     14 
     15 	var (
     16 		wrapped   = words[0]
     17 		remaining = width - len(wrapped)
     18 	)
     19 	for _, word := range words[1:] {
     20 		if len(word)+1 > remaining {
     21 			wrapped += "\n" + word
     22 			remaining = width - len(word)
     23 		} else {
     24 			wrapped += " " + word
     25 			remaining -= 1 + len(word)
     26 		}
     27 	}
     28 
     29 	return wrapped
     30 }