jayhendren
jayhendren

Reputation: 4518

Vim: change prompt on shell escape

I often use :sh while editing a file in vim so that I can perform small tasks like git commits before getting back to editing the file. However, sometimes I get confused whether my shell was started by my terminal emulator or it was started as a vim subshell, so typing exit at the prompt always runs the risk of closing the terminal emulator by accident rather than going back to my vim editing session. Is there a way to have vim modify my prompt, perhaps by the $PS1 environment variable, when I start a shell from vim so that I know whether I'm in a subshell started by vim or not?

Upvotes: 6

Views: 2262

Answers (4)

A S
A S

Reputation: 1235

Speaking of GVim/MacVim, :h guioptions now support the following flag:

  '!'   External commands are executed in a terminal window.  Without
        this flag the MS-Windows GUI will open a console window to
        execute the command.  The Unix GUI will simulate a dumb
        terminal to list the command output.
        The terminal window will be positioned at the bottom, and grow
        upwards as needed.

Set :set go+=!, run :sh in GVim/MacVim, and be surprised :).

Upvotes: 0

vesperto
vesperto

Reputation: 883

I use these two functions, one for git (always on), one for vim (visible when in a shell spawned by :sh):

parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
is_vim_sh() {
    if [ "x$VIM" != "x" ]; then
        echo " [vim]"
    fi
}
export PS1="\u@\h\[\033[32m\]\w\[\033[33m\]\$(parse_git_branch)\[\033[00m\]\$(is_vim_sh)$ "

Upvotes: 0

CS Pei
CS Pei

Reputation: 11047

You need to create a rc file to set a different $PS1 and source it inside vim like this

set shell=/bin/bash\ --rcfile\ ~/.bashforvimrc

check here http://nothingtobedoneforall.wordpress.com/2007/02/25/setting-shell-prompt-for-vim/

Update from Neatu Qvidiu Gabriel's comments,

it's preferably to execute source ~/.bashrc before assigning to PS1. Because otherwise you lose all your predefined configuration in bashrc

Upvotes: 5

romainl
romainl

Reputation: 196886

When you do :sh, a few additional Vim-specific shell variables are available to you. On this machine, I have:

$MYVIMRC
$VIM
$VIMRUNTIME

You can use $VIM, for example, in your *rc file like this:

if [ $VIM ]
then
  # set your vim-specific PS1 here
else
  # set your normal PS1 here
fi

Bonus: in GVim/MacVim the pseudo terminal you get when you do :sh is incapable of displaying colors. because Vim exports it as dumb, you can use the same logic as above to have a monochrome prompt when in GVim/MacVim and a color prompt in your shell:

if [ $TERM == 'dumb' ]
then
  # no colors
else
  # colors
fi

Upvotes: 9

Related Questions