Allow customized completion handling
diff --git a/completion.go b/completion.go
index d0adfe0..894f1d6 100644
--- a/completion.go
+++ b/completion.go
@@ -43,8 +43,6 @@
type completion struct {
parser *Parser
-
- ShowDescriptions bool
}
// Filename is a string alias which provides filename completion.
@@ -275,19 +273,17 @@
return ret
}
-func (c *completion) execute(args []string) {
- ret := c.complete(args)
-
- if c.ShowDescriptions && len(ret) > 1 {
+func (c *completion) print(items []Completion, showDescriptions bool) {
+ if showDescriptions && len(items) > 1 {
maxl := 0
- for _, v := range ret {
+ for _, v := range items {
if len(v.Item) > maxl {
maxl = len(v.Item)
}
}
- for _, v := range ret {
+ for _, v := range items {
fmt.Printf("%s", v.Item)
if len(v.Description) > 0 {
@@ -297,7 +293,7 @@
fmt.Printf("\n")
}
} else {
- for _, v := range ret {
+ for _, v := range items {
fmt.Println(v.Item)
}
}
diff --git a/parser.go b/parser.go
index df753ca..9661af3 100644
--- a/parser.go
+++ b/parser.go
@@ -32,6 +32,11 @@
// or an error to indicate a parse failure.
UnknownOptionHandler func(option string, arg SplitArgument, args []string) ([]string, error)
+ // CompletionHandler is a function gets called to handle the completion of
+ // items. By default, the items are printed and the application is exited.
+ // You can override this default behavior by specifying a custom CompletionHandler.
+ CompletionHandler func(items []Completion)
+
internalError error
}
@@ -184,13 +189,14 @@
if len(compval) != 0 {
comp := &completion{parser: p}
+ items := comp.complete(args)
- if compval == "verbose" {
- comp.ShowDescriptions = true
+ if p.CompletionHandler != nil {
+ p.CompletionHandler(items)
+ } else {
+ comp.print(items, compval == "verbose")
}
- comp.execute(args)
-
return nil, nil
}