GoLSh/utils/AutoCompleter.go
2025-06-27 15:57:36 -05:00

70 lines
1.8 KiB
Go

package utils
import (
"gosh/types"
"os"
"strings"
)
type AutoCompleter struct {
Sh *types.Shell
}
func (a *AutoCompleter) Do(line []rune, pos int) ([][]rune, int) {
cmds := []string{"ls", "cd", "pwd", "cat", "grep", "clear", "apath", "exit"}
potential_suggestions := []string{}
s_line := string(line)
words := strings.Fields(s_line)
last_word := ""
if len(words) > 0 {
last_word = words[len(words)-1]
}
// If typing the command (first word), suggest commands
if len(words) == 0 || (len(words) == 1 && s_line[len(s_line)-1] != ' ') {
potential_suggestions = append(potential_suggestions, cmds...)
} else if words[0] == "cd" || words[0] == "ls" {
// Suggest directories for 'cd'
last_word := ""
if len(words) > 1 {
last_word = words[len(words)-1]
}
children, err := os.ReadDir(a.Sh.Cd)
if err == nil {
for _, child := range children {
if child.IsDir() && (last_word == "" || strings.HasPrefix(child.Name(), last_word)) {
potential_suggestions = append(potential_suggestions, child.Name())
}
}
}
} else if words[0] == "cat" {
// Suggest directories for 'cat'
last_word := ""
if len(words) > 1 {
last_word = words[len(words)-1]
}
children, err := os.ReadDir(a.Sh.Cd)
if err == nil {
for _, child := range children {
if !child.IsDir() && (last_word == "" || strings.HasPrefix(child.Name(), last_word)) {
potential_suggestions = append(potential_suggestions, child.Name())
}
}
}
}
var suggestions [][]rune
for _, s := range potential_suggestions {
// Only append the part that should be completed (remove the prefix)
if last_word != "" && strings.HasPrefix(s, last_word) {
suggestions = append(suggestions, []rune(s[len(last_word):]))
} else {
suggestions = append(suggestions, []rune(s))
}
}
return suggestions, len([]rune(s_line))
}