(nb: this is not a complete answer; see comments and https://stackoverflow.com/a/70285039/9307265)
Recent commands are available in the history
associative array, so this should be similar to the function in your question:
function invim {
vim ${history[@][1]}
}
The history[@]
expansion gets the commands from the associative array, while [1]
references the first item, which is guaranteed to be the most recent.
But that may not do exactly what you're looking for. Unlike bash
, zsh
doesn't re-parse variable expansions as words, so executing the function right after calling foo --opt
will result in an attempt to edit a file named foo --opt
, which probably doesn't exist. We can get just the first word by using word expansion with ${=...}
, converting it an array with the (A)
parameter expansion flag, and adding another [1]
index operator.
Also, in many cases this function would only find a file in that's in the current directory. With the :c
modifier, the function can search the PATH
and find the source file.
Putting it all together:
function invim {
vim ${${(A)=history[@][1]}[1]:c}
}