Skip to content

Commit

Permalink
Merge pull request #73 from posener/point
Browse files Browse the repository at this point in the history
Add support for CMP_POINT
  • Loading branch information
posener authored Oct 19, 2018
2 parents 0d98d7e + 5fdb1ad commit ffc2cf5
Show file tree
Hide file tree
Showing 4 changed files with 210 additions and 115 deletions.
9 changes: 9 additions & 0 deletions args.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,20 @@ func newArgs(line string) Args {
}
}

// splitFields returns a list of fields from the given command line.
// If the last character is space, it appends an empty field in the end
// indicating that the field before it was completed.
// If the last field is of the form "a=b", it splits it to two fields: "a", "b",
// So it can be completed.
func splitFields(line string) []string {
parts := strings.Fields(line)

// Add empty field if the last field was completed.
if len(line) > 0 && unicode.IsSpace(rune(line[len(line)-1])) {
parts = append(parts, "")
}

// Treat the last field if it is of the form "a=b"
parts = splitLastEqual(parts)
return parts
}
Expand Down
30 changes: 21 additions & 9 deletions complete.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,16 @@ import (
"fmt"
"io"
"os"
"strconv"

"github.com/posener/complete/cmd"
"github.com/posener/complete/match"
)

const (
envComplete = "COMP_LINE"
envDebug = "COMP_DEBUG"
envLine = "COMP_LINE"
envPoint = "COMP_POINT"
envDebug = "COMP_DEBUG"
)

// Complete structs define completion for a command with CLI options
Expand Down Expand Up @@ -55,14 +57,17 @@ func (c *Complete) Run() bool {
// For installation: it assumes that flags were added and parsed before
// it was called.
func (c *Complete) Complete() bool {
line, ok := getLine()
line, point, ok := getEnv()
if !ok {
// make sure flags parsed,
// in case they were not added in the main program
return c.CLI.Run()
}
Log("Completing line: %s", line)
a := newArgs(line)

completePhrase := line[:point]

Log("Completing phrase: %s", completePhrase)
a := newArgs(completePhrase)
Log("Completing last field: %s", a.Last)
options := c.Command.Predict(a)
Log("Options: %s", options)
Expand All @@ -79,12 +84,19 @@ func (c *Complete) Complete() bool {
return true
}

func getLine() (string, bool) {
line := os.Getenv(envComplete)
func getEnv() (line string, point int, ok bool) {
line = os.Getenv(envLine)
if line == "" {
return "", false
return
}
point, err := strconv.Atoi(os.Getenv(envPoint))
if err != nil {
// If failed parsing point for some reason, set it to point
// on the end of the line.
Log("Failed parsing point %s: %v", os.Getenv(envPoint), err)
point = len(line)
}
return line, true
return line, point, true
}

func (c *Complete) output(options []string) {
Expand Down
Loading

0 comments on commit ffc2cf5

Please sign in to comment.