1
0
mirror of https://github.com/gryf/.vim.git synced 2025-12-17 11:30:29 +01:00

Added omnicompletion and indentation for javascript (including node.js).

Added Windows configuration.
This commit is contained in:
2013-01-27 20:59:07 +01:00
parent bc4032accb
commit d458cd3906
19 changed files with 2146 additions and 4 deletions

5
.vimrc
View File

@@ -425,9 +425,8 @@ if $TERM == 'linux' && !has('gui_running')
" fallback to basic 8-color colorscheme " fallback to basic 8-color colorscheme
colorscheme pablo colorscheme pablo
endif endif
if has('win32')
if has('win32') && $_PMX == '1' source $VIM/vimfiles/winrc.vim
source $VIM/vimfiles/pmxrc.vim
endif endif
"}}} "}}}
" vim:ts=4:sw=4:wrap:fdm=marker: " vim:ts=4:sw=4:wrap:fdm=marker:

View File

@@ -121,7 +121,8 @@ function! SyntaxCheckers_java_GetLocList()
" add classpathes to javac_classpath " add classpathes to javac_classpath
for path in split(g:syntastic_java_javac_classpath,"\n") for path in split(g:syntastic_java_javac_classpath,"\n")
if path != '' if path != ''
let ps = glob(path,0,1) "let ps = glob(path,0,1)
let ps = glob(path)
if type(ps) == type([]) if type(ps) == type([])
for p in ps for p in ps
if p != '' | let javac_classpath = s:AddToClasspath(javac_classpath,p) | endif if p != '' | let javac_classpath = s:AddToClasspath(javac_classpath,p) | endif

View File

@@ -0,0 +1,52 @@
# vim-javascript
JavaScript bundle for vim, this bundle provides syntax and indent plugins.
> Indentation of javascript in vim is terrible, and this is the very end of it.
## Feature
1. very correct indentation for javascript
2. support javascript indentation in html (provided by [lepture](https://github.com/lepture))
## Installation
- Install with [Vundle](https://github.com/gmarik/vundle)
If you are not using vundle, you really should have a try.
Edit your vimrc:
Bundle "pangloss/vim-javascript"
And install it:
:so ~/.vimrc
:BundleInstall
- Install with [pathogen](https://github.com/tpope/vim-pathogen)
If you prefer tpope's pathogen, that's ok. Just clone it:
cd ~/.vim/bundle
git clone https://github.com/pangloss/vim-javascript.git
## Configuration
[html indentation](http://www.vim.org/scripts/script.php?script_id=2075)
provided by Andy Wokula is faster. But you need to make some configuration.
Suggested configuration:
```vim
let g:html_indent_inctags = "html,body,head,tbody"
let g:html_indent_script1 = "inc"
let g:html_indent_style1 = "inc"
```
Head over to [vim.org](http://www.vim.org/scripts/script.php?script_id=2075)
for more information.
## Bug report
Report a bug on [GitHub Issues](https://github.com/pangloss/vim-javascript/issues).

View File

@@ -0,0 +1,89 @@
require 'rake'
require 'rake/clean'
files = ['syntax/javascript.vim', 'indent/javascript.vim']
CLEAN.include 'tmp/*_ctags'
desc "Make zip file"
file 'javascript.zip' => files do |t|
File.unlink t.name if File.exists?(t.name)
system('zip','-q',t.name,*t.prerequisites)
end
desc "Make vimball"
file 'javascript.vba' => files do |t|
File.unlink t.name if File.exists?(t.name)
File.open(t.name,"w") do |out|
out.puts '" Vimball Archiver by Charles E. Campbell, Jr., Ph.D.'
out.puts 'UseVimball'
out.puts 'finish'
t.prerequisites.each do |name|
File.open(name) do |file|
file.each_line {}
out.puts name
out.puts file.lineno
file.rewind
file.each_line {|l|out.puts l}
end
end
end
end
desc "Install"
task :install do
vimfiles = if ENV['VIMFILES']
ENV['VIMFILES']
elsif RUBY_PLATFORM =~ /(win|w)32$/
File.expand_path("~/vimfiles")
else
File.expand_path("~/.vim")
end
puts "Installing javascript.vim"
files.each do |file|
target_file = File.join(vimfiles, file)
FileUtils.mkdir_p(File.dirname(target_file))
FileUtils.rm(target_file) rescue nil
FileUtils.cp(file, target_file)
puts " Copied #{file} to #{target_file}"
end
end
desc "Copy ~/.ctags to tmp/original_ctags"
task :get_original_ctags do
if File.exists?(File.expand_path("~/.ctags"))
File.unlink('tmp/original_ctags') if File.exists?('tmp/original_ctags')
FileUtils.cp(File.expand_path("~/.ctags"), 'tmp/original_ctags')
elsif not File.exists?("tmp/original_ctags")
File.open("tmp/original_ctags", "w") { }
end
end
desc "Combine tmp/original_ctags and extras/ctags"
file 'tmp/combined_ctags' => ['tmp/original_ctags', 'extras/ctags'] do |t|
begin_string = '# Begin vim-javascript generated section'
end_string = '# End vim-javascript generated section'
File.unlink t.name if File.exists?(t.name)
File.open(t.name,"w") do |out|
orig = File.read('tmp/original_ctags')
orig.each_line.inject(true) do |can_print, line|
can_print = false if line.chomp == begin_string
out.puts line if can_print
can_print or line.chomp == end_string
end
out.puts begin_string
out.puts "# generated at #{ Time.now }"
out.puts File.read('extras/ctags')
out.puts end_string
end
end
desc "Add better javascript support to ctags"
task :ctags => [:get_original_ctags, 'tmp/combined_ctags'] do
FileUtils.cp('tmp/combined_ctags', File.expand_path('~/.ctags'))
end
task 'zip' => 'javascript.zip'
task 'vimball' => 'javascript.vba'
task :default => [:zip, :vimball]

View File

@@ -0,0 +1,8 @@
--langdef=js
--langmap=js:.js
--regex-js=/([A-Za-z0-9._$]+)[ \t]*[:=][ \t]*\{/\1/,object/
--regex-js=/([A-Za-z0-9._$()]+)[ \t]*[:=][ \t]*function[ \t]*\(/\1/,function/
--regex-js=/function[ \t]+([A-Za-z0-9._$]+)[ \t]*([^)])/\1/,function/
--regex-js=/([A-Za-z0-9._$]+)[ \t]*[:=][ \t]*\[/\1/,array/
--regex-js=/([^= ]+)[ \t]*=[ \t]*[^"]'[^']*/\1/,string/
--regex-js=/([^= ]+)[ \t]*=[ \t]*[^']"[^"]*/\1/,string/

View File

@@ -0,0 +1,4 @@
au BufNewFile,BufRead *.js setf javascript
au BufNewFile,BufRead *.jsm setf javascript
au BufNewFile,BufRead *.json setf javascript
au BufNewFile,BufRead Jakefile setf javascript

View File

@@ -0,0 +1,539 @@
" Vim indent script for HTML
" General: "{{{
" File: html.vim (Vimscript #2075)
" Author: Andy Wokula <anwoku@yahoo.de>
" Last Change: 2012 Jun 05
" Last Changed By: Hsiaoming Yang <lepture@me.com>
" Version: 0.8
" Vim Version: Vim7
" Description:
" Improved version of the distributed html indent script, faster on a
" range of lines.
"
" Customization:
" This section is about variables you can set in your vimrc.
"
" - You can set the indent for the first line after <script> and <style>
" "blocktags" (default "zero"):
"
" :let g:html_indent_script1 = "inc"
" :let g:html_indent_style1 = "inc"
"
" VALUE MEANING
" "zero" zero indent
" "auto" auto indent (same indent as the blocktag)
" "inc" auto indent + one indent step
"
" - Many tags increase the indent for what follows per default (see
" "Add Indent Tags" below in this script). You can add further tags with
"
" :let g:html_indent_inctags = "html,body,head,tbody"
"
" You can also remove such tags with
"
" :let g:html_indent_autotags = "th,td,tr,tfoot,thead"
"
" Default value is empty for both variables. Note: the initial "inctags"
" are only defined once per Vim session.
"
" User variables are only read when the script is sourced. To enable your
" changes during a session, you can manually do
" :call HtmlIndent_CheckUserSettings()
" if you don't want to reload the html file.
"
" Detail:
" Calculation of indent inside "blocktags" with "alien" content:
" BLOCKTAG INDENT EXPR WHEN APPLICABLE
" <script> : {customizable} if first line of block
" : cindent(v:lnum) if attributes empty or contain "java"
" : -1 else (vbscript, tcl, ...)
" <style> : {customizable} if first line of block
" : GetCSSIndent() else
" <!-- --> : -1
"
" Credits:
" indent/html.vim (2006 Jun 05) from J. Zellner
" indent/css.vim (2006 Dec 20) from N. Weibull
"
" History:
" 2011 Sep 09 added HTML5 tags (thx to J. Zuckerman)
" 2012 Jun 05 added JavaScript Indention (thx to Hsiaoming Yang)
" }}}
" Init Folklore, check user settings (2nd time ++) "{{{
if exists("b:did_indent")
finish
endif
" Initial indent/javascript before set did_indent = 1
ru! indent/javascript.vim
let b:did_indent = 1
setlocal indentexpr=HtmlIndent()
setlocal indentkeys=o,O,<Return>,<>>,{,},!^F
let b:indent = {"lnum": -1}
let b:undo_indent = "set inde< indk<| unlet b:indent"
" Load Once:
if exists("*HtmlIndent")
call HtmlIndent_CheckUserSettings()
finish
endif
let s:cpo_save = &cpo
set cpo-=C
"}}}
func! HtmlIndent_CheckUserSettings() "{{{
if exists("g:html_indent_inctags")
call s:AddITags(split(g:html_indent_inctags, ","))
endif
if exists("g:html_indent_autotags")
call s:RemoveITags(split(g:html_indent_autotags, ","))
endif
let indone = {"zero": 0
\,"auto": "indent(prevnonblank(v:lnum-1))"
\,"inc": "b:indent.blocktagind + &shiftwidth"}
if exists("g:html_indent_script1")
let s:js1indent = get(indone, g:html_indent_script1, indone.zero)
endif
if exists("g:html_indent_style1")
let s:css1indent = get(indone, g:html_indent_style1, indone.zero)
endif
endfunc "}}}
" Init Script Vars "{{{
let s:usestate = 1
let s:css1indent = 0
let s:js1indent = 0
" not to be changed:
let s:endtags = [0,0,0,0,0,0,0,0] " some places unused
let s:newstate = {}
let s:countonly = 0
"}}}
func! s:AddITags(taglist) "{{{
for itag in a:taglist
let s:indent_tags[itag] = 1
let s:indent_tags['/'.itag] = -1
endfor
endfunc "}}}
func! s:AddBlockTag(tag, id, ...) "{{{
if !(a:id >= 2 && a:id < 2+len(s:endtags))
return
endif
let s:indent_tags[a:tag] = a:id
if a:0 == 0
let s:indent_tags['/'.a:tag] = -a:id
let s:endtags[a:id-2] = "</".a:tag.">"
else
let s:indent_tags[a:1] = -a:id
let s:endtags[a:id-2] = a:1
endif
endfunc "}}}
func! s:RemoveITags(taglist) "{{{
" remove itags (protect blocktags from being removed)
for itag in a:taglist
if !has_key(s:indent_tags, itag) || s:indent_tags[itag] != 1
continue
endif
unlet s:indent_tags[itag]
if itag =~ '^\w\+$'
unlet s:indent_tags["/".itag]
endif
endfor
endfunc "}}}
" Add Indent Tags: {{{
if !exists("s:indent_tags")
let s:indent_tags = {}
endif
" old tags:
call s:AddITags(['a', 'abbr', 'acronym', 'address', 'b', 'bdo', 'big',
\ 'blockquote', 'button', 'caption', 'center', 'cite', 'code', 'colgroup',
\ 'del', 'dfn', 'dir', 'div', 'dl', 'em', 'fieldset', 'font', 'form',
\ 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'i', 'iframe', 'ins', 'kbd',
\ 'label', 'legend', 'map', 'menu', 'noframes', 'noscript', 'object', 'ol',
\ 'optgroup', 'q', 's', 'samp', 'select', 'small', 'span', 'strong', 'sub',
\ 'sup', 'table', 'textarea', 'title', 'tt', 'u', 'ul', 'var', 'th', 'td',
\ 'tr', 'tfoot', 'thead'])
" tags added 2011 Sep 09 (especially HTML5 tags):
call s:AddITags(['area', 'article', 'aside', 'audio', 'bdi', 'canvas',
\ 'command', 'datalist', 'details', 'embed', 'figure', 'footer',
\ 'header', 'group', 'keygen', 'mark', 'math', 'meter', 'nav', 'output',
\ 'progress', 'ruby', 'section', 'svg', 'texture', 'time', 'video',
\ 'wbr', 'text'])
"}}}
" Add Block Tags: contain alien content "{{{
call s:AddBlockTag('pre', 2)
call s:AddBlockTag('script', 3)
call s:AddBlockTag('style', 4)
call s:AddBlockTag('<!--', 5, '-->')
"}}}
func! s:CountITags(...) "{{{
" relative indent steps for current line [unit &sw]:
let s:curind = 0
" relative indent steps for next line [unit &sw]:
let s:nextrel = 0
if a:0==0
let s:block = s:newstate.block
let tmpline = substitute(s:curline, '<\zs\/\=\w\+\>\|<!--\|-->', '\=s:CheckTag(submatch(0))', 'g')
if s:block == 3
let s:newstate.scripttype = s:GetScriptType(matchstr(tmpline, '\C.*<SCRIPT\>\zs[^>]*'))
endif
let s:newstate.block = s:block
else
let s:block = 0 " assume starting outside of a block
let s:countonly = 1 " don't change state
let tmpline = substitute(s:altline, '<\zs\/\=\w\+\>\|<!--\|-->', '\=s:CheckTag(submatch(0))', 'g')
let s:countonly = 0
endif
endfunc "}}}
func! s:CheckTag(itag) "{{{
" "tag" or "/tag" or "<!--" or "-->"
let ind = get(s:indent_tags, a:itag)
if ind == -1
" closing tag
if s:block != 0
" ignore itag within a block
return "foo"
endif
if s:nextrel == 0
let s:curind -= 1
else
let s:nextrel -= 1
endif
" if s:curind >= 1
" let s:curind -= 1
" else
" let s:nextrel -= 1
" endif
elseif ind == 1
" opening tag
if s:block != 0
return "foo"
endif
let s:nextrel += 1
elseif ind != 0
" block-tag (opening or closing)
return s:Blocktag(a:itag, ind)
endif
" else ind==0 (other tag found): keep indent
return "foo" " no matter
endfunc "}}}
func! s:Blocktag(blocktag, ind) "{{{
if a:ind > 0
" a block starts here
if s:block != 0
" already in a block (nesting) - ignore
" especially ignore comments after other blocktags
return "foo"
endif
let s:block = a:ind " block type
if s:countonly
return "foo"
endif
let s:newstate.blocklnr = v:lnum
" save allover indent for the endtag
let s:newstate.blocktagind = b:indent.baseindent + (s:nextrel + s:curind) * &shiftwidth
if a:ind == 3
return "SCRIPT" " all except this must be lowercase
" line is to be checked again for the type attribute
endif
else
let s:block = 0
" we get here if starting and closing block-tag on same line
endif
return "foo"
endfunc "}}}
func! s:GetScriptType(str) "{{{
if a:str == "" || a:str =~ "java"
return "javascript"
else
return ""
endif
endfunc "}}}
func! s:FreshState(lnum) "{{{
" Look back in the file (lines 1 to a:lnum-1) to calc a state for line
" a:lnum. A state is to know ALL relevant details about the lines
" 1..a:lnum-1, initial calculating (here!) can be slow, but updating is
" fast (incremental).
" State:
" lnum last indented line == prevnonblank(a:lnum - 1)
" block = 0 a:lnum located within special tag: 0:none, 2:<pre>,
" 3:<script>, 4:<style>, 5:<!--
" baseindent use this indent for line a:lnum as a start - kind of
" autoindent (if block==0)
" scripttype = '' type attribute of a script tag (if block==3)
" blocktagind indent for current opening (get) and closing (set)
" blocktag (if block!=0)
" blocklnr lnum of starting blocktag (if block!=0)
" inattr line {lnum} starts with attributes of a tag
let state = {}
let state.lnum = prevnonblank(a:lnum - 1)
let state.scripttype = ""
let state.blocktagind = -1
let state.block = 0
let state.baseindent = 0
let state.blocklnr = 0
let state.inattr = 0
if state.lnum == 0
return state
endif
" Heuristic:
" remember startline state.lnum
" look back for <pre, </pre, <script, </script, <style, </style tags
" remember stopline
" if opening tag found,
" assume a:lnum within block
" else
" look back in result range (stopline, startline) for comment
" \ delimiters (<!--, -->)
" if comment opener found,
" assume a:lnum within comment
" else
" assume usual html for a:lnum
" if a:lnum-1 has a closing comment
" look back to get indent of comment opener
" FI
" look back for blocktag
call cursor(a:lnum, 1)
let [stopline, stopcol] = searchpos('\c<\zs\/\=\%(pre\>\|script\>\|style\>\)', "bW")
" fugly ... why isn't there searchstr()
let tagline = tolower(getline(stopline))
let blocktag = matchstr(tagline, '\/\=\%(pre\>\|script\>\|style\>\)', stopcol-1)
if stopline > 0 && blocktag[0] != "/"
" opening tag found, assume a:lnum within block
let state.block = s:indent_tags[blocktag]
if state.block == 3
let state.scripttype = s:GetScriptType(matchstr(tagline, '\>[^>]*', stopcol))
endif
let state.blocklnr = stopline
" check preceding tags in the line:
let s:altline = tagline[: stopcol-2]
call s:CountITags(1)
let state.blocktagind = indent(stopline) + (s:curind + s:nextrel) * &shiftwidth
return state
elseif stopline == state.lnum
" handle special case: previous line (= state.lnum) contains a
" closing blocktag which is preceded by line-noise;
" blocktag == "/..."
let swendtag = match(tagline, '^\s*</') >= 0
if !swendtag
let [bline, bcol] = searchpos('<'.blocktag[1:].'\>', "bW")
let s:altline = tolower(getline(bline)[: bcol-2])
call s:CountITags(1)
let state.baseindent = indent(bline) + (s:nextrel+s:curline) * &shiftwidth
return state
endif
endif
" else look back for comment
call cursor(a:lnum, 1)
let [comline, comcol, found] = searchpos('\(<!--\)\|-->', 'bpW', stopline)
if found == 2
" comment opener found, assume a:lnum within comment
let state.block = 5
let state.blocklnr = comline
" check preceding tags in the line:
let s:altline = tolower(getline(comline)[: comcol-2])
call s:CountITags(1)
let state.blocktagind = indent(comline) + (s:curind + s:nextrel) * &shiftwidth
return state
endif
" else within usual html
let s:altline = tolower(getline(state.lnum))
" check a:lnum-1 for closing comment (we need indent from the opening line)
let comcol = stridx(s:altline, '-->')
if comcol >= 0
call cursor(state.lnum, comcol+1)
let [comline, comcol] = searchpos('<!--', 'bW')
if comline == state.lnum
let s:altline = s:altline[: comcol-2]
else
let s:altline = tolower(getline(comline)[: comcol-2])
endif
call s:CountITags(1)
let state.baseindent = indent(comline) + (s:nextrel+s:curline) * &shiftwidth
return state
" TODO check tags that follow "-->"
endif
" else no comments
call s:CountITags(1)
let state.baseindent = indent(state.lnum) + s:nextrel * &shiftwidth
" line starts with end tag
let swendtag = match(s:altline, '^\s*</') >= 0
if !swendtag
let state.baseindent += s:curind * &shiftwidth
endif
return state
endfunc "}}}
func! s:Alien2() "{{{
" <pre> block
return -1
endfunc "}}}
func! s:Alien3() "{{{
" <script> javascript
if prevnonblank(v:lnum-1) == b:indent.blocklnr
" indent for the first line after <script>
return eval(s:js1indent)
endif
if b:indent.scripttype == "javascript"
"return cindent(v:lnum)
return GetJavascriptIndent()
else
return -1
endif
endfunc "}}}
func! s:Alien4() "{{{
" <style>
if prevnonblank(v:lnum-1) == b:indent.blocklnr
" indent for first content line
return eval(s:css1indent)
endif
return s:CSSIndent()
endfunc
func! s:CSSIndent() "{{{
" adopted $VIMRUNTIME/indent/css.vim
if getline(v:lnum) =~ '^\s*[*}]'
return cindent(v:lnum)
endif
let minline = b:indent.blocklnr
let pnum = s:css_prevnoncomment(v:lnum - 1, minline)
if pnum <= minline
" < is to catch errors
" indent for first content line after comments
return eval(s:css1indent)
endif
let ind = indent(pnum) + s:css_countbraces(pnum, 1) * &sw
let pline = getline(pnum)
if pline =~ '}\s*$'
let ind -= (s:css_countbraces(pnum, 0) - (pline =~ '^\s*}')) * &sw
endif
return ind
endfunc "}}}
func! s:css_prevnoncomment(lnum, stopline) "{{{
" caller starts from a line a:lnum-1 that is not a comment
let lnum = prevnonblank(a:lnum)
let ccol = match(getline(lnum), '\*/')
if ccol < 0
return lnum
endif
call cursor(lnum, ccol+1)
let lnum = search('/\*', 'bW', a:stopline)
if indent(".") == virtcol(".")-1
return prevnonblank(lnum-1)
else
return lnum
endif
endfunc "}}}
func! s:css_countbraces(lnum, count_open) "{{{
let brs = substitute(getline(a:lnum),'[''"].\{-}[''"]\|/\*.\{-}\*/\|/\*.*$\|[^{}]','','g')
let n_open = 0
let n_close = 0
for brace in split(brs, '\zs')
if brace == "{"
let n_open += 1
elseif brace == "}"
if n_open > 0
let n_open -= 1
else
let n_close += 1
endif
endif
endfor
return a:count_open ? n_open : n_close
endfunc "}}}
"}}}
func! s:Alien5() "{{{
" <!-- -->
return -1
endfunc "}}}
func! HtmlIndent() "{{{
let s:curline = tolower(getline(v:lnum))
let s:newstate = {}
let s:newstate.lnum = v:lnum
" is the first non-blank in the line the start of a tag?
let swendtag = match(s:curline, '^\s*</') >= 0
if prevnonblank(v:lnum-1) == b:indent.lnum && s:usestate
" use state (continue from previous line)
else
" start over (know nothing)
let b:indent = s:FreshState(v:lnum)
endif
if b:indent.block >= 2
" within block
let endtag = s:endtags[b:indent.block-2]
let blockend = stridx(s:curline, endtag)
if blockend >= 0
" block ends here
let s:newstate.block = 0
" calc indent for REST OF LINE (may start more blocks):
let s:curline = strpart(s:curline, blockend+strlen(endtag))
call s:CountITags()
if swendtag && b:indent.block != 5
let indent = b:indent.blocktagind + s:curind * &shiftwidth
let s:newstate.baseindent = indent + s:nextrel * &shiftwidth
else
let indent = s:Alien{b:indent.block}()
let s:newstate.baseindent = b:indent.blocktagind + s:nextrel * &shiftwidth
endif
call extend(b:indent, s:newstate, "force")
return indent
else
" block continues
" indent this line with alien method
let indent = s:Alien{b:indent.block}()
call extend(b:indent, s:newstate, "force")
return indent
endif
else
" not within a block - within usual html
" if < 2 then always 0
let s:newstate.block = b:indent.block
call s:CountITags()
if swendtag
let indent = b:indent.baseindent + s:curind * &shiftwidth
let s:newstate.baseindent = indent + s:nextrel * &shiftwidth
else
let indent = b:indent.baseindent
let s:newstate.baseindent = indent + (s:curind + s:nextrel) * &shiftwidth
endif
call extend(b:indent, s:newstate, "force")
return indent
endif
endfunc "}}}
" check user settings (first time), clear cpo, Modeline: {{{1
" DEBUG:
com! -nargs=* IndHtmlLocal <args>
call HtmlIndent_CheckUserSettings()
let &cpo = s:cpo_save
unlet s:cpo_save
" vim:set fdm=marker ts=8:

View File

@@ -0,0 +1,330 @@
" Vim indent file
" Language: Javascript
" Maintainer: Darrick Wiebe <darrick at innatesoftware.com>
" URL: http://github.com/pangloss/vim-javascript
" Version: 1.0.0
" Last Change: August 31, 2009
" Acknowledgement: Based off of vim-ruby maintained by Nikolai Weibull http://vim-ruby.rubyforge.org
" 0. Initialization {{{1
" =================
" Only load this indent file when no other was loaded.
if exists("b:did_indent")
finish
endif
let b:did_indent = 1
setlocal nosmartindent
" Now, set up our indentation expression and keys that trigger it.
setlocal indentexpr=GetJavascriptIndent()
setlocal indentkeys=0{,0},0),0],!^F,o,O,e
" Only define the function once.
if exists("*GetJavascriptIndent")
finish
endif
let s:cpo_save = &cpo
set cpo&vim
" 1. Variables {{{1
" ============
" Regex of syntax group names that are or delimit string or are comments.
let s:syng_strcom = 'javaScript\%(String\|RegexpString\|CommentTodo\|LineComment\|Comment\|DocComment\)'
" Regex of syntax group names that are strings.
let s:syng_string = 'javaScript\%(RegexpString\)'
" Regex of syntax group names that are strings or documentation.
let s:syng_multiline = 'javaScriptDocComment\|javaScriptComment'
" Expression used to check whether we should skip a match with searchpair().
let s:skip_expr = "synIDattr(synID(line('.'),col('.'),1),'name') =~ '".s:syng_strcom."'"
let s:line_term = '\s*\%(\%(\/\/\).*\)\=$'
" Regex that defines continuation lines, not including (, {, or [.
let s:continuation_regex = '\%([\\*+/.:]\|\%(<%\)\@<![=-]\|\W[|&?]\|||\|&&\)' . s:line_term
" Regex that defines continuation lines.
" TODO: this needs to deal with if ...: and so on
let s:msl_regex = '\%([\\*+/.:([]\|\%(<%\)\@<![=-]\|\W[|&?]\|||\|&&\)' . s:line_term
let s:one_line_scope_regex = '\<\%(if\|else\|for\|while\)\>[^{;]*' . s:line_term
" Regex that defines blocks.
let s:block_regex = '\%({\)\s*\%(|\%([*@]\=\h\w*,\=\s*\)\%(,\s*[*@]\=\h\w*\)*|\)\=' . s:line_term
" 2. Auxiliary Functions {{{1
" ======================
" Check if the character at lnum:col is inside a string, comment, or is ascii.
function s:IsInStringOrComment(lnum, col)
return synIDattr(synID(a:lnum, a:col, 1), 'name') =~ s:syng_strcom
endfunction
" Check if the character at lnum:col is inside a string.
function s:IsInString(lnum, col)
return synIDattr(synID(a:lnum, a:col, 1), 'name') =~ s:syng_string
endfunction
" Check if the character at lnum:col is inside a multi-line comment.
function s:IsInMultilineComment(lnum, col)
return synIDattr(synID(a:lnum, a:col, 1), 'name') =~ s:syng_multiline
endfunction
" Find line above 'lnum' that isn't empty, in a comment, or in a string.
function s:PrevNonBlankNonString(lnum)
let in_block = 0
let lnum = prevnonblank(a:lnum)
while lnum > 0
" Go in and out of blocks comments as necessary.
" If the line isn't empty (with opt. comment) or in a string, end search.
let line = getline(lnum)
if line =~ '/\*'
if in_block
let in_block = 0
else
break
endif
elseif !in_block && line =~ '\*/'
let in_block = 1
elseif !in_block && line !~ '^\s*\%(//\).*$' && !(s:IsInStringOrComment(lnum, 1) && s:IsInStringOrComment(lnum, strlen(line)))
break
endif
let lnum = prevnonblank(lnum - 1)
endwhile
return lnum
endfunction
" Find line above 'lnum' that started the continuation 'lnum' may be part of.
function s:GetMSL(lnum, in_one_line_scope)
" Start on the line we're at and use its indent.
let msl = a:lnum
let lnum = s:PrevNonBlankNonString(a:lnum - 1)
while lnum > 0
" If we have a continuation line, or we're in a string, use line as MSL.
" Otherwise, terminate search as we have found our MSL already.
let line = getline(lnum)
let col = match(line, s:msl_regex) + 1
if (col > 0 && !s:IsInStringOrComment(lnum, col)) || s:IsInString(lnum, strlen(line))
let msl = lnum
else
" Don't use lines that are part of a one line scope as msl unless the
" flag in_one_line_scope is set to 1
"
if a:in_one_line_scope
break
end
let msl_one_line = s:Match(lnum, s:one_line_scope_regex)
if msl_one_line == 0
break
endif
endif
let lnum = s:PrevNonBlankNonString(lnum - 1)
endwhile
return msl
endfunction
" Check if line 'lnum' has more opening brackets than closing ones.
function s:LineHasOpeningBrackets(lnum)
let open_0 = 0
let open_2 = 0
let open_4 = 0
let line = getline(a:lnum)
let pos = match(line, '[][(){}]', 0)
while pos != -1
if !s:IsInStringOrComment(a:lnum, pos + 1)
let idx = stridx('(){}[]', line[pos])
if idx % 2 == 0
let open_{idx} = open_{idx} + 1
else
let open_{idx - 1} = open_{idx - 1} - 1
endif
endif
let pos = match(line, '[][(){}]', pos + 1)
endwhile
return (open_0 > 0) . (open_2 > 0) . (open_4 > 0)
endfunction
function s:Match(lnum, regex)
let col = match(getline(a:lnum), a:regex) + 1
return col > 0 && !s:IsInStringOrComment(a:lnum, col) ? col : 0
endfunction
function s:IndentWithContinuation(lnum, ind, width)
" Set up variables to use and search for MSL to the previous line.
let p_lnum = a:lnum
let lnum = s:GetMSL(a:lnum, 1)
let line = getline(lnum)
" If the previous line wasn't a MSL and is continuation return its indent.
" TODO: the || s:IsInString() thing worries me a bit.
if p_lnum != lnum
if s:Match(p_lnum,s:continuation_regex)||s:IsInString(p_lnum,strlen(line))
return a:ind
endif
endif
" Set up more variables now that we know we aren't continuation bound.
let msl_ind = indent(lnum)
" If the previous line ended with [*+/.-=], start a continuation that
" indents an extra level.
if s:Match(lnum, s:continuation_regex)
if lnum == p_lnum
return msl_ind + a:width
else
return msl_ind
endif
endif
return a:ind
endfunction
function s:InOneLineScope(lnum)
let msl = s:GetMSL(a:lnum, 1)
if msl > 0 && s:Match(msl, s:one_line_scope_regex)
return msl
endif
return 0
endfunction
function s:ExitingOneLineScope(lnum)
let msl = s:GetMSL(a:lnum, 1)
if msl > 0
" if the current line is in a one line scope ..
if s:Match(msl, s:one_line_scope_regex)
return 0
else
let prev_msl = s:GetMSL(msl - 1, 1)
if s:Match(prev_msl, s:one_line_scope_regex)
return prev_msl
endif
endif
endif
return 0
endfunction
" 3. GetJavascriptIndent Function {{{1
" =========================
function GetJavascriptIndent()
" 3.1. Setup {{{2
" ----------
" Set up variables for restoring position in file. Could use v:lnum here.
let vcol = col('.')
" 3.2. Work on the current line {{{2
" -----------------------------
" Get the current line.
let line = getline(v:lnum)
let ind = -1
" If we got a closing bracket on an empty line, find its match and indent
" according to it. For parentheses we indent to its column - 1, for the
" others we indent to the containing line's MSL's level. Return -1 if fail.
let col = matchend(line, '^\s*[]})]')
if col > 0 && !s:IsInStringOrComment(v:lnum, col)
call cursor(v:lnum, col)
let bs = strpart('(){}[]', stridx(')}]', line[col - 1]) * 2, 2)
if searchpair(escape(bs[0], '\['), '', bs[1], 'bW', s:skip_expr) > 0
if line[col-1]==')' && col('.') != col('$') - 1
let ind = virtcol('.')-1
else
let ind = indent(s:GetMSL(line('.'), 0))
endif
endif
return ind
endif
" If we are in a multi-line comment, cindent does the right thing.
if s:IsInMultilineComment(v:lnum, 1)
return cindent(v:lnum)
endif
" 3.3. Work on the previous line. {{{2
" -------------------------------
" If the line is empty and the previous nonblank line was a multi-line
" comment, use that comment's indent. Deduct one char to account for the
" space in ' */'.
let nonblank_lnum = prevnonblank(v:lnum - 1)
if line =~ '^\s*$' && s:IsInMultilineComment(nonblank_lnum, 1)
return indent(nonblank_lnum) - 1
endif
" Find a non-blank, non-multi-line string line above the current line.
let lnum = s:PrevNonBlankNonString(v:lnum - 1)
" If the line is empty and inside a string, use the previous line.
if line =~ '^\s*$' && lnum != nonblank_lnum
return indent(prevnonblank(v:lnum))
endif
" At the start of the file use zero indent.
if lnum == 0
return 0
endif
" Set up variables for current line.
let line = getline(lnum)
let ind = indent(lnum)
" If the previous line ended with a block opening, add a level of indent.
if s:Match(lnum, s:block_regex)
return indent(s:GetMSL(lnum, 0)) + &sw
endif
" If the previous line contained an opening bracket, and we are still in it,
" add indent depending on the bracket type.
if line =~ '[[({]'
let counts = s:LineHasOpeningBrackets(lnum)
if counts[0] == '1' && searchpair('(', '', ')', 'bW', s:skip_expr) > 0
if col('.') + 1 == col('$')
return ind + &sw
else
return virtcol('.')
endif
elseif counts[1] == '1' || counts[2] == '1'
return ind + &sw
else
call cursor(v:lnum, vcol)
end
endif
" 3.4. Work on the MSL line. {{{2
" --------------------------
let ind_con = ind
let ind = s:IndentWithContinuation(lnum, ind_con, &sw)
" }}}2
"
"
let ols = s:InOneLineScope(lnum)
if ols > 0
let ind = ind + &sw
else
let ols = s:ExitingOneLineScope(lnum)
while ols > 0 && ind > 0
let ind = ind - &sw
let ols = s:InOneLineScope(ols - 1)
endwhile
endif
return ind
endfunction
" }}}1
let &cpo = s:cpo_save
unlet s:cpo_save
" vim:set sw=2 sts=2 ts=8 noet:

View File

@@ -0,0 +1,264 @@
" Vim syntax file
" Language: JavaScript
" Maintainer: Yi Zhao (ZHAOYI) <zzlinux AT hotmail DOT com>
" Last Change By: Marc Harter
" Last Change: February 18, 2011
" Version: 0.7.9
" Changes: Updates JSDoc syntax
"
" TODO:
" - Add the HTML syntax inside the JSDoc
if !exists("main_syntax")
if version < 600
syntax clear
elseif exists("b:current_syntax")
finish
endif
let main_syntax = 'javascript'
endif
"" Drop fold if it is set but VIM doesn't support it.
let b:javascript_fold='true'
if version < 600 " Don't support the old version
unlet! b:javascript_fold
endif
"" dollar sign is permittd anywhere in an identifier
setlocal iskeyword+=$
syntax sync fromstart
"" JavaScript comments
syntax keyword javaScriptCommentTodo TODO FIXME XXX TBD contained
syntax region javaScriptLineComment start=+\/\/+ end=+$+ keepend contains=javaScriptCommentTodo,@Spell
syntax region javaScriptEnvComment start="\%^#!" end="$" display
syntax region javaScriptLineComment start=+^\s*\/\/+ skip=+\n\s*\/\/+ end=+$+ keepend contains=javaScriptCommentTodo,@Spell fold
syntax region javaScriptCvsTag start="\$\cid:" end="\$" oneline contained
syntax region javaScriptComment start="/\*" end="\*/" contains=javaScriptCommentTodo,javaScriptCvsTag,@Spell fold
"" JSDoc / JSDoc Toolkit
if !exists("javascript_ignore_javaScriptdoc")
syntax case ignore
"" syntax coloring for javadoc comments (HTML)
"syntax include @javaHtml <sfile>:p:h/html.vim
"unlet b:current_syntax
syntax region javaScriptDocComment matchgroup=javaScriptComment start="/\*\*\s*" end="\*/" contains=javaScriptDocTags,javaScriptCommentTodo,javaScriptCvsTag,@javaScriptHtml,@Spell fold
" tags containing a param
syntax match javaScriptDocTags contained "@\(augments\|base\|borrows\|class\|constructs\|default\|exception\|exports\|extends\|file\|member\|memberOf\|methodOf\|module\|name\|namespace\|optional\|requires\|title\|throws\|version\)\>" nextgroup=javaScriptDocParam skipwhite
" tags containing type and param
syntax match javaScriptDocTags contained "@\(argument\|param\|property\)\>" nextgroup=javaScriptDocType skipwhite
" tags containing type but no param
syntax match javaScriptDocTags contained "@\(type\|return\|returns\|api\)\>" nextgroup=javaScriptDocTypeNoParam skipwhite
" tags containing references
syntax match javaScriptDocTags contained "@\(lends\|link\|see\)\>" nextgroup=javaScriptDocSeeTag skipwhite
" other tags (no extra syntax)
syntax match javaScriptDocTags contained "@\(access\|addon\|alias\|author\|beta\|constant\|const\|constructor\|copyright\|deprecated\|description\|event\|example\|exec\|field\|fileOverview\|fileoverview\|function\|global\|ignore\|inner\|license\|overview\|private\|protected\|project\|public\|readonly\|since\|static\)\>"
syntax region javaScriptDocType start="{" end="}" oneline contained nextgroup=javaScriptDocParam skipwhite
syntax match javaScriptDocType contained "\%(#\|\"\|\w\|\.\|:\|\/\)\+" nextgroup=javaScriptDocParam skipwhite
syntax region javaScriptDocTypeNoParam start="{" end="}" oneline contained
syntax match javaScriptDocTypeNoParam contained "\%(#\|\"\|\w\|\.\|:\|\/\)\+"
syntax match javaScriptDocParam contained "\%(#\|\"\|{\|}\|\w\|\.\|:\|\/\)\+"
syntax region javaScriptDocSeeTag contained matchgroup=javaScriptDocSeeTag start="{" end="}" contains=javaScriptDocTags
syntax case match
endif "" JSDoc end
syntax case match
"" Syntax in the JavaScript code
syntax match javaScriptSpecial "\\\d\d\d\|\\x\x\{2\}\|\\u\x\{4\}\|\\."
syntax region javaScriptStringD start=+"+ skip=+\\\\\|\\$"+ end=+"+ contains=javaScriptSpecial,@htmlPreproc
syntax region javaScriptStringS start=+'+ skip=+\\\\\|\\$'+ end=+'+ contains=javaScriptSpecial,@htmlPreproc
syntax region javaScriptRegexpCharClass start=+\[+ end=+\]+ contained
syntax region javaScriptRegexpString start=+\(\(\(return\|case\)\s\+\)\@<=\|\(\([)\]"']\|\d\|\w\)\s*\)\@<!\)/\(\*\|/\)\@!+ skip=+\\\\\|\\/+ end=+/[gimy]\{,4}+ contains=javaScriptSpecial,javaScriptRegexpCharClass,@htmlPreproc oneline
syntax match javaScriptNumber /\<-\=\d\+L\=\>\|\<0[xX]\x\+\>/
syntax match javaScriptFloat /\<-\=\%(\d\+\.\d\+\|\d\+\.\|\.\d\+\)\%([eE][+-]\=\d\+\)\=\>/
syntax match javaScriptLabel /\<\w\+\(\s*:\)\@=/
"" JavaScript Prototype
syntax keyword javaScriptPrototype prototype
"" Program Keywords
syntax keyword javaScriptSource import export
syntax keyword javaScriptType const undefined var void yield
syntax keyword javaScriptOperator delete new in instanceof let typeof
syntax keyword javaScriptBoolean true false
syntax keyword javaScriptNull null
syntax keyword javaScriptThis this
"" Statement Keywords
syntax keyword javaScriptConditional if else
syntax keyword javaScriptRepeat do while for
syntax keyword javaScriptBranch break continue switch case default return
syntax keyword javaScriptStatement try catch throw with finally
syntax keyword javaScriptGlobalObjects Array Boolean Date Function Infinity JavaArray JavaClass JavaObject JavaPackage Math Number NaN Object Packages RegExp String Undefined java netscape sun
syntax keyword javaScriptExceptions Error EvalError RangeError ReferenceError SyntaxError TypeError URIError
syntax keyword javaScriptFutureKeys abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws goto private transient debugger implements protected volatile double import public
"" DOM/HTML/CSS specified things
" DOM2 Objects
syntax keyword javaScriptGlobalObjects DOMImplementation DocumentFragment Document Node NodeList NamedNodeMap CharacterData Attr Element Text Comment CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
syntax keyword javaScriptExceptions DOMException
" DOM2 CONSTANT
syntax keyword javaScriptDomErrNo INDEX_SIZE_ERR DOMSTRING_SIZE_ERR HIERARCHY_REQUEST_ERR WRONG_DOCUMENT_ERR INVALID_CHARACTER_ERR NO_DATA_ALLOWED_ERR NO_MODIFICATION_ALLOWED_ERR NOT_FOUND_ERR NOT_SUPPORTED_ERR INUSE_ATTRIBUTE_ERR INVALID_STATE_ERR SYNTAX_ERR INVALID_MODIFICATION_ERR NAMESPACE_ERR INVALID_ACCESS_ERR
syntax keyword javaScriptDomNodeConsts ELEMENT_NODE ATTRIBUTE_NODE TEXT_NODE CDATA_SECTION_NODE ENTITY_REFERENCE_NODE ENTITY_NODE PROCESSING_INSTRUCTION_NODE COMMENT_NODE DOCUMENT_NODE DOCUMENT_TYPE_NODE DOCUMENT_FRAGMENT_NODE NOTATION_NODE
" HTML events and internal variables
syntax case ignore
syntax keyword javaScriptHtmlEvents onblur onclick oncontextmenu ondblclick onfocus onkeydown onkeypress onkeyup onmousedown onmousemove onmouseout onmouseover onmouseup onresize
syntax case match
" Follow stuff should be highligh within a special context
" While it can't be handled with context depended with Regex based highlight
" So, turn it off by default
if exists("javascript_enable_domhtmlcss")
" DOM2 things
syntax match javaScriptDomElemAttrs contained /\%(nodeName\|nodeValue\|nodeType\|parentNode\|childNodes\|firstChild\|lastChild\|previousSibling\|nextSibling\|attributes\|ownerDocument\|namespaceURI\|prefix\|localName\|tagName\)\>/
syntax match javaScriptDomElemFuncs contained /\%(insertBefore\|replaceChild\|removeChild\|appendChild\|hasChildNodes\|cloneNode\|normalize\|isSupported\|hasAttributes\|getAttribute\|setAttribute\|removeAttribute\|getAttributeNode\|setAttributeNode\|removeAttributeNode\|getElementsByTagName\|getAttributeNS\|setAttributeNS\|removeAttributeNS\|getAttributeNodeNS\|setAttributeNodeNS\|getElementsByTagNameNS\|hasAttribute\|hasAttributeNS\)\>/ nextgroup=javaScriptParen skipwhite
" HTML things
syntax match javaScriptHtmlElemAttrs contained /\%(className\|clientHeight\|clientLeft\|clientTop\|clientWidth\|dir\|id\|innerHTML\|lang\|length\|offsetHeight\|offsetLeft\|offsetParent\|offsetTop\|offsetWidth\|scrollHeight\|scrollLeft\|scrollTop\|scrollWidth\|style\|tabIndex\|title\)\>/
syntax match javaScriptHtmlElemFuncs contained /\%(blur\|click\|focus\|scrollIntoView\|addEventListener\|dispatchEvent\|removeEventListener\|item\)\>/ nextgroup=javaScriptParen skipwhite
" CSS Styles in JavaScript
syntax keyword javaScriptCssStyles contained color font fontFamily fontSize fontSizeAdjust fontStretch fontStyle fontVariant fontWeight letterSpacing lineBreak lineHeight quotes rubyAlign rubyOverhang rubyPosition
syntax keyword javaScriptCssStyles contained textAlign textAlignLast textAutospace textDecoration textIndent textJustify textJustifyTrim textKashidaSpace textOverflowW6 textShadow textTransform textUnderlinePosition
syntax keyword javaScriptCssStyles contained unicodeBidi whiteSpace wordBreak wordSpacing wordWrap writingMode
syntax keyword javaScriptCssStyles contained bottom height left position right top width zIndex
syntax keyword javaScriptCssStyles contained border borderBottom borderLeft borderRight borderTop borderBottomColor borderLeftColor borderTopColor borderBottomStyle borderLeftStyle borderRightStyle borderTopStyle borderBottomWidth borderLeftWidth borderRightWidth borderTopWidth borderColor borderStyle borderWidth borderCollapse borderSpacing captionSide emptyCells tableLayout
syntax keyword javaScriptCssStyles contained margin marginBottom marginLeft marginRight marginTop outline outlineColor outlineStyle outlineWidth padding paddingBottom paddingLeft paddingRight paddingTop
syntax keyword javaScriptCssStyles contained listStyle listStyleImage listStylePosition listStyleType
syntax keyword javaScriptCssStyles contained background backgroundAttachment backgroundColor backgroundImage gackgroundPosition backgroundPositionX backgroundPositionY backgroundRepeat
syntax keyword javaScriptCssStyles contained clear clip clipBottom clipLeft clipRight clipTop content counterIncrement counterReset cssFloat cursor direction display filter layoutGrid layoutGridChar layoutGridLine layoutGridMode layoutGridType
syntax keyword javaScriptCssStyles contained marks maxHeight maxWidth minHeight minWidth opacity MozOpacity overflow overflowX overflowY verticalAlign visibility zoom cssText
syntax keyword javaScriptCssStyles contained scrollbar3dLightColor scrollbarArrowColor scrollbarBaseColor scrollbarDarkShadowColor scrollbarFaceColor scrollbarHighlightColor scrollbarShadowColor scrollbarTrackColor
" Highlight ways
syntax match javaScriptDotNotation "\." nextgroup=javaScriptPrototype,javaScriptDomElemAttrs,javaScriptDomElemFuncs,javaScriptHtmlElemAttrs,javaScriptHtmlElemFuncs
syntax match javaScriptDotNotation "\.style\." nextgroup=javaScriptCssStyles
endif "DOM/HTML/CSS
"" end DOM/HTML/CSS specified things
"" Code blocks
" there is a name collision with javaScriptExpression in html.vim, hence the use of the '2' here
syntax cluster javaScriptExpression2 contains=javaScriptComment,javaScriptLineComment,javaScriptDocComment,javaScriptStringD,javaScriptStringS,javaScriptRegexpString,javaScriptNumber,javaScriptFloat,javaScriptSource,javaScriptThis,javaScriptType,javaScriptOperator,javaScriptBoolean,javaScriptNull,javaScriptFunction,javaScriptGlobalObjects,javaScriptExceptions,javaScriptFutureKeys,javaScriptDomErrNo,javaScriptDomNodeConsts,javaScriptHtmlEvents,javaScriptDotNotation,javaScriptBracket,javaScriptParen,javaScriptBlock,javaScriptParenError
syntax cluster javaScriptAll contains=@javaScriptExpression2,javaScriptLabel,javaScriptConditional,javaScriptRepeat,javaScriptBranch,javaScriptStatement,javaScriptTernaryIf
syntax region javaScriptBracket matchgroup=javaScriptBracket transparent start="\[" end="\]" contains=@javaScriptAll,javaScriptParensErrB,javaScriptParensErrC,javaScriptBracket,javaScriptParen,javaScriptBlock,@htmlPreproc
syntax region javaScriptParen matchgroup=javaScriptParen transparent start="(" end=")" contains=@javaScriptAll,javaScriptParensErrA,javaScriptParensErrC,javaScriptParen,javaScriptBracket,javaScriptBlock,@htmlPreproc
syntax region javaScriptBlock matchgroup=javaScriptBlock transparent start="{" end="}" contains=@javaScriptAll,javaScriptParensErrA,javaScriptParensErrB,javaScriptParen,javaScriptBracket,javaScriptBlock,@htmlPreproc
syntax region javaScriptTernaryIf matchgroup=javaScriptTernaryIfOperator start=+?+ end=+:+ contains=@javaScriptExpression2
"" catch errors caused by wrong parenthesis
syntax match javaScriptParensError ")\|}\|\]"
syntax match javaScriptParensErrA contained "\]"
syntax match javaScriptParensErrB contained ")"
syntax match javaScriptParensErrC contained "}"
if main_syntax == "javascript"
syntax sync clear
syntax sync ccomment javaScriptComment minlines=200
syntax sync match javaScriptHighlight grouphere javaScriptBlock /{/
endif
"" Fold control
if exists("b:javascript_fold")
syntax match javaScriptFunction /\<function\>/ nextgroup=javaScriptFuncName skipwhite
syntax match javaScriptOpAssign /=\@<!=/ nextgroup=javaScriptFuncBlock skipwhite skipempty
syntax region javaScriptFuncName contained matchgroup=javaScriptFuncName start=/\%(\$\|\w\)*\s*(/ end=/)/ contains=javaScriptLineComment,javaScriptComment nextgroup=javaScriptFuncBlock skipwhite skipempty
syntax region javaScriptFuncBlock contained matchgroup=javaScriptFuncBlock start="{" end="}" contains=@javaScriptAll,javaScriptParensErrA,javaScriptParensErrB,javaScriptParen,javaScriptBracket,javaScriptBlock fold
else
syntax keyword javaScriptFunction function
endif
" Define the default highlighting.
" For version 5.7 and earlier: only when not done already
" For version 5.8 and later: only when an item doesn't have highlighting yet
if version >= 508 || !exists("did_javascript_syn_inits")
if version < 508
let did_javascript_syn_inits = 1
command -nargs=+ HiLink hi link <args>
else
command -nargs=+ HiLink hi def link <args>
endif
HiLink javaScriptComment Comment
HiLink javaScriptLineComment Comment
HiLink javaScriptEnvComment PreProc
HiLink javaScriptDocComment Comment
HiLink javaScriptCommentTodo Todo
HiLink javaScriptCvsTag Function
HiLink javaScriptDocTags Special
HiLink javaScriptDocSeeTag Function
HiLink javaScriptDocType Type
HiLink javaScriptDocTypeNoParam Type
HiLink javaScriptDocParam Label
HiLink javaScriptStringS String
HiLink javaScriptStringD String
HiLink javaScriptTernaryIfOperator Conditional
HiLink javaScriptRegexpString String
HiLink javaScriptRegexpCharClass Character
HiLink javaScriptCharacter Character
HiLink javaScriptPrototype Type
HiLink javaScriptConditional Conditional
HiLink javaScriptBranch Conditional
HiLink javaScriptRepeat Repeat
HiLink javaScriptStatement Statement
HiLink javaScriptFunction Function
HiLink javaScriptError Error
HiLink javaScriptParensError Error
HiLink javaScriptParensErrA Error
HiLink javaScriptParensErrB Error
HiLink javaScriptParensErrC Error
HiLink javaScriptOperator Operator
HiLink javaScriptType Type
HiLink javaScriptThis Type
HiLink javaScriptNull Type
HiLink javaScriptNumber Number
HiLink javaScriptFloat Number
HiLink javaScriptBoolean Boolean
HiLink javaScriptLabel Label
HiLink javaScriptSpecial Special
HiLink javaScriptSource Special
HiLink javaScriptGlobalObjects Special
HiLink javaScriptExceptions Special
HiLink javaScriptDomErrNo Constant
HiLink javaScriptDomNodeConsts Constant
HiLink javaScriptDomElemAttrs Label
HiLink javaScriptDomElemFuncs PreProc
HiLink javaScriptHtmlEvents Special
HiLink javaScriptHtmlElemAttrs Label
HiLink javaScriptHtmlElemFuncs PreProc
HiLink javaScriptCssStyles Label
delcommand HiLink
endif
" Define the htmlJavaScript for HTML syntax html.vim
"syntax clear htmlJavaScript
"syntax clear javaScriptExpression
syntax cluster htmlJavaScript contains=@javaScriptAll,javaScriptBracket,javaScriptParen,javaScriptBlock,javaScriptParenError
syntax cluster javaScriptExpression contains=@javaScriptAll,javaScriptBracket,javaScriptParen,javaScriptBlock,javaScriptParenError,@htmlPreproc
" Vim's default html.vim highlights all javascript as 'Special'
hi! def link javaScript NONE
let b:current_syntax = "javascript"
if main_syntax == 'javascript'
unlet main_syntax
endif
" vim: ts=4

View File

View File

@@ -0,0 +1,6 @@
*.swp
# debug files
/after/autoload/nodejs-doc-all.json
/after/autoload/nodejs-doc.vim.js

View File

@@ -0,0 +1,65 @@
vim-nodejs-complete
===================
Nodejs `'omnifunc'` function of vim
Support node build-in module's method completion(`ctrl-x ctrl-o`) in `js` file with preview.
## Install
Download the [tarball](https://github.com/myhere/vim-nodejs-complete/zipball/master) and extract to your vimfiles(`~/.vim` or `~/vimfiles`) folder.
Completion require `:filetype plugin on`, please make sure it's on.
For integration with [jscomplete](https://github.com/teramako/jscomplete-vim), set `let g:node_usejscomplete = 1`. *Note*: you must install jscomplete manually.
## Example
```js
var fs = req
// then hit ctrl-x_ctrl-o you'll get:
var fs = require(
// and then hit ctrl-x_ctrl-o again you'll get module name completion
var fs = require('f
// then hit ctrl-x_ctrl-o
fs.
// then hit ctrl-x_ctrl-o
proc
// then hit ctrl-x_ctrl-o
process.ex
// then hit ctrl-x_ctrl-o
```
## Tip
1. Close the method preview window
`ctrl-w_ctrl-z` or `:pc`.
If you want close it automatically, put the code(from [spf13-vim](https://github.com/spf13/spf13-vim/blob/3.0/.vimrc)) below in your `.vimrc` file.
```vim
" automatically open and close the popup menu / preview window
au CursorMovedI,InsertLeave * if pumvisible() == 0|silent! pclose|endif
```
2. About vim's complete
Vim supports several kinds of completion, `:h ins-completion` for help.
3. Completion of module in `node_modules` will cache result of every `js` file
If you modified module in `node_modules` directory, use code below to clear the cache.
```vim
:unlet b:npm_module_names
```
## Feedback
[feedback or advice or feature-request](https://github.com/myhere/vim-nodejs-complete/issues)

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,296 @@
" Vim completion script
" Language: Javascript(node)
" Maintainer: Lin Zhang ( myhere.2009 AT gmail DOT com )
" Last Change: 2012-8-18 1:32:00
" save current dir
let s:nodejs_doc_file = expand('<sfile>:p:h') . '/nodejs-doc.vim'
function! nodejscomplete#CompleteJS(findstart, base)
if a:findstart
if exists('g:node_usejscomplete') && g:node_usejscomplete
let start = jscomplete#CompleteJS(a:findstart, a:base)
else
let start = javascriptcomplete#CompleteJS(a:findstart, a:base)
endif
" complete context
let line = getline('.')
let b:nodecompl_context = line[0:start-1]
"Decho 'start: ' . start
return start
else
let nodeCompl = s:findNodeComplete(a:base)
if exists('g:node_usejscomplete') && g:node_usejscomplete
let jsCompl = jscomplete#CompleteJS(a:findstart, a:base)
else
let jsCompl = javascriptcomplete#CompleteJS(a:findstart, a:base)
endif
return nodeCompl + jsCompl
endif
endfunction
" complete node's build-in module
function! s:findNodeComplete(base)
" get complete context
let context = b:nodecompl_context
unlet b:nodecompl_context
"Decho 'context: ' . context
"Decho 'base: ' . a:base
let ret = []
" get object name
let obj_name = matchstr(context, '\k\+\ze\.$')
if (len(obj_name) == 0) " variable complete
let ret = s:getVariableComplete(context, a:base)
else " module complete
"Decho 'obj_name: ' . obj_name
" get variable declared line number
let decl_line = search(obj_name . '\s*=\s*require\s*(.\{-})', 'bn')
"Decho 'decl_line: ' . decl_line
if (decl_line == 0)
" maybe a global module
let ret = s:getModuleComplete(obj_name, a:base, 'globals')
else
" find the node module name
let mod_name = matchstr(getline(decl_line), obj_name . '\s*=\s*require\s*(\s*\([''"]\)\zs.\{-}\ze\(\1\)\s*)')
if exists('mod_name')
let ret = s:getModuleComplete(mod_name, a:base, 'modules')
endif
endif
endif
return ret
endfunction
function! s:getModuleComplete(mod_name, prop_name, type)
"Decho 'mod_name: ' . a:mod_name
"Decho 'prop_name: ' . a:prop_name
"Decho 'type: ' . a:type
call s:loadNodeDocData()
let ret = []
let mods = {}
let mod = []
if (has_key(g:nodejs_complete_data, a:type))
let mods = g:nodejs_complete_data[a:type]
endif
if (has_key(mods, a:mod_name))
let mod = mods[a:mod_name]
endif
" no prop_name suplied
if (len(a:prop_name) == 0)
let ret = mod
else
" filter properties with prop_name
let ret = filter(copy(mod), 'v:val["word"] =~# "' . a:prop_name . '"')
endif
"Decho string(ret)
return ret
endfunction
function! s:getVariableComplete(context, var_name)
"Decho 'var_name: ' . a:var_name
" complete require's arguments
let matched = matchlist(a:context, 'require\s*(\s*\%(\([''"]\)\(\.\{1,2}.*\)\=\)\=$')
if (len(matched) > 0)
"Decho 'require: ' . string(matched)
if (len(matched[2]) > 0) " complete -> require('./
let mod_names = s:getModuleInCurrentDir(a:context, a:var_name, matched)
else
let mod_names = s:getModuleNames()
if (len(matched[1]) == 0) " complete -> require(
call map(mod_names, '"''" . v:val . "'')"')
elseif (len(a:var_name) == 0) " complete -> require('
call map(mod_names, 'v:val . "' . escape(matched[1], '"') . ')"')
else " complete -> require('ti
let mod_names = filter(mod_names, 'v:val =~# "^' . a:var_name . '"')
call map(mod_names, 'v:val . "' . escape(matched[1], '"') . ')"')
endif
endif
return mod_names
endif
" complete global variables
let vars = []
if (len(a:var_name) == 0)
return vars
endif
call s:loadNodeDocData()
if (has_key(g:nodejs_complete_data, 'vars'))
let vars = g:nodejs_complete_data.vars
endif
let ret = filter(copy(vars), 'v:val["word"] =~# "^' . a:var_name . '"')
return ret
endfunction
function! s:getModuleInCurrentDir(context, var_name, matched)
let mod_names = []
let path = a:matched[2] . a:var_name
" typed as require('..
" complete as require('../
" cause the latter one is more common
let compl_prefix = ''
if (path =~# '\.\.$')
let compl_prefix = '/'
let path = path . compl_prefix
endif
"Decho 'path: ' . path
let current_dir = expand('%:p:h')
let glob_path = current_dir . '/' . path . '*'
let files = s:fuzglob(glob_path)
"Decho 'glob: ' . glob_path
"Decho 'current dir files: ' . string(files)
for file in files
" not '.' and '..'
if ((isdirectory(file) ) || file =~? '\.json$\|\.js$')
let mod_file = file
" directory
if (file !~? '\.json$\|\.js$')
let mod_file = mod_file . '/'
endif
" get complete word
let mod_file = substitute(mod_file, '\', '/', 'g')
let start = len(glob_path) - 1 " substract character '*'
let compl_infix = strpart(mod_file, start)
"Decho 'idx: ' . start
"Decho 'compl_infix: ' . compl_infix
"Decho 'relative file: ' . mod_file
let mod_name = compl_prefix . a:var_name . compl_infix
" file module, not a directory
if (compl_infix !~# '/$')
let mod_name = mod_name . a:matched[1] . ')'
endif
"Decho 'mod_name: ' . mod_name
call add(mod_names, mod_name)
endif
endfor
"Decho 'relative path: ' . path
return mod_names
endfunction
function! s:getModuleNames()
call s:loadNodeDocData()
let mod_names = []
" build-in module name
if (has_key(g:nodejs_complete_data, 'modules'))
let mod_names = keys(g:nodejs_complete_data.modules)
endif
" find module in 'module_dir' folder
if (!exists('b:npm_module_names'))
let current_dir = expand('%:p:h')
let b:npm_module_names = s:getModuleNamesInNode_modulesFolder(current_dir)
endif
let mod_names = mod_names + b:npm_module_names
return sort(mod_names)
endfunction
function! s:getModuleNamesInNode_modulesFolder(current_dir)
" ensure platform coincidence
let base_dir = substitute(a:current_dir, '\', '/', 'g')
"Decho 'base_dir: ' . base_dir
let ret = []
let parts = split(base_dir, '/', 1)
"Decho 'parts: ' . string(parts)
let idx = 0
let len = len(parts)
let sub_parts = []
while idx < len
let sub_parts = add(sub_parts, parts[idx])
let module_dir = join(sub_parts, '/') . '/node_modules'
"Decho 'directory: ' . module_dir
if (isdirectory(module_dir))
let files = s:fuzglob(module_dir . '/*')
"Decho 'node_module files: ' . string(files)
for file in files
if (isdirectory(file) || file =~? '\.json$\|\.js$')
let mod_name = matchstr(file, '[^/\\]\+$')
let ret = add(ret, mod_name)
endif
endfor
endif
let idx = idx + 1
endwhile
"Decho 'npm modules: ' . string(ret)
return ret
endfunction
function! s:loadNodeDocData()
" load node module data
if (!exists('g:nodejs_complete_data'))
" load data from external file
let filename = s:nodejs_doc_file
"Decho 'filename: ' . filename
if (filereadable(filename))
"Decho 'readable'
execute 'so ' . filename
"Decho string(g:nodejs_complete_data)
else
"Decho 'not readable'
endif
endif
endfunction
" copied from FuzzyFinder/autoload/fuf.vim
" returns list of paths.
" An argument for glob() is normalized in order to avoid a bug on Windows.
function! s:fuzglob(expr)
" Substitutes "\", because on Windows, "**\" doesn't include ".\",
" but "**/" include "./". I don't know why.
return split(glob(substitute(a:expr, '\', '/', 'g')), "\n")
endfunction
"
" use plugin Decho(https://github.com/vim-scripts/Decho) for debug
"
" turn off debug mode
" :%s;^\(\s*\)\(Decho\);\1"\2;g
"
" turn on debug mode
" :%s;^\(\s*\)"\(Decho\);\1\2;g
"

View File

@@ -0,0 +1,283 @@
#!/usr/bin/env node
/**
* @author: Lin Zhang ( myhere.2009 AT gmail DOT com )
* @fileoverview: This script for auto-generate nodejs-doc.vim
*/
var util = require('util'),
fs = require('fs'),
path = require('path'),
os = require('os'),
emitter = new (require('events')).EventEmitter();
init();
function init() {
initEvents();
initLoading();
getNodejsDoc();
}
function initEvents() {
// uncatched exception
process.on('uncaughtException', function(err) {
clearLoading();
console.error('Error: ' + err.stack);
});
emitter.on('vimscript/done', function(message) {
clearLoading();
console.log(message);
console.log('Done!');
});
}
function initLoading() {
var chars = [
'-',
'\\',
'|',
'/'
];
var index = 0,
total = chars.length;
initLoading.timer = setInterval(function() {
index = ++index % total;
var c = chars[index];
// clear console
// @see: https://groups.google.com/forum/?fromgroups#!topic/nodejs/i-oqYFVty5I
process.stdout.write('\033[2J\033[0;0H');
console.log('please wait:');
console.log(c);
}, 200);
}
function clearLoading() {
clearInterval(initLoading.timer);
}
function getNodejsDoc() {
var http = require('http');
var req = http.get('http://nodejs.org/api/all.json', function(res){
var chunks = [];
res.on('data', function(chunk) {
chunks.push(chunk);
});
res.on('end', function() {
var buf = Buffer.concat(chunks),
body = buf.toString('utf-8');
extract2VimScript(body);
});
}).on('error', function(e) {
console.error('problem with request: ' + e.message);
});
}
function extract2VimScript(body) {
// for debug
fs.writeFileSync('./nodejs-doc-all.json', body);
var json = JSON.parse(body),
vimObject;
var _globals = sortModuleByName(mergeObject(getModInfo(json.globals), getModInfo(json.vars))),
_moduels = sortModuleByName(getModInfo(json.modules)),
_vars = (getVarInfo(json.vars)).concat(getVarInfo(json.globals)).sort(sortCompleteWord);
vimObject = {
'globals': _globals,
'modules': _moduels,
'vars': _vars
};
var filename = path.join(__dirname, 'nodejs-doc.vim'),
comment = '" this file is auto created by "' + __filename + '", please do not edit it yourself!',
content = 'let g:nodejs_complete_data = ' + JSON.stringify(vimObject),
content = comment + os.EOL + content;
fs.writeFile(filename, content, function(err) {
emitter.emit('vimscript/done', 'write file to "' + filename + '" complete.');
});
// for debug
fs.writeFileSync(filename + '.js', JSON.stringify(vimObject, null, 2));
}
function getModInfo(mods) {
var ret = {};
if (!util.isArray(mods)) {
return ret;
}
mods.forEach(function(mod) {
var list = [];
// methods
var methods = mod.methods || [];
methods.forEach(function(method) {
var item = {};
if (method.type == 'method') {
item.word = method.name + '(';
item.info = method.textRaw;
item.kind = 'f'
list.push(item);
}
});
// properties
var properties = mod.properties || [];
properties.forEach(function(property) {
var item = {};
item.word = property.name;
item.kind = 'm'
list.push(item);
});
// if empty
if (list.length == 0) {
return;
}
// sort items
list = list.sort(sortCompleteWord);
// module name
var mod_name = mod.name;
// invalid module name like 'tls_(ssl)'
// then guess the module name from textRaw 'TLS (SSL)'
if ((/[^_a-z\d\$]/i).test(mod_name)) {
var textRaw = mod.textRaw;
var matched = textRaw.match(/^[_a-z\d\$]+/i);
if (matched) {
var mod_name_len = matched[0].length;
mod_name = mod_name.substr(0, mod_name_len);
}
}
ret[mod_name] = list;
});
return ret;
}
function getVarInfo(vars) {
var ret = [];
if (!util.isArray(vars)) {
return ret;
}
vars.forEach(function(_var) {
// if var is a function
if ((/\([^\(\)]*\)\s*$/).test(_var.textRaw)) {
ret.push({
word: _var.name + '(',
info: _var.textRaw,
kind: 'f'
});
} else {
ret.push({
word: _var.name,
kind: 'v'
});
}
});
// sort
ret = ret.sort(sortCompleteWord);
return ret;
}
// helpers
/**
* @param {Object}
*/
function sortModuleByName(mods) {
var keys = Object.keys(mods);
// sort
keys.sort();
var ret = {};
keys.forEach(function(k) {
ret[k] = mods[k];
});
return ret;
}
/**
* @param {Object}
* @param {Object}
*/
function sortCompleteWord(a, b) {
var a_w = a.word.toLowerCase(),
b_w = b.word.toLowerCase();
return a_w < b_w ? -1 : (a_w > b_w ? 1 : 0);
}
/**
* @desc merge Object
* @arguemnts: {Object}
*
* @return: return the new merged Object
*/
function mergeObject() {
var ret = {},
args = Array.prototype.slice.call(arguments);
args.forEach(function(obj) {
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
ret[p] = obj[p];
}
}
});
return ret;
}
/*************** code below for test ***************
// require complete
var fs = req
var http = require(
var util = require('u
var m1 = require('..
var m1 = require('../
var m2 = require('../auto
var m4 = require('.
var m3 = require('./
var m3 = require('./node
// module methdo complete
var fs = require('fs');
fs.
fs.writ
// global variable complete
var filename = __
mo
cons
console.l
***************************************************/

View File

@@ -0,0 +1,3 @@
if exists('&ofu')
setlocal omnifunc=nodejscomplete#CompleteJS
endif

View File

@@ -0,0 +1,44 @@
setlocal cinkeys-=0#
setlocal indentkeys-=0#
setlocal expandtab
setlocal foldlevel=100
setlocal foldmethod=indent
setlocal list
setlocal noautoindent
setlocal smartindent
setlocal cinwords=if,elif,else,for,while,try,except,finally,def,class,with
setlocal smarttab
setlocal textwidth=78
setlocal colorcolumn=+1
" overwrite status line
setlocal statusline=%<%F\ %{TagInStatusLine()}\ %h%m%r%=%(%l,%c%V%)\ %3p%%
set wildignore+=*.pyc
inoremap # X<BS>#
"set ofu=syntaxcomplete#Complete
"autocmd FileType python setlocal omnifunc=pysmell#Complete
let python_highlight_all=1
"I don't want to have pyflakes errors in qfix, it interfering with Pep8/Pylint
let g:pyflakes_use_quickfix = 0
"Load views for py files
autocmd BufWinLeave *.py mkview
autocmd BufWinEnter *.py silent loadview
finish "end here. all below is just for the record.
" Pylint function, which can be optionally mapped to some keys. Currently
" not used.
if !exists('*<SID>runPyLint')
function <SID>runPyLint()
echohl Statement
echo "Running pylint (ctrl-c to cancel) ..."
echohl Normal
:Pylint
endfunction
endif

View File

@@ -0,0 +1,55 @@
if exists("b:did_pdpep8_functions")
finish " only load once
else
let b:did_pdpep8_functions = 1
endif
if !exists('*s:pdPep8')
function s:pdPep8()
set lazyredraw
" Close any existing cwindows.
cclose
let l:grepformat_save = &grepformat
let l:grepprogram_save = &grepprg
set grepformat&vim
set grepformat&vim
let &grepformat = '%f:%l:%m'
let &grepprg = 'c:\\Python27\\Scripts\\pep8.exe --repeat --ignore=E111'
if &readonly == 0 | update | endif
silent! grep! %
let &grepformat = l:grepformat_save
let &grepprg = l:grepprogram_save
let l:mod_total = 0
let l:win_count = 1
" Determine correct window height
windo let l:win_count = l:win_count + 1
if l:win_count <= 2 | let l:win_count = 4 | endif
windo let l:mod_total = l:mod_total + winheight(0)/l:win_count |
\ execute 'resize +'.l:mod_total
" Open cwindow
execute 'belowright copen '.l:mod_total
nnoremap <buffer> <silent> c :cclose<CR>
set nolazyredraw
redraw!
endfunction
command! Pep8 call s:pdPep8()
endif
if !exists('*s:pdPep8Buf')
function s:pdPep8Buf()
echohl Statement
echo "Running pep8 (ctrl-c to cancel) ..."
echohl Normal
let file = expand('%:p')
"let cmd = 'pylint --reports=n --output-format=text "' . file . '"'
let cmd = 'c:\\Python26\\Scripts\\pep8.exe "' . file . '"'
if has('win32') || has('win64')
let cmd = 'cmd /c "' . cmd . '"'
endif
exec "bel silent new " . file . ".lint"
exec "silent! read! " . cmd
endfunction
command! Pep8buf call s:pdPep8Buf()
endif

102
winrc.vim Normal file
View File

@@ -0,0 +1,102 @@
set fileencoding=utf-8
set runtimepath+=$VIM/vimfiles/bundle_win
set viewoptions=cursor
"set guifont=Consolas:h10:cEASTEUROPE
set guifont=DejaVu_Sans_Mono:h9:cEASTEUROPE
set listchars=tab:>-,trail:.
set guioptions=ceg
set mouse=a
set enc=utf-8
set printoptions=number:y
set pfn=Consolas:h10:cEASTEUROPE
let Tlist_Ctags_Cmd = expand('$VIM/bin/ctags.exe')
let g:tagbar_ctags_bin = expand('$VIM/bin/ctags.exe')
let g:browser = '"c:\Program Files\Mozilla Firefox\firefox.exe"'
autocmd BufWritePre *.spy :StripTrailingWhitespaces
autocmd BufWritePre *.spi :StripTrailingWhitespaces
autocmd BufWritePre *.opl :StripTrailingWhitespaces
autocmd BufRead *.opl set filetype=pd_opl
autocmd BufRead *.py set filetype=python
"CTRL-P
" Don't rely on VCS system, just do stuff relative to current dir. PMX sources
" are too huge
let g:ctrlp_working_path_mode = 0
"Grep
" Note: xargs from GnuWin32 package are unusable with this plugin - it refuses
" to pass find output to the grep. Fortunately, cygwin version (which is
" newer in fact) is working just fine. The only thing that is needed to
" set is to quote arguments passed to find:
let Grep_Shell_Quote_Char='"'
" If for some reason it is needed to use tools from GnuWin32 project, comment
" out following line:
let Grep_Cygwin_Find=1
" and uncomment one below:
"let Grep_Find_Use_Xargs=0
" Note: without xargs processing of the output will be much more slower than
" with it.
if has("gui_running")
highlight SpellBad term=underline gui=undercurl guisp=Orange
endif
"maximize window
au GUIEnter * simalt ~x
function GuiTabLabel()
" add the tab number
let label = '' "'['.tabpagenr()
" count number of open windows in the tab
"let wincount = tabpagewinnr(v:lnum, '$')
"if wincount > 1
" let label .= ', '.wincount
"endif
"let label .= '] '
let buflist = tabpagebuflist(v:lnum)
" add the file name without path information
let n = bufname(buflist[tabpagewinnr(v:lnum) - 1])
let label .= fnamemodify(n, ':t')
" modified since the last save?
for bufnr in buflist
if getbufvar(bufnr, '&modified')
let label .= ' *'
break
endif
endfor
return label
endfunction
set guitablabel=%{GuiTabLabel()}
if exists("g:vim_bin_path")
finish
endif
let g:vim_bin_path = expand($VIM) . '/bin'
" Switch between HG and CVS in vcscommand plugin
function <SID>VCSSwitch()
echohl Statement
if exists("g:VCSTypeOverride")
if g:VCSTypeOverride == "HG"
let g:VCSTypeOverride = "CVS"
echo "Switched to CVS"
else
let g:VCSTypeOverride = "HG"
echo "Switched to HG"
endif
else
let g:VCSTypeOverride = "HG"
echo "Switched to HG"
endif
echohl Normal
endfunction
map <F3> :call <SID>VCSSwitch()<cr>
" vim:ts=4:sw=4:wrap:fdm=marker: