This is the situation that I'm finding in regularly: I'm crafting a long command in a shell (here fish but could be bash or anything) with a bunch of flags and arguments, so I go back and forth in the command. At the end, my cursor is located just after a flag in the middle of the command. I think I'm done, so I hit enter to execute the command. But the command failed to execute because I made some mistake. So I hit the Up arrow to have the previous command back in the prompt to fix it.
But the shell doesn't restore my cursor position, it brings my cursor at the end. Which is not practical because the argument that I need to fix is located in the middle of the command, in fact at the exact location were my cursor was just before I hit enter.
I'm looking for a way for my shell to restore my cursor position on demand, for example when I hit some key combination. That would save me the time of navigating my cursor back into the right position.
I'm currently using the fish shell but I'm open to use any other shell (bash, zsh) that has this feature.
How to quickly restore the cursor at the previous position were it was before the command execution in a shell?
Thanks for any advice.
One way you can achieve this in fish-shell would be to add a pair of functions. One saves the cursor position and executes the command, the second restores the cursor position:
function save_cursor_and_exec
set -g SAVED_CURSOR (commandline --cursor)
commandline -f execute
end
function restore_cursor
commandline --cursor $SAVED_CURSOR
end
Now we bind \r
(enter) to the first function, and control-R to the second:
bind \r save_cursor_and_exec
bind \cR restore_cursor
Now after hitting up arrow, control-R will restore the cursor to the saved position.