github.com/jmigpin/editor@v1.6.0/util/parseutil/ctxstring.go (about) 1 package parseutil 2 3 import ( 4 "fmt" 5 6 "github.com/jmigpin/editor/util/iout/iorw" 7 "github.com/jmigpin/editor/util/mathutil" 8 ) 9 10 func CtxErrorStr(rd iorw.ReaderAt, filename string, pos int, msg string, contextSize int) string { 11 s, err := CtxString(rd, pos, contextSize) 12 if err != nil { 13 return fmt.Sprintf("%s", err) 14 } 15 return fmt.Sprintf("%v:%v: %s: %q", filename, pos, msg, s) 16 } 17 func CtxString(rd iorw.ReaderAt, pos int, contextSize int) (string, error) { 18 // pad n in each direction for error string 19 pad := contextSize / 2 20 i := mathutil.Max(pos-pad, 0) 21 i2 := mathutil.Min(pos+pad, rd.Max()) 22 23 // read src string 24 b, err := rd.ReadFastAt(i, i2-i) 25 if err != nil { 26 return "", fmt.Errorf("ctxstring: failed to get src: %w", err) 27 } 28 src := string(b) 29 30 // position indicator 31 c := pos - i 32 33 sep := "●" // "←" 34 src = src[:c] + sep + src[c:] 35 if i > 0 { 36 src = "..." + src 37 } 38 if i2 < rd.Max()-1 { 39 src = src + "..." 40 } 41 return src, nil 42 }