Working with str-list options

Is it possible to work with a str-list option like a stack or array?

Is this option type effectively just a string that you can concat to with set -add?

If I add several string values that each may contain spaces to a str-list, then is it possible to retrieve, say, the first item?

This post seems like a good reference for implementing pushing/popping to a str-list, but also seems to confirm my suspicion that you’d have to manually manage the format of each item added to the list.

Based on the previously referenced example, this is a minimal demonstration for working with with str-list options via shell expansion:

define-command example_str_list_consumer %{
    declare-option str-list mystrlst
    set-option global mystrlst

    set-option -add global mystrlst "list item 1"
    set-option -add global mystrlst "list item 2"

    evaluate-commands %sh{
        eval "set -- $kak_quoted_opt_mystrlst"
        printf "echo -debug ''\n"
        printf "echo -debug 'arg count: %s'\n" "$#"
        printf "echo -debug 'all args: %s'\n" "$*"
        printf "echo -debug 'arg 1: %s'\n" "$1"
        printf "echo -debug 'arg 2: %s'\n" "$2"
        printf "buffer *debug*\n"
    }
}

This will open the debug buffer with the following entries:


arg count: 2
all args: list item 1 list item 2
arg 1: list item 1
arg 2: list item 2

When referenced in this way, each item in the str-list option is preserved, spaces and all!

1 Like

As you’ve discovered, a str-list is more like a set or even a bag than a stack or an array. It keeps each item separately (there’s no need for a delimiter character or worrying about escaping) but you can’t easily iterate over the items from within Kakoune, or grab an item by index.

Beyond just adding and removing items, you can also access items by index if you write a custom command:

define-command -params 5.. access-by-index %{
    info "Item 3 is %arg{3} and item 5 is %arg{5}"
}
access-by-index %opt{mystrlst}

You can also filter the list for items matching a regex, by copying the option into a register, pasting the register into a scratch buffer, using <a-k> to filter the selections, then yanking the results back into a register and copying it back to the option.

If you bring the option into a shell block with $kak_quoted_opt_mystrlst then you get a lot more flexibility, of course.

1 Like

Those are all great tips. I never considered the possibility that a list option could represent an arg list for a plain kak command. Thanks!

1 Like