0

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.

lefuturiste
  • 87
  • 1
  • 7
  • I"m pretty sure ansi terminal escape chars can do this, but don't have time to provide you a link. If you're going anywhere beyond that simple case, then look at the `curses` tools. Good luck. – shellter Mar 07 '23 at 19:46
  • 2
    Boo, hiss re: tagging a single question for multiple shells. If you get a correct answer for fish and a separate, correct answer for zsh, how will you decide which one to accept? If you _need_ distinct answers for two different shells, ask two different questions. (Since you already have a fish-specific answer, I'd encourage you to remove the other shells from the question, and ask new questions for them if you need answers for those shells). – Charles Duffy Mar 07 '23 at 21:56
  • @CharlesDuffy Ok I keep the fish then, thanks you – lefuturiste Mar 09 '23 at 11:12

1 Answers1

3

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.

ridiculous_fish
  • 17,273
  • 1
  • 54
  • 61
  • Thanks, I adapted your solution because I use vi keys binding so I binded in both normal and insert mode to make my life easier. – lefuturiste Mar 09 '23 at 11:31