Added features for javascript

JSBeautify (,ff) added and modified to retain position
Slightly changed vimrc for different filetypes
This commit is contained in:
Andrea Mistrali 2012-02-29 09:30:19 +00:00
parent 1f96fcc64a
commit d83cd7bbd4
4 changed files with 1253 additions and 7 deletions

330
vim/indent/javascript.vim Normal file
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\%(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_stringdoc =
\'\<javaScriptDocComment\>'
" 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 string or documentation.
function s:IsInStringOrDocumentation(lnum, col)
return synIDattr(synID(a:lnum, a:col, 1), 'name') =~ s:syng_stringdoc
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(line)
" 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 + a:width
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 have a /* or */ set indent to first column.
if match(line, '^\s*\%(/\*\|\*/\)$') != -1
return 0
endif
" If we are in a multi-line string or line-comment, don't do anything to it.
if s:IsInStringOrDocumentation(v:lnum, matchend(line, '^\s*') + 1)
return indent('.')
endif
" 3.3. Work on the previous line. {{{2
" -------------------------------
" 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 != prevnonblank(v:lnum - 1)
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:

629
vim/plugin/jsbeautify.vim Normal file
View File

@ -0,0 +1,629 @@
if &cp || exists("loaded_jsbeautify")
finish
endif
let loaded_jsbeautify = 3
function! s:trim_output()
while len(s:output) > 0 && (s:output[len(s:output)-1] == " " || s:output[len(s:output)-1] == s:indent_string)
call remove(s:output, -1)
endwhile
endfunction
function! s:print_newline(ignore_repeated)
let s:if_line_flag = 0
call s:trim_output()
if len(s:output)==0
return
endif
if s:output[len(s:output)-1] != "\n" || !a:ignore_repeated
call add(s:output, "\n")
endif
let index = 0
while index < s:indent_level
call add(s:output, s:indent_string)
let index += 1
endwhile
endfunction
function! s:print_space()
let last_output = " "
if len(s:output) > 0
let last_output = s:output[len(s:output) - 1]
endif
if last_output != " " && last_output != "\n" && last_output != s:indent_string
call add(s:output, " ")
endif
endfunction
function! s:print_token()
call add(s:output, s:token_text)
endfunctio
function! s:indent()
let s:indent_level += 1
endfunction
function! s:unindent()
if s:indent_level
let s:indent_level -= 1
endif
endfunction
function! s:remove_indent()
if len(s:output)>0 && s:output[len(s:output) -1] == s:indent_string
call remove(s:output, -1)
endif
endfunction
function! s:set_mode(mode)
call add(s:modes, s:current_mode)
let s:current_mode = a:mode
endfunction
function! s:restore_mode()
if s:current_mode == "DO_BLOCK"
let s:do_block_just_closed = 1
else
let s:do_block_just_closed = 0
endif
let s:current_mode = remove(s:modes, -1)
endfunction
function! s:in_array(what, arr)
return index(a:arr, a:what) != -1
endfunction
function! s:get_next_token()
let n_newlines = 0
if s:parser_pos >= len(s:input)
return ["", "TK_EOF"]
endif
let c = s:input[s:parser_pos]
let s:parser_pos += 1
while s:in_array(c, s:whitespace)
if s:parser_pos >= len(s:input)
return ["", "TK_EOF"]
endif
if c == "\n"
let n_newlines += 1
endif
let c = s:input[s:parser_pos]
let s:parser_pos += 1
endwhile
let wanted_newline = 0
if s:opt_preserve_newlines
if n_newlines > 1
for i in [0, 1]
call s:print_newline(i==0)
endfor
endif
let wanted_newline = n_newlines == 1
endif
if s:in_array(c, s:wordchar)
if s:parser_pos < len(s:input)
while s:in_array(s:input[s:parser_pos], s:wordchar)
let c .= s:input[s:parser_pos]
let s:parser_pos += 1
if s:parser_pos == len(s:input)
break
endif
endwhile
endif
"if s:parser_pos != len(s:input) && c =~ /^[0-9]+[Ee]$/ && (s:input[s:parser_pos] == "-" || s:input[s:parser_pos] == "+")
"let sign = s:input[s:parser_pos]
"let s:parser_pos += 1
"let t = get_next_token(s:parser_pos)
"let c .= sign . t[0]
"return [c, "TK_WORD"]
" endif
if c == "in"
return [c, "TK_OPERATOR"]
endif
if wanted_newline && s:last_type != "TK_OPERATOR" && !s:if_line_flag
call s:print_newline(1)
endif
return [c, "TK_WORD"]
endif
if c == "(" || c == "["
return [c, "TK_START_EXPR"]
endif
if c == ")" || c == "]"
return [c, "TK_END_EXPR"]
endif
if c == "{"
return [c, "TK_START_BLOCK"]
endif
if c == "}"
return [c, "TK_END_BLOCK"]
endif
if c == ";"
return [c, "TK_SEMICOLON"]
endif
if c == "/"
let comment = ""
if s:input[s:parser_pos] == "*"
let s:parser_pos += 1
if s:parser_pos < len(s:input)
while !(s:input[s:parser_pos] == "*" && s:parser_pos + 1 < len(s:input) && s:input[s:parser_pos + 1] == "/" && s:parser_pos < len(s:input))
let comment .= s:input[s:parser_pos]
let s:parser_pos += 1
if s:parser_pos >= len(s:input)
break
endif
endwhile
endif
let s:parser_pos += 2
return ['/*' . comment . '*/', 'TK_BLOCK_COMMENT']
endif
" peek for comment // ...
if s:input[s:parser_pos] == "/"
let comment = c
while s:input[s:parser_pos] != "\r" && s:input[s:parser_pos] != "\n"
let comment .= s:input[s:parser_pos]
let s:parser_pos += 1
if s:parser_pos >= len(s:input)
break
endif
endwhile
let s:parser_pos += 1
if wanted_newline
call s:print_newline(1)
endif
return [comment, "TK_COMMENT"]
endif
endif
if c == "'" || c =='"' || (c == "/" && ((s:last_type == "TK_WORD" && s:last_text == "return") || (s:last_type == "TK_START_EXPR" || s:last_type == "TK_START_BLOCK" || s:last_type == "TK_END_BLOCK" || s:last_type == "TK_OPERATOR" || s:last_type == "TK_EOF" || s:last_type == "TK_SEMICOLON")))
let sep = c
let esc = 0
let resulting_string = c
if s:parser_pos < len(s:input)
while esc || s:input[s:parser_pos] != sep
let resulting_string .= s:input[s:parser_pos]
if !esc
let esc = s:input[s:parser_pos] == "\\"
else
let esc = 0
endif
let s:parser_pos += 1
if s:parser_pos >= len(s:input)
return [resulting_string, "TK_STRING"]
endif
endwhile
endif
let s:parser_pos += 1
let resulting_string .= sep
if sep == "/"
while s:parser_pos < len(s:input) && s:in_array(s:input[s:parser_pos], s:wordchar)
let resulting_string .= s:input[s:parser_pos]
let s:parser_pos += 1
endwhile
endif
return [resulting_string, "TK_STRING"]
endif
if c == "#"
let sharp = "#"
if s:parser_pos < len(s:input) && s:in_array(s:input[s:parser_pos], s:digits)
let c = s:input[s:parser_pos]
let sharp .= c
let s:parser_pos += 1
while s:parser_pos < len(s:input) && c != "#" && c !="="
let c = s:input[s:parser_pos]
let sharp .= c
let s:parser_pos += 1
endwhile
if c == "#"
return [sharp, "TK_WORD"]
else
return [sharp, "TK_OPERATOR"]
endif
endif
endif
if c == "<" && s:input[s:parser_pos-1 : s:parser_pos+3] == "<!--"
let s:parser_pos += 3
return ["<!--", "TK_COMMENT"]
endif
if c == "-" && s:input[s:parser_pos-1 : s:parser_pos+2] == "-->"
let s:parser_pos += 2
if wanted_newline
call s:print_newline(1)
endif
return ["-->", "TK_COMMENT"]
endif
if s:in_array(c, s:punct)
while s:parser_pos < len(s:input) && s:in_array(c . s:input[s:parser_pos], s:punct)
let c .= s:input[s:parser_pos]
let s:parser_pos += 1
if s:parser_pos >= len(s:input)
break
endif
endwhile
return [c, "TK_OPERATOR"]
endif
return [c, "TK_UNKNOWN"]
endif
endfunction
function! s:is_js()
return expand("%:e") == "js"
endfunction
"function! g:Jsbeautify(js_source_text, options)
function! g:Jsbeautify()
if !s:is_js()
echo "Not a JS file."
return
endif
"let a:options = {}
let s:opt_indent_size = 1
let s:opt_indent_char = "\t"
let s:opt_preserve_newlines = 1
let s:opt_indent_level = 0
let s:if_line_flag = 0
"--------------------------------
let s:indent_string = ""
while s:opt_indent_size > 0
let s:indent_string .= s:opt_indent_char
let s:opt_indent_size -= 1
endwhile
let s:indent_level = s:opt_indent_level
let lines = getline(1, "$")
let s:input = join(lines, "\n")
"let s:input = a:js_source_text
let s:last_word = "" "last 'TK_WORD' passed
let s:last_type = "TK_START_EXPR" "last token type
let s:last_text = "" "last token text
let s:output = []
let s:do_block_just_closed = 0
let s:var_line = 0
let s:var_line_tainted = 0
let s:whitespace = ["\n", "\r", "\t", " "]
let s:wordchar = split("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$", '\zs')
let s:digits = split("0123456789", '\zs')
"<!-- is a special case (ok, it"s a minor hack actually)
let s:punct = split("+ - * / % & ++ -- = += -= *= /= %= == === != !== > < >= <= >> << >>> >>>= >>= <<= && &= | || ! !! , : ? ^ ^= |= ::", " ")
let s:line_starters = split("continue,try,throw,return,var,if,switch,case,default,for,while,break", ",")
let s:current_mode = "BLOCK"
let s:modes = [s:current_mode]
let s:parser_pos = 0
let s:in_case = 0
while 1
let t = s:get_next_token()
let s:token_text = t[0]
let s:token_type = t[1]
if s:token_type == "TK_EOF"
break
endif
try
if s:token_type == "TK_START_EXPR"
let s:var_line = 0
call s:set_mode("EXPRESSION")
if s:last_text == ";"
call s:print_newline(1)
elseif s:last_type == "TK_END_EXPR" || s:last_type == "TK_START_EXPR"
" do nothing on (( and )( and ][ and ]( ..
elseif s:last_type != "TK_WORD" && s:last_type != "TK_OPERATOR"
call s:print_space()
elseif s:in_array(s:last_word, s:line_starters)
call s:print_space()
endif
call s:print_token()
elseif s:token_type == "TK_END_EXPR"
call s:print_token()
call s:restore_mode()
elseif s:token_type == "TK_START_BLOCK"
if s:last_word == "do"
call s:set_mode("DO_BLOCK")
else
call s:set_mode("BLOCK")
endif
if s:last_type != "TK_OPERATOR" && s:last_type != "TK_START_EXPR"
if s:last_type == "TK_START_BLOCK"
call s:print_newline(1)
else
call s:print_space()
endif
endif
call s:print_token()
call s:indent()
elseif s:token_type == "TK_END_BLOCK"
if s:last_type == "TK_START_BLOCK"
call s:remove_indent()
call s:unindent()
else
call s:unindent()
call s:print_newline(1)
endif
call s:print_token()
call s:restore_mode()
elseif s:token_type == "TK_WORD"
if s:do_block_just_closed
" do {} ## while ()
call s:print_space()
call s:print_token()
call s:print_space()
let s:do_block_just_closed = 0
throw "jump out"
endif
if s:token_text == "case" || s:token_text == "default"
if s:last_text == ":"
"switch cases following one another
call s:remove_indent()
else
" case statement starts in the same line where switch
call s:unindent()
call s:print_newline(1)
call s:indent()
endif
call s:print_token()
let s:in_case = 1
throw "jump out"
endif
let s:prefix = "NONE"
if s:last_type == "TK_END_BLOCK"
if !s:in_array(tolower(s:token_text), ["else", "catch", "finally"])
let s:prefix = "NEWLINE"
else
let s:prefix = "SPACE"
call s:print_space()
endif
elseif s:last_type == "TK_SEMICOLON" && (s:current_mode == "BLOCK" || s:current_mode == "DO_BLOCK")
let s:prefix = "NEWLINE"
elseif s:last_type == "TK_SEMICOLON" && s:current_mode == "EXPRESSION"
let s:prefix = "SPACE"
elseif s:last_type == "TK_STRING"
let s:prefix = "NEWLINE"
elseif s:last_type == "TK_WORD"
let s:prefix = "SPACE"
elseif s:last_type == "TK_START_BLOCK"
let s:prefix = "NEWLINE"
elseif s:last_type == "TK_END_EXPR"
call s:print_space()
let s:prefix = "NEWLINE"
endif
if s:last_type != "TK_END_BLOCK" && s:in_array(tolower(s:token_text), ["else", "catch", "finally"])
call s:print_newline(1)
elseif s:in_array(s:token_text, s:line_starters) || s:prefix == "NEWLINE"
if s:last_text == "else"
call s:print_space()
elseif (s:last_type == "TK_START_EXPR" || s:last_text == "=" || s:last_text == ",") && s:token_text == "function"
" no need to force newline on "function":
" DONOTHINT
elseif s:last_type == "TK_WORD" && (s:last_text == "return" || s:last_text == "throw")
" no newline between "return nnn"
call s:print_space()
elseif s:last_type != "TK_END_EXPR"
if (s:last_type != "TK_START_EXPR" || s:token_text != "var") && s:last_text != ":"
" no need to force newline on "var": for (var
" x = 0...)
if s:token_text == "if" && s:last_type == "TK_WORD" && s:last_word == "else"
" no newline for } else if {
call s:print_space()
else
call s:print_newline(1)
endif
endif
else
if s:in_array(s:token_text, s:line_starters) && s:last_text != ")"
call s:print_newline(1)
endif
endif
elseif s:prefix == "SPACE"
call s:print_space()
endif
call s:print_token()
let s:last_word = s:token_text
if s:token_text == "var"
let s:var_line = 1
let s:var_line_tainted = 0
endif
if s:token_text == "if" || s:token_text == "else"
let s:if_line_flag = 1
endif
elseif s:token_type == "TK_SEMICOLON"
call s:print_token()
let s:var_line = 0
elseif s:token_type == "TK_STRING"
if s:last_type == "TK_START_BLOCK" || s:last_type == "TK_END_BLOCK" || s:last_type == "TK_SEMICOLON"
call s:print_newline(1)
elseif s:last_type == "TK_WORD"
call s:print_space()
endif
call s:print_token()
elseif s:token_type == "TK_OPERATOR"
let start_delim = 1
let end_delim = 1
if s:var_line && s:token_text != ","
let s:var_line_tainted = 1
if s:token_text == ":"
let s:var_line = 0
endif
endif
if s:var_line && s:token_text=="," && s:current_mode == "EXPRESSION"
" do not break on comma, for(var a = 1, b = 2)
let s:var_line_tainted = 0
endif
if s:token_text == ":" && s:in_case
call s:print_token()
call s:print_newline(1)
throw "jump out"
endif
if s:token_text == "::"
" no spaces around exotic namespacing syntax operator
call s:print_token()
throw "jump out"
endif
let s:in_case = 0
if s:token_text == ","
if s:var_line
if s:var_line_tainted
call s:print_token()
call s:print_newline(1)
let s:var_line_tainted = 0
else
call s:print_token()
call s:print_space()
endif
elseif s:last_type == "TK_END_BLOCK"
call s:print_token()
call s:print_newline(1)
else
if s:current_mode == "BLOCK"
call s:print_token()
call s:print_newline(1)
else
" EXPR od DO_BLOCK
call s:print_token()
call s:print_space()
endif
endif
throw "jump out"
elseif s:token_text == "--" || s:token_text == "++" " unary operators special case
if s:last_text == ";"
" space for (;; ++i)
let start_delim = 1
let end_delim = 0
else
let start_delim = 0
let end_delim = 0
endif
elseif s:token_text == "!" && s:last_type == "TK_START_EXPR"
" special case handling: if (!a)
let start_delim = 0
let end_delim = 0
elseif s:last_type == "TK_OPERATOR"
let s:start_delim = 0
let s:end_delim = 0
elseif s:last_type == "TK_END_EXPR"
let s:start_delim = 1
let s:end_delim = 1
elseif s:token_text == "."
" decimal digits or object.property
let start_delim = 0
let end_delim = 0
elseif s:token_text == ":"
" zz: xx
" can"t differentiate ternary op, so for now it"s a ? b:
" c;without space before colon
if s:last_text =~ '/^\d+$/'
" a little help for ternary a ? 1 : 0
let start_delim = 1
else
let start_delim = 0
endif
endif
if start_delim
call s:print_space()
endif
call s:print_token()
if end_delim
call s:print_space()
endif
throw "jump out"
elseif s:token_type == "TK_BLOCK_COMMENT"
call s:print_newline(1)
call s:print_token()
call s:print_newline(1)
elseif s:token_type == "TK_COMMENT"
"call s:print_newline(1)
call s:print_space()
call s:print_token()
call s:print_newline(1)
elseif s:token_type == "TK_UNKNOWN"
call s:print_token()
throw "jump out"
endif
catch /.*/
if v:exception != 'jump out'
echo "exception caught: " v:exception
endif
endtry
let s:last_type = s:token_type
let s:last_text = s:token_text
endwhile
" mark position
let save_cursor = getpos(".")
let ret = join(s:output, "")
:g/.*/d
let @0 = ret
:put!0
" go back
call setpos('.', save_cursor)
endfunction
nnoremap <silent> <leader>ff :call g:Jsbeautify()<cr>

246
vim/syntax/javascript.vim Normal file
View File

@ -0,0 +1,246 @@
" Vim syntax file
" Language: JavaScript
" Maintainer: Yi Zhao (ZHAOYI) <zzlinux AT hotmail DOT com>
" Last Change: June 4, 2009
" Version: 0.7.7
" Changes: Add "undefined" as a type keyword
"
" 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 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 sigh 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 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 support start
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
syntax match javaScriptDocTags contained "@\(param\|argument\|requires\|exception\|throws\|type\|class\|extends\|see\|link\|member\|module\|method\|title\|namespace\|optional\|default\|base\|file\)\>" nextgroup=javaScriptDocParam,javaScriptDocSeeTag skipwhite
syntax match javaScriptDocTags contained "@\(beta\|deprecated\|description\|fileoverview\|author\|license\|version\|returns\=\|constructor\|private\|protected\|final\|ignore\|addon\|exec\)\>"
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 javaScriptRegexpString start=+/\(\*\|/\)\@!+ skip=+\\\\\|\\/+ end=+/[gim]\{,3}+ contains=javaScriptSpecial,@htmlPreproc oneline
syntax match javaScriptNumber /\<-\=\d\+L\=\>\|\<0[xX]\x\+\>/
syntax match javaScriptFloat /\<-\=\%(\d\+\.\d\+\|\d\+\.\|\.\d\+\)\%([eE][+-]\=\d\+\)\=\>/
syntax match javaScriptLabel /\(?\s*\)\@<!\<\w\+\(\s*:\)\@=/
"" JavaScript Prototype
syntax keyword javaScriptPrototype prototype
"" Programm Keywords
syntax keyword javaScriptSource import export
syntax keyword javaScriptType const this undefined var void yield
syntax keyword javaScriptOperator delete new in instanceof let typeof
syntax keyword javaScriptBoolean true false
syntax keyword javaScriptNull null
"" 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 const 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
syntax cluster javaScriptAll contains=javaScriptComment,javaScriptLineComment,javaScriptDocComment,javaScriptStringD,javaScriptStringS,javaScriptRegexpString,javaScriptNumber,javaScriptFloat,javaScriptLabel,javaScriptSource,javaScriptType,javaScriptOperator,javaScriptBoolean,javaScriptNull,javaScriptFunction,javaScriptConditional,javaScriptRepeat,javaScriptBranch,javaScriptStatement,javaScriptGlobalObjects,javaScriptExceptions,javaScriptFutureKeys,javaScriptDomErrNo,javaScriptDomNodeConsts,javaScriptHtmlEvents,javaScriptDotNotation
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
"" 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
if &l:filetype=='javascript' && !&diff
" Fold setting
" Redefine the foldtext (to show a JS function outline) and foldlevel
" only if the entire buffer is JavaScript, but not if JavaScript syntax
" is embedded in another syntax (e.g. HTML).
setlocal foldmethod=syntax
setlocal foldlevel=4
endif
else
syntax keyword javaScriptFunction function
setlocal foldmethod<
setlocal foldlevel<
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 javaScriptDocComment Comment
HiLink javaScriptCommentTodo Todo
HiLink javaScriptCvsTag Function
HiLink javaScriptDocTags Special
HiLink javaScriptDocSeeTag Function
HiLink javaScriptDocParam Function
HiLink javaScriptStringS String
HiLink javaScriptStringD String
HiLink javaScriptRegexpString String
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 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
let b:current_syntax = "javascript"
if main_syntax == 'javascript'
unlet main_syntax
endif
" vim: ts=4

View File

@ -12,7 +12,7 @@ set history=50
set nohlsearch set nohlsearch
set nostartofline set nostartofline
" set paste " set paste
" set autochdir set autochdir
" Let's go to 256 colors " Let's go to 256 colors
set t_Co=256 set t_Co=256
@ -46,7 +46,7 @@ set cpoptions=aAcF$
set modeline set modeline
set modelines=1 set modelines=1
set encoding=utf-8 set encoding=utf-8
set listchars=tab:->,trail:.,eol:$ set listchars=tab:->,trail:.,eol:$,extends:>,precedes:<
set smartcase set smartcase
set errorbells set errorbells
" set visualbell " set visualbell
@ -200,19 +200,60 @@ if has("autocmd")
\ exe "normal g'\"" | \ exe "normal g'\"" |
\ endif \ endif
" Mako " Mako
autocmd BufNewFile,BufRead *.mako setf mako tw=0 autocmd BufNewFile,BufRead *.mako setf mako
autocmd FileType *.mako set textwidth=0
" Python " Python
autocmd BufNewFile,BufRead *.py set textwidth=79 autocmd FileType python set textwidth=79
autocmd FileType python set omnifunc=pythoncomplete#Complete
" Plist " Plist
autocmd BufReadPre,FileReadPre *.plist set binary ft=plist syntax=xml autocmd BufReadPre,FileReadPre *.plist setf plist
autocmd FileType plist set binary syntax=xml
autocmd BufReadPost *.plist call MyBinaryPlistReadPost() autocmd BufReadPost *.plist call MyBinaryPlistReadPost()
autocmd FileReadPost *.plist call MyBinaryPlistReadPost() | let b:saveAsBinaryPlist = 0 autocmd FileReadPost *.plist call MyBinaryPlistReadPost() | let b:saveAsBinaryPlist = 0
autocmd BufWritePre,FileWritePre *.plist call MyBinaryPlistWritePre() autocmd BufWritePre,FileWritePre *.plist call MyBinaryPlistWritePre()
autocmd BufWritePost,FileWritePost *.plist call MyBinaryPlistWritePost() autocmd BufWritePost,FileWritePost *.plist call MyBinaryPlistWritePost()
" Plain text " Plain text
autocmd BufNewFile,BufRead *.txt set ft=txt tw=78 pfn=:h10 autocmd BufNewFile,BufRead *.txt setf txt
autocmd FileType txt set textwidth=78 printfont=:h10
" Javascript
autocmd FileType javascript set sw=4 ts=4 sts=4
autocmd FileType javascript set omnifunc=javascriptcomplete#CompleteJS
" Transparent editing of gpg encrypted files.
augroup encrypted
au!
" First make sure nothing is written to ~/.viminfo while editing
" an encrypted file.
autocmd BufReadPre,FileReadPre *.gpg,*.asc set viminfo=
" We don't want a swap file, as it writes unencrypted data to disk
autocmd BufReadPre,FileReadPre *.gpg,*.asc set noswapfile
" Switch to binary mode to read the encrypted file
autocmd BufReadPre,FileReadPre *.gpg,*.asc set bin
autocmd BufReadPre,FileReadPre *.gpg,*.asc let ch_save = &ch|set ch=2
autocmd BufReadPre,FileReadPre *.gpg,*.asc let shsave=&sh
autocmd BufReadPre,FileReadPre *.gpg,*.asc let &sh='sh'
autocmd BufReadPre,FileReadPre *.gpg,*.asc let ch_save = &ch|set ch=2
autocmd BufReadPost,FileReadPost *.gpg,*.asc '[,']!gpg2 --decrypt --default-recipient-self 2> /dev/null
autocmd BufReadPost,FileReadPost *.gpg,*.asc let &sh=shsave
" Switch to normal mode for editing
autocmd BufReadPost,FileReadPost *.gpg,*.asc set nobin
autocmd BufReadPost,FileReadPost *.gpg,*.asc let &ch = ch_save|unlet ch_save
autocmd BufReadPost,FileReadPost *.gpg,*.asc execute ":doautocmd BufReadPost " . expand("%:r")
" Convert all text to encrypted text before writing
autocmd BufWritePre,FileWritePre *.gpg,*.asc set bin
autocmd BufWritePre,FileWritePre *.gpg,*.asc let shsave=&sh
autocmd BufWritePre,FileWritePre *.gpg,*.asc let &sh='sh'
" GPG Binary
autocmd BufWritePre,FileWritePre *.gpg '[,']!gpg2 --encrypt --default-recipient-self 2>/dev/null
" GPG Ascii armor
autocmd BufWritePre,FileWritePre *.asc '[,']!gpg2 --armor --encrypt --default-recipient-self 2>/dev/null
autocmd BufWritePre,FileWritePre *.gpg,*.asc let &sh=shsave
" Undo the encryption so we are back in the normal text, directly
" after the file has been written.
autocmd BufWritePost,FileWritePost *.gpg,*.asc silent u
autocmd BufWritePost,FileWritePost *.gpg,*.asc set nobin
augroup END
endif endif
""" iTerm 2 Custom cursor shape """ iTerm 2 Custom cursor shape