Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

In cmdline mode, the following examples do not work for me.

!alias lol='echo lol'
!lol='echo lol'
share|improve this question
    
Possible cross site duplicate of: superuser.com/questions/47821/vim-ignores-aliases –  Ciro Santilli Apr 9 at 21:36

2 Answers 2

up vote 3 down vote accepted

When you use the :! command, a new shell is spawned from within Vim. In that shell, the alias is set, but immediately after that, the shell exits, and all is lost.

Best define the aliases in the shell that starts Vim. For environment variables, you can also set them from within Vim via :let $VAR = 'value', and you can use those in :! commands. And you can start a shell from within Vim with :shell, or suspend Vim and go back to the original shell with :stop or ^z.

share|improve this answer

vim starts one instance of a non-interactive bash (assuming bash is your login shell and you haven't modified $SHELL) for each ! command (in !cmd, vim runs bash -c cmd). So:

  1. An alias defined in one ! command, would not be available in the other shell started by the next ! command since it's a different process altogether.
  2. bash doesn't expand aliases and doesn't read ~/.bashrc when not interactive

To work around that, you could set $BASH_ENV to something that enables alias expansion and rewrites itself on exit of bash with the list of new aliases included. Something like (in ~/.vimrc):

let $BASH_ENV = $HOME . "/.bashvimrc." . getpid()
au VimLeave * silent !exec rm -f "$BASH_ENV"
silent !echo 'vim_setup() { shopt -s expand_aliases; trap write_aliases EXIT; eval "$@"; }; write_aliases() { typeset -f vim_setup write_aliases; alias; echo vim_setup \"\$@\";} > "$BASH_ENV"; vim_setup "$@"' > "$BASH_ENV"
set shell=/bin/bash
share|improve this answer
    
Thank you a lot for your detailed answer, but that's a bit too much ~/.vimrc trickery for my taste. I prefer the "use :let or drop out of vim and define them in the shell" solution from Ingo Karkat. –  bug Apr 10 '13 at 14:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.