Skip to content
Myr

tokenizer.go

This file

Path

src/tokenizer.go

338 lines · 7.4 KiB · Go

Last changed by

Not known.

History of this file

Take it

1package fzf23import (4	"bytes"5	"fmt"6	"regexp"7	"strconv"8	"strings"9	"unicode"1011	"github.com/junegunn/fzf/src/util"12)1314const rangeEllipsis = 01516// Range represents nth-expression17type Range struct {18	begin int19	end   int20}2122func (r Range) IsFull() bool {23	return r.begin == rangeEllipsis && r.end == rangeEllipsis24}2526func compareRanges(r1 []Range, r2 []Range) bool {27	if len(r1) != len(r2) {28		return false29	}30	for idx := range r1 {31		if r1[idx] != r2[idx] {32			return false33		}34	}35	return true36}3738func RangesToString(ranges []Range) string {39	strs := []string{}40	for _, r := range ranges {41		s := ""42		if r.begin == rangeEllipsis && r.end == rangeEllipsis {43			s = ".."44		} else if r.begin == r.end {45			s = strconv.Itoa(r.begin)46		} else {47			if r.begin != rangeEllipsis {48				s += strconv.Itoa(r.begin)49			}5051			if r.begin != -1 {52				s += ".."53				if r.end != rangeEllipsis {54					s += strconv.Itoa(r.end)55				}56			}57		}58		strs = append(strs, s)59	}6061	return strings.Join(strs, ",")62}6364// Token contains the tokenized part of the strings and its prefix length65type Token struct {66	text         *util.Chars67	prefixLength int3268}6970// String returns the string representation of a Token.71func (t Token) String() string {72	return fmt.Sprintf("Token{text: %s, prefixLength: %d}", t.text, t.prefixLength)73}7475// Delimiter for tokenizing the input76type Delimiter struct {77	regex *regexp.Regexp78	str   *string79}8081// IsAwk returns true if the delimiter is an AWK-style delimiter82func (d Delimiter) IsAwk() bool {83	return d.regex == nil && d.str == nil84}8586// String returns the string representation of a Delimiter.87func (d Delimiter) String() string {88	return fmt.Sprintf("Delimiter{regex: %v, str: &%q}", d.regex, *d.str)89}9091func newRange(begin int, end int) Range {92	if begin == 1 && end != 1 {93		begin = rangeEllipsis94	}95	if end == -1 {96		end = rangeEllipsis97	}98	return Range{begin, end}99}100101// ParseRange parses nth-expression and returns the corresponding Range object102func ParseRange(str *string) (Range, bool) {103	if (*str) == ".." {104		return newRange(rangeEllipsis, rangeEllipsis), true105	} else if strings.HasPrefix(*str, "..") {106		end, err := strconv.Atoi((*str)[2:])107		if err != nil || end == 0 {108			return Range{}, false109		}110		return newRange(rangeEllipsis, end), true111	} else if strings.HasSuffix(*str, "..") {112		begin, err := strconv.Atoi((*str)[:len(*str)-2])113		if err != nil || begin == 0 {114			return Range{}, false115		}116		return newRange(begin, rangeEllipsis), true117	} else if strings.Contains(*str, "..") {118		ns := strings.Split(*str, "..")119		if len(ns) != 2 {120			return Range{}, false121		}122		begin, err1 := strconv.Atoi(ns[0])123		end, err2 := strconv.Atoi(ns[1])124		if err1 != nil || err2 != nil || begin == 0 || end == 0 || begin < 0 && end > 0 {125			return Range{}, false126		}127		return newRange(begin, end), true128	}129130	n, err := strconv.Atoi(*str)131	if err != nil || n == 0 {132		return Range{}, false133	}134	return newRange(n, n), true135}136137func withPrefixLengths(tokens []string, begin int) []Token {138	ret := make([]Token, len(tokens))139140	prefixLength := begin141	for idx := range tokens {142		chars := util.ToChars(stringBytes(tokens[idx]))143		ret[idx] = Token{&chars, int32(prefixLength)}144		prefixLength += chars.Length()145	}146	return ret147}148149const (150	awkNil = iota151	awkBlack152	awkWhite153)154155func awkTokenizer(input string) ([]string, int) {156	// 9, 32157	ret := []string{}158	prefixLength := 0159	state := awkNil160	begin := 0161	end := 0162	for idx := 0; idx < len(input); idx++ {163		r := input[idx]164		white := r == 9 || r == 32 || r == 10165		switch state {166		case awkNil:167			if white {168				prefixLength++169			} else {170				state, begin, end = awkBlack, idx, idx+1171			}172		case awkBlack:173			end = idx + 1174			if white {175				state = awkWhite176			}177		case awkWhite:178			if white {179				end = idx + 1180			} else {181				ret = append(ret, input[begin:end])182				state, begin, end = awkBlack, idx, idx+1183			}184		}185	}186	if begin < end {187		ret = append(ret, input[begin:end])188	}189	return ret, prefixLength190}191192// Tokenize tokenizes the given string with the delimiter193func Tokenize(text string, delimiter Delimiter) []Token {194	if delimiter.str == nil && delimiter.regex == nil {195		// AWK-style (\S+\s*)196		tokens, prefixLength := awkTokenizer(text)197		return withPrefixLengths(tokens, prefixLength)198	}199200	if delimiter.str != nil {201		return withPrefixLengths(strings.SplitAfter(text, *delimiter.str), 0)202	}203204	// FIXME performance205	var tokens []string206	if delimiter.regex != nil {207		locs := delimiter.regex.FindAllStringIndex(text, -1)208		begin := 0209		tokens = make([]string, len(locs))210		for i, loc := range locs {211			tokens[i] = text[begin:loc[1]]212			begin = loc[1]213		}214		if begin < len(text) {215			tokens = append(tokens, text[begin:])216		}217	}218	return withPrefixLengths(tokens, 0)219}220221// StripLastDelimiter removes the trailing delimiter222func StripLastDelimiter(str string, delimiter Delimiter) string {223	if delimiter.str != nil {224		return strings.TrimSuffix(str, *delimiter.str)225	}226	if delimiter.regex != nil {227		locs := delimiter.regex.FindAllStringIndex(str, -1)228		if len(locs) > 0 {229			lastLoc := locs[len(locs)-1]230			if lastLoc[1] == len(str) {231				str = str[:lastLoc[0]]232			}233		}234		return str235	}236	return strings.TrimRightFunc(str, unicode.IsSpace)237}238239func GetLastDelimiter(str string, delimiter Delimiter) string {240	if delimiter.str != nil {241		if strings.HasSuffix(str, *delimiter.str) {242			return *delimiter.str243		}244	} else if delimiter.regex != nil {245		locs := delimiter.regex.FindAllStringIndex(str, -1)246		if len(locs) > 0 {247			lastLoc := locs[len(locs)-1]248			if lastLoc[1] == len(str) {249				return str[lastLoc[0]:]250			}251		}252	}253	return ""254}255256// JoinTokens concatenates the tokens into a single string257func JoinTokens(tokens []Token) string {258	var output bytes.Buffer259	for _, token := range tokens {260		output.WriteString(token.text.ToString())261	}262	return output.String()263}264265// Transform is used to transform the input when --with-nth option is given266func Transform(tokens []Token, withNth []Range) []Token {267	transTokens := make([]Token, len(withNth))268	numTokens := len(tokens)269	for idx, r := range withNth {270		parts := []*util.Chars{}271		minIdx := 0272		if r.begin == r.end {273			idx := r.begin274			if idx == rangeEllipsis {275				chars := util.ToChars(stringBytes(JoinTokens(tokens)))276				parts = append(parts, &chars)277			} else {278				if idx < 0 {279					idx += numTokens + 1280				}281				if idx >= 1 && idx <= numTokens {282					minIdx = idx - 1283					parts = append(parts, tokens[idx-1].text)284				}285			}286		} else {287			var begin, end int288			if r.begin == rangeEllipsis { // ..N289				begin, end = 1, r.end290				if end < 0 {291					end += numTokens + 1292				}293			} else if r.end == rangeEllipsis { // N..294				begin, end = r.begin, numTokens295				if begin < 0 {296					begin += numTokens + 1297				}298			} else {299				begin, end = r.begin, r.end300				if begin < 0 {301					begin += numTokens + 1302				}303				if end < 0 {304					end += numTokens + 1305				}306			}307			minIdx = max(0, begin-1)308			for idx := begin; idx <= end; idx++ {309				if idx >= 1 && idx <= numTokens {310					parts = append(parts, tokens[idx-1].text)311				}312			}313		}314		// Merge multiple parts315		var merged util.Chars316		switch len(parts) {317		case 0:318			merged = util.ToChars([]byte{})319		case 1:320			merged = *parts[0]321		default:322			var output bytes.Buffer323			for _, part := range parts {324				output.WriteString(part.ToString())325			}326			merged = util.ToChars(output.Bytes())327		}328329		var prefixLength int32330		if minIdx < numTokens {331			prefixLength = tokens[minIdx].prefixLength332		} else {333			prefixLength = 0334		}335		transTokens[idx] = Token{&merged, prefixLength}336	}337	return transTokens338}