github.com/richardwilkes/toolbox@v1.121.0/txt/wrap.go (about)

     1  // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the Mozilla Public
     4  // License, version 2.0. If a copy of the MPL was not distributed with
     5  // this file, You can obtain one at http://mozilla.org/MPL/2.0/.
     6  //
     7  // This Source Code Form is "Incompatible With Secondary Licenses", as
     8  // defined by the Mozilla Public License, version 2.0.
     9  
    10  package txt
    11  
    12  import (
    13  	"strings"
    14  )
    15  
    16  // Wrap text to a certain length, giving it an optional prefix on each line. Words will not be broken, even if they
    17  // exceed the maximum column size and instead will extend past the desired length.
    18  func Wrap(prefix, text string, maxColumns int) string {
    19  	var buffer strings.Builder
    20  	for i, line := range strings.Split(text, "\n") {
    21  		if i != 0 {
    22  			buffer.WriteByte('\n')
    23  		}
    24  		buffer.WriteString(prefix)
    25  		avail := maxColumns - len(prefix)
    26  		for j, token := range strings.Fields(line) {
    27  			if j != 0 {
    28  				if 1+len(token) > avail {
    29  					buffer.WriteByte('\n')
    30  					buffer.WriteString(prefix)
    31  					avail = maxColumns - len(prefix)
    32  				} else {
    33  					buffer.WriteByte(' ')
    34  					avail--
    35  				}
    36  			}
    37  			buffer.WriteString(token)
    38  			avail -= len(token)
    39  		}
    40  	}
    41  	return buffer.String()
    42  }