github.com/elves/Elvish@v0.12.0/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/parse"
     8  )
     9  
    10  // LeafNodeAtDot 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(n.Children()) > 0 {
    15  		for _, ch := range n.Children() {
    16  			if ch.Begin() <= p && p <= ch.End() {
    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  	n, _ := parse.Parse("[wordify]", src)
    29  	return wordifyInner(n, nil)
    30  }
    31  
    32  func wordifyInner(n parse.Node, words []string) []string {
    33  	if len(n.Children()) == 0 || parse.IsCompound(n) {
    34  		text := n.SourceText()
    35  		if strings.TrimFunc(text, parse.IsSpaceOrNewline) != "" {
    36  			return append(words, text)
    37  		}
    38  		return words
    39  	}
    40  	for _, ch := range n.Children() {
    41  		words = wordifyInner(ch, words)
    42  	}
    43  	return words
    44  }