Turn bash into vi style

so you are a big fan of vi/vim like me? And tired of using emacs style shell in your bash? Bash provides two modes for command line editing: emcas and vi. Emcas is the default style and you can turn it into vi mode with this one-liner:

  set -o vi

Now you are in business to use your shell in the vi way :)

How to enable history sharing between terminals in GNU screen

It annoys me for a long time that I can't save/load command history from other terminals when I am in screen, history within every single tab is erased when my session is killed, and even worse, I can't use other commands from other opened terminals. One of my colleague shares a tip with me which partially solve this issue.

You can either wrap the following in your ~/.bashrc or export every line.

  # Ignore space and do not allow duplicates
  HISTCONTROL=ignorespace:erasedups

  # Increase history size
  HISTSIZE=1000
  HISTFILESIZE=2000

  # This does the magic! It changes the default behavior from overwrite history 
  # to append into the file. Clear and reload the buffer every time it is finished.
  export PROMPT_COMMAND='history -a; history -c; history -r'

The reason I said it partially work is because I will have to clear the screen if I want to load history.

Save/load session in vim

I never realize I can save or/and load session inside vim. This is a super handy feature if you want to switch gear after a long and work on something else for a moment then come back. Bonus tip: If you are already using screen, you can simply detach and attach the current screen or open up a new tab.

To create a session

  :mksession mysession.vim

To restore a session,

  :source mysession.vim
  vim -S mysession.vim

By the way, you can always use :wall or :wa to save all changes in buffer before doing any thing crazy.

Adding line number by applying an external filter

There are occasions I want to add line numbers to my files inside vim (certainly you can turn on numbers by vim with set number, but that does not write to the file), below is a filter script to do the trick.

  %cat add_number.pl
  #! /usr/bin/perl
  my $i = 1;
  while (<>) {
    printf "%3d: %s", $i++, $_;
  } 

Enable in vim

set equalprg=add_number.pl

Select the block of code or the entire piece of Code (gg=G) then press = to apply the filter. You can come up with any filter per your desire to do all kinds of crazy things. Handy!

^ Top of Page