tokenizer.go
This file
Path
src/tokenizer.go
336 lines · 7.4 KiB · Go
Last changed by
Keep the previous delimiter before frozen columnsJunegunn Choibefore adoption1df99db
History of this fileTake it
The walk stopped after 200 commits: lines older than e491770 point at it.
[fish] Improve option prefix processingbitraidbefore adoptione491770
lines 1–208why, one step back1package 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 == 32165 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 := 0Fix lint warnings (#4586)phaniumbefore adoption91fab3b
lines 209–211why, one step back209 tokens = make([]string, len(locs))210 for i, loc := range locs {211 tokens[i] = text[begin:loc[1]][fish] Improve option prefix processingbitraidbefore adoptione491770
lines 212–236why, one step back212 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 delimiter and whitespaces222func StripLastDelimiter(str string, delimiter Delimiter) string {223 if delimiter.str != nil {224 str = strings.TrimSuffix(str, *delimiter.str)225 } else if delimiter.regex != nil {226 locs := delimiter.regex.FindAllStringIndex(str, -1)227 if len(locs) > 0 {228 lastLoc := locs[len(locs)-1]229 if lastLoc[1] == len(str) {230 str = str[:lastLoc[0]]231 }232 }233 }234 return strings.TrimRightFunc(str, unicode.IsSpace)235}236Keep the previous delimiter before frozen columnsJunegunn Choibefore adoption1df99db
lines 237–253why, one step back237func GetLastDelimiter(str string, delimiter Delimiter) string {238 if delimiter.str != nil {239 if strings.HasSuffix(str, *delimiter.str) {240 return *delimiter.str241 }242 } else if delimiter.regex != nil {243 locs := delimiter.regex.FindAllStringIndex(str, -1)244 if len(locs) > 0 {245 lastLoc := locs[len(locs)-1]246 if lastLoc[1] == len(str) {247 return str[lastLoc[0]:]248 }249 }250 }251 return ""252}253[fish] Improve option prefix processingbitraidbefore adoptione491770
lines 254–336why, one step back254// JoinTokens concatenates the tokens into a single string255func JoinTokens(tokens []Token) string {256 var output bytes.Buffer257 for _, token := range tokens {258 output.WriteString(token.text.ToString())259 }260 return output.String()261}262263// Transform is used to transform the input when --with-nth option is given264func Transform(tokens []Token, withNth []Range) []Token {265 transTokens := make([]Token, len(withNth))266 numTokens := len(tokens)267 for idx, r := range withNth {268 parts := []*util.Chars{}269 minIdx := 0270 if r.begin == r.end {271 idx := r.begin272 if idx == rangeEllipsis {273 chars := util.ToChars(stringBytes(JoinTokens(tokens)))274 parts = append(parts, &chars)275 } else {276 if idx < 0 {277 idx += numTokens + 1278 }279 if idx >= 1 && idx <= numTokens {280 minIdx = idx - 1281 parts = append(parts, tokens[idx-1].text)282 }283 }284 } else {285 var begin, end int286 if r.begin == rangeEllipsis { // ..N287 begin, end = 1, r.end288 if end < 0 {289 end += numTokens + 1290 }291 } else if r.end == rangeEllipsis { // N..292 begin, end = r.begin, numTokens293 if begin < 0 {294 begin += numTokens + 1295 }296 } else {297 begin, end = r.begin, r.end298 if begin < 0 {299 begin += numTokens + 1300 }301 if end < 0 {302 end += numTokens + 1303 }304 }305 minIdx = util.Max(0, begin-1)306 for idx := begin; idx <= end; idx++ {307 if idx >= 1 && idx <= numTokens {308 parts = append(parts, tokens[idx-1].text)309 }310 }311 }312 // Merge multiple parts313 var merged util.Chars314 switch len(parts) {315 case 0:316 merged = util.ToChars([]byte{})317 case 1:318 merged = *parts[0]319 default:320 var output bytes.Buffer321 for _, part := range parts {322 output.WriteString(part.ToString())323 }324 merged = util.ToChars(output.Bytes())325 }326327 var prefixLength int32328 if minIdx < numTokens {329 prefixLength = tokens[minIdx].prefixLength330 } else {331 prefixLength = 0332 }333 transTokens[idx] = Token{&merged, prefixLength}334 }335 return transTokens336}