39

When doing sudo visudo, the default editor is nano.
I want to change it to vi or vim.

I already made vim the default editor, and use it as a substitute for gedit to open php, .txt, .c and .h files, by placing a vim.desktop file in ~/.local/share/applications/ and by correctly editing either ~/.local/share/applications/mimeapps.list or /etc/gnome/defaults.list. However apparently this does not apply to nano.

Any clue ?

Cbhihe
  • 2,801
  • 3
  • 27
  • 47

4 Answers4

27

The problem is not that it does not apply to nano, it's that it does not apply to the shell:

Just set the VISUAL environment variable:

export VISUAL=vim

Add this too ~/.bashrc to make it permanent.

As you seem to use vim in general, set both VISUAL and EDITOR:

export VISUAL="vim"
export EDITOR="$VISUAL"

or more POSIX-correct

VISUAL="vim" ; export VISUAL
EDITOR="$VISUAL" ; export EDITOR

I assume nano was the value of one or both variables.

To make use of the editor in visudo actually, we need to handle that sudo does not keep the environment variables by normally. The option -E changes that.

sudo -E visudo

Without the -E here, you would end up with a default of nano again


The two variables where in use long before files named *.desktop or mime* even existed.
(And the impressive thing is: they were actually used as a common standard.)

See section ENVIRONMENT in man visudo:

  VISUAL           Invoked by visudo as the editor to use

EDITOR Used by visudo if VISUAL is not set

Permanent fix using update-alternatives

In Ubuntu, the system default seems to be set with sudo update-alternatives --config editor. It shows a menu to change the current association to a vi of your choice.

Volker Siegel
  • 13,295
18

If you never plan to use nano, you can also simply remove it. Then the system will use vi/vim as the default.

sudo apt-get purge nano

I know it is not the official answer, but it is one of the first commands for me after installing Ubuntu.

9

As described in this answer, add

Defaults editor=/path/to/editor

to the sudoers file.

Note: this will only work if the file being edited contains the Defaults editor=/path/to/editor line or includes a file that contains it.

For example: visudo -f /etc/sudoers.d/my_sudoers_extension will default to Nano.

Muhamed Huseinbašić
  • 1,248
  • 3
  • 14
  • 19
2

The problem with using:

export VISUAL="vim"
export EDITOR="$VISUAL"

Is that sudo visudo will sanitize the users environment variables so those variables are set in the root environment. If you are the only user of the machine (or everyone prefers VIM) you could always set those into root's environment too.

Zanna
  • 72,312