github.com/elves/elvish@v0.15.0/pkg/parse/parseutil/parseutil.go (about) 1 // Package parseutil contains utilities built on top of the parse package. 2 package parseutil 3 4 import ( 5 "strings" 6 7 "github.com/elves/elvish/pkg/parse" 8 ) 9 10 // FindLeafNode finds the leaf node at a specific position. It returns nil if 11 // position is out of bound. 12 func FindLeafNode(n parse.Node, p int) parse.Node { 13 descend: 14 for len(parse.Children(n)) > 0 { 15 for _, ch := range parse.Children(n) { 16 if ch.Range().From <= p && p <= ch.Range().To { 17 n = ch 18 continue descend 19 } 20 } 21 return nil 22 } 23 return n 24 } 25 26 // Wordify turns a piece of source code into words. 27 func Wordify(src string) []string { 28 tree, _ := parse.Parse(parse.Source{Name: "[wordify]", Code: src}) 29 return wordifyInner(tree.Root, nil) 30 } 31 32 func wordifyInner(n parse.Node, words []string) []string { 33 if len(parse.Children(n)) == 0 || isCompound(n) { 34 text := parse.SourceText(n) 35 if strings.TrimFunc(text, parse.IsWhitespace) != "" { 36 return append(words, text) 37 } 38 return words 39 } 40 for _, ch := range parse.Children(n) { 41 words = wordifyInner(ch, words) 42 } 43 return words 44 } 45 46 func isCompound(n parse.Node) bool { 47 _, ok := n.(*parse.Compound) 48 return ok 49 }