The Coded One

programming, algorithms, discrete math, open-source

vimrc

with 2 comments


" Settings and scripts for VIM

" ***********
" * General *
" ***********

set nocompatible                "turn off backwards compatibility
set backspace=indent,eol,start

" *************
" * Resources *
" *************
" How many lines of history to remember.
set history=1000

" Use all the memory needed, for maximum performance.
set maxmemtot=2000000
set maxmem=2000000
set maxmempattern=2000000

" *****************
" * Abbreviations *
" *****************
iab vdate =getDate()
iab vyear =getYear()

" ******************
" * User Interface *
" ******************

" have syntax highlighting in terminals which can display colours:
if has('syntax') && (&t_Co > 2)
  syntax on
endif

" have command-line completion  (for filenames, help topics, option names)
" first list the available options and complete the longest common part, then
" have further s cycle through the possibilities:
set wildmode=list:longest,full

set showmode                                        " displays mode in status bar
set showcmd                                         " displays partially typed command in the status bar
set mouse=a                                         " have the mouse enabled all the time:
set ruler                                           " display the current row, col in the status bar
set rulerformat=%25([%l,%v]\ %p%%%)    " displays a better format

" Show tabs and trailing spaces so I can remove them
set list
set listchars=tab:»·,trail:·

" *****************
" * Auto-complete *
" *****************

" autocomplete funcs and identifiers for languages
autocmd FileType php set omnifunc=phpcomplete#CompletePHP
autocmd FileType python set omnifunc=pythoncomplete#Complete
autocmd FileType javascript set omnifunc=javascriptcomplete#CompleteJS
autocmd FileType html set omnifunc=htmlcomplete#CompleteTags
autocmd FileType css set omnifunc=csscomplete#CompleteCSS
autocmd FileType xml set omnifunc=xmlcomplete#CompleteTags
autocmd FileType php set omnifunc=phpcomplete#CompletePHP
autocmd FileType c set omnifunc=ccomplete#Complete

" ******************************
" * Text Formatting -- General *
" ******************************

" don't make it look like there are line breaks where there aren't:
set nowrap
set shiftround
set expandtab
set autoindent

" use spaces instead of tabs
set softtabstop=4
set tabstop=4
set shiftwidth=4

" normally don't automatically format `text' as it is typed, IE only do this
" with comments, at 79 characters:
set formatoptions-=t
set textwidth=79

" enable filetype detection:
filetype on

" in human-language files, automatically format everything at 72 chars:
autocmd FileType mail,human set formatoptions+=t textwidth=72
"
" for C-like programming, have automatic indentation:
autocmd FileType c,cpp,slang set cindent

" for actual C (not C++) programming where comments have explicit end
" characters, if starting a new line in the middle of a comment automatically
" insert the comment leader characters:
autocmd FileType c set formatoptions+=ro

" for Perl programming, have things in braces indenting themselves:
autocmd FileType perl set smartindent

" for CSS, also have things in braces indented:
autocmd FileType css set smartindent

" for HTML, generally format text, but if a long line has been created
" leave it alone when editing:
autocmd FileType html set formatoptions+=tl

" for both CSS and HTML, use genuine tab characters for indentation, to
" make files a few bytes smaller:
autocmd FileType html,css set noexpandtab tabstop=2

" in makefiles, don't expand tabs to spaces, since actual tab characters
" are needed, and have indentation at 8 chars to be sure that all indents
" are tabs (despite the mappings later):
autocmd FileType make set noexpandtab shiftwidth=8

" ****************
" * PHP Specific *
" ****************
" highlights interpolated variables in sql strings and does sql-syntax highlighting. yay
autocmd FileType php let php_sql_query=1

" does exactly that. highlights html inside of php strings
autocmd FileType php let php_htmlInStrings=1

" discourages use oh short tags. c'mon its deprecated remember
autocmd FileType php let php_noShortTags=1

" automagically folds functions & methods. this is getting IDE-like isn't it?
autocmd FileType php let php_folding=1

" set "make" command when editing php files
set makeprg=php\ -l\ %
set errorformat=%m\ in\ %f\ on\ line\ %l

" ********************
" * Search & Replace *
" ********************

" make searches case-insensitive, unless they contain upper-case letters:
set ignorecase
set smartcase

" show the `best match so far' as search strings are typed:
set incsearch

" assume the /g flag on :s substitutions to replace all matches in a line:
set gdefault

" ******************************
" * Navigation / Moving Around *
" ******************************

" use  to cycle through split windows (and + to cycle backwards,
" where possible):
nnoremap  w
nnoremap  W

" have % bounce between angled brackets, as well as t'other kinds:
set matchpairs+=<:>

" have Q reformat the current paragraph (or selected text if there is any):
nnoremap Q gqap
vnoremap Q gq

" have the usual indentation keystrokes still work in visual mode:
vnoremap  >
vnoremap  
vmap  
vmap  

" *************************
" * Keystrokes -- Toggles *
"**************************

" Keystrokes to toggle options are defined here.  They are all set to normal
" mode keystrokes beginning \t but some function keys (which won't work in all
" terminals) are also mapped.

" have \tp ("toggle paste") toggle paste on/off and report the change, and
" where possible also have  do this both in normal and insert mode:
nnoremap \tp :set invpaste paste?
nmap  \tp
imap  \tp
set pastetoggle=

" ********************************
" * Keystrokes -- For HTML Files *
" ********************************

nnoremap \hc :call InsertCloseTag()
imap  \hca

nnoremap \hp :call RepeatTag(0)
imap  \hpa

nnoremap \hn :call RepeatTag(1)
imap  \hna

" there are other key mappings that it's useful to have for typing HTML
" character codes, but that are definitely not wanted in other files (unlike
" the above, which won't do any harm), so only map these when entering an HTML
" file and unmap them on leaving it:
autocmd BufEnter * if &filetype == "html"| call MapHTMLKeys() | endif

" **************************
" * User defined functions *
" **************************

" Returns the current date
function s:getDate ()
    return strftime( "%m-%d-%Y" )
endfunction

"Returns the current year
function s:getYear()
    return strftime( "%Y" )
endfunction

" sets up various insert mode key mappings suitable for typing HTML, and
" automatically removes them when switching to a non-HTML buffer
function! MapHTMLKeys(...)

  " if no parameter, or a non-zero parameter, set up the mappings:
  if a:0 == 0 || a:1 != 0

    " require two backslashes to get one:
    inoremap \\ \

    " then use backslash followed by various symbols insert HTML characters:
    inoremap \& &
    inoremap \< <
    inoremap \> >
    inoremap \. ·

    " em dash -- have \- always insert an em dash, and also have _ do it if
    " ever typed as a word on its own, but not in the middle of other words:
    inoremap \- —
    iabbrev _ —

    " hard space with +Space, and \ for when that doesn't work:
    inoremap \  
    imap  \

    " have the normal open and close single quote keys producing the character
    " codes that will produce nice curved quotes (and apostophes) on both Unix
    " and Windows:
    inoremap ` ‘
    inoremap ' ’
    " then provide the original functionality with preceding backslashes:
    inoremap \` `
    inoremap \' '

    " curved double open and closed quotes (2 and " are the same key for me):
    inoremap \2 “
    inoremap \" ”

    " when switching to a non-HTML buffer, automatically undo these mappings:
    autocmd! BufLeave * call MapHTMLKeys(0)

  " parameter of zero, so want to unmap everything:
  else
    iunmap \\
    iunmap \&
    iunmap \<
    iunmap \>
    iunmap \-
    iunabbrev _
    iunmap \
    iunmap 
    iunmap `
    iunmap '
    iunmap \`
    iunmap \'
    iunmap \2
    iunmap \"

    " once done, get rid of the autocmd that called this:
    autocmd! BufLeave *

  endif " test for mapping/unmapping

endfunction " MapHTMLKeys()

" inserts the appropriate closing HTML tag; used for the \hc operation defined
" above;
" requires ignorecase to be set, or to type HTML tags in exactly the same case
" that I do;
" doesn't treat

 as something that needs closing;
" clobbers register z and mark z
"
" by Smylers  http://www.stripey.com/vim/
" 2000 May 4
function! InsertCloseTag()

  if &filetype == 'html' || &filetype == 'php'

    " list of tags which shouldn't be closed:
    let UnaryTags = ' Area Base Br DD DT HR Img Input LI Link Meta P Param '

    " remember current position:
    normal mz

    " loop backwards looking for tags:
    let Found = 0
    while Found == 0
      " find the previous <, then go forwards one character and grab the first
      " character plus the entire word:
      execute "normal ?\\l"
      normal "zyl
      let Tag = expand('')

      " if this is a closing tag, skip back to its matching opening tag:
      if @z == '/'
        execute "normal ?\" . Tag . "\"

      " if this is a unary tag, then position the cursor for the next
      " iteration:
      elseif match(UnaryTags, ' ' . Tag . ' ') > 0
        normal h

      " otherwise this is the tag that needs closing:
      else
        let Found = 1

      endif
    endwhile " not yet found match

    " create the closing tag and insert it:
    let @z = ''
    normal `z
    if col('.') == 1
      normal "zP
    else
      normal "zp
    endif

  else " filetype is not HTML
    echohl ErrorMsg
    echo 'The InsertCloseTag() function is only intended to be used in HTML ' .
      \ 'files.'
    sleep
    echohl None

  endif " check on filetype

endfunction " InsertCloseTag()

" repeats a (non-closing) HTML tag from elsewhere in the document; call
" repeatedly until the correct tag is inserted (like with insert mode +P
" and +N completion), with Forward determining whether to copy forwards
" or backwards through the file; used for the \hp and \hn operations defined
" above;
" requires preservation of marks i and j;
" clobbers register z
"
" by Smylers  http://www.stripey.com/vim/
"
" 2000 May 4: for `Vim' 5.6
function! RepeatTag(Forward)

  if &filetype == 'html' || &filetype == 'php'

    " if the cursor is where this function left it, then continue from there:
    if line('.') == line("'i") && col('.') == col("'i")
      " delete the tag inserted last time:
      if col('.') == strlen(getline('.'))
        normal dF<[^/>].\\{-}>\mj\"zyf>`i"
    if col('.') == 1
      normal "zP
    else
      normal "zp
    endif
    normal mi

  else " filetype is not HTML
    echohl ErrorMsg
    echo 'The RepeatTag() function is only intended to be used in HTML files.'
    sleep
    echohl None

  endif

endfunction " RepeatTag()

" Functions for cleaning up tabs and spaces
function! RemoveTrailingSpaces()
    %s/\s\+$//
endfunction

function! ConvertTabsToSpaces()
    %retab
endfunction

function! CleanFile()
    call ConvertTabsToSpaces()
    call RemoveTrailingSpaces()
endfunction

" Key binding Ctrl+Shift+f to clean up file
nmap  :call CleanFile()

" Function for toggling search highlighting
function! ToggleHLSearch()
    if &hls
        set nohls
    else
        set hls
    endif
endfunction

" Key binding Ctrl+Shift+h to toggle search highlighting
nmap  :call ToggleHLSearch()

Written by Mark Basmayor

March 12, 2009 at 9:34 am

2 Responses

Subscribe to comments with RSS.

  1. […] But eventually I got comfortable and started having fun with it.  And now with VIM 7 I can do everything that I’ve been missing.  It’s got a legitimate syntax highlighting, code completion, auto formatting, etc.  And you can continue to buff it with plugins and a decent vimrc.  Here’s the one that I compiled based on some of the best vimrcs that I saw. (download) […]

  2. I’ve just started using vi a month ago (thx to mutt), and now that I see how powerful it really is, this post is so much of help now. Thank you for sharing.

    karma

    April 29, 2010 at 9:03 am


Leave a comment