chore: import official kitty sources from upstream

Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty, vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
BlackAngelTV committed 2026-11-04 11:35:59 +01:00
commit 3d174c45a4
1134 files changed
+433629

No files matched your search

+78
View File
@@ -0,0 +1,78 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package cli
import (
"fmt"
"strings"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
func bash_completion_script(commands []string) (string, error) {
return `_ksi_completions() {
builtin local src
builtin local limit
# Send all words up to the word the cursor is currently on
builtin let limit=1+$COMP_CWORD
src=$(builtin printf "%s\n" "${COMP_WORDS[@]:0:$limit}" | builtin command kitten __complete__ bash)
if [[ $? == 0 ]]; then
builtin eval "${src}"
fi
}
builtin complete -F _ksi_completions kitty
builtin complete -F _ksi_completions edit-in-kitty
builtin complete -F _ksi_completions clone-in-kitty
builtin complete -F _ksi_completions kitten
`, nil
}
func bash_output_serializer(completions []*Completions, shell_state map[string]string) ([]byte, error) {
output := strings.Builder{}
f := func(format string, args ...any) { fmt.Fprintf(&output, format+"\n", args...) }
n := completions[0].Delegate.NumToRemove
if n > 0 {
f("if builtin declare -F _command_offset >/dev/null; then")
f(" compopt +o nospace")
f(" COMP_WORDS[%d]=%s", n, utils.QuoteStringForSH(completions[0].Delegate.Command))
f(" _command_offset %d", n)
f("fi")
} else {
for _, mg := range completions[0].Groups {
if mg.NoTrailingSpace {
f("compopt -o nospace")
} else {
f("compopt +o nospace")
}
if mg.IsFiles {
f("compopt -o filenames")
for _, m := range mg.Matches {
if strings.HasSuffix(m.Word, utils.Sep) {
m.Word = m.Word[:len(m.Word)-1]
}
}
} else {
f("compopt +o filenames")
}
for _, m := range mg.Matches {
f("COMPREPLY+=(%s)", utils.QuoteStringForSH(m.Word))
}
}
}
// debugf("%#v", output.String())
return []byte(output.String()), nil
}
func bash_init_completions(completions *Completions) {
completions.split_on_equals = true
}
func init() {
completion_scripts["bash"] = bash_completion_script
input_parsers["bash"] = shell_input_parser
output_serializers["bash"] = bash_output_serializer
init_completions["bash"] = bash_init_completions
}
+593
View File
@@ -0,0 +1,593 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package cli
import (
"fmt"
"os"
"path/filepath"
"reflect"
"strings"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
type RunFunc = func(cmd *Command, args []string) (int, error)
type Command struct {
Name, Group string
Usage, ShortDescription, HelpText string
Hidden bool
// Number of non-option arguments after which to stop parsing options. 0 means no options after the first non-option arg.
AllowOptionsAfterArgs int
// If true does not fail if the first non-option arg is not a sub-command
SubCommandIsOptional bool
// If true subcommands are ignored unless they are the first non-option argument
SubCommandMustBeFirst bool
// The entry point for this command
Run RunFunc
// The completer for args
ArgCompleter CompletionFunc
// Stop completion processing at this arg num
StopCompletingAtArg int
// Consider all args as non-options args when parsing for completion
OnlyArgsAllowed bool
// Pass through all args, useful for wrapper commands
IgnoreAllArgs bool
// Specialised arg parsing
ParseArgsForCompletion func(cmd *Command, args []string, completions *Completions)
// Callback that is called on error
CallbackOnError func(cmd *Command, err error, during_parsing bool, exit_code int) (final_exit_code int)
SubCommandGroups []*CommandGroup
OptionGroups []*OptionGroup
Parent *Command
Args []string
option_map map[string]*Option
IndexOfFirstArg int
}
func (self *Command) Clone(parent *Command) *Command {
ans := *self
ans.Args = make([]string, 0, 8)
ans.Parent = parent
ans.SubCommandGroups = make([]*CommandGroup, len(self.SubCommandGroups))
ans.OptionGroups = make([]*OptionGroup, len(self.OptionGroups))
ans.option_map = nil
for i, o := range self.OptionGroups {
ans.OptionGroups[i] = o.Clone(&ans)
}
for i, g := range self.SubCommandGroups {
ans.SubCommandGroups[i] = g.Clone(&ans)
}
return &ans
}
func (self *Command) AddClone(group string, src *Command) *Command {
c := src.Clone(self)
g := self.AddSubCommandGroup(group)
c.Group = g.Title
g.SubCommands = append(g.SubCommands, c)
return c
}
func init_cmd(c *Command) {
c.SubCommandGroups = make([]*CommandGroup, 0, 8)
c.OptionGroups = make([]*OptionGroup, 0, 8)
c.Args = make([]string, 0, 8)
c.option_map = nil
}
func NewRootCommand() *Command {
ans := Command{
Name: filepath.Base(os.Args[0]),
}
init_cmd(&ans)
return &ans
}
func (self *Command) AddSubCommandGroup(title string) *CommandGroup {
for _, g := range self.SubCommandGroups {
if g.Title == title {
return g
}
}
ans := CommandGroup{Title: title, SubCommands: make([]*Command, 0, 8)}
self.SubCommandGroups = append(self.SubCommandGroups, &ans)
return &ans
}
func (self *Command) AddSubCommand(ans *Command) *Command {
g := self.AddSubCommandGroup(ans.Group)
g.SubCommands = append(g.SubCommands, ans)
init_cmd(ans)
ans.Parent = self
return ans
}
func (self *Command) Validate() error {
seen_sc := make(map[string]bool)
for _, g := range self.SubCommandGroups {
for _, sc := range g.SubCommands {
if seen_sc[sc.Name] {
return &ParseError{Message: fmt.Sprintf("The sub-command :yellow:`%s` occurs twice inside %s", sc.Name, self.Name)}
}
seen_sc[sc.Name] = true
err := sc.Validate()
if err != nil {
return err
}
}
}
seen_flags := make(map[string]bool)
self.option_map = make(map[string]*Option, 128)
validate_options := func(opt *Option) error {
if self.option_map[opt.Name] != nil {
return &ParseError{Message: fmt.Sprintf("The option :yellow:`%s` occurs twice inside %s", opt.Name, self.Name)}
}
for _, a := range opt.Aliases {
q := a.String()
if seen_flags[q] {
return &ParseError{Message: fmt.Sprintf("The option :yellow:`%s` occurs twice inside %s", q, self.Name)}
}
seen_flags[q] = true
}
self.option_map[opt.Name] = opt
return nil
}
err := self.VisitAllOptions(validate_options)
if err != nil {
return err
}
if self.option_map["Help"] == nil {
if seen_flags["-h"] || seen_flags["--help"] {
return &ParseError{Message: fmt.Sprintf("The --help or -h flags are assigned to an option other than Help in %s", self.Name)}
}
self.option_map["Help"] = self.Add(OptionSpec{Name: "--help -h", Type: "bool-set", Help: "Show help for this command"})
}
if self.Parent == nil && self.option_map["Version"] == nil {
if seen_flags["--version"] {
return &ParseError{Message: fmt.Sprintf("The --version flag is assigned to an option other than Version in %s", self.Name)}
}
self.option_map["Version"] = self.Add(OptionSpec{Name: "--version", Type: "bool-set", Help: "Show version"})
}
return nil
}
func (self *Command) Root() *Command {
p := self
for p.Parent != nil {
p = p.Parent
}
return p
}
func (self *Command) CommandStringForUsage() string {
names := make([]string, 0, 8)
p := self
for p != nil {
if p.Name != "" {
names = append(names, p.Name)
}
p = p.Parent
}
return strings.Join(utils.Reverse(names), " ")
}
func (self *Command) ParseArgs(args []string) (*Command, error) {
for ; self.Parent != nil; self = self.Parent {
}
err := self.Validate()
if err != nil {
return nil, err
}
if args == nil {
args = os.Args
}
if len(args) < 1 {
return nil, &ParseError{Message: "At least one arg must be supplied"}
}
ctx := Context{SeenCommands: make([]*Command, 0, 4)}
err = self.parse_args(&ctx, args[1:])
if err != nil {
return nil, err
}
return ctx.SeenCommands[len(ctx.SeenCommands)-1], nil
}
func (self *Command) ResetAfterParseArgs() {
for _, g := range self.SubCommandGroups {
for _, sc := range g.SubCommands {
sc.ResetAfterParseArgs()
}
}
for _, g := range self.OptionGroups {
for _, o := range g.Options {
o.reset()
}
}
self.option_map = nil
self.IndexOfFirstArg = 0
self.Args = make([]string, 0, 8)
}
func (self *Command) HasSubCommands() bool {
for _, g := range self.SubCommandGroups {
if len(g.SubCommands) > 0 {
return true
}
}
return false
}
func (self *Command) HasVisibleSubCommands() bool {
for _, g := range self.SubCommandGroups {
if g.HasVisibleSubCommands() {
return true
}
}
return false
}
func (self *Command) VisitAllOptions(callback func(*Option) error) error {
depth := 0
iter_opts := func(cmd *Command) error {
for _, g := range cmd.OptionGroups {
for _, o := range g.Options {
if o.Depth >= depth {
err := callback(o)
if err != nil {
return err
}
}
}
}
return nil
}
for p := self; p != nil; p = p.Parent {
err := iter_opts(p)
if err != nil {
return err
}
depth++
}
return nil
}
func (self *Command) AllOptions() []*Option {
ans := make([]*Option, 0, 64)
_ = self.VisitAllOptions(func(o *Option) error { ans = append(ans, o); return nil })
return ans
}
func (self *Command) GetVisibleOptions() ([]string, map[string][]*Option) {
group_titles := make([]string, 0, len(self.OptionGroups))
gmap := make(map[string][]*Option)
add_options := func(group_title string, opts []*Option) {
if len(opts) == 0 {
return
}
x := gmap[group_title]
if x == nil {
group_titles = append(group_titles, group_title)
gmap[group_title] = opts
} else {
gmap[group_title] = append(x, opts...)
}
}
depth := 0
process_cmd := func(cmd *Command) {
for _, g := range cmd.OptionGroups {
gopts := make([]*Option, 0, len(g.Options))
for _, o := range g.Options {
if !o.Hidden && o.Depth >= depth {
gopts = append(gopts, o)
}
}
add_options(g.Title, gopts)
}
}
for p := self; p != nil; p = p.Parent {
process_cmd(p)
depth++
}
return group_titles, gmap
}
func sort_levenshtein_matches(q string, matches []string) {
utils.StableSort(matches, func(a, b string) int {
la, lb := utils.LevenshteinDistance(a, q, true), utils.LevenshteinDistance(b, q, true)
if la != lb {
return la - lb
}
return strings.Compare(a, b)
})
}
func (self *Command) SuggestionsForCommand(name string, max_distance int /* good default is 2 */) []string {
ans := make([]string, 0, 8)
q := strings.ToLower(name)
for _, g := range self.SubCommandGroups {
for _, sc := range g.SubCommands {
if utils.LevenshteinDistance(sc.Name, q, true) <= max_distance {
ans = append(ans, sc.Name)
}
}
}
sort_levenshtein_matches(q, ans)
return ans
}
func (self *Command) SuggestionsForOption(name_with_hyphens string, max_distance int /* good default is 2 */) []string {
ans := make([]string, 0, 8)
q := strings.ToLower(name_with_hyphens)
_ = self.VisitAllOptions(func(opt *Option) error {
for _, a := range opt.Aliases {
as := a.String()
if utils.LevenshteinDistance(as, q, true) <= max_distance {
ans = append(ans, as)
}
}
return nil
})
sort_levenshtein_matches(q, ans)
return ans
}
func (self *Command) FindSubCommand(name string) *Command {
for _, g := range self.SubCommandGroups {
c := g.FindSubCommand(name)
if c != nil {
return c
}
}
return nil
}
func (self *Command) FindSubCommands(prefix string) []*Command {
c := self.FindSubCommand(prefix)
if c != nil {
return []*Command{c}
}
ans := make([]*Command, 0, 4)
for _, g := range self.SubCommandGroups {
ans = g.FindSubCommands(prefix, ans)
}
return ans
}
func (self *Command) AddOptionGroup(title string) *OptionGroup {
for _, g := range self.OptionGroups {
if g.Title == title {
return g
}
}
ans := OptionGroup{Title: title, Options: make([]*Option, 0, 8)}
self.OptionGroups = append(self.OptionGroups, &ans)
return &ans
}
func (self *Command) AddOptionToGroupFromString(group string, items ...string) *Option {
ans, err := self.AddOptionGroup(group).AddOptionFromString(self, items...)
if err != nil {
panic(err)
}
return ans
}
func (self *Command) AddToGroup(group string, s OptionSpec) *Option {
ans, err := self.AddOptionGroup(group).AddOption(self, s)
if err != nil {
panic(err)
}
return ans
}
func (self *Command) AddOptionFromString(items ...string) *Option {
return self.AddOptionToGroupFromString("", items...)
}
func (self *Command) Add(s OptionSpec) *Option {
return self.AddToGroup("", s)
}
func (self *Command) FindOptions(name_with_hyphens string) []*Option {
ans := make([]*Option, 0, 4)
for _, g := range self.OptionGroups {
x := g.FindOptions(name_with_hyphens)
if x != nil {
ans = append(ans, x...)
}
}
depth := 0
for p := self.Parent; p != nil; p = p.Parent {
depth++
for _, po := range p.FindOptions(name_with_hyphens) {
if po.Depth >= depth {
ans = append(ans, po)
}
}
}
return ans
}
func (self *Command) FindOption(name_with_hyphens string) *Option {
for _, g := range self.OptionGroups {
q := g.FindOption(name_with_hyphens)
if q != nil {
return q
}
}
depth := 0
for p := self.Parent; p != nil; p = p.Parent {
depth++
q := p.FindOption(name_with_hyphens)
if q != nil && q.Depth >= depth {
return q
}
}
return nil
}
type Context struct {
SeenCommands []*Command
}
func GetOptionValue[T any](self *Command, name string) (ans T, err error) {
opt := self.option_map[name]
if opt == nil {
err = fmt.Errorf("No option with the name: %s", name)
return
}
ans, ok := opt.parsed_value().(T)
if !ok {
err = fmt.Errorf("The option %s is not of the correct type", name)
}
return
}
func (self *Command) OptionsSeenOnCommandLine() map[string]bool {
ans := make(map[string]bool)
for name, opt := range self.option_map {
ans[name] = opt != nil && len(opt.values_from_cmdline) > 0
}
return ans
}
func (self *Command) GetOptionValues(pointer_to_options_struct any) error {
val := reflect.ValueOf(pointer_to_options_struct).Elem()
if val.Kind() != reflect.Struct {
return fmt.Errorf("Need a pointer to a struct to set option values on")
}
for i := 0; i < val.NumField(); i++ {
f := val.Field(i)
field_name := val.Type().Field(i).Name
if utils.Capitalize(field_name) != field_name || !f.CanSet() {
continue
}
opt := self.option_map[field_name]
if opt == nil {
return fmt.Errorf("No option with the name: %s", field_name)
}
switch opt.OptionType {
case IntegerOption, CountOption:
if f.Kind() != reflect.Int {
return fmt.Errorf("The field: %s must be an integer", field_name)
}
v := int64(opt.parsed_value().(int))
if f.OverflowInt(v) {
return fmt.Errorf("The value: %d is too large for the integer type used for the option: %s", v, field_name)
}
f.SetInt(v)
case FloatOption:
if f.Kind() != reflect.Float64 {
return fmt.Errorf("The field: %s must be a float64", field_name)
}
v := opt.parsed_value().(float64)
if f.OverflowFloat(v) {
return fmt.Errorf("The value: %f is too large for the integer type used for the option: %s", v, field_name)
}
f.SetFloat(v)
case BoolOption:
if f.Kind() != reflect.Bool {
return fmt.Errorf("The field: %s must be a boolean", field_name)
}
v := opt.parsed_value().(bool)
f.SetBool(v)
case StringOption:
if opt.IsList {
if !is_string_slice(f) {
return fmt.Errorf("The field: %s must be a []string", field_name)
}
v := opt.parsed_value().([]string)
f.Set(reflect.ValueOf(v))
} else {
if f.Kind() != reflect.String {
return fmt.Errorf("The field: %s must be a string", field_name)
}
v := opt.parsed_value().(string)
f.SetString(v)
}
}
}
return nil
}
func (self *Command) ExecArgs(args []string) (exit_code int) {
root := self
for root.Parent != nil {
root = root.Parent
}
cmd, err := root.ParseArgs(args)
if err != nil {
if self.CallbackOnError != nil {
return self.CallbackOnError(cmd, err, true, 1)
}
ShowError(err)
return 1
}
help_opt := cmd.option_map["Help"]
version_opt := root.option_map["Version"]
if help_opt != nil && help_opt.parsed_value().(bool) {
cmd.ShowHelp()
return
} else if version_opt != nil && version_opt.parsed_value().(bool) {
root.ShowVersion()
return
} else if cmd.Run != nil {
exit_code, err = cmd.Run(cmd, cmd.Args)
if err != nil {
if exit_code == 0 {
exit_code = 1
}
if self.CallbackOnError != nil {
return self.CallbackOnError(cmd, err, false, exit_code)
}
ShowError(err)
}
}
return
}
func (self *Command) GetCompletions(argv []string, init_completions func(*Completions)) *Completions {
ans := NewCompletions()
if init_completions != nil {
init_completions(ans)
}
if len(argv) > 0 {
exe := argv[0]
exe = filepath.Base(exe) // zsh completion script passes full path to exe when using aliases
cmd := self.FindSubCommand(exe)
if cmd != nil {
if cmd.ParseArgsForCompletion != nil {
cmd.ParseArgsForCompletion(cmd, argv[1:], ans)
} else {
completion_parse_args(cmd, argv[1:], ans)
}
}
}
non_empty_groups := make([]*MatchGroup, 0, len(ans.Groups))
for _, gr := range ans.Groups {
if len(gr.Matches) > 0 {
non_empty_groups = append(non_empty_groups, gr)
}
}
ans.Groups = non_empty_groups
return ans
}
+110
View File
@@ -0,0 +1,110 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package cli
import (
"encoding/json"
"fmt"
"io"
"os"
"strings"
)
func json_input_parser(data []byte, shell_state map[string]string) ([][]string, error) {
ans := make([][]string, 0, 32)
err := json.Unmarshal(data, &ans)
return ans, err
}
func json_output_serializer(completions []*Completions, shell_state map[string]string) ([]byte, error) {
return json.Marshal(completions)
}
type completion_script_func func(commands []string) (string, error)
type parser_func func(data []byte, shell_state map[string]string) ([][]string, error)
type serializer_func func(completions []*Completions, shell_state map[string]string) ([]byte, error)
var completion_scripts = make(map[string]completion_script_func, 4)
var input_parsers = make(map[string]parser_func, 4)
var output_serializers = make(map[string]serializer_func, 4)
var init_completions = make(map[string]func(*Completions), 4)
func init() {
input_parsers["json"] = json_input_parser
output_serializers["json"] = json_output_serializer
}
var registered_exes []func(root *Command)
func RegisterExeForCompletion(x func(root *Command)) {
if registered_exes == nil {
registered_exes = make([]func(root *Command), 0, 4)
}
registered_exes = append(registered_exes, x)
}
func GenerateCompletions(args []string) error {
output_type := "json"
if len(args) > 0 {
output_type = args[0]
args = args[1:]
}
n := max(1, len(args))
if output_type == "setup" {
if len(args) == 0 {
return fmt.Errorf("The shell must be specified")
}
shell_name := args[0]
args = args[1:]
completion_script := completion_scripts[shell_name]
if completion_script == nil {
return fmt.Errorf("Unsupported shell: %s", shell_name)
}
output, err := completion_script(args)
if err == nil {
_, err = os.Stdout.WriteString(output)
}
return err
}
shell_state := make(map[string]string, n)
for _, arg := range args {
k, v, found := strings.Cut(arg, "=")
if !found {
return fmt.Errorf("Invalid shell state specification: %s", arg)
}
shell_state[k] = v
}
input_parser := input_parsers[output_type]
output_serializer := output_serializers[output_type]
if input_parser == nil || output_serializer == nil {
return fmt.Errorf("Unknown output type: %s", output_type)
}
data, err := io.ReadAll(os.Stdin)
if err != nil {
return err
}
// debugf("%#v", string(data))
all_argv, err := input_parser(data, shell_state)
if err != nil {
return err
}
var root = NewRootCommand()
for _, re := range registered_exes {
re(root)
}
err = root.Validate()
if err != nil {
return err
}
all_completions := make([]*Completions, 0, 1)
for _, argv := range all_argv {
all_completions = append(all_completions, root.GetCompletions(argv, init_completions[output_type]))
root.ResetAfterParseArgs()
}
output, err := output_serializer(all_completions, shell_state)
if err == nil {
_, err = os.Stdout.Write(output)
}
return err
}
+196
View File
@@ -0,0 +1,196 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package cli
import (
"fmt"
"os"
"strings"
)
var _ = fmt.Print
var _ = os.Getenv
func (self *Completions) add_options_group(options []*Option, word string) {
group := self.AddMatchGroup("Options")
if strings.HasPrefix(word, "--") {
if word == "--" {
group.Matches = append(group.Matches, &Match{Word: "--", Description: "End of options"})
}
for _, opt := range options {
for _, q := range opt.Aliases {
if strings.HasPrefix(q.String(), word) {
group.Matches = append(group.Matches, &Match{Word: q.String(), Description: opt.Help})
break
}
}
}
} else {
if word == "-" {
group.Matches = append(group.Matches, &Match{Word: "--", Description: "End of options"})
for _, opt := range options {
has_single_letter_alias := false
for _, q := range opt.Aliases {
if q.IsShort {
group.AddMatch("-"+q.NameWithoutHyphens, opt.Help)
has_single_letter_alias = true
break
}
}
if !has_single_letter_alias {
for _, q := range opt.Aliases {
if !q.IsShort {
group.AddMatch(q.String(), opt.Help)
break
}
}
}
}
} else {
runes := []rune(word)
last_letter := string(runes[len(runes)-1])
for _, opt := range options {
for _, q := range opt.Aliases {
if q.IsShort && q.NameWithoutHyphens == last_letter {
group.AddMatch(word, opt.Help)
return
}
}
}
}
}
}
func (self *Command) sub_command_allowed_at(completions *Completions, arg_num int) bool {
if self.SubCommandMustBeFirst {
return arg_num == 1 && completions.CurrentWordIdxInParent == 1
}
return arg_num == 1
}
func complete_word(word string, completions *Completions, only_args_allowed bool, expecting_arg_for *Option, arg_num int) {
cmd := completions.CurrentCmd
if expecting_arg_for != nil {
if expecting_arg_for.Completer != nil {
expecting_arg_for.Completer(completions, word, arg_num)
}
return
}
if !only_args_allowed && strings.HasPrefix(word, "-") {
if strings.HasPrefix(word, "--") && strings.Contains(word, "=") {
idx := strings.Index(word, "=")
option := cmd.FindOption(word[:idx])
if option != nil {
if option.Completer != nil {
option.Completer(completions, word[idx+1:], arg_num)
completions.AddPrefixToAllMatches(word[:idx+1])
}
}
} else {
completions.add_options_group(cmd.AllOptions(), word)
}
return
}
if cmd.HasVisibleSubCommands() && cmd.sub_command_allowed_at(completions, arg_num) {
for _, cg := range cmd.SubCommandGroups {
group := completions.AddMatchGroup(cg.Title)
if group.Title == "" {
group.Title = "Sub-commands"
}
for _, sc := range cg.SubCommands {
if !sc.Hidden && strings.HasPrefix(sc.Name, word) {
t := sc.ShortDescription
if t == "" {
t = sc.HelpText
}
group.AddMatch(sc.Name, t)
}
}
}
if cmd.SubCommandIsOptional && cmd.ArgCompleter != nil {
cmd.ArgCompleter(completions, word, arg_num)
}
return
}
if cmd.ArgCompleter != nil {
cmd.ArgCompleter(completions, word, arg_num)
}
}
func completion_parse_args(cmd *Command, words []string, completions *Completions) {
completions.CurrentCmd = cmd
if len(words) == 0 {
complete_word("", completions, false, nil, 0)
return
}
completions.AllWords = words
var expecting_arg_for *Option
only_args_allowed := false
arg_num := 0
for i, word := range words {
cmd = completions.CurrentCmd
completions.CurrentWordIdx = i
completions.CurrentWordIdxInParent++
is_last_word := i == len(words)-1
is_option_equal := completions.split_on_equals && word == "=" && expecting_arg_for != nil
if only_args_allowed || (expecting_arg_for == nil && !strings.HasPrefix(word, "-")) {
if !is_option_equal {
arg_num++
}
if arg_num == 1 {
cmd.IndexOfFirstArg = completions.CurrentWordIdx
}
}
if is_last_word {
if is_option_equal {
word = ""
}
complete_word(word, completions, only_args_allowed, expecting_arg_for, arg_num)
} else {
if expecting_arg_for != nil {
if is_option_equal {
continue
}
expecting_arg_for = nil
continue
}
if word == "--" {
only_args_allowed = true
continue
}
if !only_args_allowed && strings.HasPrefix(word, "-") {
if !strings.Contains(word, "=") {
option := cmd.FindOption(word)
if option != nil && option.needs_argument() {
expecting_arg_for = option
}
}
continue
}
if cmd.HasVisibleSubCommands() && cmd.sub_command_allowed_at(completions, arg_num) {
sc := cmd.FindSubCommand(word)
if sc == nil {
only_args_allowed = true
continue
}
completions.CurrentCmd = sc
cmd = sc
arg_num = 0
completions.CurrentWordIdxInParent = 0
only_args_allowed = cmd.OnlyArgsAllowed
if cmd.ParseArgsForCompletion != nil {
cmd.ParseArgsForCompletion(cmd, words[i+1:], completions)
return
}
} else if cmd.StopCompletingAtArg > 0 && arg_num >= cmd.StopCompletingAtArg {
return
} else {
only_args_allowed = true
continue
}
}
}
}
+195
View File
@@ -0,0 +1,195 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package cli
import (
"fmt"
"path/filepath"
"strings"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
var _ = fmt.Print
type Match struct {
Word string `json:"word,omitempty"`
Description string `json:"description,omitempty"`
}
type MatchGroup struct {
Title string `json:"title,omitempty"`
NoTrailingSpace bool `json:"no_trailing_space,omitempty"`
IsFiles bool `json:"is_files,omitempty"`
Matches []*Match `json:"matches,omitempty"`
}
func (self *MatchGroup) remove_common_prefix() string {
if self.IsFiles {
if len(self.Matches) > 1 {
lcp := self.longest_common_prefix()
if strings.Contains(lcp, utils.Sep) {
lcp = strings.TrimRight(filepath.Dir(lcp), utils.Sep) + utils.Sep
self.remove_prefix_from_all_matches(lcp)
return lcp
}
}
} else if len(self.Matches) > 1 && strings.HasPrefix(self.Matches[0].Word, "--") && strings.Contains(self.Matches[0].Word, "=") {
lcp, _, _ := strings.Cut(self.longest_common_prefix(), "=")
lcp += "="
if len(lcp) > 3 {
self.remove_prefix_from_all_matches(lcp)
return lcp
}
}
return ""
}
func (self *MatchGroup) AddMatch(word string, description ...string) *Match {
ans := Match{Word: word, Description: strings.Join(description, " ")}
self.Matches = append(self.Matches, &ans)
return &ans
}
func (self *MatchGroup) AddPrefixToAllMatches(prefix string) {
for _, m := range self.Matches {
m.Word = prefix + m.Word
}
}
func (self *MatchGroup) remove_prefix_from_all_matches(prefix string) {
for _, m := range self.Matches {
m.Word = m.Word[len(prefix):]
}
}
func (self *MatchGroup) has_descriptions() bool {
for _, m := range self.Matches {
if m.Description != "" {
return true
}
}
return false
}
func (self *MatchGroup) max_visual_word_length(limit int) int {
ans := 0
for _, m := range self.Matches {
if q := wcswidth.Stringwidth(m.Word); q > ans {
ans = q
if ans > limit {
return limit
}
}
}
return ans
}
func (self *MatchGroup) longest_common_prefix() string {
limit := len(self.Matches)
i := 0
return utils.LongestCommon(func() (string, bool) {
if i < limit {
i++
return self.Matches[i-1].Word, false
}
return "", true
}, true)
}
type Delegate struct {
NumToRemove int `json:"num_to_remove,omitempty"`
Command string `json:"command,omitempty"`
}
type Completions struct {
Groups []*MatchGroup `json:"groups,omitempty"`
Delegate Delegate `json:"delegate"`
CurrentCmd *Command `json:"-"`
AllWords []string `json:"-"` // all words passed to parse_args()
CurrentWordIdx int `json:"-"` // index of current word in all_words
CurrentWordIdxInParent int `json:"-"` // index of current word in parents command line 1 for first word after parent
split_on_equals bool // true if the cmdline is split on = (BASH does this because readline does this)
}
func NewCompletions() *Completions {
return &Completions{Groups: make([]*MatchGroup, 0, 4)}
}
func (self *Completions) AddPrefixToAllMatches(prefix string) {
for _, mg := range self.Groups {
mg.AddPrefixToAllMatches(prefix)
}
}
func (self *Completions) MergeMatchGroup(mg *MatchGroup) {
if len(mg.Matches) == 0 {
return
}
var dest *MatchGroup
for _, q := range self.Groups {
if q.Title == mg.Title {
dest = q
break
}
}
if dest == nil {
dest = self.AddMatchGroup(mg.Title)
dest.NoTrailingSpace = mg.NoTrailingSpace
dest.IsFiles = mg.IsFiles
}
seen := utils.NewSet[string](64)
for _, q := range self.Groups {
for _, m := range q.Matches {
seen.Add(m.Word)
}
}
for _, m := range mg.Matches {
if !seen.Has(m.Word) {
seen.Add(m.Word)
dest.Matches = append(dest.Matches, m)
}
}
}
func (self *Completions) AddMatchGroup(title string) *MatchGroup {
for _, q := range self.Groups {
if q.Title == title {
return q
}
}
ans := MatchGroup{Title: title, Matches: make([]*Match, 0, 8)}
self.Groups = append(self.Groups, &ans)
return &ans
}
type CompletionFunc = func(completions *Completions, word string, arg_num int)
func NamesCompleter(title string, names ...string) CompletionFunc {
return func(completions *Completions, word string, arg_num int) {
mg := completions.AddMatchGroup(title)
for _, q := range names {
if strings.HasPrefix(q, word) {
mg.AddMatch(q)
}
}
}
}
func ChainCompleters(completers ...CompletionFunc) CompletionFunc {
return func(completions *Completions, word string, arg_num int) {
for _, f := range completers {
f(completions, word, arg_num)
}
}
}
func CompletionForWrapper(wrapped_cmd string) func(completions *Completions, word string, arg_num int) {
return func(completions *Completions, word string, arg_num int) {
completions.Delegate.NumToRemove = completions.CurrentWordIdx
completions.Delegate.Command = wrapped_cmd
}
}
+323
View File
@@ -0,0 +1,323 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package cli
import (
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"golang.org/x/sys/unix"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
func absolutize_path(path string) string {
path = utils.Expanduser(path)
q, err := filepath.Abs(path)
if err == nil {
path = q
}
return path
}
type FileEntry struct {
Name, CompletionCandidate, Abspath string
Mode os.FileMode
IsDir, IsSymlink, IsEmptyDir bool
}
func CompleteFiles(prefix string, callback func(*FileEntry), cwd string) error {
if cwd == "" {
var err error
cwd, err = os.Getwd()
if err != nil {
return err
}
}
location := absolutize_path(prefix)
base_dir := ""
joinable_prefix := ""
switch prefix {
case ".":
base_dir = "."
joinable_prefix = ""
case "./":
base_dir = "."
joinable_prefix = "./"
case "/":
base_dir = "/"
joinable_prefix = "/"
case "~":
base_dir = location
joinable_prefix = "~/"
case "":
base_dir = cwd
joinable_prefix = ""
default:
if strings.HasSuffix(prefix, utils.Sep) {
base_dir = location
joinable_prefix = prefix
} else {
idx := strings.LastIndex(prefix, utils.Sep)
if idx > -1 {
joinable_prefix = prefix[:idx+1]
base_dir = filepath.Dir(location)
}
}
}
if base_dir == "" {
base_dir = cwd
}
if !strings.HasPrefix(base_dir, "~") && !filepath.IsAbs(base_dir) {
base_dir = filepath.Join(cwd, base_dir)
}
// fmt.Printf("prefix=%#v base_dir=%#v joinable_prefix=%#v\n", prefix, base_dir, joinable_prefix)
entries, err := os.ReadDir(base_dir)
if err != nil {
return err
}
for _, entry := range entries {
q := joinable_prefix + entry.Name()
if !strings.HasPrefix(q, prefix) {
continue
}
abspath := filepath.Join(base_dir, entry.Name())
dir_to_check := ""
data := FileEntry{
Name: entry.Name(), Abspath: abspath, Mode: entry.Type(), IsDir: entry.IsDir(),
IsSymlink: entry.Type()&os.ModeSymlink == os.ModeSymlink, CompletionCandidate: q}
if data.IsSymlink {
target, err := filepath.EvalSymlinks(abspath)
if err == nil && target != base_dir {
td, err := os.Stat(target)
if err == nil && td.IsDir() {
dir_to_check = target
data.IsDir = true
}
}
}
if dir_to_check != "" {
subentries, err := os.ReadDir(dir_to_check)
data.IsEmptyDir = err != nil || len(subentries) == 0
}
if data.IsDir {
data.CompletionCandidate += utils.Sep
}
callback(&data)
}
return nil
}
func CompleteExecutablesInPath(prefix string, paths ...string) []string {
ans := make([]string, 0, 1024)
if len(paths) == 0 {
paths = filepath.SplitList(os.Getenv("PATH"))
}
for _, dir := range paths {
entries, err := os.ReadDir(dir)
if err == nil {
for _, e := range entries {
if strings.HasPrefix(e.Name(), prefix) {
// A symlink to a directory has IsDir() false but still passes the X_OK
// check, since directories are executable in the access(2) sense.
p := filepath.Join(dir, e.Name())
if unix.Access(p, unix.X_OK) == nil && !is_dir_or_symlink_to_dir(e, p) {
ans = append(ans, e.Name())
}
}
}
}
}
return ans
}
func is_dir_or_symlink_to_dir(entry os.DirEntry, path string) bool {
if entry.IsDir() {
return true
}
if entry.Type()&os.ModeSymlink == os.ModeSymlink {
p, err := filepath.EvalSymlinks(path)
if err == nil {
s, err := os.Stat(p)
if err == nil && s.IsDir() {
return true
}
}
}
return false
}
func fname_based_completer(prefix, cwd string, is_match func(string) bool) []string {
ans := make([]string, 0, 1024)
_ = CompleteFiles(prefix, func(entry *FileEntry) {
if entry.IsDir && !entry.IsEmptyDir {
entries, err := os.ReadDir(entry.Abspath)
if err == nil {
for _, e := range entries {
if is_match(strings.ToLower(e.Name())) || is_dir_or_symlink_to_dir(e, filepath.Join(entry.Abspath, e.Name())) {
ans = append(ans, entry.CompletionCandidate)
return
}
}
}
return
}
q := strings.ToLower(entry.Name)
if is_match(q) {
ans = append(ans, entry.CompletionCandidate)
}
}, cwd)
return ans
}
func complete_by_fnmatch(prefix, cwd string, patterns []string) []string {
return fname_based_completer(prefix, cwd, func(name string) bool {
for _, pat := range patterns {
matched, err := filepath.Match(pat, name)
if err == nil && matched {
return true
}
}
return false
})
}
func complete_by_mimepat(prefix, cwd string, patterns []string) []string {
all_allowed := slices.Contains(patterns, "*")
return fname_based_completer(prefix, cwd, func(name string) bool {
if all_allowed {
return true
}
mt := utils.GuessMimeType(name)
if mt == "" {
return false
}
for _, pat := range patterns {
matched, err := filepath.Match(pat, mt)
if err == nil && matched {
return true
}
}
return false
})
}
type relative_to int
const (
CWD relative_to = iota
CONFIG
)
func get_cwd_for_completion(relative_to relative_to) string {
switch relative_to {
case CONFIG:
return utils.ConfigDir()
}
return ""
}
func make_completer(title string, relative_to relative_to, patterns []string, f func(string, string, []string) []string) CompletionFunc {
lpats := make([]string, 0, len(patterns))
for _, p := range patterns {
lpats = append(lpats, strings.ToLower(p))
}
cwd := get_cwd_for_completion(relative_to)
return func(completions *Completions, word string, arg_num int) {
q := f(word, cwd, lpats)
if len(q) > 0 {
dirs, files := make([]string, 0, len(q)), make([]string, 0, len(q))
for _, x := range q {
if strings.HasSuffix(x, "/") {
dirs = append(dirs, x)
} else {
files = append(files, x)
}
}
if len(dirs) > 0 {
mg := completions.AddMatchGroup("Directories")
mg.IsFiles = true
mg.NoTrailingSpace = true
for _, c := range dirs {
mg.AddMatch(c)
}
}
mg := completions.AddMatchGroup(title)
mg.IsFiles = true
for _, c := range files {
mg.AddMatch(c)
}
}
}
}
func CompleteExecutableFirstArg(completions *Completions, word string, arg_num int) {
if arg_num > 1 {
completions.Delegate.NumToRemove = completions.CurrentCmd.IndexOfFirstArg + 1 // +1 because the first word is not present in all_words
completions.Delegate.Command = completions.AllWords[completions.CurrentCmd.IndexOfFirstArg]
return
}
exes := CompleteExecutablesInPath(word)
if len(exes) > 0 {
mg := completions.AddMatchGroup("Executables in PATH")
for _, exe := range exes {
mg.AddMatch(exe)
}
}
if len(word) > 0 {
mg := completions.AddMatchGroup("Executables")
mg.IsFiles = true
_ = CompleteFiles(word, func(entry *FileEntry) {
if entry.IsDir && !entry.IsEmptyDir {
// only allow directories that have sub-dirs or executable files in them
entries, err := os.ReadDir(entry.Abspath)
if err == nil {
for _, x := range entries {
if x.IsDir() || unix.Access(filepath.Join(entry.Abspath, x.Name()), unix.X_OK) == nil {
mg.AddMatch(entry.CompletionCandidate)
break
}
}
}
} else if unix.Access(entry.Abspath, unix.X_OK) == nil {
mg.AddMatch(entry.CompletionCandidate)
}
}, "")
}
}
func FnmatchCompleter(title string, relative_to relative_to, patterns ...string) CompletionFunc {
return make_completer(title, relative_to, patterns, complete_by_fnmatch)
}
func MimepatCompleter(title string, relative_to relative_to, patterns ...string) CompletionFunc {
return make_completer(title, relative_to, patterns, complete_by_mimepat)
}
func DirectoryCompleter(title string, relative_to relative_to) CompletionFunc {
if title == "" {
title = "Directories"
}
cwd := get_cwd_for_completion(relative_to)
return func(completions *Completions, word string, arg_num int) {
mg := completions.AddMatchGroup(title)
mg.NoTrailingSpace = true
mg.IsFiles = true
_ = CompleteFiles(word, func(entry *FileEntry) {
if entry.IsDir {
mg.AddMatch(entry.CompletionCandidate)
}
}, cwd)
}
}
+177
View File
@@ -0,0 +1,177 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package cli
import (
"fmt"
"github.com/kovidgoyal/kitty/tools/utils"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"testing"
)
var _ = fmt.Print
func TestCompleteFiles(t *testing.T) {
tdir := t.TempDir()
cwd, _ := os.Getwd()
if cwd != "" {
defer os.Chdir(cwd)
}
os.Chdir(tdir)
create := func(parts ...string) {
f, _ := os.Create(filepath.Join(tdir, filepath.Join(parts...)))
f.Close()
}
create("one.txt")
create("two.txt")
os.Mkdir(filepath.Join(tdir, "odir"), 0700)
create("odir", "three.txt")
create("odir", "four.txt")
test_candidates := func(prefix string, expected ...string) {
if expected == nil {
expected = make([]string, 0)
}
sort.Strings(expected)
actual := make([]string, 0, len(expected))
CompleteFiles(prefix, func(entry *FileEntry) {
actual = append(actual, entry.CompletionCandidate)
if _, err := os.Stat(entry.Abspath); err != nil {
t.Fatalf("Abspath does not exist: %#v", entry.Abspath)
}
}, "")
sort.Strings(actual)
if !reflect.DeepEqual(expected, actual) {
t.Fatalf("Did not get expected completion candidates for prefix: %#v\nExpected: %#v\nActual: %#v", prefix, expected, actual)
}
}
test_abs_candidates := func(prefix string, expected ...string) {
e := make([]string, len(expected))
for i, x := range expected {
if filepath.IsAbs(x) {
e[i] = x
} else {
e[i] = filepath.Join(tdir, x)
if strings.HasSuffix(x, utils.Sep) {
e[i] += utils.Sep
}
}
}
test_candidates(prefix, e...)
}
test_cwd_prefix := func(prefix string, expected ...string) {
e := make([]string, len(expected))
for i, x := range expected {
e[i] = "./" + x
}
test_candidates("./"+prefix, e...)
}
test_cwd_prefix("", "one.txt", "two.txt", "odir/")
test_cwd_prefix("t", "two.txt")
test_cwd_prefix("x")
test_abs_candidates(tdir+utils.Sep, "one.txt", "two.txt", "odir/")
test_abs_candidates(filepath.Join(tdir, "o"), "one.txt", "odir/")
test_candidates("", "one.txt", "two.txt", "odir/")
test_candidates("t", "two.txt")
test_candidates("o", "one.txt", "odir/")
test_candidates("odir", "odir/")
test_candidates("odir/", "odir/three.txt", "odir/four.txt")
test_candidates("odir/f", "odir/four.txt")
test_candidates("x")
// a prefix whose only separator is the leading one, such as /us
if entries, err := os.ReadDir(utils.Sep); err == nil && len(entries) > 0 {
name := entries[0].Name()
prefix := utils.Sep + name[:1]
found := false
CompleteFiles(prefix, func(entry *FileEntry) {
found = found || strings.TrimSuffix(entry.CompletionCandidate, utils.Sep) == utils.Sep+name
}, "")
if !found {
t.Fatalf("Did not get %#v as a completion candidate for prefix: %#v", utils.Sep+name, prefix)
}
}
// symlinks to directories are directories
os.Symlink(filepath.Join(tdir, "odir"), filepath.Join(tdir, "slink"))
c := NewCompletions()
DirectoryCompleter("", CWD)(c, "s", 0)
if len(c.Groups) != 1 || len(c.Groups[0].Matches) != 1 || c.Groups[0].Matches[0].Word != "slink/" {
t.Fatalf("Symlink to directory not completed by DirectoryCompleter: %#v", c.Groups)
}
// filenames inside a directory are matched case-insensitively against patterns
os.Mkdir(filepath.Join(tdir, "cdir"), 0700)
create("cdir", "B.CONF")
c = NewCompletions()
FnmatchCompleter("", CWD, "*.conf")(c, "c", 0)
found := false
for _, g := range c.Groups {
for _, m := range g.Matches {
found = found || m.Word == "cdir/"
}
}
if !found {
t.Fatalf("Directory containing only an uppercase extension match not completed by FnmatchCompleter: %#v", c.Groups)
}
// mime types kitty knows about but the Go stdlib does not
create("zz.py")
c = NewCompletions()
MimepatCompleter("", CWD, "text/*")(c, "zz", 0)
found = false
for _, g := range c.Groups {
for _, m := range g.Matches {
found = found || m.Word == "zz.py"
}
}
if !found {
t.Fatalf("File with a mime type known only to kitty not completed by MimepatCompleter: %#v", c.Groups)
}
}
func TestCompleteExecutables(t *testing.T) {
tdir := t.TempDir()
create := func(base string, name string, mode os.FileMode) {
f, _ := os.OpenFile(filepath.Join(tdir, base, name), os.O_CREATE, mode)
f.Close()
}
os.Mkdir(filepath.Join(tdir, "one"), 0700)
os.Mkdir(filepath.Join(tdir, "two"), 0700)
create("", "not-in-path", 0700)
create("one", "one-exec", 0700)
create("one", "one-not-exec", 0600)
create("two", "two-exec", 0700)
os.Symlink(filepath.Join(tdir, "two", "two-exec"), filepath.Join(tdir, "one", "s"))
os.Symlink(filepath.Join(tdir, "one", "one-not-exec"), filepath.Join(tdir, "one", "n"))
// A symlink to a directory passes the X_OK check, so it must not be offered as a command.
os.Mkdir(filepath.Join(tdir, "two", "subdir"), 0700)
os.Symlink(filepath.Join(tdir, "two", "subdir"), filepath.Join(tdir, "one", "d"))
t.Setenv("PATH", strings.Join([]string{filepath.Join(tdir, "one"), filepath.Join(tdir, "two")}, string(os.PathListSeparator)))
test_candidates := func(prefix string, expected ...string) {
if expected == nil {
expected = make([]string, 0)
}
actual := CompleteExecutablesInPath(prefix)
sort.Strings(expected)
sort.Strings(actual)
if !reflect.DeepEqual(expected, actual) {
t.Fatalf("Did not get expected completion candidates for prefix: %#v\nExpected: %#v\nActual: %#v", prefix, expected, actual)
}
}
test_candidates("", "one-exec", "two-exec", "s")
test_candidates("o", "one-exec")
test_candidates("x")
}
+92
View File
@@ -0,0 +1,92 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package cli
import (
"fmt"
"slices"
"strings"
"github.com/kovidgoyal/kitty/tools/cli/markup"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
func fish_completion_script(commands []string) (string, error) {
// One command in fish requires one completion script.
// Usage: kitten __complete__ setup fish [kitty|kitten|clone-in-kitty]
all_commands := map[string]bool{
"kitty": true,
"clone-in-kitty": true,
"kitten": true,
}
if len(commands) == 0 {
commands = append(commands, utils.Keys(all_commands)...)
}
script := strings.Builder{}
script.WriteString(`function __ksi_completions
set --local ct (commandline --current-token)
set --local tokens (commandline --tokenize --cut-at-cursor --current-process)
printf "%s\n" $tokens $ct | command kitten __complete__ fish | source -
end
`)
slices.Sort(commands)
for _, cmd := range commands {
if all_commands[cmd] {
fmt.Fprintf(&script, "complete -f -c %s -a \"(__ksi_completions)\"\n", cmd)
} else if strings.Contains(cmd, "=") {
// Reserved for `setup SHELL [KEY=VALUE ...]`, not used now.
continue
} else {
return "", fmt.Errorf("No fish completion script for command: %s", cmd)
}
}
return script.String(), nil
}
func fish_output_serializer(completions []*Completions, shell_state map[string]string) ([]byte, error) {
output := strings.Builder{}
f := func(format string, args ...any) { fmt.Fprintf(&output, format+"\n", args...) }
n := completions[0].Delegate.NumToRemove
fm := markup.New(false) // fish freaks out if there are escape codes in the description strings
legacy_completion := shell_state["_legacy_completion"]
// fish splits the output of the completion function on newlines, so a description
// spanning multiple lines adds its continuation lines as spurious candidates.
candidate := func(m *Match) string {
return strings.ReplaceAll(m.Word+"\t"+fm.Prettify(m.Description), "\n", " ")
}
if legacy_completion == "fish2" {
for _, mg := range completions[0].Groups {
for _, m := range mg.Matches {
f("%s", candidate(m))
}
}
} else if n > 0 {
words := make([]string, len(completions[0].AllWords)-n+1)
words[0] = completions[0].Delegate.Command
copy(words[1:], completions[0].AllWords[n:])
for i, w := range words {
words[i] = fmt.Sprintf("(string escape -- %s)", utils.QuoteStringForFish(w))
}
cmdline := strings.Join(words, " ")
f("set __ksi_cmdline " + cmdline)
f("complete -C \"$__ksi_cmdline\"")
f("set --erase __ksi_cmdline")
} else {
for _, mg := range completions[0].Groups {
for _, m := range mg.Matches {
f("echo -- %s", utils.QuoteStringForFish(candidate(m)))
}
}
}
// debugf("%#v", output.String())
return []byte(output.String()), nil
}
func init() {
completion_scripts["fish"] = fish_completion_script
input_parsers["fish"] = shell_input_parser
output_serializers["fish"] = fish_output_serializer
}
+25
View File
@@ -0,0 +1,25 @@
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
package cli
import (
"strings"
"testing"
)
func TestFishCompletionMultilineDescription(t *testing.T) {
completions := []*Completions{{Groups: []*MatchGroup{{Title: "Options", Matches: []*Match{
{Word: "--config", Description: "Specify a path to the configuration file.\n\nIf it is not specified, config files are searched for."},
}}}}}
for _, shell_state := range []map[string]string{{}, {"_legacy_completion": "fish2"}} {
data, err := fish_output_serializer(completions, shell_state)
if err != nil {
t.Fatal(err)
}
// each candidate must be a single line, since fish splits the output of the
// completion function on newlines to get the candidate list
if q := strings.TrimRight(string(data), "\n"); strings.Contains(q, "\n") {
t.Fatalf("A multi line description produced more than one candidate with shell state %#v:\n%s", shell_state, q)
}
}
}
+116
View File
@@ -0,0 +1,116 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package cli
import (
"fmt"
"strings"
)
var _ = fmt.Print
type CommandGroup struct {
SubCommands []*Command
Title string
}
func (self *CommandGroup) HasVisibleSubCommands() bool {
for _, c := range self.SubCommands {
if !c.Hidden {
return true
}
}
return false
}
func (self *CommandGroup) Clone(parent *Command) *CommandGroup {
ans := CommandGroup{Title: self.Title, SubCommands: make([]*Command, len(self.SubCommands))}
for i, o := range self.SubCommands {
ans.SubCommands[i] = o.Clone(parent)
}
return &ans
}
func (self *CommandGroup) AddSubCommand(parent *Command, name string) *Command {
ans := NewRootCommand()
ans.Parent = parent
ans.Name = name
self.SubCommands = append(self.SubCommands, ans)
return ans
}
func (self *CommandGroup) FindSubCommand(name string) *Command {
for _, c := range self.SubCommands {
if c.Name == name {
return c
}
}
return nil
}
func (self *CommandGroup) FindSubCommands(prefix string, matches []*Command) []*Command {
for _, c := range self.SubCommands {
if strings.HasPrefix(c.Name, prefix) {
matches = append(matches, c)
}
}
return matches
}
type OptionGroup struct {
Options []*Option
Title string
}
func (self *OptionGroup) Clone(parent *Command) *OptionGroup {
ans := OptionGroup{Title: self.Title, Options: make([]*Option, len(self.Options))}
for i, o := range self.Options {
c := *o
c.init_option()
c.Parent = parent
ans.Options[i] = &c
}
return &ans
}
func (self *OptionGroup) AddOption(parent *Command, spec OptionSpec) (*Option, error) {
ans, err := option_from_spec(spec)
if err == nil {
ans.Parent = parent
self.Options = append(self.Options, ans)
}
return ans, err
}
func (self *OptionGroup) AddOptionFromString(parent *Command, items ...string) (*Option, error) {
ans, err := OptionFromString(items...)
if err == nil {
ans.Parent = parent
self.Options = append(self.Options, ans)
}
return ans, err
}
func (self *OptionGroup) FindOptions(prefix_with_hyphens string) []*Option {
is_short := !strings.HasPrefix(prefix_with_hyphens, "--")
option_name := NormalizeOptionName(prefix_with_hyphens)
ans := make([]*Option, 0, 4)
for _, q := range self.Options {
if q.MatchingAlias(option_name, is_short) != "" {
ans = append(ans, q)
}
}
return ans
}
func (self *OptionGroup) FindOption(name_with_hyphens string) *Option {
is_short := !strings.HasPrefix(name_with_hyphens, "--")
option_name := NormalizeOptionName(name_with_hyphens)
for _, q := range self.Options {
if q.HasAlias(option_name, is_short) {
return q
}
}
return nil
}
+278
View File
@@ -0,0 +1,278 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package cli
import (
"fmt"
"io"
"os"
"os/exec"
"slices"
"strconv"
"strings"
"time"
"golang.org/x/sys/unix"
"github.com/kovidgoyal/kitty"
"github.com/kovidgoyal/kitty/tools/cli/markup"
"github.com/kovidgoyal/kitty/tools/tty"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/style"
)
var _ = fmt.Print
func ShowError(err error) {
formatter := markup.New(tty.IsTerminal(os.Stderr.Fd()))
msg := formatter.Prettify(err.Error())
fmt.Fprintln(os.Stderr, formatter.Err("Error")+":", msg)
}
func (self *Command) version_string(formatter *markup.Context) string {
return fmt.Sprintln(formatter.Italic(self.CommandStringForUsage()), formatter.Opt(kitty.VersionString+kitty.VersionSuffix), "created by", formatter.Title("Kovid Goyal"))
}
func (self *Command) ShowVersion() {
formatter := markup.New(tty.IsTerminal(os.Stdout.Fd()))
fmt.Fprint(os.Stdout, self.version_string(formatter))
}
func format_with_indent(output io.Writer, text string, indent string, screen_width int) {
indented := style.WrapText(text, screen_width, style.WrapOptions{Indent: indent, Ignore_lines_containing: "#placeholder_for_formatting#", Trim_whitespace: true})
io.WriteString(output, indented)
io.WriteString(output, "\n")
}
func (self *Command) FormatSubCommands(output io.Writer, formatter *markup.Context, screen_width int) {
for _, g := range self.SubCommandGroups {
if !g.HasVisibleSubCommands() {
continue
}
title := g.Title
if title == "" {
title = "Commands"
}
fmt.Fprintln(output)
fmt.Fprintln(output, formatter.Title(title)+":")
for _, c := range g.SubCommands {
if c.Hidden {
continue
}
fmt.Fprintln(output, " ", formatter.Opt(c.Name))
format_with_indent(output, formatter.Prettify(c.ShortDescription), " ", screen_width)
}
}
}
func (self *Option) FormatOptionForMan(output io.Writer) {
fmt.Fprintln(output, ".TP")
fmt.Fprint(output, ".BI \"")
for i, a := range self.Aliases {
fmt.Fprint(output, a.String())
if i != len(self.Aliases)-1 {
fmt.Fprint(output, ", ")
}
}
fmt.Fprint(output, "\" ")
defval := self.Default
switch self.OptionType {
case CountOption:
defval = ""
case BoolOption:
defval = utils.IfElse(self.Default == "true", "yes", "no")
}
if defval != "" {
fmt.Fprintf(output, "\" [=%s]\"", escape_text_for_man(defval))
}
fmt.Fprintln(output)
fmt.Fprintln(output, escape_help_for_man(self.Help))
if self.Choices != nil {
fmt.Fprintln(output)
fmt.Fprintln(output, "Choices: "+strings.Join(self.Choices, ", "))
}
}
func (self *Option) FormatOption(output io.Writer, formatter *markup.Context, screen_width int) {
fmt.Fprint(output, " ")
for i, a := range self.Aliases {
fmt.Fprint(output, formatter.Opt(a.String()))
if i != len(self.Aliases)-1 {
fmt.Fprint(output, ", ")
}
}
defval := self.Default
switch self.OptionType {
case CountOption:
defval = ""
case BoolOption:
yn := utils.IfElse(self.Default == "true", "yes", "no")
fmt.Fprintf(output, " %s", formatter.Italic("[="+yn+"]"))
defval = ""
}
if defval != "" {
fmt.Fprintf(output, " [=%s]", formatter.Italic(defval))
}
fmt.Fprintln(output)
format_with_indent(output, formatter.Prettify(prepare_help_text_for_display(self.Help)), " ", screen_width)
if self.Choices != nil {
format_with_indent(output, "Choices: "+strings.Join(self.Choices, ", "), " ", screen_width)
}
}
func (self *Command) ShowHelp() {
self.ShowHelpWithCommandString(strings.TrimSpace(self.CommandStringForUsage()))
}
func ShowHelpInPager(text string) {
pager := exec.Command(kitty.DefaultPager[0], kitty.DefaultPager[1:]...)
pager.Stdin = strings.NewReader(text)
pager.Stdout = os.Stdout
pager.Stderr = os.Stderr
if err := pager.Run(); err != nil {
os.Stdout.WriteString(text)
}
}
func getDeterministicTimestamp() time.Time {
if epoch, err := strconv.ParseInt(os.Getenv("SOURCE_DATE_EPOCH"), 10, 64); err == nil {
return time.Unix(epoch, 0).UTC()
}
return time.Now()
}
func (self *Command) GenerateManPages(level int, recurse bool) (err error) {
var names []string
p := self
for p != nil {
names = append(names, p.Name)
p = p.Parent
}
slices.Reverse(names)
name := strings.Join(names, "-")
outf, err := os.Create(fmt.Sprintf("%s.%d", name, level))
if err != nil {
return err
}
defer outf.Close()
fmt.Fprintf(outf, `.TH "%s" "1" "%s" "%s" "%s"`, name, getDeterministicTimestamp().Format("Jan 02, 2006"), kitty.VersionString, "kitten Manual")
fmt.Fprintln(outf)
fmt.Fprintln(outf, ".SH Name")
fmt.Fprintln(outf, name, "\\-", escape_text_for_man(self.ShortDescription))
fmt.Fprintln(outf, ".SH Usage")
fmt.Fprintln(outf, ".SY", `"`+self.CommandStringForUsage()+` `+self.Usage+`"`)
fmt.Fprintln(outf, ".YS")
if self.HelpText != "" {
fmt.Fprintln(outf, ".SH Description")
fmt.Fprintln(outf, escape_help_for_man(self.HelpText))
}
if self.HasVisibleSubCommands() {
for _, g := range self.SubCommandGroups {
if !g.HasVisibleSubCommands() {
continue
}
title := g.Title
if title == "" {
title = "Commands"
}
fmt.Fprintln(outf, ".SH", title)
for _, c := range utils.Sort(g.SubCommands, func(a, b *Command) int { return strings.Compare(a.Name, b.Name) }) {
if c.Hidden {
continue
}
if recurse {
if err = c.GenerateManPages(level, recurse); err != nil {
return err
}
}
fmt.Fprintln(outf, ".TP", "2")
fmt.Fprintln(outf, c.Name)
fmt.Fprintln(outf, escape_text_for_man(c.ShortDescription)+".", "See: ")
fmt.Fprintf(outf, ".MR %s %d\n", name+"-"+c.Name, level)
}
}
fmt.Fprintln(outf, ".PP")
fmt.Fprintln(outf, "Get help for an individual command by running:")
fmt.Fprintln(outf, ".SY", self.CommandStringForUsage())
fmt.Fprintln(outf, "command", "-h")
fmt.Fprintln(outf, ".YS")
}
group_titles, gmap := self.GetVisibleOptions()
if len(group_titles) > 0 {
for _, title := range group_titles {
ptitle := title
if title == "" {
ptitle = "Options"
}
fmt.Fprintln(outf, ".SH", ptitle)
for _, opt := range gmap[title] {
opt.FormatOptionForMan(outf)
}
}
}
return
}
func (self *Command) ShowHelpWithCommandString(cs string) {
formatter := markup.New(tty.IsTerminal(os.Stdout.Fd()))
screen_width := 80
if formatter.EscapeCodesAllowed() {
var sz *unix.Winsize
var tty_size_err error
for {
sz, tty_size_err = unix.IoctlGetWinsize(int(os.Stdout.Fd()), unix.TIOCGWINSZ)
if tty_size_err != unix.EINTR {
break
}
}
if tty_size_err == nil && sz.Col < 80 {
screen_width = int(sz.Col)
}
}
var output strings.Builder
fmt.Fprintln(&output, formatter.Title("Usage")+":", formatter.Exe(cs), strings.TrimSpace(formatter.Prettify(self.Usage)))
fmt.Fprintln(&output)
if self.HelpText != "" {
format_with_indent(&output, formatter.Prettify(prepare_help_text_for_display(self.HelpText)), "", screen_width)
} else if self.ShortDescription != "" {
format_with_indent(&output, formatter.Prettify(self.ShortDescription), "", screen_width)
}
if self.HasVisibleSubCommands() {
self.FormatSubCommands(&output, formatter, screen_width)
fmt.Fprintln(&output)
format_with_indent(&output, "Get help for an individual command by running:", "", screen_width)
fmt.Fprintln(&output, " ", strings.TrimSpace(self.CommandStringForUsage()), formatter.Italic("command"), "-h")
}
group_titles, gmap := self.GetVisibleOptions()
if len(group_titles) > 0 {
fmt.Fprintln(&output)
for _, title := range group_titles {
ptitle := title
if title == "" {
ptitle = "Options"
}
fmt.Fprintln(&output, formatter.Title(ptitle)+":")
for _, opt := range gmap[title] {
opt.FormatOption(&output, formatter, screen_width)
fmt.Fprintln(&output)
}
}
}
output.WriteString(self.version_string(formatter))
output_text := output.String()
// fmt.Printf("%#v\n", output_text)
if formatter.EscapeCodesAllowed() {
ShowHelpInPager(output_text)
} else {
os.Stdout.WriteString(output_text)
}
}
+205
View File
@@ -0,0 +1,205 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package markup
import (
"fmt"
"os"
"path/filepath"
"strings"
"unicode"
"github.com/kovidgoyal/kitty"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/style"
)
var _ = fmt.Print
type Context struct {
fmt_ctx style.Context
Cyan, Green, Blue, Magenta, Red, BrightRed, Yellow, Italic, Bold, Dim, Title, Exe, Opt, Emph, Err, Code func(args ...any) string
Url func(string, string) string
}
var (
fmt_ctx = style.Context{}
)
func New(allow_escape_codes bool) *Context {
ans := Context{}
ans.fmt_ctx.AllowEscapeCodes = allow_escape_codes
fmt_ctx := &ans.fmt_ctx
ans.Cyan = fmt_ctx.SprintFunc("fg=bright-cyan")
ans.Red = fmt_ctx.SprintFunc("fg=red")
ans.Magenta = fmt_ctx.SprintFunc("fg=magenta")
ans.Green = fmt_ctx.SprintFunc("fg=green")
ans.Blue = fmt_ctx.SprintFunc("fg=blue")
ans.BrightRed = fmt_ctx.SprintFunc("fg=bright-red")
ans.Yellow = fmt_ctx.SprintFunc("fg=bright-yellow")
ans.Italic = fmt_ctx.SprintFunc("italic")
ans.Bold = fmt_ctx.SprintFunc("bold")
ans.Dim = fmt_ctx.SprintFunc("dim")
ans.Title = fmt_ctx.SprintFunc("bold fg=blue")
ans.Exe = fmt_ctx.SprintFunc("bold fg=bright-yellow")
ans.Opt = ans.Green
ans.Emph = ans.BrightRed
ans.Err = fmt_ctx.SprintFunc("bold fg=bright-red")
ans.Code = ans.Cyan
ans.Url = fmt_ctx.UrlFunc("u=curly uc=cyan")
return &ans
}
func Remove_backslash_escapes(text string) string {
// see https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#escaping-mechanism
out := strings.Builder{}
prev_was_slash := false
out.Grow(len(text))
for _, ch := range text {
if prev_was_slash {
if !unicode.IsSpace(ch) {
out.WriteRune(ch)
}
prev_was_slash = false
} else {
if ch == '\\' {
prev_was_slash = true
} else {
out.WriteRune(ch)
}
}
}
return out.String()
}
func ReplaceAllRSTRoles(str string, repl func(Rst_format_match) string) string {
var m Rst_format_match
rf := func(full_match string, groupdict map[string]utils.SubMatch) string {
m.Payload = groupdict["payload"].Text
m.Role = groupdict["role"].Text
return repl(m)
}
return utils.ReplaceAll(utils.MustCompile(":(?P<role>[a-z]+):(?:(?:`(?P<payload>[^`]+)`)|(?:'(?P<payload>[^']+)'))"), str, rf)
}
func (self *Context) hyperlink_for_url(url string, text string) string {
return self.Url(url, text)
}
func (self *Context) hyperlink_for_path(path string, text string) string {
if !fmt_ctx.AllowEscapeCodes {
return text
}
path = strings.ReplaceAll(utils.Abspath(path), string(os.PathSeparator), "/")
fi, err := os.Stat(path)
if err == nil && fi.IsDir() {
path = strings.TrimSuffix(path, "/") + "/"
}
host := utils.Hostname()
url := "file://" + host + path
return self.hyperlink_for_url(url, text)
}
func Text_and_target(x string) (text string, target string) {
parts := strings.SplitN(x, "<", 2)
text = strings.TrimSpace(parts[0])
target = strings.TrimRight(parts[len(parts)-1], ">")
return
}
type Rst_format_match struct {
Role, Payload string
}
func (self *Context) link(x string) string {
text, url := Text_and_target(x)
return self.hyperlink_for_url(url, text)
}
func (self *Context) ref_hyperlink(x string, prefix string) string {
text, target := Text_and_target(x)
url := "kitty+doc://" + utils.Hostname() + "/#ref=" + prefix + target
text = ReplaceAllRSTRoles(text, func(group Rst_format_match) string {
return group.Payload
})
return self.hyperlink_for_url(url, text)
}
func (self *Context) Prettify(text string) string {
return ReplaceAllRSTRoles(text, func(group Rst_format_match) string {
val := group.Payload
switch group.Role {
case "file":
if val == "kitty.conf" && self.fmt_ctx.AllowEscapeCodes {
path := filepath.Join(utils.ConfigDir(), val)
val = self.hyperlink_for_path(path, val)
}
return self.Italic(val)
case "env", "envvar":
return self.ref_hyperlink(val, "envvar-")
case "doc":
text, target := Text_and_target(val)
no_title := text == target
target = strings.Trim(target, "/")
if title, ok := kitty.DocTitleMap[target]; ok && no_title {
val = title + " <" + target + ">"
} else {
val = text + " <" + target + ">"
}
return self.ref_hyperlink(val, "doc-")
case "iss":
return self.ref_hyperlink(val, "issues-")
case "pull":
return self.ref_hyperlink(val, "pull-")
case "disc":
return self.ref_hyperlink(val, "discussions-")
case "ref":
return self.ref_hyperlink(val, "")
case "ac":
return self.ref_hyperlink(val, "action-")
case "term":
return self.ref_hyperlink(val, "term-")
case "code":
return self.Code(Remove_backslash_escapes(val))
case "link":
return self.link(val)
case "option":
idx := strings.LastIndex(val, "--")
if idx < 0 {
idx = strings.Index(val, "-")
}
if idx > -1 {
val = strings.TrimSuffix(val[idx:], ">")
}
return self.Bold(val)
case "opt":
return self.Bold(val)
case "yellow":
return self.Yellow(val)
case "blue":
return self.Blue(val)
case "green":
return self.Green(val)
case "cyan":
return self.Cyan(val)
case "magenta":
return self.Magenta(val)
case "emph":
return self.Italic(val)
default:
return val
}
})
}
func (self *Context) SetAllowEscapeCodes(allow_escape_codes bool) {
self.fmt_ctx.AllowEscapeCodes = allow_escape_codes
}
func (self *Context) EscapeCodesAllowed() bool {
return self.fmt_ctx.AllowEscapeCodes
}
+494
View File
@@ -0,0 +1,494 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package cli
import (
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"github.com/kovidgoyal/kitty/tools/cli/markup"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/shlex"
)
var _ = fmt.Print
func camel_case_dest(x string) string {
x = strings.ReplaceAll(strings.ReplaceAll(x, "-", "_"), ",", "")
parts := strings.Split(x, "_")
for i, p := range parts {
parts[i] = utils.Capitalize(p)
}
return strings.Join(parts, "")
}
/*
Create an [Option] from a string. Syntax is:
--option-name, --option-alias, -s
type: string
dest: destination
choices: choice1, choice2, choice 3
depth: 0
default: something
Help text on multiple lines. Indented lines are preserved as indented blocks. Blank lines
are preserved as blank lines. #placeholder_for_formatting# is replaced by the empty string.
.. code:: blocks are handled specially. Lines in them starting with "$ " have the $ colored
to indicate a prompt.
Available types are: string, str, list, int, float, count, bool-set, bool-reset, choices
The default dest is the first --option-name which must be a long option. The destination is automatically CamelCased from snake_case.
If choices are specified type is set to choices automatically.
If depth is negative option is added to all subcommands. If depth is positive option is added to sub-commands upto
the specified depth.
Set the help text to "!" to have an option hidden.
*/
func OptionFromString(entries ...string) (*Option, error) {
return option_from_string(map[string]string{}, entries...)
}
func is_string_slice(f reflect.Value) bool {
if f.Kind() != reflect.Slice {
return false
}
return f.Type().Elem().Kind() == reflect.String
}
func OptionsFromStruct(pointer_to_options_struct any) ([]*Option, error) {
val := reflect.ValueOf(pointer_to_options_struct).Elem()
if val.Kind() != reflect.Struct {
return nil, fmt.Errorf("Need a pointer to a struct to set option values on")
}
ans := make([]*Option, 0, val.NumField())
for i := 0; i < val.NumField(); i++ {
f := val.Field(i)
field_name := val.Type().Field(i).Name
tag := val.Type().Field(i).Tag
if utils.Capitalize(field_name) != field_name || !f.CanSet() {
continue
}
typ := "str"
switch f.Kind() {
case reflect.Slice:
if !is_string_slice(f) {
return nil, fmt.Errorf("The field %s is not a slice of strings", field_name)
}
typ = "list"
case reflect.Int:
typ = "int"
case reflect.Float64:
typ = "float"
case reflect.Bool:
typ = "bool-set"
}
overrides := map[string]string{"dest": field_name, "type": typ}
opt, err := option_from_string(overrides, string(tag))
if err != nil {
return nil, err
}
if opt.OptionType == CountOption && f.Kind() != reflect.Int {
return nil, fmt.Errorf("The field %s is of count type but in the options struct it does not have type int", field_name)
}
ans = append(ans, opt)
}
return ans, nil
}
type multi_scan struct {
entries []string
}
var mpat *regexp.Regexp
func (self *Option) init_option() {
self.values_from_cmdline = make([]string, 0, 1)
self.parsed_values_from_cmdline = make([]any, 0, 1)
}
func option_from_spec(spec OptionSpec) (*Option, error) {
ans := Option{
Help: spec.Help,
}
ans.init_option()
parts := strings.Split(spec.Name, " ")
ans.Name = camel_case_dest(parts[0])
ans.Aliases = make([]Alias, len(parts))
for i, x := range parts {
ans.Aliases[i] = Alias{NameWithoutHyphens: strings.TrimLeft(x, "-"), IsShort: !strings.HasPrefix(x, "--")}
}
if spec.Dest != "" {
ans.Name = spec.Dest
}
ans.Depth = spec.Depth
if spec.Choices != "" {
parts := strings.Split(spec.Choices, ",")
if len(parts) == 1 {
parts = strings.Split(spec.Choices, " ")
} else {
for i, x := range parts {
parts[i] = strings.TrimSpace(x)
}
}
ans.Choices = parts
ans.OptionType = StringOption
if ans.Default == "" {
ans.Default = parts[0]
}
} else {
switch spec.Type {
case "choice", "choices":
ans.OptionType = StringOption
case "int":
ans.OptionType = IntegerOption
ans.Default = "0"
case "float":
ans.OptionType = FloatOption
ans.Default = "0"
case "count":
ans.OptionType = CountOption
ans.Default = "0"
case "bool-set":
ans.OptionType = BoolOption
ans.Default = "false"
case "bool-reset":
ans.OptionType = BoolOption
ans.Default = "true"
for _, a := range ans.Aliases {
a.IsUnset = true
}
case "list":
ans.IsList = true
fallthrough
case "str", "string", "":
ans.OptionType = StringOption
default:
return nil, fmt.Errorf("Unknown option type: %s", spec.Type)
}
}
if spec.Default != "" {
ans.Default = spec.Default
}
ans.Help = spec.Help
ans.Hidden = spec.Help == "!"
pval, err := ans.parse_value(ans.Default)
if err != nil {
return nil, err
}
ans.parsed_default = pval
if ans.IsList {
if ans.Default == "" {
ans.parsed_default = nil
} else if ans.parsed_default, err = shlex.Split(ans.Default); err != nil {
return nil, err
}
}
ans.Completer = spec.Completer
if ans.Aliases == nil || len(ans.Aliases) == 0 {
return nil, fmt.Errorf("No --aliases specified for option")
}
if ans.Name == "" {
return nil, fmt.Errorf("No dest specified for option")
}
return &ans, nil
}
func indent_of_line(x string) int {
return len(x) - len(strings.TrimLeft(x, " \n\t\v\f"))
}
func escape_text_for_man(raw string) string {
italic := func(x string) string {
return "\n.I " + x
}
bold := func(x string) string {
return "\n.B " + x
}
text_without_target := func(val string) string {
text, target := markup.Text_and_target(val)
no_title := text == target
if no_title {
return val
}
return text
}
ref_hyperlink := func(val, prefix string) string {
return text_without_target(val)
}
raw = markup.ReplaceAllRSTRoles(raw, func(group markup.Rst_format_match) string {
val := group.Payload
switch group.Role {
case "file":
return italic(val)
case "env", "envvar":
return bold(val)
case "doc":
return text_without_target(val)
case "iss":
return "Issue #" + val
case "pull":
return "PR #" + val
case "disc":
return "Discussion #" + val
case "ref":
return ref_hyperlink(val, "")
case "ac":
return ref_hyperlink(val, "action-")
case "term":
return ref_hyperlink(val, "term-")
case "code":
return markup.Remove_backslash_escapes(val)
case "link":
return text_without_target(val)
case "option":
idx := strings.LastIndex(val, "--")
if idx < 0 {
idx = strings.Index(val, "-")
}
if idx > -1 {
val = strings.TrimSuffix(val[idx:], ">")
}
return bold(val)
case "opt":
return bold(val)
case "yellow":
return val
case "blue":
return val
case "green":
return val
case "cyan":
return val
case "magenta":
return val
case "emph":
return val
default:
return val
}
})
sb := strings.Builder{}
sb.Grow(2 * len(raw))
replacements := map[rune]string{
'"': `\[dq]`, '\'': `\[aq]`, '-': `\-`, '\\': `\e`, '^': `\(ha`, '`': `\(ga`, '~': `\(ti`,
}
for _, ch := range raw {
if rep, found := replacements[ch]; found {
sb.WriteString(rep)
} else {
sb.WriteRune(ch)
}
}
return sb.String()
}
func escape_help_for_man(raw string) string {
help := strings.Builder{}
help.Grow(len(raw) + 256)
prev_indent := 0
in_code_block := false
lines := utils.Splitlines(raw)
handle_non_empty_line := func(i int, line string) int {
if strings.TrimSpace(line) == "#placeholder_for_formatting#" {
return i + 1
}
if strings.HasPrefix(line, ".. code::") {
in_code_block = true
return i + 1
}
current_indent := indent_of_line(line)
if current_indent > 1 {
if prev_indent == 0 {
help.WriteString("\n")
} else {
line = strings.TrimSpace(line)
}
}
prev_indent = current_indent
if help.Len() > 0 && !strings.HasSuffix(help.String(), "\n") {
help.WriteString(" ")
}
help.WriteString(line)
return i
}
handle_empty_line := func(i int, line string) int {
prev_indent = 0
help.WriteString("\n")
if !strings.HasSuffix(help.String(), "::") {
help.WriteString("\n")
}
return i
}
handle_code_block_line := func(i int, line string) int {
if line == "" {
help.WriteString("\n")
return i
}
current_indent := indent_of_line(line)
if current_indent == 0 {
in_code_block = false
return handle_non_empty_line(i, line)
}
line = line[4:]
is_prompt := strings.HasPrefix(line, "$ ")
if is_prompt {
help.WriteString(":yellow:`$ `")
line = line[2:]
}
help.WriteString(line)
help.WriteString("\n")
return i
}
for i := 0; i < len(lines); i++ {
line := lines[i]
if in_code_block {
i = handle_code_block_line(i, line)
continue
}
if line != "" {
i = handle_non_empty_line(i, line)
} else {
i = handle_empty_line(i, line)
}
}
return escape_text_for_man(help.String())
}
func prepare_help_text_for_display(raw string) string {
help := strings.Builder{}
help.Grow(len(raw) + 256)
prev_indent := 0
in_code_block := false
lines := utils.Splitlines(raw)
handle_non_empty_line := func(i int, line string) int {
if strings.HasPrefix(line, ".. code::") {
in_code_block = true
return i + 1
}
current_indent := indent_of_line(line)
if current_indent > 1 {
if prev_indent == 0 {
help.WriteString("\n")
} else {
line = strings.TrimSpace(line)
}
}
prev_indent = current_indent
if help.Len() > 0 && !strings.HasSuffix(help.String(), "\n") {
help.WriteString(" ")
}
help.WriteString(line)
return i
}
handle_empty_line := func(i int, line string) int {
prev_indent = 0
help.WriteString("\n")
if !strings.HasSuffix(help.String(), "::") {
help.WriteString("\n")
}
return i
}
handle_code_block_line := func(i int, line string) int {
if line == "" {
help.WriteString("\n")
return i
}
current_indent := indent_of_line(line)
if current_indent == 0 {
in_code_block = false
return handle_non_empty_line(i, line)
}
line = line[4:]
is_prompt := strings.HasPrefix(line, "$ ")
if is_prompt {
help.WriteString(":yellow:`$ `")
line = line[2:]
}
help.WriteString(line)
help.WriteString("\n")
return i
}
for i := 0; i < len(lines); i++ {
line := lines[i]
if in_code_block {
i = handle_code_block_line(i, line)
continue
}
if line != "" {
i = handle_non_empty_line(i, line)
} else {
i = handle_empty_line(i, line)
}
}
return help.String()
}
func option_from_string(overrides map[string]string, entries ...string) (*Option, error) {
if mpat == nil {
mpat = regexp.MustCompile("^([a-z]+)=(.+)")
}
spec := OptionSpec{}
scanner := utils.NewScanLines(entries...)
in_help := false
help := strings.Builder{}
help.Grow(2048)
if dq, found := overrides["type"]; found {
spec.Type = dq
}
if dq, found := overrides["dest"]; found {
spec.Dest = dq
}
for scanner.Scan() {
line := scanner.Text()
if spec.Name == "" {
if strings.HasPrefix(line, "--") {
spec.Name = line
}
} else if in_help {
spec.Help += line + "\n"
} else {
line = strings.TrimSpace(line)
matches := mpat.FindStringSubmatch(line)
if matches == nil {
continue
}
k, v := matches[1], matches[2]
switch k {
case "choices":
spec.Choices = v
case "default":
if overrides["default"] == "" {
spec.Default = v
}
case "dest":
if overrides["dest"] == "" {
spec.Dest = v
}
case "depth":
depth, err := strconv.ParseInt(v, 0, 0)
if err != nil {
return nil, err
}
spec.Depth = int(depth)
case "condition", "completion":
default:
return nil, fmt.Errorf("Unknown option metadata key: %s", k)
case "type":
spec.Type = v
}
}
}
return option_from_spec(spec)
}
+219
View File
@@ -0,0 +1,219 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package cli
import (
"fmt"
"slices"
"strconv"
"strings"
)
var _ = fmt.Print
type OptionType int
const (
StringOption OptionType = iota
IntegerOption
FloatOption
BoolOption
CountOption
)
type Alias struct {
NameWithoutHyphens string
IsShort bool
IsUnset bool
}
func (self *Alias) String() string {
if self.IsShort {
return "-" + self.NameWithoutHyphens
}
return "--" + self.NameWithoutHyphens
}
type OptionSpec struct {
Name string
Type string
Dest string
Choices string
Depth int
Default string
Help string
Completer CompletionFunc
}
type Option struct {
Name string
Aliases []Alias
Choices []string
Default string
OptionType OptionType
Hidden bool
Depth int
Help string
IsList bool
Parent *Command
Completer CompletionFunc
values_from_cmdline []string
parsed_values_from_cmdline []any
parsed_default any
seen_option string
}
func (self *Option) reset() {
self.values_from_cmdline = self.values_from_cmdline[:0]
self.parsed_values_from_cmdline = self.parsed_values_from_cmdline[:0]
self.seen_option = ""
}
func (self *Option) needs_argument() bool {
return self.OptionType != BoolOption && self.OptionType != CountOption
}
func (self *Option) MatchingAlias(prefix_without_hyphens string, is_short bool) string {
for _, a := range self.Aliases {
if a.IsShort == is_short && strings.HasPrefix(a.NameWithoutHyphens, prefix_without_hyphens) {
return a.String()
}
}
return ""
}
func (self *Option) HasAlias(name_without_hyphens string, is_short bool) bool {
for _, a := range self.Aliases {
if a.IsShort == is_short && a.NameWithoutHyphens == name_without_hyphens {
return true
}
}
return false
}
type ParseError struct {
Option *Option
Message string
}
func (self *ParseError) Error() string { return self.Message }
func NormalizeOptionName(name string) string {
return strings.ReplaceAll(strings.TrimLeft(name, "-"), "_", "-")
}
func (self *Option) parsed_value() any {
if len(self.values_from_cmdline) == 0 {
if self.IsList {
if self.parsed_default == nil {
return []string{}
}
}
return self.parsed_default
}
switch self.OptionType {
case CountOption:
return len(self.parsed_values_from_cmdline)
case StringOption:
if self.IsList {
ans := make([]string, 0, len(self.parsed_values_from_cmdline)+2)
if self.parsed_default != nil {
ans = append(ans, self.parsed_default.([]string)...)
}
for _, x := range self.parsed_values_from_cmdline {
ans = append(ans, x.(string))
}
return ans
}
fallthrough
default:
return self.parsed_values_from_cmdline[len(self.parsed_values_from_cmdline)-1]
}
}
func (self *Option) parse_value(val string) (any, error) {
switch self.OptionType {
case BoolOption:
switch val {
case "y", "yes", "true":
return true, nil
case "n", "no", "false":
return false, nil
default:
return nil, &ParseError{Option: self, Message: fmt.Sprintf(":yellow:`%s` is not a valid value for :bold:`%s`.", val, self.seen_option)}
}
case StringOption:
return val, nil
case IntegerOption, CountOption:
pval, err := strconv.ParseInt(val, 0, 0)
if err != nil {
return nil, &ParseError{Option: self, Message: fmt.Sprintf(
":yellow:`%s` is not a valid number for :bold:`%s`. Only integers in decimal, hexadecimal, binary or octal notation are accepted.", val, self.seen_option)}
}
return int(pval), nil
case FloatOption:
pval, err := strconv.ParseFloat(val, 64)
if err != nil {
return nil, &ParseError{Option: self, Message: fmt.Sprintf(
":yellow:`%s` is not a valid number for :bold:`%s`. Only floats in decimal and hexadecimal notation are accepted.", val, self.seen_option)}
}
return pval, nil
default:
return nil, &ParseError{Option: self, Message: fmt.Sprintf("Unknown option type for %s", self.Name)}
}
}
func (self *Option) add_value(val string) error {
name_without_hyphens := NormalizeOptionName(self.seen_option)
switch self.OptionType {
case BoolOption:
if val == "" {
for _, x := range self.Aliases {
if x.NameWithoutHyphens == name_without_hyphens {
if x.IsUnset {
self.values_from_cmdline = append(self.values_from_cmdline, "false")
self.parsed_values_from_cmdline = append(self.parsed_values_from_cmdline, false)
} else {
self.values_from_cmdline = append(self.values_from_cmdline, "true")
self.parsed_values_from_cmdline = append(self.parsed_values_from_cmdline, true)
}
return nil
}
}
} else {
switch val {
case "y", "yes", "true":
self.values_from_cmdline = append(self.values_from_cmdline, "true")
self.parsed_values_from_cmdline = append(self.parsed_values_from_cmdline, true)
case "n", "no", "false":
self.values_from_cmdline = append(self.values_from_cmdline, "false")
self.parsed_values_from_cmdline = append(self.parsed_values_from_cmdline, false)
default:
return &ParseError{Option: self, Message: fmt.Sprintf(":yellow:`%s` is not a valid value for :bold:`%s`. Valid values: %s",
val, self.seen_option, "y, yes, true, n, no and false",
)}
}
}
case StringOption:
if self.Choices != nil && !slices.Contains(self.Choices, val) {
return &ParseError{Option: self, Message: fmt.Sprintf(":yellow:`%s` is not a valid value for :bold:`%s`. Valid values: %s",
val, self.seen_option, strings.Join(self.Choices, ", "),
)}
}
self.values_from_cmdline = append(self.values_from_cmdline, val)
self.parsed_values_from_cmdline = append(self.parsed_values_from_cmdline, val)
case IntegerOption, FloatOption:
pval, err := self.parse_value(val)
if err != nil {
return err
}
self.values_from_cmdline = append(self.values_from_cmdline, val)
self.parsed_values_from_cmdline = append(self.parsed_values_from_cmdline, pval)
case CountOption:
self.values_from_cmdline = append(self.values_from_cmdline, val)
self.parsed_values_from_cmdline = append(self.parsed_values_from_cmdline, 1)
}
return nil
}
+146
View File
@@ -0,0 +1,146 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package cli
import (
"fmt"
"strings"
)
var _ = fmt.Print
func (self *Command) parse_args(ctx *Context, args []string) error {
args_to_parse := make([]string, len(args))
copy(args_to_parse, args)
ctx.SeenCommands = append(ctx.SeenCommands, self)
if self.IgnoreAllArgs {
self.Args = args
return nil
}
var expecting_arg_for *Option
options_allowed := true
consume_arg := func() string { ans := args_to_parse[0]; args_to_parse = args_to_parse[1:]; return ans }
handle_option := func(opt_str string, has_val bool, opt_val string, val_not_allowed bool) error {
possible_options := self.FindOptions(opt_str)
var opt *Option
if len(possible_options) == 1 {
opt = possible_options[0]
opt_str = opt.MatchingAlias(NormalizeOptionName(opt_str), !strings.HasPrefix(opt_str, "--"))
} else if len(possible_options) == 0 {
possibles := self.SuggestionsForOption(opt_str, 2)
if len(possibles) > 0 {
return &ParseError{Message: fmt.Sprintf("Unknown option: :yellow:`%s`. Did you mean:\n\t%s", opt_str, strings.Join(possibles, "\n\t"))}
}
return &ParseError{Message: fmt.Sprintf("Unknown option: :yellow:`%s`", opt_str)}
} else {
ambi := make([]string, len(possible_options))
for i, o := range possible_options {
ambi[i] = o.MatchingAlias(NormalizeOptionName(opt_str), !strings.HasPrefix(opt_str, "--"))
if ambi[i] == opt_str {
opt = o
break
}
}
if opt == nil {
return &ParseError{Message: fmt.Sprintf("Ambiguous option: :yellow:`%s` could be any of: %s", opt_str, strings.Join(ambi, ", "))}
}
}
opt.seen_option = opt_str
needs_arg := opt.needs_argument()
if needs_arg && val_not_allowed {
return &ParseError{Message: fmt.Sprintf("The option: :yellow:`%s` must be followed by a value not another option", opt_str)}
}
if has_val {
if !needs_arg {
if opt.OptionType == BoolOption {
if err := opt.add_value(opt_val); err != nil {
return err
}
} else {
return &ParseError{Message: fmt.Sprintf("The option: :yellow:`%s` does not take values", opt_str)}
}
}
return opt.add_value(opt_val)
} else if needs_arg {
expecting_arg_for = opt
} else {
opt.add_value("")
}
return nil
}
for len(args_to_parse) > 0 {
arg := consume_arg()
if expecting_arg_for == nil {
if options_allowed && strings.HasPrefix(arg, "-") && arg != "-" {
// handle option arg
if arg == "--" {
options_allowed = false
continue
}
opt_str, opt_val, has_val := strings.Cut(arg, "=")
if strings.HasPrefix(opt_str, "--") {
err := handle_option(opt_str, has_val, opt_val, false)
if err != nil {
return err
}
} else {
runes := []rune(opt_str[1:])
for i, sl := range runes {
var err error
if i == len(runes)-1 {
err = handle_option("-"+string(sl), has_val, opt_val, false)
} else {
err = handle_option("-"+string(sl), false, "", true)
}
if err != nil {
return err
}
}
}
} else {
// handle non option arg
if self.AllowOptionsAfterArgs <= len(self.Args) {
options_allowed = false
}
if self.HasSubCommands() {
possible_cmds := self.FindSubCommands(arg)
if len(possible_cmds) == 1 {
return possible_cmds[0].parse_args(ctx, args_to_parse)
}
if !self.SubCommandIsOptional {
if len(possible_cmds) == 0 {
possibles := self.SuggestionsForCommand(arg, 2)
if len(possibles) > 0 {
return &ParseError{Message: fmt.Sprintf("Unknown subcommand: :yellow:`%s`. Did you mean:\n\t%s", arg, strings.Join(possibles, "\n\t"))}
}
return &ParseError{Message: fmt.Sprintf(":yellow:`%s` is not a known subcommand for :emph:`%s`. Use --help to get a list of valid subcommands.", arg, self.Name)}
}
cn := make([]string, len(possible_cmds))
for i, x := range possible_cmds {
cn[i] = x.Name
}
return &ParseError{Message: fmt.Sprintf(
":yellow:`%s` is not a known subcommand for :emph:`%s`. Did you mean:\n\t%s", arg, self.Name, strings.Join(cn, "\n\t"))}
}
}
self.Args = append(self.Args, arg)
}
} else {
// handle option value
err := expecting_arg_for.add_value(arg)
if err != nil {
return err
}
expecting_arg_for = nil
}
}
if expecting_arg_for != nil {
return &ParseError{Option: expecting_arg_for, Message: fmt.Sprintf("The option: :yellow:`%s` requires a value", expecting_arg_for.seen_option)}
}
return nil
}
+159
View File
@@ -0,0 +1,159 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package cli
import (
"errors"
"fmt"
"reflect"
"strings"
"testing"
"github.com/kovidgoyal/kitty/tools/utils/shlex"
"github.com/google/go-cmp/cmp"
)
var _ = fmt.Print
type empty_options struct {
}
type base_options struct {
FromParent int
}
type options struct {
FromParent int
SimpleString string
Choices string
SetMe bool
Int int
Float float64
List []string
ListWithDefault []string
}
func TestCLIRequiredOptionValues(t *testing.T) {
for _, typ := range []string{"string", "int", "float", "list", "choices"} {
for _, tc := range []struct {
args []string
option string
}{
{[]string{"--value"}, "--value"},
{[]string{"-v"}, "-v"},
{[]string{"-bv"}, "-v"},
{[]string{"--value", "1", "--value"}, "--value"},
} {
for _, child := range []bool{false, true} {
t.Run(fmt.Sprintf("%s/%s/child=%t", typ, strings.Join(tc.args, " "), child), func(t *testing.T) {
root := NewRootCommand()
root.Add(OptionSpec{Name: "--bool -b", Type: "bool-set", Depth: 1})
spec := OptionSpec{Name: "--value -v", Type: typ, Depth: 1}
if typ == "choices" {
spec.Choices = "1 2"
}
root.Add(spec)
args := []string{"test"}
if child {
root.AddSubCommand(&Command{Name: "child"})
args = append(args, "child")
}
_, err := root.ParseArgs(append(args, tc.args...))
var pe *ParseError
if !errors.As(err, &pe) || pe.Option == nil || !strings.Contains(pe.Error(), tc.option) || !strings.Contains(pe.Error(), "requires a value") {
t.Fatalf("Expected missing-value error for %s, got %v", tc.option, err)
}
})
}
}
}
}
func TestCLIParsing(t *testing.T) {
rt := func(expected_cmd *Command, cmdline string, expected_options any, expected_args ...string) {
if opts, ok := expected_options.(*options); ok && opts.ListWithDefault == nil {
opts.ListWithDefault = []string{`1`, `2`}
}
cp, err := shlex.Split(cmdline)
if err != nil {
t.Fatal(err)
}
cmd, err := expected_cmd.ParseArgs(cp)
if err != nil {
t.Fatal(err)
}
if s, ok := expected_options.(*options); ok {
if s.Choices == "" {
s.Choices = "a"
}
if s.List == nil {
s.List = make([]string, 0)
}
}
actual_options := reflect.New(reflect.TypeOf(expected_options).Elem()).Interface()
err = cmd.GetOptionValues(actual_options)
if err != nil {
t.Fatal(err)
}
if diff := cmp.Diff(expected_options, actual_options); diff != "" {
t.Fatalf("Option values incorrect (expected != actual):\nCommand line: %s\n%s", cmdline, diff)
}
if expected_args == nil {
expected_args = []string{}
}
if diff := cmp.Diff(expected_args, cmd.Args); diff != "" {
t.Fatalf("Argument values incorrect (expected != actual):\nCommand line: %s\n%s", cmdline, diff)
}
cmd.Root().ResetAfterParseArgs()
}
root := NewRootCommand()
root.Add(OptionSpec{Name: "--from-parent -p", Type: "count", Depth: 1})
child1 := root.AddSubCommand(&Command{Name: "child1"})
child1.Add(OptionSpec{Name: "--choices", Choices: "a b c"})
child1.Add(OptionSpec{Name: "--simple-string -s"})
child1.Add(OptionSpec{Name: "--set-me -b", Type: "bool-set"})
child1.Add(OptionSpec{Name: "--int -i", Type: "int"})
child1.Add(OptionSpec{Name: "--float", Type: "float"})
child1.Add(OptionSpec{Name: "--list", Type: "list"})
child1.Add(OptionSpec{Name: "--list-with-default -L", Type: "list", Default: "1 2"})
child1.SubCommandIsOptional = true
gc1 := child1.AddSubCommand(&Command{Name: "gc1"})
rt(
child1, "test --from-parent child1 -ps ss --choices b --from-parent one two",
&options{SimpleString: "ss", Choices: "b", FromParent: 3},
"one", "two",
)
rt(child1, "test child1", &options{})
rt(child1, "test child1 --set-me one", &options{SetMe: true}, "one")
rt(child1, "test child1 --set-me=y one", &options{SetMe: true}, "one")
rt(child1, "test child1 --set-me=n one", &options{SetMe: false}, "one")
rt(child1, "test child1 --set-me=n --set-me one", &options{SetMe: true}, "one")
rt(child1, "test child1 --set-me=y -b=n one", &options{SetMe: false}, "one")
rt(child1, "test child1 --set-me --simple-string=foo one", &options{SimpleString: "foo", SetMe: true}, "one")
rt(child1, "test child1 --set-me --simp=foo one", &options{SimpleString: "foo", SetMe: true}, "one")
rt(child1, "test child1 --set-me --simple-string= one", &options{SetMe: true}, "one")
rt(child1, "test child1 --simple-string ''", &options{})
rt(child1, "test child1 -bs ''", &options{SetMe: true})
rt(child1, "test child1 -bp", &options{SetMe: true, FromParent: 1})
rt(child1, "test child1 --simple-string --", &options{SimpleString: "--"})
rt(child1, "test child1 --int -3 --simple-s -s --float=3.3", &options{SimpleString: "-s", Int: -3, Float: 3.3})
rt(child1, "test child1 -bi=3 --float=3.3", &options{SetMe: true, Int: 3, Float: 3.3})
rt(child1, "test child1 --list -3 -p --list one", &options{FromParent: 1, List: []string{"-3", "one"}})
rt(child1, "test child1 -L 3 -L 4", &options{ListWithDefault: []string{`1`, `2`, `3`, `4`}})
rt(gc1, "test -p child1 -p gc1 xxx", &empty_options{}, "xxx")
_, err := child1.ParseArgs(strings.Split("test child1 --choices x", " "))
if err == nil {
t.Fatalf("Invalid choice not caught")
}
root.ResetAfterParseArgs()
gc1.ParseArgs(strings.Split("test child1 -p gc1 xxx", " "))
err = gc1.GetOptionValues(&base_options{})
if err == nil {
t.Fatalf("Invalid choice not caught")
}
}
+268
View File
@@ -0,0 +1,268 @@
package cli
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"strings"
"github.com/google/go-cmp/cmp"
"github.com/kovidgoyal/kitty"
"github.com/kovidgoyal/kitty/tools/tty"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/style"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
var _ = fmt.Print
type cpos struct {
x, y int
}
func cpos_from_report(csi string) (ans cpos, err error) {
before, after, found := strings.Cut(csi, ";")
if !found {
return ans, fmt.Errorf("Malformed Cursor Position Report from terminal with no ;")
}
if ans.y, err = strconv.Atoi(before); err != nil {
return ans, fmt.Errorf("Malformed Cursor Position Report from terminal: %s", csi)
}
if ans.x, err = strconv.Atoi(after); err != nil {
return ans, fmt.Errorf("Malformed Cursor Position Report from terminal: %s", csi)
}
// convert 1-based indexing to zero based indexing
ans.x--
ans.y--
return
}
type test_struct struct {
description string
num int
expected_cursor_positions []int
actual_cursor_positions []cpos
payload string
tester func(actual_cursor_positions []cpos, screen_width int) string
payload_gen func(width_in_cells int) string
}
const cursor_position_report = "\x1b[6n"
const reset_line = "\r\x1b[K"
func wrap_gen(width_in_cells int) string {
return strings.Repeat(" ", width_in_cells-2) + "\U0001f1ee" + cursor_position_report + "\U0001f1f3" + cursor_position_report
}
func wrap_tester(actual_cursor_positions []cpos, screen_width int) string {
if actual_cursor_positions[0].x != actual_cursor_positions[1].x {
return fmt.Sprintf("The cursor moved after adding a combining char from: %v -> %v", actual_cursor_positions[0], actual_cursor_positions[1])
}
return ""
}
func run_tests(tests []*test_struct) (err error) {
lp, err := loop.New(loop.NoAlternateScreen)
if err != nil {
return err
}
num_reports := 0
expected_num_reports := 0
gen_payload := func(screen_width int) string {
buf := strings.Builder{}
buf.WriteString(loop.PENDING_UPDATE.EscapeCodeToSet())
for _, t := range tests {
payload := t.payload
if t.payload_gen != nil {
payload = t.payload_gen(screen_width)
}
expected_num_reports += strings.Count(payload, cursor_position_report)
buf.WriteString(payload)
buf.WriteString(reset_line)
if buf.Len() > 512*1024 {
buf.WriteString(loop.PENDING_UPDATE.EscapeCodeToReset())
buf.WriteString(loop.PENDING_UPDATE.EscapeCodeToSet())
}
}
buf.WriteString(loop.PENDING_UPDATE.EscapeCodeToReset())
buf.WriteString("\x1b[c")
return buf.String()
}
print_para := func(text string) {
sz, _ := lp.ScreenSize()
for _, line := range style.WrapTextAsLines(text, int(sz.WidthCells), style.WrapOptions{Trim_whitespace: true}) {
lp.Println(line)
}
lp.Println()
}
screen_width := 80
lp.OnInitialize = func() (string, error) {
sz, _ := lp.ScreenSize()
screen_width = int(sz.WidthCells)
print_para("These tests work by sending text to the terminal and then querying it for its cursor position. Every test is thus different strings sent to the terminal along with a list of expected cursor positions after each string. A failure means the actual cursor position was different from the expected one. A failure where the first expected cursor position is correct but subsequent ones are not, means that the complete string was rendered at the correct width but individual graphemes from the string were not.")
print_para("The individual test descriptions use the character ÷ to indicate a position where a break is expected to occur and the character × to indicate a position where no break should happen. ")
lp.Printf("Running %d tests, please wait...\n", len(tests))
lp.SaveCursorPosition()
lp.SetCursorVisible(false)
lp.QueueWriteString(gen_payload(screen_width))
return "", err
}
lp.OnFinalize = func() string {
lp.SetCursorVisible(true)
lp.RestoreCursorPosition()
lp.ClearToEndOfScreen()
return ""
}
current_test_idx := 0
lp.OnEscapeCode = func(typ loop.EscapeCodeType, data []byte) error {
if typ == loop.CSI {
switch data[len(data)-1] {
case 'c':
lp.Quit(0)
case 'R':
if found := bytes.Contains(data, []byte{';'}); found {
if cpos, err := cpos_from_report(utils.UnsafeBytesToString(data[:len(data)-1])); err != nil {
return err
} else {
num_reports++
t := tests[current_test_idx]
if len(t.actual_cursor_positions) >= len(t.expected_cursor_positions) && current_test_idx+1 < len(tests) {
current_test_idx += 1
t = tests[current_test_idx]
}
t.actual_cursor_positions = append(t.actual_cursor_positions, cpos)
}
}
}
}
return nil
}
if err = lp.Run(); err != nil {
return err
}
if num_reports != expected_num_reports {
return fmt.Errorf("Terminal did not report the cursor position as many times as expected. %d != %d", expected_num_reports, num_reports)
}
return show_results(tests, screen_width)
}
func show_results(tests []*test_struct, screen_width int) (err error) {
num_failures := 0
for _, t := range tests {
diff := ""
if t.tester == nil {
ac := make([]int, len(t.actual_cursor_positions))
for i, cp := range t.actual_cursor_positions {
ac[i] = cp.x
}
diff = cmp.Diff(t.expected_cursor_positions, ac)
} else {
diff = t.tester(t.actual_cursor_positions, screen_width)
}
if diff != "" {
fmt.Printf("\x1b[31mTest number %d failed\x1b[39m: %s\n", t.num, t.description)
fmt.Println(diff)
num_failures++
}
}
if num_failures > 0 {
err = fmt.Errorf("%d out of %d tests failed.", num_failures, len(tests))
} else {
fmt.Println("All tests passed!")
}
return
}
func has_control_chars(text string) bool {
for _, ch := range text {
if ch < ' ' {
return true
}
}
return false
}
func create_tests(gb_tests []kitty.GraphemeBreakTest, width_in_cells int) (tests []*test_struct) {
for _, t := range gb_tests {
text := strings.Join(t.Data, "")
rt, _ := json.Marshal(text)
desc := fmt.Sprintf("Unicode GraphemeBreakTest: Text: %s Expected breaks:\n%s", string(rt), t.Comment)
if has_control_chars(text) {
continue
}
buf := strings.Builder{}
buf.WriteString(" " + text + cursor_position_report + reset_line + " ")
expected_cursor_positions := []int{1 + wcswidth.Stringwidth(text)}
// Now test cursor position after each individual grapheme
pos := 0
for _, grapheme := range t.Data {
buf.WriteString(grapheme + cursor_position_report)
pos += wcswidth.Stringwidth(grapheme)
expected_cursor_positions = append(expected_cursor_positions, 1+pos)
}
test := test_struct{num: len(tests) + 1, description: desc, payload: buf.String(), expected_cursor_positions: expected_cursor_positions}
tests = append(tests, &test)
}
test := test_struct{
num: len(tests) + 1, description: "Check that combining characters are merged into last cell even when cursor is on the next line",
payload_gen: wrap_gen, tester: wrap_tester}
tests = append(tests, &test)
return
}
func main(allowed_tests *utils.Set[int]) (rc int, err error) {
term, err := tty.OpenControllingTerm()
if err != nil {
return 1, fmt.Errorf("Could not open controlling terminal with error: %w", err)
}
sz, err := term.GetSize()
term.Close()
if err != nil {
return 1, fmt.Errorf("Could not get size of controlling terminal with error: %w", err)
}
width_in_cells := int(sz.Col)
if gb_tests, err := kitty.LoadGraphemeBreakTests(); err == nil {
tests := create_tests(gb_tests, width_in_cells)
if allowed_tests.Len() > 0 {
temp := make([]*test_struct, 0, len(tests))
for _, t := range tests {
if allowed_tests.Has(t.num) {
temp = append(temp, t)
}
}
tests = temp
}
if err = run_tests(tests); err != nil {
return 1, err
}
} else {
return 1, err
}
return
}
func WcswidthKittenEntryPoint(root *Command) {
root.AddSubCommand(&Command{
Name: "__width_test__",
Usage: "[test number to run...]",
HelpText: "Test the terminal for compliance with the kitty text-sizing specification's splitting of text into cells. You can optionally specify specific test numbers to run.",
Hidden: true,
OnlyArgsAllowed: true,
Run: func(cmd *Command, args []string) (rc int, err error) {
allowed_tests := utils.NewSet[int]()
for _, arg := range args {
if x, err := strconv.Atoi(arg); err == nil {
allowed_tests.Add(x)
} else {
return 1, fmt.Errorf("%s is not a valid test number", arg)
}
}
return main(allowed_tests)
},
})
}
+182
View File
@@ -0,0 +1,182 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package cli
import (
"fmt"
"github.com/kovidgoyal/kitty/tools/cli/markup"
"github.com/kovidgoyal/kitty/tools/tty"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/style"
"github.com/kovidgoyal/kitty/tools/wcswidth"
"strings"
)
var _ = fmt.Print
func zsh_completion_script(commands []string) (string, error) {
return `#compdef kitty
_kitty() {
(( ${+commands[kitten]} )) || builtin return
builtin local src cmd=${(F)words:0:$CURRENT}
# Send all words up to the word the cursor is currently on.
src=$(builtin command kitten __complete__ zsh "_matcher=$_matcher" <<<$cmd) || builtin return
builtin eval "$src"
}
if (( $+functions[compdef] )); then
compdef _kitty kitty
compdef _kitty clone-in-kitty
compdef _kitty kitten
fi
`, nil
}
func shell_input_parser(data []byte, shell_state map[string]string) ([][]string, error) {
raw := string(data)
new_word := strings.HasSuffix(raw, "\n\n")
raw = strings.TrimRight(raw, "\n \t")
scanner := utils.NewLineScanner(raw)
words := make([]string, 0, 32)
for scanner.Scan() {
words = append(words, scanner.Text())
}
if new_word {
words = append(words, "")
}
return [][]string{words}, nil
}
var debugprintln = tty.DebugPrintln
var _ = debugprintln
func zsh_input_parser(data []byte, shell_state map[string]string) ([][]string, error) {
matcher := shell_state["_matcher"]
q := ""
if matcher != "" {
q = strings.Split(strings.ToLower(matcher), ":")[0][:1]
}
if q != "" && strings.Contains("lrbe", q) {
// this is zsh anchor based matching
// https://zsh.sourceforge.io/Doc/Release/Completion-Widgets.html#Completion-Matching-Control
// can be specified with matcher-list and some systems do it by default,
// for example, Debian, which adds the following to zshrc
// zstyle ':completion:*' matcher-list '' 'm:{a-z}={A-Z}' 'm:{a-zA-Z}={A-Za-z}' 'r:|[._-]=* r:|=* l:|=*'
// For some reason that I dont have the
// time/interest to figure out, returning completion candidates for
// these matcher types break completion, so just abort in this case.
return nil, fmt.Errorf("ZSH anchor based matching active, cannot complete. Turn it off by setting zstyle :completion: to something that does not use anchors in your ~/.zshrc")
}
return shell_input_parser(data, shell_state)
}
func (self *Match) FormatForCompletionList(max_word_len int, f *markup.Context, screen_width int) string {
word := self.Word
desc := self.Description
if desc == "" {
return word
}
word_len := wcswidth.Stringwidth(word)
line, _, _ := strings.Cut(strings.TrimSpace(desc), "\n")
desc = f.Prettify(line)
multiline := false
max_desc_len := screen_width - max_word_len - 3
if word_len > max_word_len {
multiline = true
} else {
word += strings.Repeat(" ", max_word_len-word_len)
}
if wcswidth.Stringwidth(desc) > max_desc_len {
desc = style.WrapTextAsLines(desc, max_desc_len-2, style.WrapOptions{})[0] + "…"
}
if multiline {
return word + "\n" + strings.Repeat(" ", max_word_len+2) + desc
}
return word + " " + desc
}
func serialize(completions *Completions, f *markup.Context, screen_width int) ([]byte, error) {
output := strings.Builder{}
if completions.Delegate.NumToRemove > 0 {
for i := 0; i < completions.Delegate.NumToRemove; i++ {
fmt.Fprintln(&output, "shift words")
fmt.Fprintln(&output, "(( CURRENT-- ))")
}
service := utils.QuoteStringForSH(completions.Delegate.Command)
fmt.Fprintln(&output, "words[1]="+service)
fmt.Fprintln(&output, "_normal -p", service)
} else {
if len(completions.Groups) > 0 {
// Respect the user's description format, falling back to bold group titles
fmt.Fprintln(&output, "builtin local _kitty_fmt _kitty_expl")
output.WriteString(`builtin zstyle -s ":completion:${curcontext}:descriptions" format _kitty_fmt || _kitty_fmt='%B%d%b'` + "\n")
}
for _, mg := range completions.Groups {
fmt.Fprintln(&output, "builtin zformat -f _kitty_expl \"$_kitty_fmt\"", utils.QuoteStringForSH("d:"+mg.Title))
cmd := strings.Builder{}
escape_ourselves := mg.IsFiles // zsh quoting quotes a leading ~/ in filenames which is wrong
cmd.WriteString("compadd -U ")
if escape_ourselves {
cmd.WriteString("-Q ")
}
cmd.WriteString("-J ")
cmd.WriteString(utils.QuoteStringForSH(mg.Title))
cmd.WriteString(` -X "$_kitty_expl"`)
if mg.NoTrailingSpace {
cmd.WriteString(" -S ''")
}
if mg.IsFiles {
cmd.WriteString(" -f")
}
lcp := mg.remove_common_prefix()
if lcp != "" {
cmd.WriteString(" -p ")
cmd.WriteString(utils.QuoteStringForSH(lcp))
}
if mg.has_descriptions() {
fmt.Fprintln(&output, "compdescriptions=(")
limit := mg.max_visual_word_length(16)
for _, m := range mg.Matches {
fmt.Fprintln(&output, utils.QuoteStringForSH(wcswidth.StripEscapeCodes(m.FormatForCompletionList(limit, f, screen_width))))
}
fmt.Fprintln(&output, ")")
cmd.WriteString(" -l -d compdescriptions")
}
cmd.WriteString(" --")
for _, m := range mg.Matches {
cmd.WriteString(" ")
w := m.Word
if escape_ourselves {
w = utils.EscapeSHMetaCharacters(m.Word)
}
cmd.WriteString(utils.QuoteStringForSH(w))
}
fmt.Fprintln(&output, cmd.String(), ";")
}
}
// debugf("%#v", output.String())
return []byte(output.String()), nil
}
func zsh_output_serializer(completions []*Completions, shell_state map[string]string) ([]byte, error) {
var f *markup.Context
screen_width := 80
ctty, err := tty.OpenControllingTerm()
if err == nil {
sz, err := ctty.GetSize()
ctty.Close()
if err == nil {
screen_width = int(sz.Col)
}
}
f = markup.New(false) // ZSH freaks out if there are escape codes in the description strings
return serialize(completions[0], f, screen_width)
}
func init() {
completion_scripts["zsh"] = zsh_completion_script
input_parsers["zsh"] = zsh_input_parser
output_serializers["zsh"] = zsh_output_serializer
}