Saturday, February 3, 2024

How to reference the previous string in Zsh command-line

In `zsh`, you can get the last string in a list of strings separated by spaces by using parameter expansion. Here's a simple command to achieve this:

```zsh
# Assuming a list of strings separated by spaces
list_of_strings="string1 string2 string3 string4"
# Use parameter expansion to get the last string
last_string=${(s: :)list_of_strings}[-1]

# Print the last string
echo $last_string
```

In this example, `(s: :)` is a parameter expansion flag that splits the variable `list_of_strings` on spaces, treating it as an array. `[-1]` then accesses the last element of this array.

To put this into a function that you can use in an interactive shell to get the last string before the cursor, you can use the following `zsh` function:

```zsh
# Define the function to get the last string before the cursor
get_last_string_before_cursor() {
  # Split LBUFFER into an array of words
  local words=(${(z)LBUFFER})
  # Get the last word
  local last_word=${words[-1]}
  # Print the last word
  echo $last_word
}

# Create a ZLE (Zsh Line Editor) widget that binds the function
zle -N get_last_string_before_cursor_widget get_last_string_before_cursor

# Bind the widget to a keyboard shortcut, for example, Ctrl + t
bindkey '^T' get_last_string_before_cursor_widget
```

Add this function to your `.zshrc` file. After reloading your shell, you can press `Ctrl + t` to print the last string before the cursor on the command line.