Never been to DZone Snippets before?
Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
toggle between last edited buffer : control-shift-6
// insert code here..
vim folding for RSpec editing
" fold text between context and specify function! ShowRSpecContext() let spec_idx = search('specify\s\+".\+"', 'Wbn', '^') let ctx_idx = search('context\s\+".\+"', 'Wbn', '^') if spec_idx && ctx_idx exec (ctx_idx+1).','.(spec_idx-1).'fold' endif endfunction " fold text between all contexts and specify lines function! ShowRSpecAnnotation() call cursor('$', 0) try foldo! catch endtry let cur_line = line('$') while cur_line > 0 let prev_spec = search('\(context\|specify\)\s\+".\+"', 'Wb', '^') if ! prev_spec break endif exec (prev_spec).','.cur_line.'fold' let cur_line=prev_spec-1 endwhile endfunction command! Sx :call ShowRSpecContext() command! Sa :call ShowRSpecAnnotation()
remove empty lines in VIM
:%s/^[\ \t]*\n//g
Syntax highlighting with vim & Ruby
This snippet will convert source code files to syntax-colored html files.
usage: vim-syntax-highlighting.rb src.rb src.html
require 'tempfile' $VERBOSE=nil STDERR.reopen(Tempfile::new($$)) unless STDIN.tty? fin, fout, _ = ARGV fin = ((fin.nil? or fin == '-') ? STDIN : open(fin)) fout = ((fout.nil? or fout == '-') ? STDOUT : open(fout,'w+')) ts = Tempfile::new($$), Tempfile::new($$) ts[0].write fin.read ts.each{|t| t.close} command = %Q( vim -f +'syn on' +'set filetype=ruby' +'set background=light' +'run! syntax/2html.vim' +'w! #{ ts[1].path }' +'qa!' - < #{ ts[0].path } > /dev/null 2>&1 ) #command = %Q( vim -f +'syn on' +'set filetype=c' +'set background=dark' +'run! syntax/2html.vim' +'w! #{ ts[1].path }' +'qa!' - < #{ ts[0].path } > /dev/null 2>&1 ) system command ts.each{|t| t.open; t.rewind} fout.write(ts[1].read) ts.each{|t| t.close!}
Rails and Vim
#!/usr/bin/env ruby if ARGV.empty? puts "usage: #{File.basename($0)} string" puts " Scans related Rails directories for " + "files begining with string " puts " and opens them in vi." exit end files = [] ignore = [/CVS$/] # Find models or controllers that match args ARGV.each do |arg| models = Dir["app/models/#{arg}*"] controllers = Dir["app/controllers/#{arg}*"] files += models + controllers end # Remove duplicates files.sort!.uniq! # Add unit tests for models files.grep(%r{app/models/(.*?).rb}) do tests = Dir["test/unit/#{$1}_test.rb"] files += tests end # Add views and functional tests for controllers files.grep(%r{app/controllers/(.*?)_controller.rb}) do views = Dir["app/views/#{$1}/*"] tests = Dir["test/functional/#{$1}_controller_test.rb"] files += views + tests end # Add views and fixtures for mailers files.grep(%r{app/models/(.*?_mailer).rb}) do views = Dir["app/views/#{$1}/*"] fixtures = Dir["test/fixtures/#{$1}/*"] files += views + fixtures end # Again remove duplicates files.sort!.uniq! # Remove files that match ignore list files.delete_if do |filename| result = false ignore.each do |i| if filename =~ i result = true break end end result end system "vi -o #{files.join(' ')}"
Drop it in a file called "edit" in your path and you can open related rails files with a few key strokes:
# open AccountController and related tests and views: edit account_c # open AccountMailer and related tests, views, and fixtures: edit account_m # open everything related to accounts: edit account
A detailed explanation here: http://wiseheartdesign.com/articles/2006/07/27/rails-and-vim/.
HTTP Client for vim
" require vimproc( http://tokyo.cool.ne.jp/hopper2/ )" let g:HTTP = {} function g:HTTP.new(host, ...) let self.host = a:host if a:0 >= 1 let self.port = a:1 else let self.port = 80 endif let self.headers = {'Host': self.host} let self.query = {} return deepcopy(self) endfunction function g:HTTP.get(path) return self.access(a:path, 'GET') endfunction function g:HTTP.head(path) return self.access(a:path, 'HEAD') endfunction function g:HTTP.access(path, method) call g:vimproc.load() let sock = g:vimproc.socket_open(self.host, self.port) call sock.write(self.make_header(a:path, a:method)) let re = "" while !sock.eof let re .= sock.read() endwhile call g:vimproc.unload() return g:HTTP.Response.new(re) endfunction function g:HTTP.make_header(path, method) let hds = [] call add(hds, a:method . " " . a:path . " HTTP/1.0") for key in keys(self.headers) call add(hds, key . ": " . self.headers[key]) endfor return join(hds, "\r\n") . "\r\n\r\n" endfunction let g:HTTP.Response = {} function g:HTTP.Response.new(str) call self.parse(a:str) return deepcopy(self) endfunction function g:HTTP.Response.parse(str) let lists = split(a:str, "\r\n\r\n") let header_lists = split(lists[0], "\r\n") let first = remove(header_lists, 0) let self.code = matchstr(first, '[1-5]\d\d') let self.headers = {} for header in header_lists let h = split(header, ': ') let self.headers[h[0]] = join(h[1:], ': ') endfor let self.body = join(lists[1:], "\r\n\r\n") endfunction
let h = HTTP.new('www.bigbold.com') let res = h.get('/snippets/') echo res.headers if res.code < 400 echo res.body else echo 'error ' . res.code endif
Basic ant script with vim & jikes
ant is a modern alternative to make. The build script is an XML file. It works particularly well with java. Download it for free from the Apache ant site. Most people find ant a lot nicer to live with than make.
<?xml version="1.0"?> <project name="Hello" default="compile" basedir="."> <property name="name" value="Hello"/> <property name="version" value="1.0"/> <!-- Project directories. --> <property name="build" value="build"/> <property name="dist" value="dist"/> <property name="src" value="src"/> <!-- Compiler directives. --> <property name="optimize" value="off"/> <property name="deprecation" value="on"/> <property name="debug" value="on"/> <property name="build.compiler" value="jikes"/> <property name="build.compiler.emacs" value="true"/> <target name="init"> <tstamp/> <mkdir dir="${build}"/> </target> <!-- Compile all the .java files from the source directory into the build directory. --> <target name="compile" depends="init"> <javac srcdir="${src}" destdir="${build}" includes="**/*.java" debug="${debug}" deprecation="${deprecation}" optimize="${optimize}"> </javac> </target> <target name="clean" depends="init"> <delete dir="${build}"/> <delete dir="${dist}"/> </target> <target name="test" depends="compile"> <java classname="HelloWorld" fork="yes"> <classpath> <pathelement location="${build}"/> </classpath> </java> </target> </project>
vim configuration - graphics mode
set guifont=Monospace\ 11 " Overrides settings in vim's configuration. I prefer minimal colour. hi Normal guifg=Black guibg=White hi NonText guifg=Black guibg=White hi Comment gui=none guifg=DarkGray hi Constant gui=none guifg=Magenta hi Identifier gui=none guifg=DarkGreen hi Statement gui=none guifg=Blue hi PreProc gui=none guifg=Blue hi Type gui=none guifg=Blue hi Special gui=none guifg=DarkGreen hi Ignore gui=none guifg=DarkGreen hi Error gui=none guifg=DarkGreen hi Todo gui=none guifg=DarkGreen hi Cursor gui=none guifg=White guibg=Black autocmd GUIEnter * winpos 66 28 autocmd GUIEnter * winsize 80 45 " What is this menu for? No documentation, something to do with 'C' " or C++ perhaps? Dunno, but I don't want it. aunmenu Bicycle\ Repair\ Man " If I have Python, create a dummy project menu and exececute the " vimproject script. if has ("python") if filereadable ("/home/mrw/bin/vimproject.py") amenu Project.Dummy dummy pyfile /home/mrw/bin/vimproject.py endif endif
vim configuration
:autocmd! set nohlsearch " Press F2 to word-wrap a block of text. It's almost like using Word " Star all over again. map #2 !}fmt -65 " Personally, I wouldn't use a C++ keyword as a Java identifier, but " if someone else does, I don't want an ugly display, so turn off " flagging of this as an error: let java_allow_cpp_keywords=1 set autoindent set cmdheight=2 " Strewth, what a mess. Copied from the vim docs, if memory serves. set comments=s:/*,mb:**,ex:*/,://,b:#,b:##,:%,:XCOMM,n:>,fb:- set formatoptions=orc set history=20 set incsearch set ignorecase set keywordprg= set mouse=a set mousehide set mousemodel=popup_setpos set nowrapscan set path=.,/usr/include,/usr/local/include set smartcase set nosmartindent set smarttab set showmode set textwidth=70 set viminfo='50,\"10000,n~/.viminfo set wildchar=9 set wildignore+=*.class,*.pyc set wildmenu syntax on :autocmd FileType * set shiftwidth=4 :autocmd FileType xml,html set shiftwidth=2 :autocmd FileType java,c,cc,cpp set nocindent set makeprg=ant " Bleurgh! This makes sense of ant/jikes error messages so the ":make" " command works. But, I ask you, how the f**k can anyone make sense of " that mess? set efm=\ %#[javac]\ %#%f:%l:%c:%*\\d:%*\\d:\ %t%[%^:]%#:%m,\%A\ %#[javac]\ %f:%l:\ %m,%-Z\ %#[javac]\ %p^,%-C%.%# " For the style of comments I like in 'C', C++ and Java. autocmd BufNewFile,BufRead *.java set comments=s:/*,mb:**,ex:*/ autocmd BufNewFile,BufRead *.c set comments=s:/*,mb:**,ex:*/ autocmd BufNewFile,BufRead *.cc set comments=s:/*,mb:**,ex:*/