Shell – Forcing emacs to run with `-nw` when called from terminal

emacsshell

note: This question might have been asked before ( I think I saw it somewhere), but a quick search did not reveal anything.

I would like to tell the difference when a command is run from a shell.

Emacs can be initialized with the -nw flag to disable the gui window, and I want this to be the default behaviour. However if emacs is run from a non-shell environment, ( e.g. from the Open With in your filemanager, a desktop configured hotkey, or even from bashrun ), it should not be called with the -nw flag.

update: This should be a global change, running sudo emacs in Terminal should'nt suddenly open a gui. Where do I make these changes?

Best Answer

I think you want to determine if a command is run in a terminal.

if [ -t 2 ]; then
  # Standard error is a terminal
  emacs -nw "$@"
elif [ -n "$DISPLAY" ]; then
  # An X display is available
  xterm -e emacs -nw "$@"
else
  # We have nothing
  emacs --daemon "$@"
fi

If you want this to always happen when you run Emacs, put it in a script and invoke that script instead. You can call the script /usr/local/bin/emacs (assuming Linux) if you want it to be called emacs and invoked in preference to the “real” emacs executable in /usr/bin.

Note that to edit files as root, you should use sudoedit (benefits: the editor runs as you so you get all your settings; the edited file is put into place atomically when you finish editing, reducing the chance of a mishap). You can also edit files as root directly inside Emacs by opening /sudo::/path/to/file.

Related Question