]> git.lizzy.rs Git - micro.git/blobdiff - cmd/micro/util.go
Improve tab completion in command mode
[micro.git] / cmd / micro / util.go
index 46da66da2918fd51a984bebc556fef36043313c6..4dc2fddeef1ea59fce6dec715a68b9dcd18b8fba 100644 (file)
@@ -112,6 +112,17 @@ func IsSpaces(str string) bool {
        return true
 }
 
+// IsSpacesOrTabs checks if a given string contains only spaces and tabs
+func IsSpacesOrTabs(str string) bool {
+       for _, c := range str {
+               if c != ' ' && c != '\t' {
+                       return false
+               }
+       }
+
+       return true
+}
+
 // ParseBool is almost exactly like strconv.ParseBool, except it also accepts 'on' and 'off'
 // as 'true' and 'false' respectively
 func ParseBool(str string) (bool, error) {
@@ -140,18 +151,21 @@ func GetModTime(path string) (time.Time, bool) {
        return info.ModTime(), true
 }
 
-func StringWidth(str string) int {
+// StringWidth returns the width of a string where tabs count as `tabsize` width
+func StringWidth(str string, tabsize int) int {
        sw := runewidth.StringWidth(str)
-       sw += NumOccurences(str, '\t') * (int(settings["tabsize"].(float64)) - 1)
+       sw += NumOccurences(str, '\t') * (tabsize - 1)
        return sw
 }
 
-func WidthOfLargeRunes(str string) int {
+// WidthOfLargeRunes searches all the runes in a string and counts up all the widths of runes
+// that have a width larger than 1 (this also counts tabs as `tabsize` width)
+func WidthOfLargeRunes(str string, tabsize int) int {
        count := 0
        for _, ch := range str {
                var w int
                if ch == '\t' {
-                       w = int(settings["tabsize"].(float64))
+                       w = tabsize
                } else {
                        w = runewidth.RuneWidth(ch)
                }
@@ -162,6 +176,44 @@ func WidthOfLargeRunes(str string) int {
        return count
 }
 
+// RunePos returns the rune index of a given byte index
+// This could cause problems if the byte index is between code points
 func runePos(p int, str string) int {
        return utf8.RuneCountInString(str[:p])
 }
+
+func lcs(a, b string) string {
+       arunes := []rune(a)
+       brunes := []rune(b)
+
+       lcs := ""
+       for i, r := range arunes {
+               if i >= len(brunes) {
+                       break
+               }
+               if r == brunes[i] {
+                       lcs += string(r)
+               } else {
+                       break
+               }
+       }
+       return lcs
+}
+
+func CommonSubstring(arr ...string) string {
+       commonStr := arr[0]
+
+       for _, str := range arr[1:] {
+               commonStr = lcs(commonStr, str)
+       }
+
+       return commonStr
+}
+
+// Abs is a simple absolute value function for ints
+func Abs(n int) int {
+       if n < 0 {
+               return -n
+       }
+       return n
+}