github.com/neatlab/neatio@v1.7.3-0.20220425043230-d903e92fcc75/internal/jsre/completion.go (about)

     1  package jsre
     2  
     3  import (
     4  	"sort"
     5  	"strings"
     6  
     7  	"github.com/robertkrimen/otto"
     8  )
     9  
    10  func (jsre *JSRE) CompleteKeywords(line string) []string {
    11  	var results []string
    12  	jsre.Do(func(vm *otto.Otto) {
    13  		results = getCompletions(vm, line)
    14  	})
    15  	return results
    16  }
    17  
    18  func getCompletions(vm *otto.Otto, line string) (results []string) {
    19  	parts := strings.Split(line, ".")
    20  	objRef := "this"
    21  	prefix := line
    22  	if len(parts) > 1 {
    23  		objRef = strings.Join(parts[0:len(parts)-1], ".")
    24  		prefix = parts[len(parts)-1]
    25  	}
    26  
    27  	obj, _ := vm.Object(objRef)
    28  	if obj == nil {
    29  		return nil
    30  	}
    31  	iterOwnAndConstructorKeys(vm, obj, func(k string) {
    32  		if strings.HasPrefix(k, prefix) {
    33  			if objRef == "this" {
    34  				results = append(results, k)
    35  			} else {
    36  				results = append(results, strings.Join(parts[:len(parts)-1], ".")+"."+k)
    37  			}
    38  		}
    39  	})
    40  
    41  	if len(results) == 1 && results[0] == line {
    42  		obj, _ := vm.Object(line)
    43  		if obj != nil {
    44  			if obj.Class() == "Function" {
    45  				results[0] += "("
    46  			} else {
    47  				results[0] += "."
    48  			}
    49  		}
    50  	}
    51  
    52  	sort.Strings(results)
    53  	return results
    54  }