Archive for April, 2011

VIM configuration file (vimrc)

Some nice defaults for VIM. The font setting is currently for windows, on other systems you may need to adjust it.

Simple VIM setup

Feel free to improve:

set nocompatible
syntax enable
filetype plugin indent on
setlocal spell spelllang=en
set autochdir " Automatically change directory to match
set backup " make backup files
"set clipboard+=unnamed " Synchronize unnamed register with windows clipboard
set wildmenu " Show multiple options when tab-completing a command
set wildmode=list:longest,full
set cursorline " Highlight current line
set shortmess=aOstT
set statusline=%F%m%r%h%w[%L][%{&ff}]%y[%p%%][%04l,%04v]

set autoindent
set smartindent

set number
set ruler " Show the current line/character
set scrolloff=5 " Show 5 lines of context
set sidescrolloff=10 " Show 10 characters of context when scrolling horizontally
set incsearch

set expandtab
set shiftwidth=2
set tabstop=2
"set softtabstop=2

set bs=2 " Allow backspace to delete characters
set showmatch " Highlight matching brackets

colorscheme desert
"colorscheme xaria265 "this is not available by default, you have to download it manually
if has("win32")
set guifont=Consolas:h14:cANSI
else
set guifont=Mono\ 12
endif

set guioptions-=T " Hide toolbar

set guioptions-=m " Hide menubar

set history=50

au BufWinLeave *.c,*.c++,*.cpp,*.h mkview
au BufWinEnter *.c,*.c++,*.cpp,*.h silent loadview

highlight RedundantSpaces ctermbg=darkgreen guibg=darkgreen
au Syntax * syn match RedundantSpaces /\s\+$\| \+\ze\t/

"Alternative method of showing whitespace (tabs and traling white space)
"set listchars=tab:ยป\ ,trail:~
"highlight SpecialKey guifg=#444444 ctermfg=darkgrey
"set list

"Alternative method of showing whitespace (tabs and traling white space) for very basic terminals
"set listchars=tab:>\ ,trail:~
"highlight SpecialKey ctermfg=darkgrey ctermbg=grey
"set list

set synmaxcol=200 "make sure that long lines do not slow down syntax highlighting

Extended VIM setup with package manager

The following .vimrc will automatically install the VIM Addon Manager plugin. When new plugins are added to the activated plugins, they will be automatically downloaded (if not installed yet) and activated on startup.

The configuration is split into two files. First the main .vimrc:

set nocompatible
syntax enable
filetype plugin indent on

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Package manager for plugins
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
source ~/.vimrcvam
call SetupVAM()
let addons=[]
call add(addons, 'xoria256')
call add(addons, 'bufexplorer.zip')
call add(addons, 'FuzzyFinder')
call add(addons, 'The_NERD_tree')
call add(addons, 'a') " alternate between cpp and h files
call vam#ActivateAddons(addons, {'auto_install' : 1})
messages

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Plugin setup
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Tlist
let Tlist_Close_On_Select=0

" Custom color scheme
colorscheme xoria256
 
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Custom key bindings
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
inoremap <c-j> <Esc>/<++><CR><Esc>cf>
nmap <F7> :BufExplorer<Enter>
nmap <F4> :<Enter>

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Vim settings
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
set autoindent
set smartindent
set shiftwidth=2
set expandtab

set incsearch

set cursorline " Highlight current line
set showmatch " Highlight matching brackets

setlocal spell spelllang=en

set autochdir " Automatically change directory to match
 
set wildmenu " Show multiple options when tab-completing a command
set wildmode=list:longest,full
set completeopt+=menu
set completeopt+=longest
set completeopt+=preview

set bs=2 " Allow backspace to delete characters

set history=200
 
set tags=./tags;/ " Walk directory tree up to / and use 'tags' files
 
set foldmethod=syntax
set nofoldenable " Do not fold by default, only when requested
 
set synmaxcol=500 "make sure that long lines do not slow down syntax highlighting
 
" Highlighting of special characters
set listchars=tab:»\ ,trail:¤
highlight SpecialKey guifg=#444444 ctermfg=darkgrey
set list
 
"Alternative method of showing whitespace (tabs and traling white space) for very basic terminals
"set listchars=tab:>\ ,trail:~
"highlight SpecialKey ctermfg=darkgrey ctermbg=grey
"set list
 
highlight RedundantSpaces ctermbg=darkgreen guibg=darkgreen
au Syntax * syn match RedundantSpaces /\s\+$\| \+\ze\t/
"au Filetype cpp highlight AllTabs ctermbg=darkgreen guibg=darkgreen
"au FileType cpp au Syntax * syn match AllTabs /\t/

" Window behavior and displayed information
set number
set ruler " Show the current line/character
set scrolloff=5 " Show 5 lines of context
set sidescrolloff=10 " Show 10 characters of context when scrolling horizontally
 
set shortmess=aOstT
set statusline=%F%m%r%h%w[%L][%{&ff}]%y[%p%%][%04l,%04v]
 
" GVIM
if has("win32")
    set guifont=Consolas:h14:cANSI
else
    set guifont=Monospace\ 11
endif
set guioptions-=T " Hide toolbar
set guioptions-=m " Hide menu

" Management of views (store state of opened files) 
"au BufWinLeave *.c,*.c++,*.cpp,*.h mkview
"au BufWinEnter *.c,*.c++,*.cpp,*.h silent loadview

" Backup
let backup_dir_path = expand('$HOME') . '/.vim/backup'
if !isdirectory(backup_dir_path)
  call mkdir(backup_dir_path, 'p')
endif
set backup " make backup files
set backupdir=~/.vim/backup
 
" Undo
let undo_dir_path = expand('$HOME') . '/.vim/undo'
if !isdirectory(undo_dir_path)
  call mkdir(undo_dir_path, 'p')
endif
set undofile
set undodir=~/.vim/undo
set undolevels=10000
set undoreload=10000

" Session management
set sessionoptions-=options

function! MakeSession()
  let b:filename = '~/vim_session'
  exe "mksession! " . b:filename
endfunction
 
function! LoadSession()
  let b:sessionfile = '~/vim_session'
  if (filereadable(b:sessionfile))
    exe 'source ' b:sessionfile
  else
    echo "No session loaded."
  endif
endfunction
au VimEnter * :call LoadSession()
au VimLeave * :call MakeSession()

The following file (.vimrcvam) contains functionality to set up the VIM addon manager.

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" VIM-Addon-Manager setup
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
fun! EnsureVamIsOnDisk(vam_install_path)
  " windows users may want to use http://mawercer.de/~marc/vam/index.php
  " to fetch VAM, VAM-known-repositories and the listed plugins
  " without having to install curl, 7-zip and git tools first
  " -> BUG [4] (git-less installation)
  let is_installed_c = "isdirectory(a:vam_install_path.'/vim-addon-manager/autoload')"
  if eval(is_installed_c)
    return 1
  else
    if 1 == confirm("Clone VAM into ".a:vam_install_path."?","&Y\n&N")
      " I'm sorry having to add this reminder. Eventually it'll pay off.
      call confirm("Remind yourself that most plugins ship with ".
            \"documentation (README*, doc/*.txt). It is your ".
            \"first source of knowledge. If you can't find ".
            \"the info you're looking for in reasonable ".
            \"time ask maintainers to improve documentation")
      call mkdir(a:vam_install_path, 'p')
      execute '!git clone --depth=1 git://github.com/MarcWeber/vim-addon-manager '.shellescape(a:vam_install_path, 1).'/vim-addon-manager'
      " VAM runs helptags automatically when you install or update
      " plugins
      exec 'helptags '.fnameescape(a:vam_install_path.'/vim-addon-manager/doc')
    endif
    return eval(is_installed_c)
  endif
endf
 
fun! SetupVAM()
  " Set advanced options like this:
  " let g:vim_addon_manager = {}
  " let g:vim_addon_manager['key'] = value
 
  " Example: drop git sources unless git is in PATH. Same plugins can
  " be installed from www.vim.org. Lookup MergeSources to get more control
  " let g:vim_addon_manager['drop_git_sources'] = !executable('git')
  " let g:vim_addon_manager.debug_activation = 1
 
  " VAM install location:
  let vam_install_path = expand('$HOME') . '/.vim/vim-addons'
  if !EnsureVamIsOnDisk(vam_install_path)
    echohl ErrorMsg
    echomsg "No VAM found!"
    echohl NONE
    return
  endif
  exec 'set runtimepath+='.vam_install_path.'/vim-addon-manager'
 
  " Addons are put into vam_install_path/plugin-name directory
  " unless those directories exist. Then they are activated.
  " Activating means adding addon dirs to rtp and do some additional
  " magic
 
 
  " How to find addon names?
  " - look up source from pool
  " - (<c-x><c-p> complete plugin names):
  " You can use name rewritings to point to sources:
  "    ..ActivateAddons(["github:foo", .. => github://foo/vim-addon-foo
  "    ..ActivateAddons(["github:user/repo", .. => github://user/repo
  " Also see section "2.2. names of addons and addon sources" in VAM's documentation
endfun
Thursday, April 21st, 2011 Uncategorized No Comments

VIM wordwise operations

Change in word (excluding whitespace) if cursor inside the word

ciw

Change all word (including whitespace) if cursor inside the word

caw

Changing a WORD (until next whitespace, this also works text objects such as file paths)

cW

The i (in) and a (all) operations also work for round brackets () , angular brackets<>, and square brackets []:


ci(
ci< ci[ [/bash]

Monday, April 18th, 2011 Uncategorized No Comments

Access excel sheet contents from Python

If you need to automatically process Excel spreadsheet data from python XLRD is a nice library.

If you have easy_install you can install it as follows:

easy_install xlrd

To access some data you can do the following:

import xlrd
book = xlrd.open_workbook('workbook.xls')
sheet = book.sheet_by_index(0) # First sheet
for row_index in range(sheet.nrows):
  for col_index in range(sheet.ncols):
    print sheet.cell(row_index,col_index).value
Friday, April 15th, 2011 Uncategorized No Comments

Accessing internal server from internal network via external IP (DNAT)

On the router add the following iptables rule:

iptables -t nat -I PREROUTING -d <EXTERNAL IP> -j DNAT --to-destination <INTERNAL SERVER IP>
Wednesday, April 13th, 2011 Uncategorized No Comments