github.com/richardwilkes/toolbox@v1.121.0/xio/term/terminal.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 term provides terminal utilities. 11 package term 12 13 import ( 14 "fmt" 15 "io" 16 "strings" 17 ) 18 19 const ( 20 defColumns = 80 21 defRows = 24 22 ) 23 24 // WrapText prints the 'prefix' to 'out' and then wraps 'text' in the remaining space. 25 func WrapText(out io.Writer, prefix, text string) { 26 fmt.Fprint(out, prefix) 27 avail, _ := Size() 28 avail -= 1 + len(prefix) 29 if avail < 1 { 30 avail = 1 31 } 32 remaining := avail 33 indent := strings.Repeat(" ", len(prefix)) 34 for _, line := range strings.Split(text, "\n") { 35 for _, ch := range line { 36 if ch == ' ' { 37 fmt.Fprint(out, " ") 38 remaining-- 39 } else { 40 break 41 } 42 } 43 for i, token := range strings.Fields(line) { 44 length := len(token) + 1 45 if i != 0 { 46 if length > remaining { 47 fmt.Fprintln(out) 48 fmt.Fprint(out, indent) 49 remaining = avail 50 } else { 51 fmt.Fprint(out, " ") 52 } 53 } 54 fmt.Fprint(out, token) 55 remaining -= length 56 } 57 fmt.Fprintln(out) 58 } 59 }