mirror of
1
0
Fork 0

Updated plugins

This commit is contained in:
amix 2015-03-14 20:02:10 +00:00
parent d195ccb777
commit 2cb073a57d
73 changed files with 1098 additions and 525 deletions

View File

@ -53,17 +53,17 @@ are detected, the user is notified and is happy because they didn't have to
compile their code or execute their script to find them. compile their code or execute their script to find them.
At the time of this writing, syntastic has checking plugins for ActionScript, At the time of this writing, syntastic has checking plugins for ActionScript,
Ada, AppleScript, AsciiDoc, ASM, BEMHTML, Bro, Bourne shell, C, C++, C#, Cabal, Ada, API Blueprint, AppleScript, AsciiDoc, ASM, BEMHTML, Bro, Bourne shell,
Chef, CoffeeScript, Coco, Coq, CSS, Cucumber, CUDA, D, Dart, DocBook, Dust, C, C++, C#, Cabal, Chef, CoffeeScript, Coco, Coq, CSS, Cucumber, CUDA, D,
Elixir, Erlang, eRuby, Fortran, Gentoo metadata, GLSL, Go, Haml, Haskell, Dart, DocBook, Dust, Elixir, Erlang, eRuby, Fortran, Gentoo metadata, GLSL,
Haxe, Handlebars, HSS, HTML, Java, JavaScript, JSON, JSX, LESS, Lex, Limbo, Go, Haml, Haskell, Haxe, Handlebars, HSS, HTML, Java, JavaScript, JSON, JSX,
LISP, LLVM intermediate language, Lua, Markdown, MATLAB, NASM, Objective-C, LESS, Lex, Limbo, LISP, LLVM intermediate language, Lua, Markdown, MATLAB,
Objective-C++, OCaml, Perl, Perl POD, PHP, gettext Portable Object, OS X and NASM, Objective-C, Objective-C++, OCaml, Perl, Perl POD, PHP, gettext Portable
iOS property lists, Puppet, Python, R, Racket, Relax NG, reStructuredText, RPM Object, OS X and iOS property lists, Puppet, Python, R, Racket, Relax NG,
spec, Ruby, SASS/SCSS, Scala, Slim, SML, Tcl, TeX, Texinfo, Twig, TypeScript, reStructuredText, RPM spec, Ruby, SASS/SCSS, Scala, Slim, SML, Tcl, TeX,
Vala, Verilog, VHDL, VimL, xHtml, XML, XSLT, YACC, YAML, z80, Zope page Texinfo, Twig, TypeScript, Vala, Verilog, VHDL, VimL, xHtml, XML, XSLT, YACC,
templates, and zsh. See the [wiki][3] for details about the corresponding YAML, z80, Zope page templates, and zsh. See the [wiki][3] for details about
supported checkers. the corresponding supported checkers.
A number of third-party Vim plugins also provide checkers for syntastic, A number of third-party Vim plugins also provide checkers for syntastic,
for example: [omnisharp-vim][25], [rust.vim][12], [syntastic-extras][26], for example: [omnisharp-vim][25], [rust.vim][12], [syntastic-extras][26],
@ -196,10 +196,24 @@ which checkers are enabled. You can tell syntastic which checkers (among the
available ones) you want to run by setting `g:syntastic_<filetype>_checkers` in available ones) you want to run by setting `g:syntastic_<filetype>_checkers` in
your `vimrc` (see [below](#faqcheckers)). your `vimrc` (see [below](#faqcheckers)).
Another reason it could fail is that either the command line options or the A third possible reason is that the `$PATH` seen by syntastic might not be same
error output for a syntax checker may have changed. In this case, make sure you as the `$PATH` in your login shell. Syntastic runs checkers using the shell
have the latest version of the syntax checker installed. If it still fails then pointed to by Vim's `shell` (or by `g:syntastic_shell`, if set), and that's the
post an [issue][4] - or better yet, create a pull request. shell you need to configure to set the proper `$PATH` and environment variables
for your checkers. You can see syntastic's idea of `$PATH` by running
```vim
:echo syntastic#util#system('echo "$PATH"')
```
on UNIX and Mac OS-X systems, or
```vim
:echo syntastic#util#system('echo %PATH%')
```
on Windows.
Finally, another reason it could fail is that either the command line options
or the error output for a syntax checker may have changed. In this case, make
sure you have the latest version of the syntax checker installed. If it still
fails then post an [issue][4] - or better yet, create a pull request.
<a name="faqpython3"></a> <a name="faqpython3"></a>
@ -217,8 +231,10 @@ __4.3. Q. Are there any local checkers for HTML5 that I can use with syntastic?_
[HTML Tidy][18] has a fork named [HTML Tidy for HTML5][19]. It's a drop [HTML Tidy][18] has a fork named [HTML Tidy for HTML5][19]. It's a drop
in replacement, and syntastic can use it without changes. Just install it in replacement, and syntastic can use it without changes. Just install it
somewhere and point `g:syntastic_html_tidy_exec` to its executable. somewhere and point `g:syntastic_html_tidy_exec` to its executable:
```vim
let g:syntastic_html_tidy_exec = 'tidy5'
```
Alternatively, you can install [vnu.jar][21] from the [validator.nu][20] Alternatively, you can install [vnu.jar][21] from the [validator.nu][20]
project and run it as a [HTTP server][23]: project and run it as a [HTTP server][23]:
```sh ```sh
@ -431,7 +447,7 @@ a look at [jedi-vim][7], [python-mode][8], or [YouCompleteMe][9].
[16]: https://github.com/junegunn/vim-plug/ [16]: https://github.com/junegunn/vim-plug/
[17]: https://github.com/gmarik/Vundle.vim [17]: https://github.com/gmarik/Vundle.vim
[18]: http://tidy.sourceforge.net/ [18]: http://tidy.sourceforge.net/
[19]: http://w3c.github.io/tidy-html5/ [19]: http://www.htacg.org/tidy-html5/
[20]: http://about.validator.nu/ [20]: http://about.validator.nu/
[21]: https://github.com/validator/validator/releases/latest [21]: https://github.com/validator/validator/releases/latest
[22]: https://github.com/scrooloose/syntastic/wiki/HTML%3A---validator [22]: https://github.com/scrooloose/syntastic/wiki/HTML%3A---validator

View File

@ -133,7 +133,7 @@ function! s:_checkPackage(name, ...) abort " {{{2
if executable('pkg-config') if executable('pkg-config')
if !has_key(s:cflags, a:name) if !has_key(s:cflags, a:name)
for pkg in a:000 for pkg in a:000
let pkg_flags = system('pkg-config --cflags ' . pkg) let pkg_flags = syntastic#util#system('pkg-config --cflags ' . pkg)
" since we cannot necessarily trust the pkg-config exit code " since we cannot necessarily trust the pkg-config exit code
" we have to check for an error output as well " we have to check for an error output as well
if v:shell_error == 0 && pkg_flags !~? 'not found' if v:shell_error == 0 && pkg_flags !~? 'not found'
@ -153,7 +153,7 @@ endfunction " }}}2
function! s:_checkPhp() abort " {{{2 function! s:_checkPhp() abort " {{{2
if executable('php-config') if executable('php-config')
if !has_key(s:cflags, 'php') if !has_key(s:cflags, 'php')
let s:cflags['php'] = system('php-config --includes') let s:cflags['php'] = syntastic#util#system('php-config --includes')
let s:cflags['php'] = ' ' . substitute(s:cflags['php'], "\n", '', '') let s:cflags['php'] = ' ' . substitute(s:cflags['php'], "\n", '', '')
endif endif
return s:cflags['php'] return s:cflags['php']
@ -165,7 +165,7 @@ endfunction " }}}2
function! s:_checkPython() abort " {{{2 function! s:_checkPython() abort " {{{2
if executable('python') if executable('python')
if !has_key(s:cflags, 'python') if !has_key(s:cflags, 'python')
let s:cflags['python'] = system('python -c ''from distutils import ' . let s:cflags['python'] = syntastic#util#system('python -c ''from distutils import ' .
\ 'sysconfig; import sys; sys.stdout.write(sysconfig.get_python_inc())''') \ 'sysconfig; import sys; sys.stdout.write(sysconfig.get_python_inc())''')
let s:cflags['python'] = substitute(s:cflags['python'], "\n", '', '') let s:cflags['python'] = substitute(s:cflags['python'], "\n", '', '')
let s:cflags['python'] = ' -I' . s:cflags['python'] let s:cflags['python'] = ' -I' . s:cflags['python']
@ -179,7 +179,7 @@ endfunction " }}}2
function! s:_checkRuby() abort " {{{2 function! s:_checkRuby() abort " {{{2
if executable('ruby') if executable('ruby')
if !has_key(s:cflags, 'ruby') if !has_key(s:cflags, 'ruby')
let s:cflags['ruby'] = system('ruby -r rbconfig -e ' . let s:cflags['ruby'] = syntastic#util#system('ruby -r rbconfig -e ' .
\ '''puts RbConfig::CONFIG["rubyhdrdir"] || RbConfig::CONFIG["archdir"]''') \ '''puts RbConfig::CONFIG["rubyhdrdir"] || RbConfig::CONFIG["archdir"]''')
let s:cflags['ruby'] = substitute(s:cflags['ruby'], "\n", '', '') let s:cflags['ruby'] = substitute(s:cflags['ruby'], "\n", '', '')
let s:cflags['ruby'] = ' -I' . s:cflags['ruby'] let s:cflags['ruby'] = ' -I' . s:cflags['ruby']

View File

@ -25,7 +25,26 @@ function! syntastic#util#Slash() abort " {{{2
endfunction " }}}2 endfunction " }}}2
function! syntastic#util#CygwinPath(path) abort " {{{2 function! syntastic#util#CygwinPath(path) abort " {{{2
return substitute(system('cygpath -m ' . syntastic#util#shescape(a:path)), "\n", '', 'g') return substitute(syntastic#util#system('cygpath -m ' . syntastic#util#shescape(a:path)), "\n", '', 'g')
endfunction " }}}2
function! syntastic#util#system(command) abort " {{{2
let old_shell = &shell
let old_lc_messages = $LC_MESSAGES
let old_lc_all = $LC_ALL
let &shell = syntastic#util#var('shell')
let $LC_MESSAGES = 'C'
let $LC_ALL = ''
let out = system(a:command)
let $LC_ALL = old_lc_all
let $LC_MESSAGES = old_lc_messages
let &shell = old_shell
return out
endfunction " }}}2 endfunction " }}}2
" Create a temporary directory " Create a temporary directory
@ -35,7 +54,7 @@ function! syntastic#util#tmpdir() abort " {{{2
if (has('unix') || has('mac')) && executable('mktemp') if (has('unix') || has('mac')) && executable('mktemp')
" TODO: option "-t" to mktemp(1) is not portable " TODO: option "-t" to mktemp(1) is not portable
let tmp = $TMPDIR != '' ? $TMPDIR : $TMP != '' ? $TMP : '/tmp' let tmp = $TMPDIR != '' ? $TMPDIR : $TMP != '' ? $TMP : '/tmp'
let out = split(system('mktemp -q -d ' . tmp . '/vim-syntastic-' . getpid() . '-XXXXXXXX'), "\n") let out = split(syntastic#util#system('mktemp -q -d ' . tmp . '/vim-syntastic-' . getpid() . '-XXXXXXXX'), "\n")
if v:shell_error == 0 && len(out) == 1 if v:shell_error == 0 && len(out) == 1
let tempdir = out[0] let tempdir = out[0]
endif endif
@ -79,7 +98,7 @@ function! syntastic#util#rmrf(what) abort " {{{2
endif endif
if s:rmrf != '' if s:rmrf != ''
silent! call system(s:rmrf . ' ' . syntastic#util#shescape(a:what)) silent! call syntastic#util#system(s:rmrf . ' ' . syntastic#util#shescape(a:what))
else else
call s:_rmrf(a:what) call s:_rmrf(a:what)
endif endif
@ -382,7 +401,7 @@ function! s:_rmrf(what) abort " {{{2
for f in split(globpath(a:what, '*', 1), "\n") for f in split(globpath(a:what, '*', 1), "\n")
call s:_rmrf(f) call s:_rmrf(f)
endfor endfor
silent! call system(s:rmdir . ' ' . syntastic#util#shescape(a:what)) silent! call syntastic#util#system(s:rmdir . ' ' . syntastic#util#shescape(a:what))
else else
silent! call delete(a:what) silent! call delete(a:what)
endif endif

View File

@ -39,16 +39,19 @@ CONTENTS *syntastic-contents*
6.Notes........................................|syntastic-notes| 6.Notes........................................|syntastic-notes|
6.1.Handling of composite filetypes........|syntastic-composite| 6.1.Handling of composite filetypes........|syntastic-composite|
6.2.Editing files over network.............|syntastic-netrw| 6.2.Editing files over network.............|syntastic-netrw|
6.3.Interaction with python-mode...........|syntastic-pymode| 6.3.The 'shellslash' option................|syntastic-shellslash|
6.4.Interaction with YouCompleteMe.........|syntastic-ycm| 7.Compatibility with other software............|syntastic-compatibility|
6.5.Interaction with the fish shell........|syntastic-fish| 7.1.The csh and tcsh shells................|syntastic-csh|
6.6.Interaction with PowerShell............|syntastic-powershell| 7.2.Eclim..................................|syntastic-eclim|
6.7.Using syntastic with the fizsh shell...|syntastic-fizsh| 7.3.The fish shell.........................|syntastic-fish|
6.8.Interaction with Eclim.................|syntastic-eclim| 7.4.The fizsh shell........................|syntastic-fizsh|
6.9.Interaction with vim-virtualenv........|syntastic-vim-virtualenv| 7.5.The PowerShell shell...................|syntastic-powershell|
6.10.Interaction with vim-auto-save........|syntastic-vim-auto-save| 7.6.python-mode............................|syntastic-pymode|
7.About........................................|syntastic-about| 7.7.vim-auto-save..........................|syntastic-vim-auto-save|
8.License......................................|syntastic-license| 7.8.vim-virtualenv.........................|syntastic-vim-virtualenv|
7.9.YouCompleteMe..........................|syntastic-ycm|
8.About........................................|syntastic-about|
9.License......................................|syntastic-license|
============================================================================== ==============================================================================
@ -602,6 +605,20 @@ looking at their exit codes. The "cmd.exe" shell on Windows make these checks
meaningless, by returning 1 to Vim when the checkers exit with non-zero codes. meaningless, by returning 1 to Vim when the checkers exit with non-zero codes.
The above variable can be used to disable exit code checks in syntastic. The above variable can be used to disable exit code checks in syntastic.
*'syntastic_shell'*
Default: Vim's 'shell'
This is the (full path to) the shell syntastic will use to run the checkers.
On UNIX and Mac OS-X this shell must accept Bourne-compatible syntax for
file "stdout" and "stderr" redirections ">file" and "2>file". Examples of
compatible shells are "zsh", "bash", "ksh", and of course the original Bourne
"sh".
This shell is independent of Vim's 'shell', and it isn't used for interactive
operations. It must take care to initialize all environment variables needed
by the checkers you're using. Example: >
let g:syntastic_shell = "/bin/sh"
<
*'syntastic_debug'* *'syntastic_debug'*
Default: 0 Default: 0
Set this to the sum of one or more of the following flags to enable Set this to the sum of one or more of the following flags to enable
@ -782,64 +799,32 @@ of operation. It can only check files that can be accessed directly by local
checkers, without any translation or conversion. checkers, without any translation or conversion.
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
6.3 Interaction with python-mode *syntastic-pymode* 6.3 The 'shellslash' option *syntastic-shellslash*
Syntastic can be used along with the 'python-mode' Vim plugin (see The 'shellslash' option is relevant only on Windows systems. This option
https://github.com/klen/python-mode). However, they both run syntax checks by determines (among other things) the rules for quoting command lines, and there
default when you save buffers to disk, and this is probably not what you want. is no easy way for syntastic to make sure its state is appropriate for your
To avoid both plugins opening error windows, you can either set passive mode shell. It should be turned off if your 'shell' (or |g:syntastic_shell|) is
for python in syntastic (see |syntastic_mode_map|), or disable lint checks in "cmd.exe", and on for shells that expect an UNIX-like syntax, such as Cygwin's
'python-mode', by setting |pymode_lint_write| to 0. E.g.: > "sh". Most checkers will stop working if 'shellslash' is set to the wrong
let g:pymode_lint_write = 0 value.
==============================================================================
7. Compatibility with other software *syntastic-compatibility*
------------------------------------------------------------------------------
7.1 The csh and tcsh shells *syntastic-csh*
The "csh" and "tcsh" shells are mostly compatible with syntastic. However,
some checkers assume Bourne shell syntax for redirecting "stderr". For this
reason, you should point |g:syntastic_shell| to a Bourne-compatible shell,
such as "zsh", "bash", "ksh", or even the original Bourne "sh": >
let g:syntastic_shell = "/bin/sh"
< <
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
6.4 Interaction with YouCompleteMe *syntastic-ycm* 7.2. Eclim *syntastic-eclim*
Syntastic can be used together with the 'YouCompleteMe' Vim plugin (see Syntastic can be used together with "Eclim" (see http://eclim.org/). However,
http://valloric.github.io/YouCompleteMe/). However, by default 'YouCompleteMe'
disables syntastic's checkers for the "c", "cpp", "objc", and "objcpp"
filetypes, in order to allow its own checkers to run. If you want to use YCM's
identifier completer but still run syntastic's checkers for those filetypes you
have to set |ycm_show_diagnostics_ui| to 0. E.g.: >
let g:ycm_show_diagnostics_ui = 0
<
------------------------------------------------------------------------------
6.5 Interaction with the fish shell *syntastic-fish*
At the time of this writing the 'fish' shell (see http://fishshell.com/)
doesn't support the standard UNIX syntax for file redirections, and thus it
can't be used together with syntastic. You don't need to change your login
shell to address this problem, but you do have to point Vim's 'shell' to a more
traditional shell, such as "zsh", "bash", "ksh", or even the original Bourne
"sh": >
set shell=bash
<
------------------------------------------------------------------------------
6.6. Interaction with PowerShell *syntastic-powershell*
At the time of this writing, syntastic is not compatible with using 'Windows
PowerShell' (http://technet.microsoft.com/en-us/library/bb978526.aspx) as Vim's
'shell'. You may still run Vim from 'PowerShell', but you do have to point
Vim's 'shell' to a more traditional program, such as 'cmd.exe': >
set shell=cmd.exe
<
------------------------------------------------------------------------------
6.7. Using syntastic with the fizsh shell *syntastic-fizsh*
Using syntastic with the 'fizsh' shell (see https://github.com/zsh-users/fizsh)
is possible, but potentially problematic. In order to do it you'll need to set
'shellredir' like this: >
set shellredir=>%s\ 2>&1
<
Please keep in mind however that Vim can't take advantage of any of the
interactive features of 'fizsh'. Using a more traditional shell such as "zsh",
"bash", "ksh", or the original Bourne "sh" might be a better choice: >
set shell=zsh
<
------------------------------------------------------------------------------
6.8. Interaction with Eclim *syntastic-eclim*
Syntastic can be used together with 'Eclim' (see http://eclim.org/). However,
by default Eclim disables syntastic's checks for the filetypes it supports, in by default Eclim disables syntastic's checks for the filetypes it supports, in
order to run its own validation. If you'd prefer to use Eclim but still run order to run its own validation. If you'd prefer to use Eclim but still run
syntastic's checks, set |g:EclimFileTypeValidate| to 0: > syntastic's checks, set |g:EclimFileTypeValidate| to 0: >
@ -850,28 +835,76 @@ run Eclim's validation for others. Please consult Eclim's documentation for
details. details.
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
6.9. Interaction with vim-virtualenv *syntastic-vim-virtualenv* 7.3 The fish shell *syntastic-fish*
At the time of this writing, syntastic can't run checkers installed At the time of this writing the "fish" shell (see http://fishshell.com/)
in Python virtual environments activated by 'vim-virtualenv' (see doesn't support the standard UNIX syntax for file redirections, and thus it
https://github.com/jmcantrell/vim-virtualenv). This is a limitation of can't be used together with syntastic. You can however set |g:syntastic_shell|
'vim-virtualenv'. to a more traditional shell, such as "zsh", "bash", "ksh", or even the
original Bourne "sh": >
let g:syntastic_shell = "/bin/sh"
<
------------------------------------------------------------------------------
7.4. The fizsh shell *syntastic-fizsh*
Using syntastic with the "fizsh" shell (see https://github.com/zsh-users/fizsh)
is possible, but potentially problematic. In order to do it you'll need to set
'shellredir' like this: >
set shellredir=>%s\ 2>&1
<
Please keep in mind however that Vim can't take advantage of any of the
interactive features of "fizsh". Using a more traditional shell such as "zsh",
"bash", "ksh", or the original Bourne "sh" might be a better choice: >
let g:syntastic_shell = "/bin/sh"
<
------------------------------------------------------------------------------
7.5. The PowerShell shell *syntastic-powershell*
At the time of this writing, syntastic is not compatible with using "Windows
PowerShell" (http://technet.microsoft.com/en-us/library/bb978526.aspx) as Vim's
'shell'. You may still run Vim from 'PowerShell', but you do have to point
Vim's 'shell' to a more traditional program, such as "cmd.exe": >
set shell=cmd.exe
<
------------------------------------------------------------------------------
7.6 python-mode *syntastic-pymode*
Syntastic can be used along with the "python-mode" Vim plugin (see
https://github.com/klen/python-mode). However, they both run syntax checks by
default when you save buffers to disk, and this is probably not what you want.
To avoid both plugins opening error windows, you can either set passive mode
for python in syntastic (see |syntastic_mode_map|), or disable lint checks in
"python-mode", by setting |pymode_lint_write| to 0. E.g.: >
let g:pymode_lint_write = 0
<
------------------------------------------------------------------------------
7.7. vim-auto-save *syntastic-vim-auto-save*
Syntastic can be used together with the "vim-auto-save" Vim plugin (see
https://github.com/907th/vim-auto-save). However, syntastic checks in active
mode only work with "vim-auto-save" version 0.1.7 or later.
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
6.10. Interaction with vim-auto-save *syntastic-vim-auto-save* 7.8. vim-virtualenv *syntastic-vim-virtualenv*
At the time of this writing, syntastic checks in active mode are not triggered At the time of this writing, syntastic can't run checkers installed
by 'vim-auto-save' (see https://github.com/907th/vim-auto-save). The reason is in Python virtual environments activated by "vim-virtualenv" (see
a limitation in 'vim-auto-save', namely a missing flag to an 'autocmd' (see https://github.com/jmcantrell/vim-virtualenv). This is a limitation of
|autocmd-nested|). Fortunately it's pretty easy to achieve a similar effect "vim-virtualenv".
without 'vim-auto-save'': >
augroup syntastic ------------------------------------------------------------------------------
autocmd CursorHold * nested update 7.9 YouCompleteMe *syntastic-ycm*
augroup END
set updatetime=200 Syntastic can be used together with the "YouCompleteMe" Vim plugin (see
http://valloric.github.io/YouCompleteMe/). However, by default "YouCompleteMe"
disables syntastic's checkers for the "c", "cpp", "objc", and "objcpp"
filetypes, in order to allow its own checkers to run. If you want to use YCM's
identifier completer but still run syntastic's checkers for those filetypes you
have to set |ycm_show_diagnostics_ui| to 0. E.g.: >
let g:ycm_show_diagnostics_ui = 0
< <
============================================================================== ==============================================================================
7. About *syntastic-about* 8. About *syntastic-about*
The core maintainers of syntastic are: The core maintainers of syntastic are:
Martin Grenfell (GitHub: scrooloose) Martin Grenfell (GitHub: scrooloose)
@ -883,9 +916,9 @@ Find the latest version of syntastic at:
http://github.com/scrooloose/syntastic http://github.com/scrooloose/syntastic
============================================================================== ==============================================================================
8. License *syntastic-license* 9. License *syntastic-license*
Syntastic is released under the wtfpl. Syntastic is released under the WTFPL.
See http://sam.zoy.org/wtfpl/COPYING. See http://sam.zoy.org/wtfpl/COPYING.
vim:tw=78:sw=4:ft=help:norl: vim:tw=78:sw=4:ft=help:norl:

View File

@ -19,7 +19,7 @@ if has('reltime')
lockvar! g:_SYNTASTIC_START lockvar! g:_SYNTASTIC_START
endif endif
let g:_SYNTASTIC_VERSION = '3.6.0-44' let g:_SYNTASTIC_VERSION = '3.6.0-57'
lockvar g:_SYNTASTIC_VERSION lockvar g:_SYNTASTIC_VERSION
" Sanity checks {{{1 " Sanity checks {{{1
@ -42,13 +42,17 @@ endfor
let s:_running_windows = syntastic#util#isRunningWindows() let s:_running_windows = syntastic#util#isRunningWindows()
lockvar s:_running_windows lockvar s:_running_windows
if !exists('g:syntastic_shell')
let g:syntastic_shell = &shell
endif
if s:_running_windows if s:_running_windows
let g:_SYNTASTIC_UNAME = 'Windows' let g:_SYNTASTIC_UNAME = 'Windows'
elseif executable('uname') elseif executable('uname')
try try
let g:_SYNTASTIC_UNAME = split(system('uname'), "\n")[0] let g:_SYNTASTIC_UNAME = split(syntastic#util#system('uname'), "\n")[0]
catch /\m^Vim\%((\a\+)\)\=:E484/ catch /\m^Vim\%((\a\+)\)\=:E484/
call syntastic#log#error("your shell " . &shell . " can't handle traditional UNIX syntax for redirections") call syntastic#log#error("your shell " . syntastic#util#var('shell') . " can't handle traditional UNIX syntax for redirections")
finish finish
catch /\m^Vim\%((\a\+)\)\=:E684/ catch /\m^Vim\%((\a\+)\)\=:E684/
let g:_SYNTASTIC_UNAME = 'Unknown' let g:_SYNTASTIC_UNAME = 'Unknown'
@ -67,7 +71,6 @@ let g:_SYNTASTIC_DEFAULTS = {
\ 'always_populate_loc_list': 0, \ 'always_populate_loc_list': 0,
\ 'auto_jump': 0, \ 'auto_jump': 0,
\ 'auto_loc_list': 2, \ 'auto_loc_list': 2,
\ 'bash_hack': 0,
\ 'check_on_open': 0, \ 'check_on_open': 0,
\ 'check_on_wq': 1, \ 'check_on_wq': 1,
\ 'cursor_columns': 1, \ 'cursor_columns': 1,
@ -77,7 +80,7 @@ let g:_SYNTASTIC_DEFAULTS = {
\ 'enable_highlighting': 1, \ 'enable_highlighting': 1,
\ 'enable_signs': 1, \ 'enable_signs': 1,
\ 'error_symbol': '>>', \ 'error_symbol': '>>',
\ 'exit_checks': !(s:_running_windows && &shell =~? '\m\<cmd\.exe$'), \ 'exit_checks': !(s:_running_windows && syntastic#util#var('shell', &shell) =~? '\m\<cmd\.exe$'),
\ 'filetype_map': {}, \ 'filetype_map': {},
\ 'full_redraws': !(has('gui_running') || has('gui_macvim')), \ 'full_redraws': !(has('gui_running') || has('gui_macvim')),
\ 'id_checkers': 1, \ 'id_checkers': 1,
@ -86,6 +89,7 @@ let g:_SYNTASTIC_DEFAULTS = {
\ 'loc_list_height': 10, \ 'loc_list_height': 10,
\ 'quiet_messages': {}, \ 'quiet_messages': {},
\ 'reuse_loc_lists': 0, \ 'reuse_loc_lists': 0,
\ 'shell': &shell,
\ 'sort_aggregated_errors': 1, \ 'sort_aggregated_errors': 1,
\ 'stl_format': '[Syntax: line:%F (%t)]', \ 'stl_format': '[Syntax: line:%F (%t)]',
\ 'style_error_symbol': 'S>', \ 'style_error_symbol': 'S>',
@ -463,16 +467,11 @@ function! SyntasticMake(options) abort " {{{2
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_TRACE, 'SyntasticMake: called with options:', a:options) call syntastic#log#debug(g:_SYNTASTIC_DEBUG_TRACE, 'SyntasticMake: called with options:', a:options)
" save options and locale env variables {{{3 " save options and locale env variables {{{3
let old_shellredir = &shellredir
let old_local_errorformat = &l:errorformat let old_local_errorformat = &l:errorformat
let old_errorformat = &errorformat let old_errorformat = &errorformat
let old_cwd = getcwd() let old_cwd = getcwd()
let old_lc_messages = $LC_MESSAGES
let old_lc_all = $LC_ALL
" }}}3 " }}}3
call s:_bash_hack()
if has_key(a:options, 'errorformat') if has_key(a:options, 'errorformat')
let &errorformat = a:options['errorformat'] let &errorformat = a:options['errorformat']
endif endif
@ -491,15 +490,11 @@ function! SyntasticMake(options) abort " {{{2
endif endif
endfor endfor
endif endif
let $LC_MESSAGES = 'C'
let $LC_ALL = ''
" }}}3 " }}}3
let err_lines = split(system(a:options['makeprg']), "\n", 1) let err_lines = split(syntastic#util#system(a:options['makeprg']), "\n", 1)
" restore environment variables {{{3 " restore environment variables {{{3
let $LC_ALL = old_lc_all
let $LC_MESSAGES = old_lc_messages
if len(env_save) if len(env_save)
for key in keys(env_save) for key in keys(env_save)
execute 'let $' . key . ' = ' . string(env_save[key]) execute 'let $' . key . ' = ' . string(env_save[key])
@ -547,7 +542,6 @@ function! SyntasticMake(options) abort " {{{2
" restore options {{{3 " restore options {{{3
let &errorformat = old_errorformat let &errorformat = old_errorformat
let &l:errorformat = old_local_errorformat let &l:errorformat = old_local_errorformat
let &shellredir = old_shellredir
" }}}3 " }}}3
if !s:_running_windows && (s:_os_name() =~? "FreeBSD" || s:_os_name() =~? "OpenBSD") if !s:_running_windows && (s:_os_name() =~? "FreeBSD" || s:_os_name() =~? "OpenBSD")
@ -666,24 +660,6 @@ function! s:_add_to_errors(errors, options) abort " {{{2
return a:errors return a:errors
endfunction " }}}2 endfunction " }}}2
" XXX: Is this still needed?
" The script changes &shellredir to stop the screen
" flicking when shelling out to syntax checkers.
function! s:_bash_hack() abort " {{{2
if g:syntastic_bash_hack
if !exists('s:shell_is_bash')
let s:shell_is_bash =
\ !s:_running_windows &&
\ (s:_os_name() !~# "FreeBSD") && (s:_os_name() !~# "OpenBSD") &&
\ &shell =~# '\m\<bash$'
endif
if s:shell_is_bash
let &shellredir = '&>'
endif
endif
endfunction " }}}2
function! s:_os_name() abort " {{{2 function! s:_os_name() abort " {{{2
return g:_SYNTASTIC_UNAME return g:_SYNTASTIC_UNAME
endfunction " }}}2 endfunction " }}}2

View File

@ -80,10 +80,16 @@ function! g:SyntasticChecker.getLocListRaw() abort " {{{2
let name = self._filetype . '/' . self._name let name = self._filetype . '/' . self._name
try try
let list = self._locListFunc() let list = self._locListFunc()
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_TRACE, 'getLocList: checker ' . name . ' returned ' . v:shell_error) if self._exec != ''
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_TRACE, 'getLocList: checker ' . name . ' returned ' . v:shell_error)
endif
catch /\m\C^Syntastic: checker error$/ catch /\m\C^Syntastic: checker error$/
let list = [] let list = []
call syntastic#log#error('checker ' . name . ' returned abnormal status ' . v:shell_error) if self._exec != ''
call syntastic#log#error('checker ' . name . ' returned abnormal status ' . v:shell_error)
else
call syntastic#log#error('checker ' . name . ' aborted')
endif
endtry endtry
call self._populateHighlightRegexes(list) call self._populateHighlightRegexes(list)
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_LOCLIST, name . ' raw:', list) call syntastic#log#debug(g:_SYNTASTIC_DEBUG_LOCLIST, name . ' raw:', list)
@ -98,7 +104,7 @@ endfunction " }}}2
function! g:SyntasticChecker.getVersion(...) abort " {{{2 function! g:SyntasticChecker.getVersion(...) abort " {{{2
if !exists('self._version') if !exists('self._version')
let command = a:0 ? a:1 : self.getExecEscaped() . ' --version' let command = a:0 ? a:1 : self.getExecEscaped() . ' --version'
let version_output = system(command) let version_output = syntastic#util#system(command)
call self.log('getVersion: ' . string(command) . ': ' . call self.log('getVersion: ' . string(command) . ': ' .
\ string(split(version_output, "\n", 1)) . \ string(split(version_output, "\n", 1)) .
\ (v:shell_error ? ' (exit code ' . v:shell_error . ')' : '') ) \ (v:shell_error ? ' (exit code ' . v:shell_error . ')' : '') )

View File

@ -6,93 +6,94 @@ let g:loaded_syntastic_registry = 1
" Initialisation {{{1 " Initialisation {{{1
let s:_DEFAULT_CHECKERS = { let s:_DEFAULT_CHECKERS = {
\ 'actionscript':['mxmlc'], \ 'actionscript': ['mxmlc'],
\ 'ada': ['gcc'], \ 'ada': ['gcc'],
\ 'applescript': ['osacompile'], \ 'apiblueprint': ['snowcrash'],
\ 'asciidoc': ['asciidoc'], \ 'applescript': ['osacompile'],
\ 'asm': ['gcc'], \ 'asciidoc': ['asciidoc'],
\ 'bro': ['bro'], \ 'asm': ['gcc'],
\ 'bemhtml': ['bemhtmllint'], \ 'bro': ['bro'],
\ 'c': ['gcc'], \ 'bemhtml': ['bemhtmllint'],
\ 'cabal': ['cabal'], \ 'c': ['gcc'],
\ 'chef': ['foodcritic'], \ 'cabal': ['cabal'],
\ 'co': ['coco'], \ 'chef': ['foodcritic'],
\ 'cobol': ['cobc'], \ 'co': ['coco'],
\ 'coffee': ['coffee', 'coffeelint'], \ 'cobol': ['cobc'],
\ 'coq': ['coqtop'], \ 'coffee': ['coffee', 'coffeelint'],
\ 'cpp': ['gcc'], \ 'coq': ['coqtop'],
\ 'cs': ['mcs'], \ 'cpp': ['gcc'],
\ 'css': ['csslint'], \ 'cs': ['mcs'],
\ 'cucumber': ['cucumber'], \ 'css': ['csslint'],
\ 'cuda': ['nvcc'], \ 'cucumber': ['cucumber'],
\ 'd': ['dmd'], \ 'cuda': ['nvcc'],
\ 'dart': ['dartanalyzer'], \ 'd': ['dmd'],
\ 'docbk': ['xmllint'], \ 'dart': ['dartanalyzer'],
\ 'dustjs': ['swiffer'], \ 'docbk': ['xmllint'],
\ 'elixir': [], \ 'dustjs': ['swiffer'],
\ 'erlang': ['escript'], \ 'elixir': [],
\ 'eruby': ['ruby'], \ 'erlang': ['escript'],
\ 'fortran': ['gfortran'], \ 'eruby': ['ruby'],
\ 'glsl': ['cgc'], \ 'fortran': ['gfortran'],
\ 'go': ['go'], \ 'glsl': ['cgc'],
\ 'haml': ['haml'], \ 'go': ['go'],
\ 'handlebars': ['handlebars'], \ 'haml': ['haml'],
\ 'haskell': ['ghc_mod', 'hdevtools', 'hlint'], \ 'handlebars': ['handlebars'],
\ 'haxe': ['haxe'], \ 'haskell': ['ghc_mod', 'hdevtools', 'hlint'],
\ 'hss': ['hss'], \ 'haxe': ['haxe'],
\ 'html': ['tidy'], \ 'hss': ['hss'],
\ 'java': ['javac'], \ 'html': ['tidy'],
\ 'javascript': ['jshint', 'jslint'], \ 'java': ['javac'],
\ 'json': ['jsonlint', 'jsonval'], \ 'javascript': ['jshint', 'jslint'],
\ 'less': ['lessc'], \ 'json': ['jsonlint', 'jsonval'],
\ 'lex': ['flex'], \ 'less': ['lessc'],
\ 'limbo': ['limbo'], \ 'lex': ['flex'],
\ 'lisp': ['clisp'], \ 'limbo': ['limbo'],
\ 'llvm': ['llvm'], \ 'lisp': ['clisp'],
\ 'lua': ['luac'], \ 'llvm': ['llvm'],
\ 'markdown': ['mdl'], \ 'lua': ['luac'],
\ 'matlab': ['mlint'], \ 'markdown': ['mdl'],
\ 'nasm': ['nasm'], \ 'matlab': ['mlint'],
\ 'nroff': ['mandoc'], \ 'nasm': ['nasm'],
\ 'objc': ['gcc'], \ 'nroff': ['mandoc'],
\ 'objcpp': ['gcc'], \ 'objc': ['gcc'],
\ 'ocaml': ['camlp4o'], \ 'objcpp': ['gcc'],
\ 'perl': ['perlcritic'], \ 'ocaml': ['camlp4o'],
\ 'php': ['php', 'phpcs', 'phpmd'], \ 'perl': ['perlcritic'],
\ 'po': ['msgfmt'], \ 'php': ['php', 'phpcs', 'phpmd'],
\ 'pod': ['podchecker'], \ 'po': ['msgfmt'],
\ 'puppet': ['puppet', 'puppetlint'], \ 'pod': ['podchecker'],
\ 'python': ['python', 'flake8', 'pylint'], \ 'puppet': ['puppet', 'puppetlint'],
\ 'r': [], \ 'python': ['python', 'flake8', 'pylint'],
\ 'racket': ['racket'], \ 'r': [],
\ 'rnc': ['rnv'], \ 'racket': ['racket'],
\ 'rst': ['rst2pseudoxml'], \ 'rnc': ['rnv'],
\ 'ruby': ['mri'], \ 'rst': ['rst2pseudoxml'],
\ 'sass': ['sass'], \ 'ruby': ['mri'],
\ 'scala': ['fsc', 'scalac'], \ 'sass': ['sass'],
\ 'scss': ['sass', 'scss_lint'], \ 'scala': ['fsc', 'scalac'],
\ 'sh': ['sh', 'shellcheck'], \ 'scss': ['sass', 'scss_lint'],
\ 'slim': ['slimrb'], \ 'sh': ['sh', 'shellcheck'],
\ 'sml': ['smlnj'], \ 'slim': ['slimrb'],
\ 'spec': ['rpmlint'], \ 'sml': ['smlnj'],
\ 'tcl': ['nagelfar'], \ 'spec': ['rpmlint'],
\ 'tex': ['lacheck', 'chktex'], \ 'tcl': ['nagelfar'],
\ 'texinfo': ['makeinfo'], \ 'tex': ['lacheck', 'chktex'],
\ 'text': [], \ 'texinfo': ['makeinfo'],
\ 'twig': ['twiglint'], \ 'text': [],
\ 'typescript': ['tsc'], \ 'twig': ['twiglint'],
\ 'vala': ['valac'], \ 'typescript': ['tsc'],
\ 'verilog': ['verilator'], \ 'vala': ['valac'],
\ 'vhdl': ['ghdl'], \ 'verilog': ['verilator'],
\ 'vim': ['vimlint'], \ 'vhdl': ['ghdl'],
\ 'xhtml': ['tidy'], \ 'vim': ['vimlint'],
\ 'xml': ['xmllint'], \ 'xhtml': ['tidy'],
\ 'xslt': ['xmllint'], \ 'xml': ['xmllint'],
\ 'yacc': ['bison'], \ 'xslt': ['xmllint'],
\ 'yaml': ['jsyaml'], \ 'yacc': ['bison'],
\ 'z80': ['z80syntaxchecker'], \ 'yaml': ['jsyaml'],
\ 'zpt': ['zptlint'], \ 'z80': ['z80syntaxchecker'],
\ 'zsh': ['zsh', 'shellcheck'], \ 'zpt': ['zptlint'],
\ 'zsh': ['zsh', 'shellcheck'],
\ } \ }
lockvar! s:_DEFAULT_CHECKERS lockvar! s:_DEFAULT_CHECKERS

View File

@ -0,0 +1,66 @@
"============================================================================
"File: snowcrash.vim
"Description: Syntax checking plugin for syntastic.vim
"Maintainer: LCD 47 <lcd047 at gmail dot com>
"License: This program is free software. It comes without any warranty,
" to the extent permitted by applicable law. You can redistribute
" it and/or modify it under the terms of the Do What The Fuck You
" Want To Public License, Version 2, as published by Sam Hocevar.
" See http://sam.zoy.org/wtfpl/COPYING for more details.
"
"============================================================================
if exists("g:loaded_syntastic_apiblueprint_snowcrash_checker")
finish
endif
let g:loaded_syntastic_apiblueprint_snowcrash_checker = 1
if !exists('g:syntastic_apiblueprint_snowcrash_sort')
let g:syntastic_apiblueprint_snowcrash_sort = 1
endif
let s:save_cpo = &cpo
set cpo&vim
function! SyntaxCheckers_apiblueprint_snowcrash_GetLocList() dict
let makeprg = self.makeprgBuild({ 'post_args': '-u -l' })
let errorformat =
\ '%trror: (%n) %m,' .
\ '%tarning: (%n) %m,' .
\ '%-G%.%#'
let loclist = SyntasticMake({
\ 'makeprg': makeprg,
\ 'errorformat': errorformat,
\ 'defaults': {'bufnr': bufnr('')},
\ 'returns': [0, 2] })
for e in loclist
let matches = matchlist(e['text'], '\v^(.+); line (\d+), column (\d+) - line (\d+), column (\d+)$')
if len(matches) > 5
let e['lnum'] = str2nr(matches[2])
let e['col'] = str2nr(matches[3])
let e['vcol'] = 0
if matches[2] == matches[4]
let e['hl'] = '\%>' . (e['col'] - 1) . 'c\%<' . matches[5] . 'c'
endif
let e['text'] = matches[1]
else
let e['valid'] = 0
endif
endfor
return loclist
endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({
\ 'filetype': 'apiblueprint',
\ 'name': 'snowcrash'})
let &cpo = s:save_cpo
unlet s:save_cpo
" vim: set sw=4 sts=4 et fdm=marker:

View File

@ -28,7 +28,7 @@ function! SyntaxCheckers_bro_bro_IsAvailable() dict
return 0 return 0
endif endif
if system(self.getExecEscaped() . ' --help') !~# '--parse-only' if syntastic#util#system(self.getExecEscaped() . ' --help') !~# '--parse-only'
call self.log('unknown option "--parse-only"') call self.log('unknown option "--parse-only"')
return 0 return 0
endif endif

View File

@ -44,7 +44,9 @@ function! SyntaxCheckers_elixir_elixir_GetLocList() dict
let make_options['makeprg'] = self.makeprgBuild({ 'exe': compile_command }) let make_options['makeprg'] = self.makeprgBuild({ 'exe': compile_command })
let make_options['errorformat'] = '** %*[^\ ] %f:%l: %m' let make_options['errorformat'] =
\ '%E** %*[^\ ] %f:%l: %m,' .
\ '%W%f:%l: warning: %m'
return SyntasticMake(make_options) return SyntasticMake(make_options)
endfunction endfunction

View File

@ -30,10 +30,10 @@ function! SyntaxCheckers_haskell_ghc_mod_IsAvailable() dict
" know the version in order to know how to find out the version. :) " know the version in order to know how to find out the version. :)
" Try "ghc-mod version". " Try "ghc-mod version".
let ver = filter(split(system(self.getExecEscaped() . ' version'), '\n'), 'v:val =~# ''\m\sversion''') let ver = filter(split(syntastic#util#system(self.getExecEscaped() . ' version'), '\n'), 'v:val =~# ''\m\sversion''')
if !len(ver) if !len(ver)
" That didn't work. Try "ghc-mod" alone. " That didn't work. Try "ghc-mod" alone.
let ver = filter(split(system(self.getExecEscaped()), '\n'), 'v:val =~# ''\m\sversion''') let ver = filter(split(syntastic#util#system(self.getExecEscaped()), '\n'), 'v:val =~# ''\m\sversion''')
endif endif
if len(ver) if len(ver)

View File

@ -46,7 +46,7 @@ function! SyntaxCheckers_java_checkstyle_GetLocList() dict
let fname = syntastic#util#shescape( expand('%:p:h', 1) . syntastic#util#Slash() . expand('%:t', 1) ) let fname = syntastic#util#shescape( expand('%:p:h', 1) . syntastic#util#Slash() . expand('%:t', 1) )
if has('win32unix') if has('win32unix')
let fname = substitute(system('cygpath -m ' . fname), '\m\%x00', '', 'g') let fname = substitute(syntastic#util#system('cygpath -m ' . fname), '\m\%x00', '', 'g')
endif endif
let makeprg = self.makeprgBuild({ let makeprg = self.makeprgBuild({

View File

@ -129,7 +129,7 @@ function! SyntaxCheckers_java_javac_GetLocList() dict " {{{1
" load custom classpath {{{2 " load custom classpath {{{2
if g:syntastic_java_javac_custom_classpath_command != '' if g:syntastic_java_javac_custom_classpath_command != ''
let lines = system(g:syntastic_java_javac_custom_classpath_command) let lines = syntastic#util#system(g:syntastic_java_javac_custom_classpath_command)
if syntastic#util#isRunningWindows() || has('win32unix') if syntastic#util#isRunningWindows() || has('win32unix')
let lines = substitute(lines, "\r\n", "\n", 'g') let lines = substitute(lines, "\r\n", "\n", 'g')
endif endif
@ -306,7 +306,7 @@ function! s:GetMavenProperties() " {{{2
\ ' -f ' . syntastic#util#shescape(pom) . \ ' -f ' . syntastic#util#shescape(pom) .
\ ' ' . g:syntastic_java_maven_options \ ' ' . g:syntastic_java_maven_options
let mvn_is_managed_tag = 1 let mvn_is_managed_tag = 1
let mvn_settings_output = split(system(mvn_cmd . ' help:effective-pom'), "\n") let mvn_settings_output = split(syntastic#util#system(mvn_cmd . ' help:effective-pom'), "\n")
let current_path = 'project' let current_path = 'project'
for line in mvn_settings_output for line in mvn_settings_output
let matches = matchlist(line, '\m^\s*<\([a-zA-Z0-9\-\.]\+\)>\s*$') let matches = matchlist(line, '\m^\s*<\([a-zA-Z0-9\-\.]\+\)>\s*$')
@ -340,7 +340,7 @@ function! s:GetMavenClasspath() " {{{2
let mvn_cmd = syntastic#util#shexpand(g:syntastic_java_maven_executable) . let mvn_cmd = syntastic#util#shexpand(g:syntastic_java_maven_executable) .
\ ' -f ' . syntastic#util#shescape(pom) . \ ' -f ' . syntastic#util#shescape(pom) .
\ ' ' . g:syntastic_java_maven_options \ ' ' . g:syntastic_java_maven_options
let mvn_classpath_output = split(system(mvn_cmd . ' dependency:build-classpath'), "\n") let mvn_classpath_output = split(syntastic#util#system(mvn_cmd . ' dependency:build-classpath'), "\n")
let mvn_classpath = '' let mvn_classpath = ''
let class_path_next = 0 let class_path_next = 0

View File

@ -23,7 +23,7 @@ set cpo&vim
function! SyntaxCheckers_javascript_flow_GetLocList() dict function! SyntaxCheckers_javascript_flow_GetLocList() dict
let makeprg = self.makeprgBuild({ let makeprg = self.makeprgBuild({
\ 'exe_after': 'check', \ 'exe': self.getExecEscaped() . ' check',
\ 'args_after': '--show-all-errors --json' }) \ 'args_after': '--show-all-errors --json' })
let errorformat = let errorformat =

View File

@ -18,7 +18,7 @@ let s:save_cpo = &cpo
set cpo&vim set cpo&vim
function! SyntaxCheckers_javascript_jsxhint_IsAvailable() dict function! SyntaxCheckers_javascript_jsxhint_IsAvailable() dict
let jsxhint_version = system(self.getExecEscaped() . ' --version') let jsxhint_version = syntastic#util#system(self.getExecEscaped() . ' --version')
if v:shell_error || (jsxhint_version !~# '\m^JSXHint\>') if v:shell_error || (jsxhint_version !~# '\m^JSXHint\>')
return 0 return 0
endif endif

View File

@ -51,17 +51,31 @@ function! SyntaxCheckers_ocaml_camlp4o_GetLocList() dict " {{{1
endif endif
let errorformat = let errorformat =
\ '%AFile "%f"\, line %l\, characters %c-%*\d:,'. \ '%WWarning: File "%f"\, line %l\, chars %c-%n:,'.
\ '%WWarning: line %l\, chars %c-%n:,'.
\ '%AFile "%f"\, line %l\, characters %c-%n:,'.
\ '%AFile "%f"\, line %l\, characters %c-%*\d (end at line %*\d\, character %*\d):,'. \ '%AFile "%f"\, line %l\, characters %c-%*\d (end at line %*\d\, character %*\d):,'.
\ '%AFile "%f"\, line %l\, character %c:,'. \ '%AFile "%f"\, line %l\, character %c:,'.
\ '%AFile "%f"\, line %l\, character %c:%m,'. \ '%AFile "%f"\, line %l\, character %c:%m,'.
\ '%-GPreprocessing error %.%#,'. \ '%-GPreprocessing error %.%#,'.
\ '%-GCommand exited %.%#,'. \ '%-GCommand exited %.%#,'.
\ '%C%tarning %n: %m,'. \ '%C%tarning %*\d: %m,'.
\ '%C%m,'. \ '%C%m,'.
\ '%-G+%.%#' \ '%-G+%.%#'
return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat }) let loclist = SyntasticMake({
\ 'makeprg': makeprg,
\ 'errorformat': errorformat,
\ 'defaults': {'bufnr': bufnr("")} })
for e in loclist
if get(e, 'col', 0) && get(e, 'nr', 0)
let e['hl'] = '\%>' . (e['col'] - 1) . 'c\%<' . (e['nr'] + 1) . 'c'
let e['nr'] = 0
endif
endfor
return loclist
endfunction " }}}1 endfunction " }}}1
" Utilities {{{1 " Utilities {{{1

View File

@ -46,7 +46,7 @@ function! SyntaxCheckers_perl_perl_IsAvailable() dict
" don't call executable() here, to allow things like " don't call executable() here, to allow things like
" let g:syntastic_perl_interpreter='/usr/bin/env perl' " let g:syntastic_perl_interpreter='/usr/bin/env perl'
silent! call system(self.getExecEscaped() . ' -e ' . syntastic#util#shescape('exit(0)')) silent! call syntastic#util#system(self.getExecEscaped() . ' -e ' . syntastic#util#shescape('exit(0)'))
return v:shell_error == 0 return v:shell_error == 0
endfunction endfunction

View File

@ -32,7 +32,7 @@ function! SyntaxCheckers_python_pylint_IsAvailable() dict
" On new-ish Fedora it's "python3-pylint 1.2.0". " On new-ish Fedora it's "python3-pylint 1.2.0".
" Have you guys considered switching to creative writing yet? ;) " Have you guys considered switching to creative writing yet? ;)
let pylint_version = filter( split(system(self.getExecEscaped() . ' --version'), '\m, \=\|\n'), let pylint_version = filter( split(syntastic#util#system(self.getExecEscaped() . ' --version'), '\m, \=\|\n'),
\ 'v:val =~# ''\m^\(python[-0-9]*-\|\.\)\=pylint[-0-9]*\>''' )[0] \ 'v:val =~# ''\m^\(python[-0-9]*-\|\.\)\=pylint[-0-9]*\>''' )[0]
let ver = syntastic#util#parseVersion(substitute(pylint_version, '\v^\S+\s+', '', '')) let ver = syntastic#util#parseVersion(substitute(pylint_version, '\v^\S+\s+', '', ''))
call self.setVersion(ver) call self.setVersion(ver)

View File

@ -38,7 +38,7 @@ function! SyntaxCheckers_r_lint_IsAvailable() dict
if !executable(self.getExec()) if !executable(self.getExec())
return 0 return 0
endif endif
call system(self.getExecEscaped() . ' --slave --restore --no-save -e ' . syntastic#util#shescape('library(lint)')) call syntastic#util#system(self.getExecEscaped() . ' --slave --restore --no-save -e ' . syntastic#util#shescape('library(lint)'))
return v:shell_error == 0 return v:shell_error == 0
endfunction endfunction

View File

@ -41,7 +41,7 @@ function! SyntaxCheckers_r_svtools_IsAvailable() dict
if !executable(self.getExec()) if !executable(self.getExec())
return 0 return 0
endif endif
call system(self.getExecEscaped() . ' --slave --restore --no-save -e ' . syntastic#util#shescape('library(svTools)')) call syntastic#util#system(self.getExecEscaped() . ' --slave --restore --no-save -e ' . syntastic#util#shescape('library(svTools)'))
return v:shell_error == 0 return v:shell_error == 0
endfunction endfunction

View File

@ -20,8 +20,8 @@ set cpo&vim
function! SyntaxCheckers_ruby_jruby_GetLocList() dict function! SyntaxCheckers_ruby_jruby_GetLocList() dict
let makeprg = self.makeprgBuild({ let makeprg = self.makeprgBuild({
\ 'args': (syntastic#util#isRunningWindows() ? '-T1' : ''), \ 'args': (syntastic#util#isRunningWindows() ? '-T1 -W1' : '-W1'),
\ 'args_after': '-W1 -c' }) \ 'args_after': '-c' })
let errorformat = let errorformat =
\ '%-GSyntax OK for %f,'. \ '%-GSyntax OK for %f,'.

View File

@ -18,7 +18,9 @@ let s:save_cpo = &cpo
set cpo&vim set cpo&vim
function! SyntaxCheckers_ruby_macruby_GetLocList() dict function! SyntaxCheckers_ruby_macruby_GetLocList() dict
let makeprg = self.makeprgBuild({ 'args_after': '-W1 -c' }) let makeprg = self.makeprgBuild({
\ 'args': '-W1',
\ 'args_after': '-c' })
let errorformat = let errorformat =
\ '%-GSyntax OK,'. \ '%-GSyntax OK,'.

View File

@ -36,7 +36,9 @@ function! SyntaxCheckers_ruby_mri_GetHighlightRegex(i)
endfunction endfunction
function! SyntaxCheckers_ruby_mri_GetLocList() dict function! SyntaxCheckers_ruby_mri_GetLocList() dict
let makeprg = self.makeprgBuild({ 'args_after': '-w -T1 -c' }) let makeprg = self.makeprgBuild({
\ 'args': '-w -T1',
\ 'args_after': '-c' })
"this is a hack to filter out a repeated useless warning in rspec files "this is a hack to filter out a repeated useless warning in rspec files
"containing lines like "containing lines like

View File

@ -97,7 +97,7 @@ endfunction " }}}2
call g:SyntasticRegistry.CreateAndRegisterChecker({ call g:SyntasticRegistry.CreateAndRegisterChecker({
\ 'filetype': 'vim', \ 'filetype': 'vim',
\ 'name': 'vimlint', \ 'name': 'vimlint',
\ 'exec': 'vim' }) \ 'exec': '' })
let &cpo = s:save_cpo let &cpo = s:save_cpo
unlet s:save_cpo unlet s:save_cpo

View File

@ -29,7 +29,7 @@ function! SyntaxCheckers_yaml_yamlxs_IsAvailable() dict
" don't call executable() here, to allow things like " don't call executable() here, to allow things like
" let g:syntastic_perl_interpreter='/usr/bin/env perl' " let g:syntastic_perl_interpreter='/usr/bin/env perl'
silent! call system(self.getExecEscaped() . ' ' . s:Modules() . ' -e ' . syntastic#util#shescape('exit(0)')) silent! call syntastic#util#system(self.getExecEscaped() . ' ' . s:Modules() . ' -e ' . syntastic#util#shescape('exit(0)'))
return v:shell_error == 0 return v:shell_error == 0
endfunction endfunction

View File

@ -7,7 +7,7 @@ Lean &amp; mean status/tabline for vim that's light as air.
# Features # Features
* Tiny core written with extensibility in mind ([open/closed principle][8]). * Tiny core written with extensibility in mind ([open/closed principle][8]).
* Integrates with a variety of plugins, including: [vim-bufferline][6], [fugitive][4], [unite][9], [ctrlp][10], [minibufexpl][15], [gundo][16], [undotree][17], [nerdtree][18], [tagbar][19], [vim-gitgutter][29], [vim-signify][30], [syntastic][5], [eclim][34], [lawrencium][21], [virtualenv][31], [tmuxline][35]. * Integrates with a variety of plugins, including: [vim-bufferline][6], [fugitive][4], [unite][9], [ctrlp][10], [minibufexpl][15], [gundo][16], [undotree][17], [nerdtree][18], [tagbar][19], [vim-gitgutter][29], [vim-signify][30], [syntastic][5], [eclim][34], [lawrencium][21], [virtualenv][31], [tmuxline][35], [taboo.vim][37], [ctrlspace][38] and more.
* Looks good with regular fonts and provides configuration points so you can use unicode or powerline symbols. * Looks good with regular fonts and provides configuration points so you can use unicode or powerline symbols.
* Optimized for speed; it loads in under a millisecond. * Optimized for speed; it loads in under a millisecond.
* Extensive suite of themes for popular color schemes including [solarized][23] (dark and light), [tomorrow][24] (all variants), [base16][32] (all variants), [molokai][25], [jellybeans][26] and others; have a look at the [screenshots][14] in the wiki. * Extensive suite of themes for popular color schemes including [solarized][23] (dark and light), [tomorrow][24] (all variants), [base16][32] (all variants), [molokai][25], [jellybeans][26] and others; have a look at the [screenshots][14] in the wiki.
@ -151,10 +151,12 @@ Whoa! Everything got slow all of a sudden...
vim-airline strives to make it easy to use out of the box, which means that by default it will look for all compatible plugins that you have installed and enable the relevant extension. vim-airline strives to make it easy to use out of the box, which means that by default it will look for all compatible plugins that you have installed and enable the relevant extension.
Many optimizations have been made such that the majority of users will not see any performance degradation, but it can still happen. For example, users who routinely open very large files may want to disable the tagbar extension, as it can be very expensive to scan for the name of the current function. Many optimizations have been made such that the majority of users will not see any performance degradation, but it can still happen. For example, users who routinely open very large files may want to disable the `tagbar` extension, as it can be very expensive to scan for the name of the current function.
The [minivimrc][7] project has some helper mappings to troubleshoot performance related issues. The [minivimrc][7] project has some helper mappings to troubleshoot performance related issues.
If you don't want all the bells and whistles enabled by default, you can define a value for `g:airline_extensions`. When this variable is defined, only the extensions listed will be loaded; an empty array would effectively disable all extensions.
# Screenshots # Screenshots
A full list of screenshots for various themes can be found in the [Wiki][14]. A full list of screenshots for various themes can be found in the [Wiki][14].
@ -219,3 +221,5 @@ MIT License. Copyright (c) 2013-2015 Bailey Ling.
[34]: http://eclim.org [34]: http://eclim.org
[35]: https://github.com/edkolev/tmuxline.vim [35]: https://github.com/edkolev/tmuxline.vim
[36]: https://github.com/edkolev/promptline.vim [36]: https://github.com/edkolev/promptline.vim
[37]: https://github.com/gcmt/taboo.vim
[38]: https://github.com/szw/vim-ctrlspace

View File

@ -46,6 +46,7 @@ function! airline#load_theme()
call airline#highlighter#load_theme() call airline#highlighter#load_theme()
call airline#extensions#load_theme() call airline#extensions#load_theme()
call airline#update_statusline()
endfunction endfunction
function! airline#switch_theme(name) function! airline#switch_theme(name)
@ -62,7 +63,6 @@ function! airline#switch_theme(name)
endtry endtry
let w:airline_lastmode = '' let w:airline_lastmode = ''
call airline#update_statusline()
call airline#load_theme() call airline#load_theme()
" this is required to prevent clobbering the startup info message, i don't know why... " this is required to prevent clobbering the startup info message, i don't know why...

View File

@ -121,6 +121,13 @@ function! airline#extensions#load()
" non-trivial number of external plugins use eventignore=all, so we need to account for that " non-trivial number of external plugins use eventignore=all, so we need to account for that
autocmd CursorMoved * call <sid>sync_active_winnr() autocmd CursorMoved * call <sid>sync_active_winnr()
if exists('g:airline_extensions')
for ext in g:airline_extensions
call airline#extensions#{ext}#init(s:ext)
endfor
return
endif
call airline#extensions#quickfix#init(s:ext) call airline#extensions#quickfix#init(s:ext)
if get(g:, 'loaded_unite', 0) if get(g:, 'loaded_unite', 0)
@ -139,6 +146,10 @@ function! airline#extensions#load()
call airline#extensions#ctrlp#init(s:ext) call airline#extensions#ctrlp#init(s:ext)
endif endif
if get(g:, 'ctrlspace_loaded', 0)
call airline#extensions#ctrlspace#init(s:ext)
endif
if get(g:, 'command_t_loaded', 0) if get(g:, 'command_t_loaded', 0)
call airline#extensions#commandt#init(s:ext) call airline#extensions#commandt#init(s:ext)
endif endif

View File

@ -9,6 +9,21 @@ if !s:has_fugitive && !s:has_lawrencium && !s:has_vcscommand
finish finish
endif endif
let s:head_format = get(g:, 'airline#extensions#branch#format', 0)
if s:head_format == 1
function! s:format_name(name)
return fnamemodify(a:name, ':t')
endfunction
elseif type(s:head_format) == type('')
function! s:format_name(name)
return call(s:head_format, [a:name])
endfunction
else
function! s:format_name(name)
return a:name
endfunction
endif
let s:git_dirs = {} let s:git_dirs = {}
function! s:get_git_branch(path) function! s:get_git_branch(path)
if has_key(s:git_dirs, a:path) if has_key(s:git_dirs, a:path)
@ -72,6 +87,8 @@ function! airline#extensions#branch#head()
let b:airline_head = '' let b:airline_head = ''
endif endif
let b:airline_head = s:format_name(b:airline_head)
if exists("g:airline#extensions#branch#displayed_head_limit") if exists("g:airline#extensions#branch#displayed_head_limit")
let w:displayed_head_limit = g:airline#extensions#branch#displayed_head_limit let w:displayed_head_limit = g:airline#extensions#branch#displayed_head_limit
if len(b:airline_head) > w:displayed_head_limit - 1 if len(b:airline_head) > w:displayed_head_limit - 1

View File

@ -0,0 +1,18 @@
" MIT License. Copyright (c) 2013-2015 Bailey Ling.
" vim: et ts=2 sts=2 sw=2
let s:spc = g:airline_symbols.space
let s:padding = s:spc . s:spc . s:spc
function! airline#extensions#ctrlspace#statusline(...)
let b = airline#builder#new({ 'active': 1 })
call b.add_section('airline_a', s:padding . g:ctrlspace_symbols.cs . s:padding)
call b.add_section('airline_b', s:padding . ctrlspace#statusline_mode_segment(s:padding))
call b.split()
call b.add_section('airline_x', s:spc . ctrlspace#statusline_tab_segment() . s:spc)
return b.build()
endfunction
function! airline#extensions#ctrlspace#init(ext)
let g:ctrlspace_statusline_function = 'airline#extensions#ctrlspace#statusline()'
endfunction

View File

@ -5,6 +5,12 @@ let s:formatter = get(g:, 'airline#extensions#tabline#formatter', 'default')
let s:show_buffers = get(g:, 'airline#extensions#tabline#show_buffers', 1) let s:show_buffers = get(g:, 'airline#extensions#tabline#show_buffers', 1)
let s:show_tabs = get(g:, 'airline#extensions#tabline#show_tabs', 1) let s:show_tabs = get(g:, 'airline#extensions#tabline#show_tabs', 1)
let s:taboo = get(g:, 'airline#extensions#taboo#enabled', 1) && get(g:, 'loaded_taboo', 0)
if s:taboo
let g:taboo_tabline = 0
endif
function! airline#extensions#tabline#init(ext) function! airline#extensions#tabline#init(ext)
if has('gui_running') if has('gui_running')
set guioptions-=e set guioptions-=e
@ -72,9 +78,18 @@ function! airline#extensions#tabline#get()
endfunction endfunction
function! airline#extensions#tabline#title(n) function! airline#extensions#tabline#title(n)
let buflist = tabpagebuflist(a:n) let title = ''
let winnr = tabpagewinnr(a:n) if s:taboo
return airline#extensions#tabline#get_buffer_name(buflist[winnr - 1]) let title = TabooTabTitle(a:n)
endif
if empty(title)
let buflist = tabpagebuflist(a:n)
let winnr = tabpagewinnr(a:n)
return airline#extensions#tabline#get_buffer_name(buflist[winnr - 1])
endif
return title
endfunction endfunction
function! airline#extensions#tabline#get_buffer_name(nr) function! airline#extensions#tabline#get_buffer_name(nr)

View File

@ -172,6 +172,14 @@ function! s:select_tab(buf_index)
endif endif
endfunction endfunction
function! s:jump_to_tab(offset)
let l = s:current_visible_buffers
let i = index(l, bufnr('%'))
if i > -1
exec 'b!' . l[float2nr(fmod(i + a:offset, len(l)))]
endif
endfunction
if s:buffer_idx_mode if s:buffer_idx_mode
noremap <unique> <Plug>AirlineSelectTab1 :call <SID>select_tab(0)<CR> noremap <unique> <Plug>AirlineSelectTab1 :call <SID>select_tab(0)<CR>
noremap <unique> <Plug>AirlineSelectTab2 :call <SID>select_tab(1)<CR> noremap <unique> <Plug>AirlineSelectTab2 :call <SID>select_tab(1)<CR>
@ -182,4 +190,6 @@ if s:buffer_idx_mode
noremap <unique> <Plug>AirlineSelectTab7 :call <SID>select_tab(6)<CR> noremap <unique> <Plug>AirlineSelectTab7 :call <SID>select_tab(6)<CR>
noremap <unique> <Plug>AirlineSelectTab8 :call <SID>select_tab(7)<CR> noremap <unique> <Plug>AirlineSelectTab8 :call <SID>select_tab(7)<CR>
noremap <unique> <Plug>AirlineSelectTab9 :call <SID>select_tab(8)<CR> noremap <unique> <Plug>AirlineSelectTab9 :call <SID>select_tab(8)<CR>
noremap <unique> <Plug>AirlineSelectPrevTab :<C-u>call <SID>jump_to_tab(-v:count1)<CR>
noremap <unique> <Plug>AirlineSelectNextTab :<C-u>call <SID>jump_to_tab(v:count1)<CR>
endif endif

View File

@ -23,5 +23,10 @@ function! airline#extensions#tabline#formatters#unique_tail#format(bufnr, buffer
let map[nr] = airline#extensions#tabline#formatters#default#wrap_name(nr, fnamemodify(bufname(nr), ':p:.')) let map[nr] = airline#extensions#tabline#formatters#default#wrap_name(nr, fnamemodify(bufname(nr), ':p:.'))
endfor endfor
return map[a:bufnr] if has_key(map, a:bufnr)
return map[a:bufnr]
endif
" if we get here, the buffer list isn't in sync with the selected buffer yet, fall back to the default
return airline#extensions#tabline#formatters#default#format(a:bufnr, a:buffers)
endfunction endfunction

View File

@ -55,9 +55,11 @@ function! airline#extensions#tabline#tabs#get()
let val = '%(' let val = '%('
if s:show_tab_nr if s:show_tab_nr
if s:tab_nr_type == 0 if s:tab_nr_type == 0
let val .= ' %{len(tabpagebuflist('.i.'))}' let val .= (g:airline_symbols.space).'%{len(tabpagebuflist('.i.'))}'
else elseif s:tab_nr_type == 1
let val .= (g:airline_symbols.space).i let val .= (g:airline_symbols.space).i
else "== 2
let val .= (g:airline_symbols.space).i.'.%{len(tabpagebuflist('.i.'))}'
endif endif
endif endif
call b.add_section(group, val.'%'.i.'T %{airline#extensions#tabline#title('.i.')} %)') call b.add_section(group, val.'%'.i.'T %{airline#extensions#tabline#title('.i.')} %)')

View File

@ -1,7 +1,8 @@
" MIT License. Copyright (c) 2013-2015 Bailey Ling. " MIT License. Copyright (c) 2013-2015 Bailey Ling.
" vim: et ts=2 sts=2 sw=2 " vim: et ts=2 sts=2 sw=2
let s:is_win32term = (has('win32') || has('win64')) && !has('gui_running') let s:is_win32term = (has('win32') || has('win64')) && !has('gui_running') && (empty($CONEMUBUILD) || &term !=? 'xterm')
let s:separators = {} let s:separators = {}
let s:accents = {} let s:accents = {}

View File

@ -1,3 +1,6 @@
let g:airline#themes#durant#palette = {}
let s:N1 = [ '#005f00' , '#afd700' , 22 , 148 ] let s:N1 = [ '#005f00' , '#afd700' , 22 , 148 ]
let s:N2 = [ '#93a1a1' , '#586e75' , 245 , 240 ] let s:N2 = [ '#93a1a1' , '#586e75' , 245 , 240 ]
let s:N3 = [ '#93a1a1' , '#073642' , 240 , 233 ] let s:N3 = [ '#93a1a1' , '#073642' , 240 , 233 ]

View File

@ -0,0 +1,34 @@
" vim-airline theme based on vim-hybrid and powerline
" (https://github.com/w0ng/vim-hybrid)
" (https://github.com/Lokaltog/powerline)
let g:airline#themes#hybridline#palette = {}
let s:N1 = [ '#282a2e' , '#c5c8c6' , 'black' , 15 ]
let s:N2 = [ '#c5c8c6' , '#373b41' , 15 , 8 ]
let s:N3 = [ '#ffffff' , '#282a2e' , 255 , 'black' ]
let g:airline#themes#hybridline#palette.normal = airline#themes#generate_color_map(s:N1, s:N2, s:N3)
let g:airline#themes#hybridline#palette.normal.airline_a = ['#005f00', '#b5bd68', 22, 10, '']
let s:I1 = [ '#005f5f' , '#8abeb7' , 23 , 14 ]
let s:I2 = [ '#c5c8c6' , '#0087af' , 15 , 31 ]
let s:I3 = [ '#ffffff' , '#005f87' , 255 , 24 ]
let g:airline#themes#hybridline#palette.insert = airline#themes#generate_color_map(s:I1, s:I2, s:I3)
let g:airline#themes#hybridline#palette.insert_paste = {
\ 'airline_a': ['#000000', '#ac4142', 16 , 1, ''] ,
\ }
let g:airline#themes#hybridline#palette.replace = airline#themes#generate_color_map(s:N1, s:N2, s:N3)
let g:airline#themes#hybridline#palette.replace.airline_a = ['#000000', '#CC6666', 16, 9]
let g:airline#themes#hybridline#palette.visual = airline#themes#generate_color_map(s:N1, s:N2, s:N3)
let g:airline#themes#hybridline#palette.visual.airline_a = ['#000000', '#de935f', 16, 3]
let s:IA1 = [ '#4e4e4e' , '#1c1c1c' , 239 , 234 , '' ]
let s:IA2 = [ '#4e4e4e' , '#262626' , 239 , 235 , '' ]
let s:IA3 = [ '#4e4e4e' , '#303030' , 239 , 236 , '' ]
let g:airline#themes#hybridline#palette.inactive = airline#themes#generate_color_map(s:IA1, s:IA2, s:IA3)
let g:airline#themes#hybridline#palette.accents = {
\ 'red': [ '#ff0000' , '' , 160 , '' ]
\ }

View File

@ -242,6 +242,15 @@ cost. You can disable the check with the following flag. >
Note: Third party plugins that rely on this behavior will be affected. You Note: Third party plugins that rely on this behavior will be affected. You
will need to manually load them. will need to manually load them.
Alternatively, if you want a minimalistic setup and would rather opt-in which
extensions get loaded instead of disabling each individually, you can declare
the following list variable: >
" an empty list disables all extensions
let g:airline_extensions = []
" or only load what you want
let g:airline_extensions = ['branch', 'tabline']
<
------------------------------------- *airline-default* ------------------------------------- *airline-default*
The default extension understands all of the `g:` variables in the The default extension understands all of the `g:` variables in the
|airline-configuration| section, however it also has some more fine-tuned |airline-configuration| section, however it also has some more fine-tuned
@ -296,13 +305,27 @@ vcscommand <http://www.vim.org/scripts/script.php?script_id=90>
< <
* change the text for when no branch is detected > * change the text for when no branch is detected >
let g:airline#extensions#branch#empty_message = '' let g:airline#extensions#branch#empty_message = ''
<
* use vcscommand.vim if available > * use vcscommand.vim if available >
let g:airline#extensions#branch#use_vcscommand = 0 let g:airline#extensions#branch#use_vcscommand = 0
<
* truncate long branch names to a fixed length > * truncate long branch names to a fixed length >
let g:airline#extensions#branch#displayed_head_limit = 10 let g:airline#extensions#branch#displayed_head_limit = 10
<
* customize formatting of branch name >
" default value leaves the name unmodifed
let g:airline#extensions#branch#format = 0
" to only show the tail, e.g. a branch 'feature/foo' show 'foo'
let g:airline#extensions#branch#format = 1
" if a string is provided, it should be the name of a function that
" takes a string and returns the desired value
let g:airline#extensions#branch#format = 'CustomBranchName'
function! CustomBranchName(name)
return '[' . a:name . ']'
endfunction
<
------------------------------------- *airline-syntastic* ------------------------------------- *airline-syntastic*
syntastic <https://github.com/scrooloose/syntastic> syntastic <https://github.com/scrooloose/syntastic>
@ -414,9 +437,10 @@ eclim <https://eclim.org>
* configure filename match rules to exclude from the tabline. > * configure filename match rules to exclude from the tabline. >
let g:airline#extensions#tabline#excludes = [] let g:airline#extensions#tabline#excludes = []
< <
* configure how numbers are calculated in tab mode. > * configure how numbers are displayed in tab mode. >
let g:airline#extensions#tabline#tab_nr_type = 0 " # of splits (default) let g:airline#extensions#tabline#tab_nr_type = 0 " # of splits (default)
let g:airline#extensions#tabline#tab_nr_type = 1 " tab number let g:airline#extensions#tabline#tab_nr_type = 1 " tab number
let g:airline#extensions#tabline#tab_nr_type = 2 " splits and tab number
< <
* enable/disable displaying tab number in tabs mode. > * enable/disable displaying tab number in tabs mode. >
let g:airline#extensions#tabline#show_tab_nr = 1 let g:airline#extensions#tabline#show_tab_nr = 1
@ -538,19 +562,19 @@ promptline <https://github.com/edkolev/promptline.vim>
let airline#extensions#promptline#color_template = 'visual' let airline#extensions#promptline#color_template = 'visual'
let airline#extensions#promptline#color_template = 'replace' let airline#extensions#promptline#color_template = 'replace'
< <
------------------------------------- *airline-nrrwrgn* ------------------------------------- *airline-nrrwrgn*
NrrwRgn <https://github.com/chrisbra/NrrwRgn> NrrwRgn <https://github.com/chrisbra/NrrwRgn>
* enable/disable NrrwRgn integration > * enable/disable NrrwRgn integration >
let g:airline#extensions#nrrwrgn#enabled = 1 let g:airline#extensions#nrrwrgn#enabled = 1
------------------------------------- *airline-capslock* ------------------------------------- *airline-capslock*
vim-capslock <https://github.com/tpope/vim-capslock> vim-capslock <https://github.com/tpope/vim-capslock>
* enable/disable vim-capslock integration > * enable/disable vim-capslock integration >
let g:airline#extensions#capslock#enabled = 1 let g:airline#extensions#capslock#enabled = 1
------------------------------------- *airline-windowswap* ------------------------------------- *airline-windowswap*
vim-windowswap <https://github.com/wesQ3/vim-windowswap> vim-windowswap <https://github.com/wesQ3/vim-windowswap>
* enable/disable vim-windowswap integration > * enable/disable vim-windowswap integration >
@ -559,6 +583,18 @@ vim-windowswap <https://github.com/wesQ3/vim-windowswap>
* set marked window indicator string > * set marked window indicator string >
let g:airline#extensions#windowswap#indicator_text = 'WS' let g:airline#extensions#windowswap#indicator_text = 'WS'
< <
------------------------------------- *airline-taboo*
taboo.vim <https://github.com/gcmt/taboo.vim>
* enable/disable taboo.vim integration >
let g:airline#extensions#taboo#enabled = 1
<
------------------------------------- *airline-ctrlspace*
vim-ctrlspace <https://github.com/szw/vim-ctrlspace>
* enable/disable vim-ctrlspace integration >
let g:airline#extensions#ctrlspace#enabled = 1
<
============================================================================== ==============================================================================
ADVANCED CUSTOMIZATION *airline-advanced-customization* ADVANCED CUSTOMIZATION *airline-advanced-customization*

View File

@ -6,9 +6,14 @@ if &cp || v:version < 702 || (exists('g:loaded_airline') && g:loaded_airline)
endif endif
let g:loaded_airline = 1 let g:loaded_airline = 1
let s:airline_initialized = 0
let s:airline_theme_defined = 0 let s:airline_theme_defined = 0
function! s:init() function! s:init()
call airline#init#bootstrap() if s:airline_initialized
return
endif
let s:airline_initialized = 1
call airline#extensions#load() call airline#extensions#load()
call airline#init#sections() call airline#init#sections()
@ -19,17 +24,18 @@ function! s:init()
endif endif
silent doautocmd User AirlineAfterInit silent doautocmd User AirlineAfterInit
call s:airline_toggle()
endfunction endfunction
function! s:on_window_changed() function! s:on_window_changed()
if pumvisible() if pumvisible()
return return
endif endif
call s:init()
call airline#update_statusline() call airline#update_statusline()
endfunction endfunction
function! s:on_colorscheme_changed() function! s:on_colorscheme_changed()
call s:init()
if !s:airline_theme_defined if !s:airline_theme_defined
if airline#switch_matching_theme() if airline#switch_matching_theme()
return return
@ -75,7 +81,10 @@ function! s:airline_toggle()
\ | call airline#load_theme() \ | call airline#load_theme()
augroup END augroup END
call <sid>on_window_changed() if s:airline_initialized
call s:on_window_changed()
endif
silent doautocmd User AirlineToggledOn silent doautocmd User AirlineToggledOn
endif endif
endfunction endfunction
@ -95,9 +104,11 @@ endfunction
command! -nargs=? -complete=customlist,<sid>get_airline_themes AirlineTheme call <sid>airline_theme(<f-args>) command! -nargs=? -complete=customlist,<sid>get_airline_themes AirlineTheme call <sid>airline_theme(<f-args>)
command! AirlineToggleWhitespace call airline#extensions#whitespace#toggle() command! AirlineToggleWhitespace call airline#extensions#whitespace#toggle()
command! AirlineToggle call <sid>airline_toggle() command! AirlineToggle call s:airline_toggle()
command! AirlineRefresh call airline#load_theme() | call airline#update_statusline() command! AirlineRefresh call airline#load_theme() | call airline#update_statusline()
autocmd VimEnter * call airline#deprecation#check() call airline#init#bootstrap()
autocmd VimEnter * call s:init() call s:airline_toggle()
autocmd VimEnter * call airline#deprecation#check()

View File

@ -1,7 +1,7 @@
let g:airline_theme = 'dark' let g:airline_theme = 'dark'
call airline#init#bootstrap()
call airline#init#sections()
source plugin/airline.vim source plugin/airline.vim
doautocmd VimEnter
function! MyFuncref(...) function! MyFuncref(...)
call a:1.add_raw('hello world') call a:1.add_raw('hello world')

View File

@ -1,7 +1,5 @@
call airline#init#bootstrap()
call airline#init#sections()
source plugin/airline.vim source plugin/airline.vim
doautocmd VimEnter
describe 'commands' describe 'commands'
it 'should toggle off and on' it 'should toggle off and on'

View File

@ -1,8 +1,10 @@
let g:airline_theme = 'dark' let g:airline#extensions#default#layout = [
call airline#init#bootstrap() \ [ 'c', 'a', 'b', 'warning' ],
call airline#init#sections() \ [ 'x', 'z', 'y' ]
\ ]
source plugin/airline.vim source plugin/airline.vim
call airline#load_theme() doautocmd VimEnter
describe 'default' describe 'default'
before before
@ -10,10 +12,6 @@ describe 'default'
end end
it 'should use the layout' it 'should use the layout'
let g:airline#extensions#default#layout = [
\ [ 'c', 'a', 'b', 'warning' ],
\ [ 'x', 'z', 'y' ]
\ ]
call airline#extensions#default#apply(s:builder, { 'winnr': 1, 'active': 1 }) call airline#extensions#default#apply(s:builder, { 'winnr': 1, 'active': 1 })
let stl = s:builder.build() let stl = s:builder.build()
Expect stl =~ 'airline_c_to_airline_a' Expect stl =~ 'airline_c_to_airline_a'

View File

@ -88,7 +88,7 @@ vim-go has several `<Plug>` mappings which can be used to create custom
mappings. Below are some examples you might find useful: mappings. Below are some examples you might find useful:
Show a list of interfaces which is implemented by the type under your cursor Show a list of interfaces which is implemented by the type under your cursor
with `<leader>s` with `<leader>s`
```vim ```vim
au FileType go nmap <Leader>s <Plug>(go-implements) au FileType go nmap <Leader>s <Plug>(go-implements)
@ -187,6 +187,8 @@ To change it:
let g:go_highlight_functions = 1 let g:go_highlight_functions = 1
let g:go_highlight_methods = 1 let g:go_highlight_methods = 1
let g:go_highlight_structs = 1 let g:go_highlight_structs = 1
let g:go_highlight_operators = 1
let g:go_highlight_build_constraints = 1
``` ```
## Troubleshooting ## Troubleshooting
@ -198,13 +200,13 @@ If trying to use `:GoDef`, `:GoInfo` and get a `command not found`, check that
Before opening vim, check your current `$PATH`: Before opening vim, check your current `$PATH`:
echo $PATH echo $PATH
after opening vim, run `:echo $PATH`, the output must be your current `$PATH` + `$PATH/bin` (the location where `:GoInstallBinaries` installed the binaries after opening vim, run `:echo $PATH`, the output must be your current `$PATH` + `$GOPATH/bin` (the location where `:GoInstallBinaries` installed the binaries
If problem persists and you are using maybe 'csh' or other shell, try adding this to your .vimrc: If problem persists and you are using maybe 'csh' or other shell, try adding this to your .vimrc:
set shell=/bin/sh set shell=/bin/sh
### I'm using Fish shell but have some problems using Vim-go ### I'm using Fish shell but have some problems using Vim-go
@ -240,7 +242,7 @@ Give it a try. I hope you like it. Feel free to contribute to the project.
## Donations ## Donations
Vim-go is an open source project and I'm working on it on my free times. I'm spending a lot of time and thoughts to make it stable, fixing bugs, adding new features, etc... If you like vim-go and find it helpful, you might give me a gift from some of the books (kindle) I have in my wish list: Vim-go is an open source project and I'm working on it on my free times. I'm spending a lot of time and thoughts to make it stable, fixing bugs, adding new features, etc... If you like vim-go and find it helpful, you might give me a gift from some of the books (kindle) I have in my wish list:
[Amazon.com Fatih's Wish List](http://amzn.com/w/3RUTKZC0U30P6). Thanks! [Amazon.com Fatih's Wish List](http://amzn.com/w/3RUTKZC0U30P6). Thanks!

View File

@ -81,13 +81,25 @@ function! go#cmd#Build(bang, ...)
let &makeprg = default_makeprg let &makeprg = default_makeprg
endfunction endfunction
function! go#cmd#Test(...) function! go#cmd#Test(compile, ...)
let command = "go test ." let command = "go test "
if len(a:000)
let command = "go test " . expand(a:1) " don't run the test, only compile it. Useful to capture and fix errors or
" to create a test binary.
if a:compile
let command .= "-c"
endif
if len(a:000)
let command .= expand(a:1)
endif
if a:compile
echon "vim-go: " | echohl Identifier | echon "compiling tests ..." | echohl None
else
echon "vim-go: " | echohl Identifier | echon "testing ..." | echohl None
endif endif
echon "vim-go: " | echohl Identifier | echon "testing ..." | echohl None
redraw redraw
let out = go#tool#ExecuteInDir(command) let out = go#tool#ExecuteInDir(command)
if v:shell_error if v:shell_error
@ -103,7 +115,12 @@ function! go#cmd#Test(...)
else else
call setqflist([]) call setqflist([])
cwindow cwindow
echon "vim-go: " | echohl Function | echon "[test] PASS" | echohl None
if a:compile
echon "vim-go: " | echohl Function | echon "[test] SUCCESS" | echohl None
else
echon "vim-go: " | echohl Function | echon "[test] PASS" | echohl None
endif
endif endif
endfunction endfunction

View File

@ -135,6 +135,11 @@ function! go#complete#Info()
endif endif
endfunction endfunction
function! s:trim_bracket(val)
let a:val.word = substitute(a:val.word, '[(){}\[\]]\+$', '', '')
return a:val
endfunction
fu! go#complete#Complete(findstart, base) fu! go#complete#Complete(findstart, base)
"findstart = 1 when we need to get the text length "findstart = 1 when we need to get the text length
if a:findstart == 1 if a:findstart == 1
@ -142,6 +147,10 @@ fu! go#complete#Complete(findstart, base)
return col('.') - g:gocomplete_completions[0] - 1 return col('.') - g:gocomplete_completions[0] - 1
"findstart = 0 when we need to return the list of completions "findstart = 0 when we need to return the list of completions
else else
let s = getline(".")[col('.') - 1]
if s =~ '[(){}\{\}]'
return map(copy(g:gocomplete_completions[1]), 's:trim_bracket(v:val)')
endif
return g:gocomplete_completions[1] return g:gocomplete_completions[1]
endif endif
endf endf

View File

@ -56,7 +56,7 @@ func! s:qflistSecond(output)
" We discard line2 and col2 for the first errorformat, because it's not " We discard line2 and col2 for the first errorformat, because it's not
" useful and quickfix only has the ability to show one line and column " useful and quickfix only has the ability to show one line and column
" number " number
let &errorformat = "%f:%l.%c-%.%#:\ %m,%f:%l:%c:\ %m" let &errorformat = "%f:%l.%c-%[%^:]%#:\ %m,%f:%l:%c:\ %m"
" create the quickfix list and open it " create the quickfix list and open it
cgetexpr split(a:output, "\n") cgetexpr split(a:output, "\n")
@ -189,6 +189,27 @@ endfunction
" Show all refs to entity denoted by selected identifier " Show all refs to entity denoted by selected identifier
function! go#oracle#Referrers(selected) function! go#oracle#Referrers(selected)
let out = s:RunOracle('referrers', a:selected) let out = s:RunOracle('referrers', a:selected)
" append line contents from Go source file for some messages:
" '...: referenced here'
" '...: reference to NAME'
let lines = split(out, "\n")
let extlines = []
for line in lines
if line =~# '\v: referenced here$|: reference to [^ :]*$'
let parts = split(line, ':')
" Note: we count -3 from end, to support additional comma in
" Windows-style C:\... paths
let filename = join(parts[0:-3], ':')
let linenum = parts[-2]
let extline = line . ': ' . readfile(filename, '', linenum)[linenum-1]
call add(extlines, extline)
else
call add(extlines, line)
endif
endfor
let out = join(extlines, "\n")
call s:qflistSecond(out) call s:qflistSecond(out)
endfunction endfunction

View File

@ -124,17 +124,21 @@ function! go#tool#BinPath(binpath)
let old_path = $PATH let old_path = $PATH
let $PATH = $PATH . PathSep() .go_bin_path let $PATH = $PATH . PathSep() .go_bin_path
if !executable(binpath) if !executable(basename)
echo "vim-go: could not find '" . basename . "'. Run :GoInstallBinaries to fix it." echo "vim-go: could not find '" . basename . "'. Run :GoInstallBinaries to fix it."
" restore back!
let $PATH = old_path
return "" return ""
endif endif
" restore back! let $PATH = old_path
if go_bin_path
let $PATH = old_path let sep = '/'
if IsWin()
let sep = '\'
endif endif
return go_bin_path . '/' . basename return go_bin_path . sep . basename
endfunction endfunction
" following two functions are from: https://github.com/mattn/gist-vim " following two functions are from: https://github.com/mattn/gist-vim

View File

@ -38,10 +38,13 @@ easily.
* Better `gofmt` on save, keeps cursor position and doesn't break your undo * Better `gofmt` on save, keeps cursor position and doesn't break your undo
history history
* Go to symbol/declaration with `godef` * Go to symbol/declaration with `godef`
* Look up documentation with `godoc` inside Vim or open it in browser.
* Automatically import packages via `goimports` * Automatically import packages via `goimports`
* Compile and `go build` your package, install it with `go install` * Compile and `go build` your package, install it with `go install`
* `go run` quickly your current file/files * `go run` quickly your current file/files
* Run `go test` and see any errors in quickfix window * Run `go test` and see any errors in quickfix window
* Create a coverage profile and display annotated source code in browser to
see which functions are covered.
* Lint your code with `golint` * Lint your code with `golint`
* Run your code trough `go vet` to catch static errors. * Run your code trough `go vet` to catch static errors.
* Advanced source analysis tool with `oracle` * Advanced source analysis tool with `oracle`
@ -50,30 +53,49 @@ easily.
* Checking with `errcheck` for unchecked errors. * Checking with `errcheck` for unchecked errors.
* Integrated and improved snippets. Supports `ultisnips` or `neosnippet` * Integrated and improved snippets. Supports `ultisnips` or `neosnippet`
* Share your current code to play.golang.org * Share your current code to play.golang.org
* Type information about the underlying identifier * On-the-fly type information about the word under the cursor
* Tagbar support to show tags of the source code in a sidebar with `gotags` * Tagbar support to show tags of the source code in a sidebar with `gotags`
* Custom vim text objects, such a `a function` or `inner function`
=============================================================================== ===============================================================================
INSTALL *go-install* INSTALL *go-install*
If you use pathogen, just clone it into your bundle directory: > Vim-go follows the standard runtime path structure, so I highly recommend to use
a common and well known plugin manager to install vim-go. Do not use vim-go with
other Go plugins. For Pathogen just clone the repo, for other plugin managers
add the appropriate lines and execute the plugin's install command.
$ cd ~/.vim/bundle * https://github.com/tpope/vim-pathogen >
$ git clone https://github.com/fatih/vim-go.git
git clone https://github.com/fatih/vim-go.git ~/.vim/bundle/vim-go
< <
For Vundle add this line to your vimrc: * https://github.com/junegunn/vim-plug >
>
Plugin 'fatih/vim-go' Plug 'fatih/vim-go'
<
* https://github.com/Shougo/neobundle.vim >
NeoBundle 'fatih/vim-go'
< <
and execute `:PluginInstall` (or `:BundleInstall` for older versions of Vundle)
* https://github.com/gmarik/vundle >
Please be sure all necessary binares are installed (such as `gocode`, `godef`, Plugin 'fatih/vim-go'
<
* Manual >
Copy all of the files into your `~/.vim` directory
<
Please be sure all necessary binaries are installed (such as `gocode`, `godef`,
`goimports`, etc..). You can easily install them with the included `goimports`, etc..). You can easily install them with the included
|GoInstallBinaries|. Those binaries will be automatically downloaded and |GoInstallBinaries| command. If you invoke it, all necessary binaries will be
installed to your `$GOBIN` environment (if not set it will use `$GOPATH/bin`). automatically downloaded and installed to your `$GOBIN` environment (if not set
It requires `git` and `hg` for fetching the individual Go packages. it will use `$GOPATH/bin`). It requires `git` for fetching the individual Go
packages.
* Autocompletion is enabled by default via `<C-x><C-o>`, to get real-time * Autocompletion is enabled by default via `<C-x><C-o>`, to get real-time
completion (completion by type) install: completion (completion by type) install:
@ -199,9 +221,18 @@ COMMANDS *go-commands*
*:GoTest* *:GoTest*
:GoTest [expand] :GoTest [expand]
Test your _test.go files via in your current directory. Errors are Run the tests on your _test.go files via in your current directory. Errors
are populated in quickfix window. If an argument is passed, 'expand' is
used as file selector (useful for cases like `:GoTest ./...`).
*:GoTestCompile*
:GoTestCompile [expand]
Compile your _test.go files via in your current directory. Errors are
populated in quickfix window. If an argument is passed, 'expand' is used populated in quickfix window. If an argument is passed, 'expand' is used
as file selector (useful for cases like `:GoTest ./...`). as file selector (useful for cases like `:GoTest ./...`). Useful to not
run the tests and capture/fix errors before running the tests or to
create test binary.
*:GoCoverage* *:GoCoverage*
:GoCoverage :GoCoverage
@ -359,6 +390,10 @@ Calls `go install` for the current package
Calls `go test` for the current package Calls `go test` for the current package
*(go-test-compile)*
Calls `go test -c` for the current package
*(go-coverage)* *(go-coverage)*
Calls `go test -coverprofile-temp.out` for the current package Calls `go test -coverprofile-temp.out` for the current package
@ -699,7 +734,8 @@ or
set shell='/bin/sh' set shell='/bin/sh'
> >
I'm seeing weirds errors during the startup~ I'm seeing weirds errors during installation of binaries with
GoInstallBinaries:
If you see errors like this: If you see errors like this:
> >

View File

@ -8,7 +8,8 @@ let g:go_loaded_commands = 1
nnoremap <silent> <Plug>(go-run) :<C-u>call go#cmd#Run(expand('%'))<CR> nnoremap <silent> <Plug>(go-run) :<C-u>call go#cmd#Run(expand('%'))<CR>
nnoremap <silent> <Plug>(go-build) :<C-u>call go#cmd#Build('')<CR> nnoremap <silent> <Plug>(go-build) :<C-u>call go#cmd#Build('')<CR>
nnoremap <silent> <Plug>(go-install) :<C-u>call go#cmd#Install()<CR> nnoremap <silent> <Plug>(go-install) :<C-u>call go#cmd#Install()<CR>
nnoremap <silent> <Plug>(go-test) :<C-u>call go#cmd#Test('')<CR> nnoremap <silent> <Plug>(go-test) :<C-u>call go#cmd#Test(0, '')<CR>
nnoremap <silent> <Plug>(go-test-compile) :<C-u>call go#cmd#Test(1, '')<CR>
nnoremap <silent> <Plug>(go-coverage) :<C-u>call go#cmd#Coverage('')<CR> nnoremap <silent> <Plug>(go-coverage) :<C-u>call go#cmd#Coverage('')<CR>
nnoremap <silent> <Plug>(go-vet) :<C-u>call go#cmd#Vet()<CR> nnoremap <silent> <Plug>(go-vet) :<C-u>call go#cmd#Vet()<CR>
nnoremap <silent> <Plug>(go-files) :<C-u>call go#tool#Files()<CR> nnoremap <silent> <Plug>(go-files) :<C-u>call go#tool#Files()<CR>
@ -63,7 +64,8 @@ command! -nargs=* GoInfo call go#complete#Info()
command! -nargs=* -bang GoRun call go#cmd#Run(<bang>0,<f-args>) command! -nargs=* -bang GoRun call go#cmd#Run(<bang>0,<f-args>)
command! -nargs=* -bang GoBuild call go#cmd#Build(<bang>0,<f-args>) command! -nargs=* -bang GoBuild call go#cmd#Build(<bang>0,<f-args>)
command! -nargs=* GoInstall call go#cmd#Install(<f-args>) command! -nargs=* GoInstall call go#cmd#Install(<f-args>)
command! -nargs=* GoTest call go#cmd#Test(<f-args>) command! -nargs=* GoTest call go#cmd#Test(0, <f-args>)
command! -nargs=* GoTestCompile call go#cmd#Test(1, <f-args>)
command! -nargs=* GoCoverage call go#cmd#Coverage(<f-args>) command! -nargs=* GoCoverage call go#cmd#Coverage(<f-args>)
command! -nargs=0 GoVet call go#cmd#Vet() command! -nargs=0 GoVet call go#cmd#Vet()

View File

@ -38,7 +38,7 @@ endsnippet
# case # case
snippet case "case ...:" snippet case "case ...:"
case ${1:value}: case ${1:value}:
${0} ${0:${VISUAL}}
endsnippet endsnippet
# constant # constant
@ -70,8 +70,7 @@ endsnippet
# default case # default case
snippet default "default: ..." snippet default "default: ..."
default: default:
${0} ${0:${VISUAL}}
endsnippet endsnippet
# defer # defer
@ -82,7 +81,7 @@ endsnippet
snippet def "defer func() { ... }" snippet def "defer func() { ... }"
defer func() { defer func() {
${0} ${0:${VISUAL}}
}() }()
endsnippet endsnippet
@ -90,7 +89,7 @@ endsnippet
snippet defr snippet defr
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {
${0} ${0:${VISUAL}}
} }
}() }()
endsnippet endsnippet
@ -133,14 +132,14 @@ endsnippet
# if condition # if condition
snippet if "if ... { ... }" snippet if "if ... { ... }"
if ${1:condition} { if ${1:condition} {
${0} ${0:${VISUAL}}
} }
endsnippet endsnippet
# else snippet # else snippet
snippet else snippet else
else { else {
${0} ${0:${VISUAL}}
} }
endsnippet endsnippet
@ -167,6 +166,14 @@ if err != nil {
${0} ${0}
endsnippet endsnippet
snippet errh "Error handle and return" !b
if err != nil {
${1}
return
}
${0}
endsnippet
snippet json "\`json:key\`" snippet json "\`json:key\`"
\`json:"${1:keyName}"\` \`json:"${1:keyName}"\`
endsnippet endsnippet
@ -179,21 +186,21 @@ endsnippet
# for loop # for loop
snippet for "for ... { ... }" snippet for "for ... { ... }"
for ${1} { for ${1} {
${0} ${0:${VISUAL}}
} }
endsnippet endsnippet
# for integer loop # for integer loop
snippet fori "for 0..N-1 { ... }" snippet fori "for 0..N-1 { ... }"
for ${1:i} := 0; $1 < ${2:N}; $1++ { for ${1:i} := 0; $1 < ${2:N}; $1++ {
${0} ${0:${VISUAL}}
} }
endsnippet endsnippet
# for range loop # for range loop
snippet forr "for k, v := range items { ... }" snippet forr "for k, v := range items { ... }"
for ${2:k}, ${3:v} := range ${1} { for ${2:k}, ${3:v} := range ${1} {
${0} ${0:${VISUAL}}
} }
endsnippet endsnippet
@ -211,17 +218,17 @@ endsnippet
# Fmt Println debug # Fmt Println debug
snippet fn "fmt.Println(...)" snippet fn "fmt.Println(...)"
fmt.Println("${1}") fmt.Println("${1:${VISUAL}}")
endsnippet endsnippet
# log printf # log printf
snippet lf "log.Printf(...)" snippet lf "log.Printf(...)"
log.Printf("${1} = %+v\n", $1) log.Printf("${1:${VISUAL}} = %+v\n", $1)
endsnippet endsnippet
# log println # log println
snippet ln "log.Println(...)" snippet ln "log.Println(...)"
log.Println("${1}") log.Println("${1:${VISUAL}}")
endsnippet endsnippet
# make # make
@ -237,7 +244,7 @@ endsnippet
# main() # main()
snippet main "func main() { ... }" snippet main "func main() { ... }"
func main() { func main() {
${0} ${0:${VISUAL}}
} }
endsnippet endsnippet
@ -251,7 +258,7 @@ endsnippet
# ok # ok
snippet ok "if !ok { ... }" snippet ok "if !ok { ... }"
if !ok { if !ok {
${0} ${0:${VISUAL}}
} }
endsnippet endsnippet
@ -269,7 +276,7 @@ endsnippet
# return # return
snippet rt "return" snippet rt "return"
return ${0} return ${0:${VISUAL}}
endsnippet endsnippet
# select # select
@ -316,7 +323,7 @@ endsnippet
# test function # test function
snippet test "func TestXYZ(t *testing.T) { ... }" snippet test "func TestXYZ(t *testing.T) { ... }"
func Test${1:Function}(t *testing.T) { func Test${1:Function}(t *testing.T) {
${0} ${0:${VISUAL}}
} }
endsnippet endsnippet
@ -346,16 +353,26 @@ endsnippet
# variable declaration # variable declaration
snippet var "var x Type [= ...]" snippet var "var x Type [= ...]"
var ${1:x} ${2:Type}${3: = ${0:value\}} var ${1:x} ${2:Type}${3: = ${0:value}}
endsnippet endsnippet
# variables declaration # variables declaration
snippet vars "var ( ... )" snippet vars "var ( ... )"
var ( var (
${1:x} ${2:Type}${3: = ${0:value\}} ${1:x} ${2:Type}${3: = ${0:value}}
) )
endsnippet endsnippet
# equals fails the test if exp is not equal to act.
snippet eq "equals: test two identifiers with DeepEqual"
if !reflect.DeepEqual(${1:expected}, ${2:actual}) {
_, file, line, _ := runtime.Caller(0)
fmt.Printf("%s:%d:\n\n\texp: %#v\n\n\tgot: %#v\n\n", filepath.Base(file), line, $1, $2)
t.FailNow()
}
endsnippet
global !p global !p
import re import re

View File

@ -139,6 +139,16 @@ abbr if err != nil { return [...], err }
} }
${0} ${0}
# error snippet handle and return
snippet errh
abbr if err != nil { return }
if err != nil {
${1}
return
}
${0}
# json snippet # json snippet
snippet json snippet json
abbr \`json:key\` abbr \`json:key\`
@ -304,3 +314,11 @@ abbr var ( ... )
var ( var (
${1:x} ${2:Type}${3: = ${0:value\}} ${1:x} ${2:Type}${3: = ${0:value\}}
) )
# equals fails the test if exp is not equal to act.
snippet eq
abbr equals: test two identifiers with DeepEqual
if !reflect.DeepEqual(${1:expected}, ${2:actual}) {
_, file, line, _ := runtime.Caller(0)
fmt.Printf("%s:%d:\n\n\texp: %#v\n\n\tgot: %#v\n\n", filepath.Base(file), line, $1, $2)
t.FailNow()
}

View File

@ -14,6 +14,7 @@ The following plugins support repeat.vim:
* [abolish.vim](https://github.com/tpope/vim-abolish) * [abolish.vim](https://github.com/tpope/vim-abolish)
* [unimpaired.vim](https://github.com/tpope/vim-unimpaired) * [unimpaired.vim](https://github.com/tpope/vim-unimpaired)
* [commentary.vim](https://github.com/tpope/vim-commentary) * [commentary.vim](https://github.com/tpope/vim-commentary)
* [vim-easyclip](https://github.com/svermeulen/vim-easyclip)
Adding support to a plugin is generally as simple as the following Adding support to a plugin is generally as simple as the following
command at the end of your map functions. command at the end of your map functions.

View File

@ -29,6 +29,7 @@ additional contributions from:
* [lpil](https://github.com/lpil) * [lpil](https://github.com/lpil)
* [marutanm](https://github.com/marutanm) * [marutanm](https://github.com/marutanm)
* [MicahElliott](https://github.com/MicahElliott) * [MicahElliott](https://github.com/MicahElliott)
* [mikeastock](https://github.com/mikeastock)
* [muffinresearch](https://github.com/muffinresearch) * [muffinresearch](https://github.com/muffinresearch)
* [pielgrzym](https://github.com/pielgrzym) * [pielgrzym](https://github.com/pielgrzym)
* [pose](https://github.com/pose) * [pose](https://github.com/pose)

View File

@ -37,17 +37,43 @@ looking at the [vim-snippets][vim-snippets] repository.
% git clone https://github.com/honza/vim-snippets.git % git clone https://github.com/honza/vim-snippets.git
* Using [Vundle][vundle], add the following to your `vimrc` then run * Using [Vundle][vundle], add the following to your `vimrc` then run
`:BundleInstall` `:PluginInstall`
Bundle "MarcWeber/vim-addon-mw-utils" Plugin "MarcWeber/vim-addon-mw-utils"
Bundle "tomtom/tlib_vim" Plugin "tomtom/tlib_vim"
Bundle "garbas/vim-snipmate" Plugin "garbas/vim-snipmate"
" Optional: " Optional:
Bundle "honza/vim-snippets" Plugin "honza/vim-snippets"
## FAQ ## ## FAQ ##
> SnipMate doesn't work / My snippets aren't triggering
Try all of the following:
* Check that SnipMate is loaded. This can be done by looking for
`<Plug>snipMateTrigger` and similar maps in the output of `:imap`.
Additionally make sure either `<Plug>snipMateTrigger` or
`<Plug>snipMateNextOrTrigger` is mapped to the key you expect.
* Check that the snippets file you mean to use exists, and that it contains the
snippet you're trying to expand.
* Check that your snippets file is located inside a `foo/snippets` directory,
where `foo` is a path listed in your `runtimepath`.
* Check that your snippets file is in scope by either the filetype matching the
path of the snippet file or the scope explicitly loaded.
* Check if any snippets from your snippets file are available. This can be done
with the "show available snips` map, by default bound to `<C-R><Tab>` in
insert mode.
If all of the above check out, please open an issue stating your Vim version,
a sample snippet, and a description of exactly what happens when you try to
trigger a snippet.
> How does SnipMate determine which snippets to load? How can I separate, for > How does SnipMate determine which snippets to load? How can I separate, for
> example, my Rails snippets from my Ruby snippets? > example, my Rails snippets from my Ruby snippets?

View File

@ -331,7 +331,7 @@ function! s:snippet_filenames(scope, trigger) abort
let mid = ['', '_*', '/*'] let mid = ['', '_*', '/*']
let mid += map(copy(mid), "'/' . a:trigger . '*' . v:val") let mid += map(copy(mid), "'/' . a:trigger . '*' . v:val")
call map(mid, "'snippets/' . a:scope . v:val . '.snippet'") call map(mid, "'snippets/' . a:scope . v:val . '.snippet'")
return join(map(mid[:2], 'v:val . "s"') + mid[3:]) return map(mid[:2], 'v:val . "s"') + mid[3:]
endfunction endfunction
function! snipMate#SetByPath(dict, trigger, path, snippet, bang, snipversion) abort function! snipMate#SetByPath(dict, trigger, path, snippet, bang, snipversion) abort
@ -342,12 +342,27 @@ function! snipMate#SetByPath(dict, trigger, path, snippet, bang, snipversion) ab
let d[a:trigger][a:path] = [a:snippet, a:snipversion] let d[a:trigger][a:path] = [a:snippet, a:snipversion]
endfunction endfunction
if v:version < 704 || has('win32')
function! s:Glob(path, expr)
let res = []
for p in split(a:path, ',')
let h = split(fnamemodify(a:expr, ':h'), '/')[0]
if isdirectory(p . '/' . h)
call extend(res, split(glob(p . '/' . a:expr), "\n"))
endif
endfor
return filter(res, 'filereadable(v:val)')
endfunction
else
function! s:Glob(path, expr)
return split(globpath(a:path, a:expr), "\n")
endfunction
endif
" default triggers based on paths " default triggers based on paths
function! snipMate#DefaultPool(scopes, trigger, result) abort function! snipMate#DefaultPool(scopes, trigger, result) abort
let scopes = s:AddScopeAliases(a:scopes) let scopes = s:AddScopeAliases(a:scopes)
let scopes_done = [] let scopes_done = []
let rtp_save = &rtp
let &rtp = join(g:snipMate.snippet_dirs, ',')
let s:lookup_state = {} let s:lookup_state = {}
let s:lookup_state.snips = [] let s:lookup_state.snips = []
@ -356,7 +371,13 @@ function! snipMate#DefaultPool(scopes, trigger, result) abort
let s:lookup_state.scope = scope let s:lookup_state.scope = scope
let s:lookup_state.extends = [] let s:lookup_state.extends = []
exec 'runtime!' s:snippet_filenames(scope, escape(a:trigger, "*[]?{}`'$|#%")) for expr in s:snippet_filenames(scope, escape(a:trigger, "*[]?{}`'$|#%"))
for path in g:snipMate.snippet_dirs
for file in s:Glob(path, expr)
source `=file`
endfor
endfor
endfor
call add(scopes_done, scope) call add(scopes_done, scope)
call extend(scopes, s:lookup_state.extends) call extend(scopes, s:lookup_state.extends)
@ -368,8 +389,6 @@ function! snipMate#DefaultPool(scopes, trigger, result) abort
call snipMate#SetByPath(a:result, trigger, desc, contents, bang, snipversion) call snipMate#SetByPath(a:result, trigger, desc, contents, bang, snipversion)
endif endif
endfor endfor
let &rtp = rtp_save
endfunction endfunction
" return a dict of snippets found in runtimepath matching trigger " return a dict of snippets found in runtimepath matching trigger
@ -385,64 +404,28 @@ fun! snipMate#GetSnippets(scopes, trigger) abort
return result return result
endf endf
" adds leading tab function! snipMate#OpenSnippetFiles() abort
" and replaces leading spaces by tabs let files = []
" see ftplugin/snippet.vim let scopes_done = []
fun! snipMate#RetabSnip() range abort let exists = []
let leadingTab = expand('%:e') == 'snippets' let notexists = []
for scope in s:AddScopeAliases(snipMate#ScopesByFile())
let lines = getline(a:firstline, a:lastline) let files += split(s:snippet_filenames(scope, ''))
" remove leading "\t"
let allIndented = 1
for l in lines
if l[0] != '\t' | let allIndented = 0 | endif
endfor
" retab
if allIndented
call map(lines, 'v:val[1:]')
endif
let leadingSp = filter(map(copy(lines),'matchstr(v:val,"^\\s*") '),'v:val !=""')
if !empty(leadingSp)
" lines containing leading spaces found
let smallestInd = len(sort(leadingSp)[-1])
let ind = input('retab, spaces per tab: ', smallestInd)
for i in range(0, len(lines)-1)
let ml = matchlist(lines[i], '^\(\s*\)\(.*\)')
let lines[i] = repeat("\t", len(ml[1]) / ind)
\ . repeat( " ", len(ml[1]) % ind)
\ . ml[2]
endfor endfor
endif call filter(files, "v:val !~# '\\*'")
" readd tab for path in split(g:snipMate.snippet_dirs, ',')
let tab = leadingTab ? "\t" : "" let fullpaths = map(copy(files), 'printf("%s/%s", path, v:val)')
for i in range(0,len(lines)-1) let exists += filter(copy(fullpaths), 'filereadable(v:val)')
call setline(a:firstline + i, tab.lines[i]) let notexists += map(filter(copy(fullpaths),
endfor \ 'v:val =~# "\.snippets" && !filereadable(v:val)'),
endf \ '"does not exist: " . v:val')
endfor
fun! snipMate#OpenSnippetFiles() abort let all = exists + notexists
let dict = snipMate#GetSnippetFiles(0, snipMate#ScopesByFile(), '*') let select = tlib#input#List('mi', 'select files to be opened in splits', all)
" sort by files wether they exist - put existing files first for idx in select
let exists = [] exec 'sp' all[idx - 1]
let notExists = [] endfor
for [file, v] in items(dict) endfunction
let v['file'] = file
if v['exists']
call add(exists, v)
else
call add(notExists, v)
endif
endfor
let all = exists + notExists
let show = map(copy(all),'(v:val["exists"] ? "exists:" : "does not exist yet:")." ".v:val["file"]')
let select = tlib#input#List('mi', 'select files to be opened in splits', show)
for idx in select
exec 'sp '.all[idx - 1]['file']
endfor
endf
fun! snipMate#ScopesByFile() abort fun! snipMate#ScopesByFile() abort
" duplicates are removed in AddScopeAliases " duplicates are removed in AddScopeAliases

View File

@ -1,8 +0,0 @@
command! -buffer -range=% RetabSnip <line1>,<line2>call snipMate#RetabSnip()
vnoremap <buffer> <cr> :RetabSnip<cr>
if !exists('g:snippet_no_indentation_settings')
setlocal sw=4
setlocal tabstop=4
setlocal noexpandtab
endif

View File

@ -1 +1,20 @@
runtime! ftplugin/snippet.vim " Vim filetype plugin for SnipMate snippets (.snippets and .snippet files)
if exists("b:did_ftplugin")
finish
endif
let b:did_ftplugin = 1
let b:undo_ftplugin = "setl et< sts< cms< fdm< fde<"
" Use hard tabs
setlocal noexpandtab softtabstop=0
setlocal foldmethod=expr foldexpr=getline(v:lnum)!~'^\\t\\\\|^$'?'>1':1
setlocal commentstring=#\ %s
setlocal nospell
command! -buffer -range=% RetabSnip
\ echom "This command is deprecated. Use :retab and = instead. Doing that now."
\ | <line1>,<line2>retab! | <line1>,<line2>normal =

View File

@ -0,0 +1,32 @@
" Simple indent support for SnipMate snippets files
if exists('b:did_indent')
finish
endif
let b:did_indent = 1
setlocal nosmartindent
setlocal indentkeys=!^F,o,O,=snippet,=version,=extends
setlocal indentexpr=GetSnippetIndent()
if exists("*GetSnippetIndent")
finish
endif
function! GetSnippetIndent()
let line = getline(v:lnum)
let prev_lnum = v:lnum - 1
let prev_line = prev_lnum != 0 ? getline(prev_lnum) : ""
if line =~# '\v^(snippet|extends|version) '
return 0
elseif indent(v:lnum) > 0
return indent(v:lnum)
elseif prev_line =~# '^snippet '
return &sw
elseif indent(prev_lnum) > 0
return indent(prev_lnum)
endif
return 0
endfunction

View File

@ -28,11 +28,12 @@ if (!exists('g:snipMateSources'))
let g:snipMateSources['default'] = funcref#Function('snipMate#DefaultPool') let g:snipMateSources['default'] = funcref#Function('snipMate#DefaultPool')
endif endif
au BufRead,BufNewFile *.snippet set ft=snippet au BufRead,BufNewFile *.snippet,*.snippets setlocal filetype=snippets
au FileType snippet setl noet nospell au FileType snippets if expand('<afile>:e') =~# 'snippet$'
\ | setlocal syntax=snippet
au BufRead,BufNewFile *.snippets set ft=snippets \ | else
au FileType snippets setl noet nospell fdm=expr fde=getline(v:lnum)!~'^\\t\\\\|^$'?'>1':1 \ | setlocal syntax=snippets
\ | endif
inoremap <silent> <Plug>snipMateNextOrTrigger <C-R>=snipMate#TriggerSnippet()<CR> inoremap <silent> <Plug>snipMateNextOrTrigger <C-R>=snipMate#TriggerSnippet()<CR>
snoremap <silent> <Plug>snipMateNextOrTrigger <Esc>a<C-R>=snipMate#TriggerSnippet()<CR> snoremap <silent> <Plug>snipMateNextOrTrigger <Esc>a<C-R>=snipMate#TriggerSnippet()<CR>

View File

@ -7,10 +7,10 @@ syn match snipEscape '\\\\\|\\`'
syn match snipCommand '\%(\\\@<!\%(\\\\\)*\)\@<=`.\{-}\%(\\\@<!\%(\\\\\)*\)\@<=`' syn match snipCommand '\%(\\\@<!\%(\\\\\)*\)\@<=`.\{-}\%(\\\@<!\%(\\\\\)*\)\@<=`'
syn match snippet '^snippet.*' contains=multiSnipText,snipKeyword syn match snippet '^snippet.*' contains=multiSnipText,snipKeyword
syn match snippet '^extends.*' contains=snipKeyword syn match snippet '^extends.*' contains=snipKeyword
syn match snippet '^guard\s\+.*' contains=multiSnipText,snipKeyword syn match snippet '^version.*' contains=snipKeyword
syn match multiSnipText '\S\+ \zs.*' contained syn match multiSnipText '\S\+ \zs.*' contained
syn match snipKeyword '^(snippet|extends)'me=s+8 contained syn match snipKeyword '^(snippet|extends|version)'me=s+8 contained
syn match snipError "^[^#se\t].*$" syn match snipError "^[^#vse\t].*$"
hi link snippet Identifier hi link snippet Identifier
hi link snipComment Comment hi link snipComment Comment

View File

@ -0,0 +1,3 @@
priority -50
extends html

View File

@ -79,8 +79,8 @@ snippet f. "f.password_field"
`!p textmate_var('TM_RAILS_TEMPLATE_START_RUBY_EXPR', snip)`f.password_field :${1:attribute}`!p textmate_var('TM_RAILS_TEMPLATE_END_RUBY_EXPR', snip)` `!p textmate_var('TM_RAILS_TEMPLATE_START_RUBY_EXPR', snip)`f.password_field :${1:attribute}`!p textmate_var('TM_RAILS_TEMPLATE_END_RUBY_EXPR', snip)`
endsnippet endsnippet
snippet f. "f.radio_box" snippet f. "f.radio_button"
`!p textmate_var('TM_RAILS_TEMPLATE_START_RUBY_EXPR', snip)`f.radio_box :${1:attribute}, :${2:tag_value}`!p textmate_var('TM_RAILS_TEMPLATE_END_RUBY_EXPR', snip)` `!p textmate_var('TM_RAILS_TEMPLATE_START_RUBY_EXPR', snip)`f.radio_button :${1:attribute}, :${2:tag_value}`!p textmate_var('TM_RAILS_TEMPLATE_END_RUBY_EXPR', snip)`
endsnippet endsnippet
snippet f. "f.submit" snippet f. "f.submit"

View File

@ -111,6 +111,12 @@ func ${1:name}(${2:params})${3/(.+)/ /}${3:type} {
} }
endsnippet endsnippet
snippet funch "HTTP handler" b
func ${1:handler}(${2:w} http.ResponseWriter, ${3:r} *http.Request) {
${0:${VISUAL}}
}
endsnippet
# types and variables # types and variables
snippet map "Map type" b snippet map "Map type" b
map[${1:keytype}]${2:valtype} map[${1:keytype}]${2:valtype}
@ -135,3 +141,10 @@ snippet json "JSON field"
endsnippet endsnippet
# vim:ft=snippets: # vim:ft=snippets:
# error handling
snippet err "Basic error handling" b
if err != nil {
log.${1:Fatal}(err)
}
endsnippet

View File

@ -160,14 +160,18 @@ snippet base "XHTML <base>" w
<base href="$1"${2: target="$3"}`!p x(snip)`> <base href="$1"${2: target="$3"}`!p x(snip)`>
endsnippet endsnippet
snippet body "XHTML <body>" snippet body "<body>"
<body id="${1:`!p <body>
snip.rv = snip.fn and 'Hallo' or 'Nothin'
`}"${2: onload="$3"}>
$0 $0
</body> </body>
endsnippet endsnippet
snippet div "<div>" w
<div>
$0
</div>
endsnippet
snippet div. "<div> with class" w snippet div. "<div> with class" w
<div`!p snip.rv=' class="' if t[1] else ""`${1:name}`!p snip.rv = '"' if t[1] else ""`> <div`!p snip.rv=' class="' if t[1] else ""`${1:name}`!p snip.rv = '"' if t[1] else ""`>
$0 $0

View File

@ -29,5 +29,5 @@ snippet textarea
endsnippet endsnippet
snippet img snippet img
<img src="$1"${2: alt="$3"}/> <img src="$1"${2: alt="$3"}/>
endsnippet endsnippet

View File

@ -4,12 +4,34 @@
priority -50 priority -50
snippet fn "A function, optionally with arguments and return type." b snippet let "let variable declaration" b
let ${1:name}${2:: ${3:type}} = ${4};
endsnippet
snippet letm "let mut variable declaration" b
let mut ${1:name}${2:: ${3:type}} = ${4};
endsnippet
snippet fn "A function, optionally with arguments and return type."
fn ${1:function_name}(${2})${3/..*/ -> /}${3} { fn ${1:function_name}(${2})${3/..*/ -> /}${3} {
${VISUAL}${0} ${VISUAL}${0}
} }
endsnippet endsnippet
snippet arg "Function Arguments" i
${1:a}: ${2:T}${3:, arg}
endsnippet
snippet || "Closure, anonymous function (inline)" i
${1:move }|${2}| { $3 }
endsnippet
snippet |} "Closure, anonymous function (block)" i
${1:move }|${2}| {
$3
}
endsnippet
snippet pri "print!(..)" b snippet pri "print!(..)" b
print!("${1}"${2/..*/, /}${2}); print!("${1}"${2/..*/, /}${2});
endsnippet endsnippet
@ -30,7 +52,7 @@ macro_rules! ${1:name} (
) )
endsnippet endsnippet
snippet mod "A module" b snippet mod "A module" b
mod ${1:`!p snip.rv = snip.basename.lower() or "name"`} { mod ${1:`!p snip.rv = snip.basename.lower() or "name"`} {
${VISUAL}${0} ${VISUAL}${0}
} }
@ -52,18 +74,27 @@ struct ${1:`!p snip.rv = snip.basename.title() or "Name"`} {
} }
endsnippet endsnippet
# TODO: fancy dynamic field mirroring like Python slotclass
snippet stn "Struct with new constructor." b snippet stn "Struct with new constructor." b
pub struct ${1:`!p snip.rv = snip.basename.title() or "Name"`} { pub struct ${1:`!p snip.rv = snip.basename.title() or "Name"`} {
${3} fd${0}
} }
impl $1 { impl $1 {
pub fn new(${2}) -> $1 { pub fn new(${2}) -> $1 {
${4}return $1 { $1 { ${3} };
${5}
};
} }
} }
endsnippet endsnippet
snippet fd "Struct field definition" w
${1:name}: ${2:Type},
endsnippet
snippet impl "Struct/Trait implementation" b
impl ${1:Type/Trait}${2: for ${3:Type}} {
${0}
}
endsnippet
# vim:ft=snippets: # vim:ft=snippets:

View File

@ -0,0 +1,6 @@
snippet %
<% ${0} %>
snippet =
<%= ${1} %>
snippet end
<% end %>

View File

@ -32,13 +32,13 @@ snippet unlesse: unless .. do: .. else:
unless ${1:condition}, do: ${2}, else: ${0} unless ${1:condition}, do: ${2}, else: ${0}
snippet cond snippet cond
cond do cond do
${1} -> ${1} ->
${0} ${0}
end end
snippet case snippet case
case ${1} do case ${1} do
${2} -> ${2} ->
${0} ${0}
end end
snippet df snippet df
def ${1:name}, do: ${2} def ${1:name}, do: ${2}
@ -114,4 +114,4 @@ snippet try try .. rescue .. end
end end
snippet pry snippet pry
require IEx; IEx.pry require IEx; IEx.pry
$0 ${0}

View File

@ -592,6 +592,10 @@ snippet link:rss
<link rel="alternate" href="${1:rss.xml}" title="RSS" type="application/atom+xml" /> <link rel="alternate" href="${1:rss.xml}" title="RSS" type="application/atom+xml" />
snippet link:touch snippet link:touch
<link rel="apple-touch-icon" href="${1:favicon.png}" /> <link rel="apple-touch-icon" href="${1:favicon.png}" />
snippet main
<main role="main">
${0}
</main>
snippet map snippet map
<map name="${1}"> <map name="${1}">
${0} ${0}

View File

@ -15,6 +15,11 @@ snippet f
function(${1}) { function(${1}) {
${0} ${0}
} }
# Anonymous Function assigned to variable
snippet vaf
var ${1:function_name} = function(${2}) {
${0}
};
# Function assigned to variable # Function assigned to variable
snippet vf snippet vf
var ${1:function_name} = function $1(${2}) { var ${1:function_name} = function $1(${2}) {
@ -252,6 +257,10 @@ snippet cdir
# Misc # Misc
# 'use strict';
snippet us
'use strict';
# setTimeout function # setTimeout function
snippet timeout snippet timeout
setTimeout(function () {${0}}${2}, ${1:10}); setTimeout(function () {${0}}${2}, ${1:10});

View File

@ -36,7 +36,7 @@ snippet crw
cattr_accessor :${0:attr_names} cattr_accessor :${0:attr_names}
snippet defcreate snippet defcreate
def create def create
@${1:model_class_name} = ${2:ModelClassName}.new(params[:$1]) @${1:model_class_name} = ${2:ModelClassName}.new($1_params)
respond_to do |format| respond_to do |format|
if @$1.save if @$1.save
@ -95,7 +95,7 @@ snippet defupdate
@${1:model_class_name} = ${2:ModelClassName}.find(params[:id]) @${1:model_class_name} = ${2:ModelClassName}.find(params[:id])
respond_to do |format| respond_to do |format|
if @$1.update_attributes(params[:$1]) if @$1.update($1_params)
flash[:notice] = '$2 was successfully updated.' flash[:notice] = '$2 was successfully updated.'
format.html { redirect_to(@$1) } format.html { redirect_to(@$1) }
format.xml { head :ok } format.xml { head :ok }
@ -105,6 +105,10 @@ snippet defupdate
end end
end end
end end
snippet defparams
def ${1:model_class_name}_params
params.require(:$1).permit()
end
snippet dele delegate .. to snippet dele delegate .. to
delegate :${1:methods}, to: :${0:object} delegate :${1:methods}, to: :${0:object}
snippet dele delegate .. to .. prefix .. allow_nil snippet dele delegate .. to .. prefix .. allow_nil

View File

@ -3,11 +3,11 @@
################# #################
# Functions # Functions
snippet fn snippet fn "Function definition"
fn ${1:function_name}(${2})${3} { fn ${1:function_name}(${2})${3} {
${0} ${0}
} }
snippet test snippet test "Unit test function"
#[test] #[test]
fn ${1:test_function_name}() { fn ${1:test_function_name}() {
${0} ${0}
@ -19,32 +19,51 @@ snippet bench "Bench function" b
${0} ${0}
}) })
} }
snippet new snippet new "Constructor function"
pub fn new(${2}) -> ${1:Name} { pub fn new(${2}) -> ${1:Name} {
${0}return $1 { ${3} }; $1 { ${3} };
} }
snippet main snippet main "Main function"
pub fn main() { pub fn main() {
${0} ${0}
} }
snippet let snippet let "let variable declaration"
let ${1:name: type} = ${2}; let ${1:name}${2:: ${3:type}} = ${4};
snippet let snippet letm "let mut variable declaration"
let mut ${1:name: type} = ${2}; let mut ${1:name}${2:: ${3:type}} = ${4};
snippet pln snippet pln "println!"
println!("${1}"); println!("${1}");
snippet pln, snippet pln, "println! with format param"
println!("${1}", ${2}); println!("${1}", ${2});
snippet ec # Modules
snippet ec "extern crate"
extern crate ${1:sync}; extern crate ${1:sync};
snippet ecl snippet ecl "extern crate log"
#![feature(phase)] #[macro_use]
#[phase(plugin, link)] extern crate log; extern crate log;
snippet mod snippet mod
mod ${1:`substitute(vim_snippets#Filename(), '\(_\|^\)\(.\)', '\u\2', 'g')`} { mod ${1:`substitute(vim_snippets#Filename(), '\(_\|^\)\(.\)', '\u\2', 'g')`} {
${0} ${0}
} /* $1 */ } /* $1 */
snippet crate snippet testmod "Test module" b
#[cfg(test)]
mod tests {
use super::${1:*};
test${0}
}
# Attributes
snippet allow "allow lint attribute" b
#[allow(${1:unused_variable})]
snippet cfg "cfg attribute" b
#[cfg(${1:target_os = "linux"})]
snippet feat "feature attribute" b
#![feature(${1:plugin})]
snippet der "#[derive(..)]" b
#[derive(${1:Debug})]
snippet attr "#[..]" b
#[${1:inline}]
snippet crate "Define create meta attributes"
// Crate name // Crate name
#![crate_name = "${1:crate_name}"] #![crate_name = "${1:crate_name}"]
// Additional metadata attributes // Additional metadata attributes
@ -53,110 +72,107 @@ snippet crate
#![comment = "${4:Comment.}"] #![comment = "${4:Comment.}"]
// Specify the output type // Specify the output type
#![crate_type = "${5:lib}"] #![crate_type = "${5:lib}"]
snippet allow
#[allow(${1:unused_variable})]
snippet feat
#![feature(${1:macro_rules})]
snippet der "#[deriving(..)]" b
#[deriving(${1:Show})]
snippet attr "#[..]" b
#[${1:inline}]
# Common types # Common types
snippet opt snippet opt "Option<T>"
Option<${1:int}> Option<${1:i32}>
snippet res snippet res "Result<T, E>"
Result<${1:~str}, ${2:()}> Result<${1:~str}, ${2:()}>
# Control structures
snippet if snippet if
if ${1} { if ${1} {
${0} ${0}
} }
snippet ife snippet ife "if / else"
if ${1} { if ${1} {
${2} ${2}
} else { } else {
${0} ${0}
} }
snippet el snippet el "else"
else { else {
${0} ${0}
} }
snippet eli snippet eli "else if"
else if ${1} { else if ${1} {
${0} ${0}
} }
snippet mat snippet mat "match pattern"
match ${1} { match ${1} {
${2} => ${3}, ${2} => ${3}
} }
snippet case "Case clause of pattern match"
${1:_} => ${2:expression}
snippet loop "loop {}" b snippet loop "loop {}" b
loop { loop {
${0} ${0}
} }
snippet while snippet while "while loop"
while ${1:condition} { while ${1:condition} {
${0} ${0}
} }
snippet for snippet for "for ... in ... loop"
for ${1:i} in ${2:0u..10} { for ${1:i} in ${2:0u..10} {
${0} ${0}
} }
snippet spawn
spawn(proc() {
${0}
});
snippet chan
let (${1:tx}, ${2:rx}): (Sender<${3:int}>, Receiver<${4:int}>) = channel();
snippet duplex
let (${1:from_child}, ${2:to_child}) = sync::duplex();
# TODO commenting # TODO commenting
snippet todo snippet todo "TODO comment"
// [TODO]: ${0:Description} // [TODO]: ${0:Description}
snippet fixme "FIXME comment" snippet fixme "FIXME comment"
// FIXME: $0 // FIXME: $0
# Struct # Struct
snippet st snippet st "Struct definition"
struct ${1:`substitute(vim_snippets#Filename(), '\(_\|^\)\(.\)', '\u\2', 'g')`} { struct ${1:`substitute(vim_snippets#Filename(), '\(_\|^\)\(.\)', '\u\2', 'g')`} {
${0} ${0}
} }
snippet stn snippet impl "Struct/Trait implementation"
struct ${1:`substitute(vim_snippets#Filename(), '\(_\|^\)\(.\)', '\u\2', 'g')`} { impl ${1:Type/Trait}${2: for ${3:Type}} {
${0}
}
snippet stn "Struct with new constructor"
pub struct ${1:`substitute(vim_snippets#Filename(), '\(_\|^\)\(.\)', '\u\2', 'g')`} {
${0} ${0}
} }
impl $1 { impl $1 {
pub fn new(${2}) -> $1 { pub fn new(${2}) -> $1 {
${4}return $1 { $1 { ${3} };
${5}
};
} }
} }
snippet typ snippet type "Type alias"
type ${1:NewName} = $0; type ${1:NewName} = $2;
# Enum snippet enum "enum definition"
snippet enum
enum ${1:Name} { enum ${1:Name} {
${0}, ${2},
} }
# Impl # Traits
snippet imp snippet trait "Trait definition"
impl ${1:Name} { trait ${1:Name} {
${0} ${0}
} }
snippet drop snippet drop "Drop trait implementation (destructor)"
impl Drop for ${1:Name} { impl Drop for ${1:Name} {
fn drop(&mut self) { fn drop(&mut self) {
${0} ${0}
} }
} }
# Traits
snippet trait
trait ${1:Name} {
${0}
}
# Statics # Statics
snippet ss snippet ss "static string declaration"
static ${1}: &'static str = "${0}"; static ${1}: &'static str = "${0}";
snippet stat snippet stat "static item declaration"
static ${1}: ${2:usize} = ${0}; static ${1}: ${2:usize} = ${0};
# Concurrency
snippet scoped "spawn a scoped thread"
thread::scoped(${1:move }|| {
${0}
});
snippet spawn "spawn a thread"
thread::spawn(${1:move }|| {
${0}
});
snippet chan "Declare (Sender, Receiver) pair of asynchronous channel()"
let (${1:tx}, ${2:rx}): (Sender<${3:i32}>, Receiver<${4:i32}>) = channel();
# Testing
snippet as "assert!"
assert!(${1:predicate})
snippet ase "assert_eq!"
assert_eq!(${1:expected}, ${2:actual})

View File

@ -1,5 +1,8 @@
# Shebang. Executing bash via /usr/bin/env makes scripts more portable. # Shebang. Executing bash via /usr/bin/env makes scripts more portable.
snippet #! snippet #!
#!/usr/bin/env sh
snippet bash
#!/usr/bin/env bash #!/usr/bin/env bash
snippet if snippet if
@ -51,15 +54,12 @@ snippet getopt
#=============================================================================== #===============================================================================
function usage () function usage ()
{ {
cat <<- EOT echo "Usage : $${0:0} [options] [--]
Usage : $${0:0} [options] [--] Options:
-h|help Display this message
-v|version Display script version"
Options:
-h|help Display this message
-v|version Display script version
EOT
} # ---------- end of function usage ---------- } # ---------- end of function usage ----------
#----------------------------------------------------------------------- #-----------------------------------------------------------------------
@ -74,7 +74,7 @@ snippet getopt
v|version ) echo "$${0:0} -- Version $__ScriptVersion"; exit 0 ;; v|version ) echo "$${0:0} -- Version $__ScriptVersion"; exit 0 ;;
\? ) echo -e "\n Option does not exist : $OPTARG\n" * ) echo -e "\n Option does not exist : $OPTARG\n"
usage; exit 1 ;; usage; exit 1 ;;
esac # --- end of case --- esac # --- end of case ---
@ -82,11 +82,13 @@ snippet getopt
shift $(($OPTIND-1)) shift $(($OPTIND-1))
snippet root snippet root
if [ \$(id -u) -ne 0 ]; then exec sudo \$0; fi if [ \$(id -u) -ne 0 ]; then exec sudo \$0; fi
snippet fun
snippet fun-sh
${1:function_name}() { ${1:function_name}() {
${0:#function_body} ${0:#function_body}
} }
snippet ffun
snippet fun
function ${1:function_name}() { function ${1:function_name}() {
${0:#function_body} ${0:#function_body}
} }