13

When using vim for “replying” to some program – typically git – it can be useful to deliberate exit with error, to abort the entire action that opened the window. Like

$ git commit -a
# vim opens, showing me the staged files and asking for a commit message
# oops, I see some stuff staged that wasn't supposed to be committed
:cq     # exit vim with nonzero exit code

This will prevent git from actually doing the commit.

Now unfortunately, some machines have nano configured as the default editor, so I occasionally find myself in that editor and correspondingly helpless.

What I've done for now was: log in with another ssh session and killall editor.

Is there a way to do the same thing from within nano itself, corresponding to vim's :cq?

leftaroundabout
  • 454
  • 1
  • 3
  • 15

2 Answers2

10

If already in nano

This is what I can do in interactive sh (or bash etc.) with job control:

I can suspend nano with Ctrl+Z (^Z). Note: if the message is Suspension is not enabled then I need to press Alt+Z (M-Z) to enable. As far as I know these are default keybindings in nano.

If the command was nano || foo then foo will be triggered immediately.

Now I'm back in the shell with nano as a job (see jobs). kill %% will send a signal to it, still nano won't exit yet. I need to fg after sending the signal, only then nano terminates.

Not as fast as vim's :cq but still without additional SSH session.


Avoiding the problem before it occurs

By default, Git uses whatever you’ve set as your default text editor via one of the shell environment variables VISUAL or EDITOR, or else falls back to the vi editor to create and edit your commit and tag messages. To change that default to something else, you can use the core.editor setting:

$ git config --global core.editor emacs

Now, no matter what is set as your default shell editor, Git will fire up Emacs to edit messages.

(source)

Many other programs respect VISUAL or EDITOR. If you can, configure them and/or the environment beforehand. It may be as simple as running:

export VISUAL=vim

in (the startup script of) your shell.

Kamil Maciorowski
  • 69,815
  • 22
  • 136
  • 202
2

In the case of git, exiting the editor with an empty message will cancel the commit (unless you use --allow-empty-message). Leaving the lines starting with # in is fine.

For git commands such as commit --amend or merge that already provide a message, you need to delete that message before saving and exiting.

(But yep, it would be nice if nano had an exit-with-error feature, particularly in the latter case.)

ak2
  • 3,675
  • 17
  • 17