package bash
import (
"fmt"
"os"
"strings"
"github.com/rsteube/carapace/internal/common"
)
var sanitizer = strings .NewReplacer (
"\n" , `` ,
"\r" , `` ,
"\t" , `` ,
)
var valueReplacer = strings .NewReplacer (
`\` , `\\` ,
`"` , `\"` ,
`$` , `\$` ,
"`" , "\\`" ,
)
var displayReplacer = strings .NewReplacer (
`${` , `\\\${` ,
)
func commonPrefix(a , b string ) string {
i := 0
for i < len (a ) && i < len (b ) && a [i ] == b [i ] {
i ++
}
return a [0 :i ]
}
func commonDisplayPrefix(values ...common .RawValue ) (prefix string ) {
for index , val := range values {
if index == 0 {
prefix = val .Display
} else {
prefix = commonPrefix (prefix , val .Display )
}
}
return
}
func commonValuePrefix(values ...common .RawValue ) (prefix string ) {
for index , val := range values {
if index == 0 {
prefix = val .Value
} else {
prefix = commonPrefix (prefix , val .Value )
}
}
return
}
func ActionRawValues (currentWord string , meta common .Meta , values common .RawValues ) string {
for index , value := range values {
values [index ].Value = strings .TrimPrefix (value .Value , wordbreakPrefix )
}
lastSegment := strings .TrimPrefix (currentWord , wordbreakPrefix )
if len (values ) > 1 && commonDisplayPrefix (values ...) != "" {
if valuePrefix := commonValuePrefix (values ...); lastSegment != valuePrefix {
values = common .RawValuesFrom (commonValuePrefix (values ...))
} else {
values [0 ].Display = " " + values [0 ].Display
}
meta .Nospace .Add ('*' )
}
nospace := true
vals := make ([]string , len (values ))
for index , val := range values {
if len (values ) == 1 {
if !meta .Nospace .Matches (val .Value ) {
nospace = false
}
vals [index ] = sanitizer .Replace (val .Value )
if requiresQuoting (vals [index ]) {
vals [index ] = valueReplacer .Replace (vals [index ])
switch {
case strings .HasPrefix (vals [index ], "~" ):
if splitted := strings .SplitAfterN (vals [index ], "/" , 2 ); len (splitted ) == 2 {
vals [index ] = fmt .Sprintf (`%v"%v"` , splitted [0 ], splitted [1 ])
} else {
vals [index ] = fmt .Sprintf (`~"%v"` , strings .TrimPrefix (vals [index ], "~" ))
}
default :
vals [index ] = fmt .Sprintf (`"%v"` , vals [index ])
}
}
} else {
val .Display = displayReplacer .Replace (val .Display )
val .Description = displayReplacer .Replace (val .Description )
if val .Description != "" {
vals [index ] = fmt .Sprintf ("%v (%v)" , val .Display , sanitizer .Replace (val .TrimmedDescription ()))
} else {
vals [index ] = val .Display
}
}
}
return fmt .Sprintf ("%v\001%v" , nospace , strings .Join (vals , "\n" ))
}
func requiresQuoting(s string ) bool {
chars := " \t\r\n`" + `[]{}()<>;|$&:*#`
chars += os .Getenv ("COMP_WORDBREAKS" )
chars += `\`
return strings .ContainsAny (s , chars )
}
The pages are generated with Golds v0.8.2 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .