1
0
Fork 0
mirror of synced 2024-12-23 23:33:21 -05:00

Updated plugins

This commit is contained in:
amix 2014-10-31 21:30:24 +00:00
parent fe77d23852
commit a304deea56
94 changed files with 5065 additions and 393 deletions

View file

@ -87,7 +87,9 @@ A. Stick this in your vimrc
__Q. How can I map a specific key or shortcut to open NERDTree?__
A. Stick this in your vimrc to open NERDTree with `Ctrl+n` (you can set whatever key you want): `map <C-n> :NERDTreeToggle<CR>`
A. Stick this in your vimrc to open NERDTree with `Ctrl+n` (you can set whatever key you want):
`map <C-n> :NERDTreeToggle<CR>`
__Q. How can I close vim if the only window left open is a NERDTree?__

View file

@ -652,25 +652,15 @@ endfunction
"Return: the string for this path that is suitable to be used with the :edit
"command
function! s:Path._strForEdit()
let p = escape(self.str({'format': 'UI'}), self._escChars())
let cwd = getcwd() . s:Path.Slash()
let p = escape(self.str(), self._escChars())
"return a relative path if we can
let isRelative = 0
if nerdtree#runningWindows()
let isRelative = stridx(tolower(p), tolower(cwd)) == 0
else
let isRelative = stridx(p, cwd) == 0
endif
"make it relative
let p = fnamemodify(p, ':.')
if isRelative
let p = strpart(p, strlen(cwd))
"handle the edge case where the file begins with a + (vim interprets
"the +foo in `:e +foo` as an option to :edit)
if p[0] == "+"
let p = '\' . p
endif
"handle the edge case where the file begins with a + (vim interprets
"the +foo in `:e +foo` as an option to :edit)
if p[0] == "+"
let p = '\' . p
endif
if p ==# ''

View file

@ -24,7 +24,7 @@ call NERDTreeAddMenuItem({'text': '(a)dd a childnode', 'shortcut': 'a', 'callbac
call NERDTreeAddMenuItem({'text': '(m)ove the current node', 'shortcut': 'm', 'callback': 'NERDTreeMoveNode'})
call NERDTreeAddMenuItem({'text': '(d)elete the current node', 'shortcut': 'd', 'callback': 'NERDTreeDeleteNode'})
if has("gui_mac") || has("gui_macvim")
if has("gui_mac") || has("gui_macvim")
call NERDTreeAddMenuItem({'text': '(r)eveal in Finder the current node', 'shortcut': 'r', 'callback': 'NERDTreeRevealInFinder'})
call NERDTreeAddMenuItem({'text': '(o)pen the current node with system editor', 'shortcut': 'o', 'callback': 'NERDTreeExecuteFile'})
call NERDTreeAddMenuItem({'text': '(q)uicklook the current node', 'shortcut': 'q', 'callback': 'NERDTreeQuickLook'})
@ -86,10 +86,11 @@ function! s:promptToRenameBuffer(bufnum, msg, newFileName)
" 1. ensure that a new buffer is loaded
exec "badd " . quotedFileName
" 2. ensure that all windows which display the just deleted filename
" display a buffer for a new filename.
" display a buffer for a new filename.
let s:originalTabNumber = tabpagenr()
let s:originalWindowNumber = winnr()
exec "tabdo windo if winbufnr(0) == " . a:bufnum . " | exec \":e! " . quotedFileName . "\" | endif"
let editStr = g:NERDTreePath.New(a:newFileName).str({'format': 'Edit'})
exec "tabdo windo if winbufnr(0) == " . a:bufnum . " | exec ':e! " . editStr . "' | endif"
exec "tabnext " . s:originalTabNumber
exec s:originalWindowNumber . "wincmd w"
" 3. We don't need a previous buffer anymore

View file

@ -28,11 +28,11 @@
## 1\. Introduction
Syntastic is a syntax checking plugin for Vim that runs files through external
syntax checkers and displays any resulting errors to the user. This can be done
on demand, or automatically as files are saved. If syntax errors 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.
Syntastic is a syntax checking plugin for [Vim][13] that runs files through
external syntax checkers and displays any resulting errors to the user. This
can be done on demand, or automatically as files are saved. If syntax errors
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.
At the time of this writing, syntax checking plugins exist for ActionScript,
Ada, AppleScript, Arduino, AsciiDoc, ASM, BEMHTML, Bro, Bourne shell, C,
@ -64,16 +64,40 @@ enabled.
## 2\. Installation
Installing syntastic is easy but first you need to have the [pathogen][1]
plugin installed. If you already have [pathogen][1] working then skip
[Step 1](#step1) and go to [Step 2](#step2).
<a name="requirements"></a>
### 2.1\. Requirements
Syntastic itself has rather relaxed requirements: it doesn't have any external
dependencies, and it needs a version of [Vim][13] compiled with a few common
features: `autocmd`, `eval`, `file_in_path`, `modify_fname`, `quickfix`,
`reltime`, and `user_commands`. Not all possible combinations of features that
include the ones above make equal sense on all operating systems, but Vim
version 7 or later with the "normal", "big", or "huge" feature sets should be
fine.
Syntastic should work with any modern plugin managers for Vim, such as
[NeoBundle][14], [Pathogen][1], [Vim-Addon-Manager][15], [Vim-Plug][16], or
[Vundle][17]. Instructions for installing syntastic with [Pathogen][1] are
included below for completeness.
Last but not least: syntastic doesn't know how to do any syntax checks by
itself. In order to get meaningful results you need to install external
checkers corresponding to the types of files you use. Please consult the
[wiki][3] for a list of supported checkers.
<a name="installpathogen"></a>
### 2.2\. Installing syntastic with Pathogen
If you already have [Pathogen][1] working then skip [Step 1](#step1) and go to
[Step 2](#step2).
<a name="step1"></a>
### 2.1\. Step 1: Install pathogen.vim
#### 2.2.1\. Step 1: Install pathogen.vim
First I'll show you how to install Tim Pope's [pathogen][1] so that it's easy to
First I'll show you how to install Tim Pope's [Pathogen][1] so that it's easy to
install syntastic. Do this in your terminal so that you get the `pathogen.vim`
file and the directories it needs:
```sh
@ -87,7 +111,7 @@ execute pathogen#infect()
<a name="step2"></a>
### 2.2\. Step 2: Install syntastic as a pathogen bundle
#### 2.2.2\. Step 2: Install syntastic as a Pathogen bundle
You now have pathogen installed and can put syntastic into `~/.vim/bundle` like
this:
@ -100,7 +124,8 @@ Quit vim and start it back up to reload it, then type:
:Helptags
```
If you get an error when you do this, then you probably didn't install
[pathogen][1] right. Go back to [Step 1](#step1) and make sure you did the following:
[Pathogen][1] right. Go back to [Step 1](#step1) and make sure you did the
following:
1. Created both the `~/.vim/autoload` and `~/.vim/bundle` directories.
2. Added the `call pathogen#infect()` line to your `~/.vimrc` file
@ -328,6 +353,11 @@ a look at [jedi-vim][7], [python-mode][8], or [YouCompleteMe][9].
[10]: http://perldoc.perl.org/perlrun.html#*-c*
[11]: https://github.com/scrooloose/syntastic/wiki/Syntax-Checker-Guide
[12]: https://github.com/rust-lang/rust/
[13]: http://www.vim.org/
[14]: https://github.com/Shougo/neobundle.vim
[15]: https://github.com/MarcWeber/vim-addon-manager
[16]: https://github.com/junegunn/vim-plug/
[17]: https://github.com/gmarik/Vundle.vim
<!--
vim:tw=79:sw=4:

View file

@ -120,7 +120,7 @@ function! syntastic#log#debugDump(level) " {{{2
return
endif
call syntastic#log#debugShowVariables( a:level, sort(keys(g:syntastic_defaults)) )
call syntastic#log#debugShowVariables( a:level, sort(keys(g:_SYNTASTIC_DEFAULTS)) )
endfunction " }}}2
" }}}1
@ -155,7 +155,7 @@ function! s:_logRedirect(on) " {{{2
endfunction " }}}2
function! s:_logTimestamp() " {{{2
return 'syntastic: ' . split(reltimestr(reltime(g:syntastic_start)))[0] . ': '
return 'syntastic: ' . split(reltimestr(reltime(g:_SYNTASTIC_START)))[0] . ': '
endfunction " }}}2
function! s:_formatVariable(name) " {{{2

View file

@ -76,6 +76,56 @@ function! syntastic#preprocess#perl(errors) " {{{2
return syntastic#util#unique(out)
endfunction " }}}2
function! syntastic#preprocess#prospector(errors) " {{{2
" JSON artifacts
let true = 1
let false = 0
let null = ''
" A hat tip to Marc Weber for this trick
" http://stackoverflow.com/questions/17751186/iterating-over-a-string-in-vimscript-or-parse-a-json-file/19105763#19105763
try
let errs = eval(join(a:errors, ''))
catch
let errs = {}
endtry
let out = []
if type(errs) == type({}) && has_key(errs, 'messages') && type(errs['messages']) == type([])
for e in errs['messages']
if type(e) == type({})
try
if e['source'] ==# 'pylint'
let e['location']['character'] += 1
endif
let msg =
\ e['location']['path'] . ':' .
\ e['location']['line'] . ':' .
\ e['location']['character'] . ': ' .
\ e['code'] . ' ' .
\ e['message'] . ' ' .
\ '[' . e['source'] . ']'
call add(out, msg)
catch /\m^Vim\%((\a\+)\)\=:E716/
call syntastic#log#warn('checker python/prospector: unknown error format')
let out = []
break
endtry
else
call syntastic#log#warn('checker python/prospector: unknown error format')
let out = []
break
endif
endfor
else
call syntastic#log#warn('checker python/prospector: unknown error format')
endif
return out
endfunction " }}}2
function! syntastic#preprocess#rparse(errors) " {{{2
let errlist = copy(a:errors)

View file

@ -274,7 +274,7 @@ endfunction " }}}2
function! syntastic#util#dictFilter(errors, filter) " {{{2
let rules = s:_translateFilter(a:filter)
" call syntastic#log#debug(g:SyntasticDebugFilters, "applying filter:", rules)
" call syntastic#log#debug(g:_SYNTASTIC_DEBUG_TRACE, "applying filter:", rules)
try
call filter(a:errors, rules)
catch /\m^Vim\%((\a\+)\)\=:E/
@ -287,7 +287,7 @@ endfunction " }}}2
" (hopefully high resolution) since program start
" TODO: This assumes reltime() returns a list of integers.
function! syntastic#util#stamp() " {{{2
return reltime(g:syntastic_start)
return reltime(g:_SYNTASTIC_START)
endfunction " }}}2
" }}}1

View file

@ -34,6 +34,7 @@ CONTENTS *syntastic-contents*
5.1.Choosing which checkers to use.........|syntastic-filetype-checkers|
5.2.Choosing the executable................|syntastic-config-exec|
5.3.Configuring specific checkers..........|syntastic-config-makeprg|
5.4.Sorting errors.........................|syntastic-config-sort|
6.Notes........................................|syntastic-notes|
6.1.Handling of composite filetypes........|syntastic-composite|
6.2.Editing files over network.............|syntastic-netrw|
@ -44,6 +45,7 @@ CONTENTS *syntastic-contents*
6.7.Using syntastic with the fizsh shell...|syntastic-fizsh|
6.8.Interaction with Eclim.................|syntastic-eclim|
6.9.Interaction with vim-virtualenv........|syntastic-vim-virtualenv|
6.10.Interaction with vim-auto-save........|syntastic-vim-auto-save|
7.About........................................|syntastic-about|
8.License......................................|syntastic-license|
@ -207,7 +209,8 @@ disable generation of these labels by turning off '|syntastic_id_checkers|'.
If |'syntastic_sort_aggregated_errors'| is set (which is the default), messages
in the aggregated list are grouped by file, then sorted by line number, then
type, then column number. Otherwise messages produced by the same checker are
grouped together.
grouped together, and sorting within each group is decided by the variables
|'syntastic_<filetype>_<checker>_sort'|.
------------------------------------------------------------------------------
2.6 Filtering errors *syntastic-filtering-errors*
@ -687,6 +690,25 @@ Example: >
<
See |syntastic_quiet_messages| for the syntax.
------------------------------------------------------------------------------
5.4 Sorting errors *syntastic-config-sort*
*'syntastic_<filetype>_<checker>_sort'*
Syntastic may decide to group the errors produced by some checkers by file,
then sort them by line number, then by type, then by column number. If you'd
prefer to see the errors in the order in which they are output by the external
checker you can set the variable |'g:syntastic_<filetype>_<checker>_sort'| to 0.
Alternatively, if syntastic doesn't reorder the errors produced by a checker
but you'd like it to sort them, you can set the same variable to 1.
There is also a local version |'b:syntastic_<filetype>_<checker>_sort'| of
this variable, that takes precedence over it in the buffers where it is
defined.
For aggregated lists (see |syntastic-aggregating-errors|) these variables are
ignored if |syntastic_sort_aggregated_errors| is set (which is the default).
==============================================================================
6. Notes *syntastic-notes*
@ -724,7 +746,7 @@ for python in syntastic (see |syntastic_mode_map|), or disable lint checks in
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"
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.: >
@ -766,11 +788,15 @@ interactive features of 'fizsh'. Using a more traditional shell such as "zsh",
------------------------------------------------------------------------------
6.8. Interaction with Eclim *syntastic-eclim*
As far as syntastic is concerned there shouldn't be any compatibility problems
with the 'Eclim' Vim plugin (see http://eclim.org/). However, at the time of
this writing there are several reports that 'Eclim' triggers a bug in Vim that
makes syntastic forget some of its configuration parameters. No solutions or
workarounds are known for now.
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
order to run its own validation. If you'd prefer to use Eclim but still run
syntastic's checks, set |g:EclimFileTypeValidate| to 0: >
let g:EclimFileTypeValidate = 0
<
It is also possible to re-enable syntastic checks only for some filetypes, and
run Eclim's validation for others. Please consult Eclim's documentation for
details.
------------------------------------------------------------------------------
6.9. Interaction with vim-virtualenv *syntastic-vim-virtualenv*
@ -780,6 +806,19 @@ in Python virtual environments activated by 'vim-virtualenv' (see
https://github.com/jmcantrell/vim-virtualenv). This is a limitation of
'vim-virtualenv'.
------------------------------------------------------------------------------
6.10. Interaction with vim-auto-save *syntastic-vim-auto-save*
At the time of this writing, syntastic checks in active mode are not triggered
by 'vim-auto-save' (see https://github.com/907th/vim-auto-save). The reason is
a limitation in 'vim-auto-save', namely a missing flag to an 'autocmd' (see
|autocmd-nested|). Fortunately it's pretty easy to achieve a similar effect
without 'vim-auto-save'': >
augroup syntastic
autocmd CursorHold * nested update
augroup END
set updatetime=200
<
==============================================================================
7. About *syntastic-about*

View file

@ -15,12 +15,12 @@ endif
let g:loaded_syntastic_plugin = 1
if has('reltime')
let g:syntastic_start = reltime()
lockvar! g:syntastic_start
let g:_SYNTASTIC_START = reltime()
lockvar! g:_SYNTASTIC_START
endif
let g:syntastic_version = '3.5.0-65'
lockvar g:syntastic_version
let g:_SYNTASTIC_VERSION = '3.5.0-72'
lockvar g:_SYNTASTIC_VERSION
" Sanity checks {{{1
@ -39,24 +39,24 @@ for s:feature in [
endif
endfor
let s:running_windows = syntastic#util#isRunningWindows()
lockvar s:running_windows
let s:_running_windows = syntastic#util#isRunningWindows()
lockvar s:_running_windows
if !s:running_windows && executable('uname')
if !s:_running_windows && executable('uname')
try
let s:uname = system('uname')
let s:_uname = system('uname')
catch /\m^Vim\%((\a\+)\)\=:E484/
call syntastic#log#error("your shell " . &shell . " can't handle traditional UNIX syntax for redirections")
finish
endtry
lockvar s:uname
lockvar s:_uname
endif
" }}}1
" Defaults {{{1
let g:syntastic_defaults = {
let g:_SYNTASTIC_DEFAULTS = {
\ 'aggregate_errors': 0,
\ 'always_populate_loc_list': 0,
\ 'auto_jump': 0,
@ -71,7 +71,7 @@ let g:syntastic_defaults = {
\ 'enable_highlighting': 1,
\ 'enable_signs': 1,
\ 'error_symbol': '>>',
\ 'exit_checks': !(s:running_windows && &shell =~? '\m\<cmd\.exe$'),
\ 'exit_checks': !(s:_running_windows && &shell =~? '\m\<cmd\.exe$'),
\ 'filetype_map': {},
\ 'full_redraws': !(has('gui_running') || has('gui_macvim')),
\ 'id_checkers': 1,
@ -86,11 +86,11 @@ let g:syntastic_defaults = {
\ 'style_warning_symbol': 'S>',
\ 'warning_symbol': '>>'
\ }
lockvar! g:syntastic_defaults
lockvar! g:_SYNTASTIC_DEFAULTS
for s:key in keys(g:syntastic_defaults)
for s:key in keys(g:_SYNTASTIC_DEFAULTS)
if !exists('g:syntastic_' . s:key)
let g:syntastic_{s:key} = copy(g:syntastic_defaults[s:key])
let g:syntastic_{s:key} = copy(g:_SYNTASTIC_DEFAULTS[s:key])
endif
endfor
@ -110,7 +110,7 @@ endif
" Debug {{{1
let s:debug_dump_options = [
let s:_DEBUG_DUMP_OPTIONS = [
\ 'shell',
\ 'shellcmdflag',
\ 'shellpipe',
@ -121,23 +121,23 @@ let s:debug_dump_options = [
\ 'shellxquote'
\ ]
if v:version > 703 || (v:version == 703 && has('patch446'))
call add(s:debug_dump_options, 'shellxescape')
call add(s:_DEBUG_DUMP_OPTIONS, 'shellxescape')
endif
lockvar! s:debug_dump_options
lockvar! s:_DEBUG_DUMP_OPTIONS
" debug constants
let g:SyntasticDebugTrace = 1
lockvar g:SyntasticDebugTrace
let g:SyntasticDebugLoclist = 2
lockvar g:SyntasticDebugLoclist
let g:SyntasticDebugNotifications = 4
lockvar g:SyntasticDebugNotifications
let g:SyntasticDebugAutocommands = 8
lockvar g:SyntasticDebugAutocommands
let g:SyntasticDebugVariables = 16
lockvar g:SyntasticDebugVariables
let g:SyntasticDebugCheckers = 32
lockvar g:SyntasticDebugCheckers
let g:_SYNTASTIC_DEBUG_TRACE = 1
lockvar g:_SYNTASTIC_DEBUG_TRACE
let g:_SYNTASTIC_DEBUG_LOCLIST = 2
lockvar g:_SYNTASTIC_DEBUG_LOCLIST
let g:_SYNTASTIC_DEBUG_NOTIFICATIONS = 4
lockvar g:_SYNTASTIC_DEBUG_NOTIFICATIONS
let g:_SYNTASTIC_DEBUG_AUTOCOMMANDS = 8
lockvar g:_SYNTASTIC_DEBUG_AUTOCOMMANDS
let g:_SYNTASTIC_DEBUG_VARIABLES = 16
lockvar g:_SYNTASTIC_DEBUG_VARIABLES
let g:_SYNTASTIC_DEBUG_CHECKERS = 32
lockvar g:_SYNTASTIC_DEBUG_CHECKERS
" }}}1
@ -180,10 +180,11 @@ command! -nargs=* -complete=custom,s:CompleteCheckerName SyntasticCheck
\ call syntastic#util#redraw(g:syntastic_full_redraws)
command! Errors call s:ShowLocList()
command! -nargs=? -complete=custom,s:CompleteFiletypes SyntasticInfo
\ call s:modemap.modeInfo(<f-args>) |
\ call s:registry.echoInfoFor(s:resolveFiletypes(<f-args>))
\ call s:modemap.modeInfo(<f-args>) <bar>
\ call s:registry.echoInfoFor(s:resolveFiletypes(<f-args>)) <bar>
\ call s:explainSkip(<f-args>)
command! SyntasticReset
\ call s:ClearCache() |
\ call s:ClearCache() <bar>
\ call s:notifiers.refresh(g:SyntasticLoclist.New([]))
command! SyntasticSetLoclist call g:SyntasticLoclist.current().setloclist()
@ -206,20 +207,20 @@ endif
function! s:BufReadPostHook() " {{{2
if g:syntastic_check_on_open
call syntastic#log#debug(g:SyntasticDebugAutocommands,
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_AUTOCOMMANDS,
\ 'autocmd: BufReadPost, buffer ' . bufnr("") . ' = ' . string(bufname(str2nr(bufnr("")))))
call s:UpdateErrors(1)
endif
endfunction " }}}2
function! s:BufWritePostHook() " {{{2
call syntastic#log#debug(g:SyntasticDebugAutocommands,
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_AUTOCOMMANDS,
\ 'autocmd: BufWritePost, buffer ' . bufnr("") . ' = ' . string(bufname(str2nr(bufnr("")))))
call s:UpdateErrors(1)
endfunction " }}}2
function! s:BufEnterHook() " {{{2
call syntastic#log#debug(g:SyntasticDebugAutocommands,
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_AUTOCOMMANDS,
\ 'autocmd: BufEnter, buffer ' . bufnr("") . ' = ' . string(bufname(str2nr(bufnr("")))) .
\ ', &buftype = ' . string(&buftype))
if &buftype == ''
@ -238,7 +239,7 @@ function! s:BufEnterHook() " {{{2
endfunction " }}}2
function! s:QuitPreHook() " {{{2
call syntastic#log#debug(g:SyntasticDebugAutocommands,
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_AUTOCOMMANDS,
\ 'autocmd: QuitPre, buffer ' . bufnr("") . ' = ' . string(bufname(str2nr(bufnr("")))))
let b:syntastic_skip_checks = get(b:, 'syntastic_skip_checks', 0) || !syntastic#util#var('check_on_wq')
call SyntasticLoclistHide()
@ -250,10 +251,10 @@ endfunction " }}}2
"refresh and redraw all the error info for this buf when saving or reading
function! s:UpdateErrors(auto_invoked, ...) " {{{2
call syntastic#log#debugShowVariables(g:SyntasticDebugTrace, 'version')
call syntastic#log#debugShowOptions(g:SyntasticDebugTrace, s:debug_dump_options)
call syntastic#log#debugDump(g:SyntasticDebugVariables)
call syntastic#log#debug(g:SyntasticDebugTrace, 'UpdateErrors' . (a:auto_invoked ? ' (auto)' : '') .
call syntastic#log#debugShowVariables(g:_SYNTASTIC_DEBUG_TRACE, 'version')
call syntastic#log#debugShowOptions(g:_SYNTASTIC_DEBUG_TRACE, s:_DEBUG_DUMP_OPTIONS)
call syntastic#log#debugDump(g:_SYNTASTIC_DEBUG_VARIABLES)
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_TRACE, 'UpdateErrors' . (a:auto_invoked ? ' (auto)' : '') .
\ ': ' . (a:0 ? join(a:000) : 'default checkers'))
if s:skipFile()
return
@ -277,11 +278,11 @@ function! s:UpdateErrors(auto_invoked, ...) " {{{2
let w:syntastic_loclist_set = 0
if syntastic#util#var('always_populate_loc_list') || do_jump
call syntastic#log#debug(g:SyntasticDebugNotifications, 'loclist: setloclist (new)')
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_NOTIFICATIONS, 'loclist: setloclist (new)')
call setloclist(0, loclist.getRaw())
let w:syntastic_loclist_set = 1
if run_checks && do_jump && !loclist.isEmpty()
call syntastic#log#debug(g:SyntasticDebugNotifications, 'loclist: jump')
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_NOTIFICATIONS, 'loclist: jump')
silent! lrewind
" XXX: Vim doesn't call autocmd commands in a predictible
@ -306,15 +307,15 @@ endfunction " }}}2
"detect and cache all syntax errors in this buffer
function! s:CacheErrors(checker_names) " {{{2
call syntastic#log#debug(g:SyntasticDebugTrace, 'CacheErrors: ' .
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_TRACE, 'CacheErrors: ' .
\ (len(a:checker_names) ? join(a:checker_names) : 'default checkers'))
call s:ClearCache()
let newLoclist = g:SyntasticLoclist.New([])
if !s:skipFile()
" debug logging {{{3
call syntastic#log#debugShowVariables(g:SyntasticDebugTrace, 'aggregate_errors')
call syntastic#log#debug(g:SyntasticDebugTrace, 'getcwd() = ' . getcwd())
call syntastic#log#debugShowVariables(g:_SYNTASTIC_DEBUG_TRACE, 'aggregate_errors')
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_TRACE, 'getcwd() = ' . getcwd())
" }}}3
let filetypes = s:resolveFiletypes()
@ -332,12 +333,12 @@ function! s:CacheErrors(checker_names) " {{{2
for checker in clist
let cname = checker.getFiletype() . '/' . checker.getName()
if !checker.isAvailable()
call syntastic#log#debug(g:SyntasticDebugTrace, 'CacheErrors: Checker ' . cname . ' is not available')
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_TRACE, 'CacheErrors: Checker ' . cname . ' is not available')
let unavailable_checkers += 1
continue
endif
call syntastic#log#debug(g:SyntasticDebugTrace, 'CacheErrors: Invoking checker: ' . cname)
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_TRACE, 'CacheErrors: Invoking checker: ' . cname)
let loclist = checker.getLocList()
@ -346,9 +347,9 @@ function! s:CacheErrors(checker_names) " {{{2
call loclist.decorate(cname)
endif
call add(names, cname)
if checker.getWantSort() && !sort_aggregated_errors
if checker.wantSort() && !sort_aggregated_errors
call loclist.sort()
call syntastic#log#debug(g:SyntasticDebugLoclist, 'sorted:', loclist)
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_LOCLIST, 'sorted:', loclist)
endif
let newLoclist = newLoclist.extend(loclist)
@ -381,15 +382,15 @@ function! s:CacheErrors(checker_names) " {{{2
call syntastic#log#warn('checkers ' . join(a:checker_names, ', ') . ' are not available')
endif
else
call syntastic#log#debug(g:SyntasticDebugTrace, 'CacheErrors: no checkers available for ' . &filetype)
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_TRACE, 'CacheErrors: no checkers available for ' . &filetype)
endif
endif
" }}}3
call syntastic#log#debug(g:SyntasticDebugLoclist, 'aggregated:', newLoclist)
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_LOCLIST, 'aggregated:', newLoclist)
if sort_aggregated_errors
call newLoclist.sort()
call syntastic#log#debug(g:SyntasticDebugLoclist, 'sorted:', newLoclist)
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_LOCLIST, 'sorted:', newLoclist)
endif
endif
@ -428,7 +429,7 @@ endfunction " }}}2
" 'returns' - a list of valid exit codes for the checker
" @vimlint(EVL102, 1, l:env_save)
function! SyntasticMake(options) " {{{2
call syntastic#log#debug(g:SyntasticDebugTrace, '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
let old_shellredir = &shellredir
@ -475,32 +476,42 @@ function! SyntasticMake(options) " {{{2
endif
" }}}3
call syntastic#log#debug(g:SyntasticDebugLoclist, 'checker output:', err_lines)
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_LOCLIST, 'checker output:', err_lines)
if has_key(a:options, 'Preprocess')
let err_lines = call(a:options['Preprocess'], [err_lines])
call syntastic#log#debug(g:SyntasticDebugLoclist, 'preprocess (external):', err_lines)
elseif has_key(a:options, 'preprocess')
let err_lines = call('syntastic#preprocess#' . a:options['preprocess'], [err_lines])
call syntastic#log#debug(g:SyntasticDebugLoclist, 'preprocess:', err_lines)
" Does it still make sense to go on?
let bailout =
\ syntastic#util#var('exit_checks') &&
\ has_key(a:options, 'returns') &&
\ index(a:options['returns'], v:shell_error) == -1
if !bailout
if has_key(a:options, 'Preprocess')
let err_lines = call(a:options['Preprocess'], [err_lines])
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_LOCLIST, 'preprocess (external):', err_lines)
elseif has_key(a:options, 'preprocess')
let err_lines = call('syntastic#preprocess#' . a:options['preprocess'], [err_lines])
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_LOCLIST, 'preprocess:', err_lines)
endif
lgetexpr err_lines
let errors = deepcopy(getloclist(0))
if has_key(a:options, 'cwd')
execute 'lcd ' . fnameescape(old_cwd)
endif
try
silent lolder
catch /\m^Vim\%((\a\+)\)\=:E380/
" E380: At bottom of quickfix stack
call setloclist(0, [], 'r')
catch /\m^Vim\%((\a\+)\)\=:E776/
" E776: No location list
" do nothing
endtry
else
let errors = []
endif
lgetexpr err_lines
let errors = deepcopy(getloclist(0))
if has_key(a:options, 'cwd')
execute 'lcd ' . fnameescape(old_cwd)
endif
try
silent lolder
catch /\m^Vim\%((\a\+)\)\=:E380/
" E380: At bottom of quickfix stack
call setloclist(0, [], 'r')
catch /\m^Vim\%((\a\+)\)\=:E776/
" E776: No location list
" do nothing
endtry
" restore options {{{3
let &errorformat = old_errorformat
@ -508,16 +519,16 @@ function! SyntasticMake(options) " {{{2
let &shellredir = old_shellredir
" }}}3
if !s:running_windows && (s:uname() =~ "FreeBSD" || s:uname() =~ "OpenBSD")
if !s:_running_windows && (s:uname() =~ "FreeBSD" || s:uname() =~ "OpenBSD")
call syntastic#util#redraw(g:syntastic_full_redraws)
endif
call syntastic#log#debug(g:SyntasticDebugLoclist, 'raw loclist:', errors)
if syntastic#util#var('exit_checks') && has_key(a:options, 'returns') && index(a:options['returns'], v:shell_error) == -1
if bailout
throw 'Syntastic: checker error'
endif
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_LOCLIST, 'raw loclist:', errors)
if has_key(a:options, 'defaults')
call s:addToErrors(errors, a:options['defaults'])
endif
@ -531,12 +542,12 @@ function! SyntasticMake(options) " {{{2
for rule in a:options['Postprocess']
let errors = call(rule, [errors])
endfor
call syntastic#log#debug(g:SyntasticDebugLoclist, 'postprocess (external):', errors)
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_LOCLIST, 'postprocess (external):', errors)
elseif has_key(a:options, 'postprocess') && !empty(a:options['postprocess'])
for rule in a:options['postprocess']
let errors = call('syntastic#postprocess#' . rule, [errors])
endfor
call syntastic#log#debug(g:SyntasticDebugLoclist, 'postprocess:', errors)
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_LOCLIST, 'postprocess:', errors)
endif
return errors
@ -577,11 +588,40 @@ function! s:skipFile() " {{{2
\ !filereadable(fname) || getwinvar(0, '&diff') || s:ignoreFile(fname) ||
\ fnamemodify(fname, ':e') =~? g:syntastic_ignore_extensions
if skip
call syntastic#log#debug(g:SyntasticDebugTrace, 'skipFile: skipping')
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_TRACE, 'skipFile: skipping')
endif
return skip
endfunction " }}}2
" Explain why checks will be skipped for the current file
function! s:explainSkip(...) " {{{2
if !a:0 && s:skipFile()
let why = []
let fname = expand('%')
if get(b:, 'syntastic_skip_checks', 0)
call add(why, 'b:syntastic_skip_checks set')
endif
if &buftype != ''
call add(why, 'buftype = ' . string(&buftype))
endif
if !filereadable(fname)
call add(why, 'file not readable / not local')
endif
if getwinvar(0, '&diff')
call add(why, 'diff mode')
endif
if s:ignoreFile(fname)
call add(why, 'filename matching g:syntastic_ignore_files')
endif
if fnamemodify(fname, ':e') =~? g:syntastic_ignore_extensions
call add(why, 'extension matching g:syntastic_ignore_extensions')
endif
echomsg 'The current file will not be checked (' . join(why, ', ') . ')'
endif
endfunction " }}}2
" Take a list of errors and add default values to them from a:options
function! s:addToErrors(errors, options) " {{{2
for err in a:errors
@ -602,7 +642,7 @@ function! s:bashHack() " {{{2
if g:syntastic_bash_hack
if !exists('s:shell_is_bash')
let s:shell_is_bash =
\ !s:running_windows &&
\ !s:_running_windows &&
\ (s:uname() !~# "FreeBSD") && (s:uname() !~# "OpenBSD") &&
\ &shell =~# '\m\<bash$'
endif
@ -614,11 +654,11 @@ function! s:bashHack() " {{{2
endfunction " }}}2
function! s:uname() " {{{2
if !exists('s:uname')
let s:uname = system('uname')
lockvar s:uname
if !exists('s:_uname')
let s:_uname = system('uname')
lockvar s:_uname
endif
return s:uname
return s:_uname
endfunction " }}}2
" }}}1

View file

@ -13,12 +13,12 @@ function! g:SyntasticAutoloclistNotifier.New() " {{{2
endfunction " }}}2
function! g:SyntasticAutoloclistNotifier.refresh(loclist) " {{{2
call syntastic#log#debug(g:SyntasticDebugNotifications, 'autoloclist: refresh')
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_NOTIFICATIONS, 'autoloclist: refresh')
call g:SyntasticAutoloclistNotifier.AutoToggle(a:loclist)
endfunction " }}}2
function! g:SyntasticAutoloclistNotifier.AutoToggle(loclist) " {{{2
call syntastic#log#debug(g:SyntasticDebugNotifications, 'autoloclist: toggle')
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_NOTIFICATIONS, 'autoloclist: toggle')
if !a:loclist.isEmpty()
if syntastic#util#var('auto_loc_list') == 1
call a:loclist.show()

View file

@ -22,20 +22,11 @@ endfunction " }}}2
" Update the error balloons
function! g:SyntasticBalloonsNotifier.refresh(loclist) " {{{2
let b:syntastic_balloons = {}
unlet! b:syntastic_balloons
if self.enabled() && !a:loclist.isEmpty()
call syntastic#log#debug(g:SyntasticDebugNotifications, 'balloons: refresh')
let buf = bufnr('')
let issues = filter(a:loclist.copyRaw(), 'v:val["bufnr"] == buf')
if !empty(issues)
for i in issues
if has_key(b:syntastic_balloons, i['lnum'])
let b:syntastic_balloons[i['lnum']] .= "\n" . i['text']
else
let b:syntastic_balloons[i['lnum']] = i['text']
endif
endfor
set beval bexpr=SyntasticBalloonsExprNotifier()
let b:syntastic_balloons = a:loclist.balloons()
if !empty(b:syntastic_balloons)
set ballooneval balloonexpr=SyntasticBalloonsExprNotifier()
endif
endif
endfunction " }}}2
@ -45,8 +36,9 @@ endfunction " }}}2
function! g:SyntasticBalloonsNotifier.reset(loclist) " {{{2
let b:syntastic_balloons = {}
if has('balloon_eval')
call syntastic#log#debug(g:SyntasticDebugNotifications, 'balloons: reset')
set nobeval
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_NOTIFICATIONS, 'balloons: reset')
unlet! b:syntastic_balloons
set noballooneval
endif
endfunction " }}}2
" @vimlint(EVL103, 0, a:loclist)

View file

@ -13,11 +13,14 @@ function! g:SyntasticChecker.New(args) " {{{2
let newObj._filetype = a:args['filetype']
let newObj._name = a:args['name']
let newObj._exec = get(a:args, 'exec', newObj._name)
let newObj._sort = 0
if has_key(a:args, 'redirect')
let [filetype, name] = split(a:args['redirect'], '/')
let prefix = 'SyntaxCheckers_' . filetype . '_' . name . '_'
if exists('g:syntastic_' . filetype . '_' . name . '_sort') && !exists('g:syntastic_' . newObj._filetype . '_' . newObj._name . '_sort')
let g:syntastic_{newObj._filetype}_{newObj._name}_sort = g:syntastic_{filetype}_{name}_sort
endif
else
let prefix = 'SyntaxCheckers_' . newObj._filetype . '_' . newObj._name . '_'
endif
@ -59,13 +62,13 @@ function! g:SyntasticChecker.getLocListRaw() " {{{2
let name = self._filetype . '/' . self._name
try
let list = self._locListFunc()
call syntastic#log#debug(g:SyntasticDebugTrace, 'getLocList: checker ' . name . ' returned ' . v:shell_error)
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_TRACE, 'getLocList: checker ' . name . ' returned ' . v:shell_error)
catch /\m\C^Syntastic: checker error$/
let list = []
call syntastic#log#error('checker ' . name . ' returned abnormal status ' . v:shell_error)
endtry
call self._populateHighlightRegexes(list)
call syntastic#log#debug(g:SyntasticDebugLoclist, name . ' raw:', list)
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_LOCLIST, name . ' raw:', list)
call self._quietMessages(list)
return list
endfunction " }}}2
@ -74,20 +77,12 @@ function! g:SyntasticChecker.getLocList() " {{{2
return g:SyntasticLoclist.New(self.getLocListRaw())
endfunction " }}}2
function! g:SyntasticChecker.getWantSort() " {{{2
return self._sort
endfunction " }}}2
function! g:SyntasticChecker.setWantSort(val) " {{{2
let self._sort = a:val
endfunction " }}}2
function! g:SyntasticChecker.log(msg, ...) " {{{2
let leader = self._filetype . '/' . self._name . ': '
if a:0 > 0
call syntastic#log#debug(g:SyntasticDebugCheckers, leader . a:msg, a:1)
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_CHECKERS, leader . a:msg, a:1)
else
call syntastic#log#debug(g:SyntasticDebugCheckers, leader . a:msg)
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_CHECKERS, leader . a:msg)
endif
endfunction " }}}2
@ -111,6 +106,18 @@ function! g:SyntasticChecker.isAvailable() " {{{2
return self._available
endfunction " }}}2
function! g:SyntasticChecker.wantSort() " {{{2
return syntastic#util#var(self._filetype . '_' . self._name . '_sort', 0)
endfunction " }}}2
" This method is no longer used by syntastic. It's here only to maintain
" backwards compatibility with external checkers which might depend on it.
function! g:SyntasticChecker.setWantSort(val) " {{{2
if !exists('g:syntastic_' . self._filetype . '_' . self._name . '_sort')
let g:syntastic_{self._filetype}_{self._name}_sort = a:val
endif
endfunction " }}}2
" }}}1
" Private methods {{{1
@ -132,11 +139,11 @@ function! g:SyntasticChecker._quietMessages(errors) " {{{2
call syntastic#log#warn('ignoring invalid syntastic_' . name . '_quiet_messages')
endtry
call syntastic#log#debug(g:SyntasticDebugLoclist, 'quiet_messages filter:', quiet_filters)
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_LOCLIST, 'quiet_messages filter:', quiet_filters)
if !empty(quiet_filters)
call syntastic#util#dictFilter(a:errors, quiet_filters)
call syntastic#log#debug(g:SyntasticDebugLoclist, 'filtered by quiet_messages:', a:errors)
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_LOCLIST, 'filtered by quiet_messages:', a:errors)
endif
endfunction " }}}2

View file

@ -18,7 +18,7 @@ endfunction " }}}2
function! g:SyntasticCursorNotifier.refresh(loclist) " {{{2
if self.enabled() && !a:loclist.isEmpty()
call syntastic#log#debug(g:SyntasticDebugNotifications, 'cursor: refresh')
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_NOTIFICATIONS, 'cursor: refresh')
let b:syntastic_messages = copy(a:loclist.messages(bufnr('')))
let b:syntastic_line = -1
let b:syntastic_cursor_columns = a:loclist.getCursorColumns()
@ -29,7 +29,7 @@ endfunction " }}}2
" @vimlint(EVL103, 1, a:loclist)
function! g:SyntasticCursorNotifier.reset(loclist) " {{{2
call syntastic#log#debug(g:SyntasticDebugNotifications, 'cursor: reset')
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_NOTIFICATIONS, 'cursor: reset')
autocmd! syntastic CursorMoved
unlet! b:syntastic_messages
let b:syntastic_line = -1

View file

@ -32,7 +32,7 @@ endfunction " }}}2
" Sets error highlights in the cuirrent window
function! g:SyntasticHighlightingNotifier.refresh(loclist) " {{{2
if self.enabled()
call syntastic#log#debug(g:SyntasticDebugNotifications, 'highlighting: refresh')
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_NOTIFICATIONS, 'highlighting: refresh')
call self._reset()
let buf = bufnr('')
let issues = filter(a:loclist.copyRaw(), 'v:val["bufnr"] == buf')
@ -63,7 +63,7 @@ endfunction " }}}2
" @vimlint(EVL103, 1, a:loclist)
function! g:SyntasticHighlightingNotifier.reset(loclist) " {{{2
if s:has_highlighting
call syntastic#log#debug(g:SyntasticDebugNotifications, 'highlighting: reset')
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_NOTIFICATIONS, 'highlighting: reset')
call self._reset()
endif
endfunction " }}}2

View file

@ -173,6 +173,29 @@ function! g:SyntasticLoclist.decorate(tag) " {{{2
endfor
endfunction " }}}2
function! g:SyntasticLoclist.balloons() " {{{2
if !exists("self._cachedBalloons")
let sep = has("balloon_multiline") ? "\n" : ' | '
let self._cachedBalloons = {}
for e in self._rawLoclist
let buf = e['bufnr']
if !has_key(self._cachedBalloons, buf)
let self._cachedBalloons[buf] = {}
endif
if has_key(self._cachedBalloons[buf], e['lnum'])
let self._cachedBalloons[buf][e['lnum']] .= sep . e['text']
else
let self._cachedBalloons[buf][e['lnum']] = e['text']
endif
endfor
endif
return get(self._cachedBalloons, bufnr(''), {})
endfunction " }}}2
function! g:SyntasticLoclist.errors() " {{{2
if !exists("self._cachedErrors")
let self._cachedErrors = self.filter({'type': "E"})
@ -258,14 +281,14 @@ function! g:SyntasticLoclist.setloclist() " {{{2
let w:syntastic_loclist_set = 0
endif
let replace = g:syntastic_reuse_loc_lists && w:syntastic_loclist_set
call syntastic#log#debug(g:SyntasticDebugNotifications, 'loclist: setloclist ' . (replace ? '(replace)' : '(new)'))
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_NOTIFICATIONS, 'loclist: setloclist ' . (replace ? '(replace)' : '(new)'))
call setloclist(0, self.getRaw(), replace ? 'r' : ' ')
let w:syntastic_loclist_set = 1
endfunction " }}}2
"display the cached errors for this buf in the location list
function! g:SyntasticLoclist.show() " {{{2
call syntastic#log#debug(g:SyntasticDebugNotifications, 'loclist: show')
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_NOTIFICATIONS, 'loclist: show')
call self.setloclist()
if !self.isEmpty()
@ -300,7 +323,7 @@ endfunction " }}}2
" Non-method functions {{{1
function! SyntasticLoclistHide() " {{{2
call syntastic#log#debug(g:SyntasticDebugNotifications, 'loclist: hide')
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_NOTIFICATIONS, 'loclist: hide')
silent! lclose
endfunction " }}}2

View file

@ -63,7 +63,7 @@ function! g:SyntasticModeMap.echoMode() " {{{2
endfunction " }}}2
function! g:SyntasticModeMap.modeInfo(...) " {{{2
echomsg 'Syntastic version: ' . g:syntastic_version
echomsg 'Syntastic version: ' . g:_SYNTASTIC_VERSION
let type = a:0 ? a:1 : &filetype
echomsg 'Info for filetype: ' . type

View file

@ -5,11 +5,11 @@ let g:loaded_syntastic_notifiers = 1
let g:SyntasticNotifiers = {}
let s:notifier_types = ['signs', 'balloons', 'highlighting', 'cursor', 'autoloclist']
lockvar! s:notifier_types
let s:_NOTIFIER_TYPES = ['signs', 'balloons', 'highlighting', 'cursor', 'autoloclist']
lockvar! s:_NOTIFIER_TYPES
let s:persistent_notifiers = ['signs', 'balloons']
lockvar! s:persistent_notifiers
let s:_PERSISTENT_NOTIFIERS = ['signs', 'balloons']
lockvar! s:_PERSISTENT_NOTIFIERS
" Public methods {{{1
@ -28,11 +28,11 @@ function! g:SyntasticNotifiers.refresh(loclist) " {{{2
return
endif
call syntastic#log#debug(g:SyntasticDebugNotifications, 'notifiers: refresh')
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_NOTIFICATIONS, 'notifiers: refresh')
for type in self._enabled_types
let class = substitute(type, '\m.*', 'Syntastic\u&Notifier', '')
if !has_key(g:{class}, 'enabled') || self._notifier[type].enabled()
if index(s:persistent_notifiers, type) > -1
if index(s:_PERSISTENT_NOTIFIERS, type) > -1
" refresh only if loclist has changed since last call
if !exists('b:syntastic_' . type . '_stamp')
let b:syntastic_{type}_stamp = []
@ -49,7 +49,7 @@ function! g:SyntasticNotifiers.refresh(loclist) " {{{2
endfunction " }}}2
function! g:SyntasticNotifiers.reset(loclist) " {{{2
call syntastic#log#debug(g:SyntasticDebugNotifications, 'notifiers: reset')
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_NOTIFICATIONS, 'notifiers: reset')
for type in self._enabled_types
let class = substitute(type, '\m.*', 'Syntastic\u&Notifier', '')
@ -61,7 +61,7 @@ function! g:SyntasticNotifiers.reset(loclist) " {{{2
endif
" also reset stamps
if index(s:persistent_notifiers, type) > -1
if index(s:_PERSISTENT_NOTIFIERS, type) > -1
let b:syntastic_{type}_stamp = []
endif
endfor
@ -73,12 +73,12 @@ endfunction " }}}2
function! g:SyntasticNotifiers._initNotifiers() " {{{2
let self._notifier = {}
for type in s:notifier_types
for type in s:_NOTIFIER_TYPES
let class = substitute(type, '\m.*', 'Syntastic\u&Notifier', '')
let self._notifier[type] = g:{class}.New()
endfor
let self._enabled_types = copy(s:notifier_types)
let self._enabled_types = copy(s:_NOTIFIER_TYPES)
endfunction " }}}2
" }}}1

View file

@ -5,7 +5,7 @@ let g:loaded_syntastic_registry = 1
" Initialisation {{{1
let s:defaultCheckers = {
let s:_DEFAULT_CHECKERS = {
\ 'actionscript':['mxmlc'],
\ 'ada': ['gcc'],
\ 'applescript': ['osacompile'],
@ -94,9 +94,9 @@ let s:defaultCheckers = {
\ 'zpt': ['zptlint'],
\ 'zsh': ['zsh', 'shellcheck']
\ }
lockvar! s:defaultCheckers
lockvar! s:_DEFAULT_CHECKERS
let s:defaultFiletypeMap = {
let s:_DEFAULT_FILETYPE_MAP = {
\ 'gentoo-metadata': 'xml',
\ 'groff': 'nroff',
\ 'lhaskell': 'haskell',
@ -106,7 +106,7 @@ let s:defaultFiletypeMap = {
\ 'sgml': 'docbk',
\ 'sgmllnx': 'docbk',
\ }
lockvar! s:defaultFiletypeMap
lockvar! s:_DEFAULT_FILETYPE_MAP
let g:SyntasticRegistry = {}
@ -152,7 +152,7 @@ function! g:SyntasticRegistry.getCheckers(ftalias, hints_list) " {{{2
\ !empty(a:hints_list) ? syntastic#util#unique(a:hints_list) :
\ exists('b:syntastic_checkers') ? b:syntastic_checkers :
\ exists('g:syntastic_' . ft . '_checkers') ? g:syntastic_{ft}_checkers :
\ get(s:defaultCheckers, ft, 0)
\ get(s:_DEFAULT_CHECKERS, ft, 0)
return type(names) == type([]) ?
\ self._filterCheckersByName(checkers_map, names) : [checkers_map[keys(checkers_map)[0]]]
@ -165,9 +165,9 @@ function! g:SyntasticRegistry.getCheckersAvailable(ftalias, hints_list) " {{{2
endfunction " }}}2
function! g:SyntasticRegistry.getKnownFiletypes() " {{{2
let types = keys(s:defaultCheckers)
let types = keys(s:_DEFAULT_CHECKERS)
call extend(types, keys(s:defaultFiletypeMap))
call extend(types, keys(s:_DEFAULT_FILETYPE_MAP))
if exists('g:syntastic_filetype_map')
call extend(types, keys(g:syntastic_filetype_map))
@ -262,7 +262,7 @@ endfunction " }}}2
"resolve filetype aliases, and replace - with _ otherwise we cant name
"syntax checker functions legally for filetypes like "gentoo-metadata"
function! s:_normaliseFiletype(ftalias) " {{{2
let ft = get(s:defaultFiletypeMap, a:ftalias, a:ftalias)
let ft = get(s:_DEFAULT_FILETYPE_MAP, a:ftalias, a:ftalias)
let ft = get(g:syntastic_filetype_map, ft, ft)
let ft = substitute(ft, '\m-', '_', 'g')
return ft

View file

@ -36,7 +36,7 @@ function! g:SyntasticSignsNotifier.enabled() " {{{2
endfunction " }}}2
function! g:SyntasticSignsNotifier.refresh(loclist) " {{{2
call syntastic#log#debug(g:SyntasticDebugNotifications, 'signs: refresh')
call syntastic#log#debug(g:_SYNTASTIC_DEBUG_NOTIFICATIONS, 'signs: refresh')
let old_signs = copy(self._bufSignIds())
if self.enabled()
call self._signErrors(a:loclist)

View file

@ -18,6 +18,10 @@ if !exists('g:syntastic_clang_check_config_file')
let g:syntastic_clang_check_config_file = '.syntastic_clang_check_config'
endif
if !exists('g:syntastic_c_clang_check_sort')
let g:syntastic_c_clang_check_sort = 1
endif
let s:save_cpo = &cpo
set cpo&vim
@ -39,15 +43,11 @@ function! SyntaxCheckers_c_clang_check_GetLocList() dict
\ '%-G%\m%\%%(LLVM ERROR:%\|No compilation database found%\)%\@!%.%#,' .
\ '%E%m'
let loclist = SyntasticMake({
return SyntasticMake({
\ 'makeprg': makeprg,
\ 'errorformat': errorformat,
\ 'defaults': {'bufnr': bufnr('')},
\ 'returns': [0, 1] })
call self.setWantSort(1)
return loclist
endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({

View file

@ -18,6 +18,10 @@ if !exists('g:syntastic_clang_tidy_config_file')
let g:syntastic_clang_tidy_config_file = '.syntastic_clang_tidy_config'
endif
if !exists('g:syntastic_c_clang_tidy_sort')
let g:syntastic_c_clang_tidy_sort = 1
endif
let s:save_cpo = &cpo
set cpo&vim
@ -39,15 +43,11 @@ function! SyntaxCheckers_c_clang_tidy_GetLocList() dict
\ '%-G%\m%\%%(LLVM ERROR:%\|No compilation database found%\)%\@!%.%#,' .
\ '%E%m'
let loclist = SyntasticMake({
return SyntasticMake({
\ 'makeprg': makeprg,
\ 'errorformat': errorformat,
\ 'defaults': {'bufnr': bufnr('')},
\ 'returns': [0, 1] })
call self.setWantSort(1)
return loclist
endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({

View file

@ -25,6 +25,10 @@ if !exists('g:syntastic_oclint_config_file')
let g:syntastic_oclint_config_file = '.syntastic_oclint_config'
endif
if !exists('g:syntastic_c_oclint_sort')
let g:syntastic_c_oclint_sort = 1
endif
let s:save_cpo = &cpo
set cpo&vim
@ -55,8 +59,6 @@ function! SyntaxCheckers_c_oclint_GetLocList() dict
let e['text'] = substitute(e['text'], '\m\C P[1-3] ', ': ', '')
endfor
call self.setWantSort(1)
return loclist
endfunction

View file

@ -20,6 +20,10 @@ if exists("g:loaded_syntastic_css_prettycss_checker")
endif
let g:loaded_syntastic_css_prettycss_checker = 1
if !exists('g:syntastic_css_prettycss_sort')
let g:syntastic_css_prettycss_sort = 1
endif
let s:save_cpo = &cpo
set cpo&vim
@ -49,8 +53,6 @@ function! SyntaxCheckers_css_prettycss_GetLocList() dict
let e["text"] .= ')'
endfor
call self.setWantSort(1)
return loclist
endfunction

View file

@ -20,7 +20,7 @@ set cpo&vim
" TODO: we should probably split this into separate checkers
function! SyntaxCheckers_elixir_elixir_IsAvailable() dict
call self.log(g:SyntasticDebugCheckers,
call self.log(
\ 'executable("elixir") = ' . executable('elixir') . ', ' .
\ 'executable("mix") = ' . executable('mix'))
return executable('elixir') && executable('mix')

View file

@ -15,6 +15,10 @@ if exists('g:loaded_syntastic_haskell_scan_checker')
endif
let g:loaded_syntastic_haskell_scan_checker = 1
if !exists('g:syntastic_haskell_scan_sort')
let g:syntastic_haskell_scan_sort = 1
endif
let s:save_cpo = &cpo
set cpo&vim
@ -23,14 +27,10 @@ function! SyntaxCheckers_haskell_scan_GetLocList() dict
let errorformat = '%f:%l:%v: %m'
let loclist = SyntasticMake({
return SyntasticMake({
\ 'makeprg': makeprg,
\ 'errorformat': errorformat,
\ 'subtype': 'Style' })
call self.setWantSort(1)
return loclist
endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({

View file

@ -37,8 +37,6 @@ function! SyntaxCheckers_html_jshint_GetLocList() dict
let errorformat = '%A%f: line %l\, col %v\, %m \(%t%*\d\)'
call self.setWantSort(1)
return SyntasticMake({
\ 'makeprg': makeprg,
\ 'errorformat': errorformat,

View file

@ -55,7 +55,7 @@ set cpo&vim
" TODO: join this with xhtml.vim for DRY's sake?
function! s:TidyEncOptByFenc()
let tidy_opts = {
let TIDY_OPTS = {
\ 'utf-8': '-utf8',
\ 'ascii': '-ascii',
\ 'latin1': '-latin1',
@ -69,10 +69,10 @@ function! s:TidyEncOptByFenc()
\ 'sjis': '-shiftjis',
\ 'cp850': '-ibm858',
\ }
return get(tidy_opts, &fileencoding, '-utf8')
return get(TIDY_OPTS, &fileencoding, '-utf8')
endfunction
let s:ignore_errors = [
let s:IGNORE_ERRORS = [
\ "<table> lacks \"summary\" attribute",
\ "not approved by W3C",
\ "<input> proprietary attribute \"placeholder\"",
@ -123,9 +123,9 @@ let s:ignore_errors = [
\ "proprietary attribute \"aria-valuenow\"",
\ "proprietary attribute \"aria-valuetext\""
\ ]
lockvar! s:ignore_errors
lockvar! s:IGNORE_ERRORS
let s:blocklevel_tags = [
let s:BLOCKLEVEL_TAGS = [
\ "main",
\ "section",
\ "article",
@ -136,9 +136,9 @@ let s:blocklevel_tags = [
\ "figure",
\ "figcaption"
\ ]
lockvar! s:blocklevel_tags
lockvar! s:BLOCKLEVEL_TAGS
let s:inline_tags = [
let s:INLINE_TAGS = [
\ "video",
\ "audio",
\ "source",
@ -155,16 +155,16 @@ let s:inline_tags = [
\ "details",
\ "datalist"
\ ]
lockvar! s:inline_tags
lockvar! s:INLINE_TAGS
let s:empty_tags = [
let s:EMPTY_TAGS = [
\ "wbr",
\ "keygen"
\ ]
lockvar! s:empty_tags
lockvar! s:EMPTY_TAGS
function! s:IgnoreError(text)
for item in s:ignore_errors + g:syntastic_html_tidy_ignore_errors
for item in s:IGNORE_ERRORS + g:syntastic_html_tidy_ignore_errors
if stridx(a:text, item) != -1
return 1
endif
@ -173,7 +173,7 @@ function! s:IgnoreError(text)
endfunction
function! s:NewTags(name)
return syntastic#util#shescape(join( s:{a:name} + g:syntastic_html_tidy_{a:name}, ',' ))
return syntastic#util#shescape(join( s:{toupper(a:name)} + g:syntastic_html_tidy_{a:name}, ',' ))
endfunction
function! s:Args()

View file

@ -24,6 +24,11 @@ function! SyntaxCheckers_javascript_closurecompiler_IsAvailable() dict
return 0
endif
let s:has_script = exists('g:syntastic_javascript_closurecompiler_script')
if s:has_script
return 1
endif
let cp = get(g:, 'syntastic_javascript_closurecompiler_path', '')
call self.log('g:syntastic_javascript_closurecompiler_path =', cp)
@ -45,14 +50,13 @@ function! SyntaxCheckers_javascript_closurecompiler_GetLocList() dict
endif
let makeprg = self.makeprgBuild({
\ 'exe_after': ['-jar', expand(g:syntastic_javascript_closurecompiler_path)],
\ 'exe_after': (s:has_script ? [] : ['-jar', expand(g:syntastic_javascript_closurecompiler_path)]),
\ 'args_after': '--js',
\ 'fname': file_list })
let errorformat =
\ '%-GOK,'.
\ '%E%f:%l: ERROR - %m,'.
\ '%Z%p^,'.
\ '%W%f:%l: WARNING - %m,'.
\ '%Z%p^'
@ -64,7 +68,7 @@ endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({
\ 'filetype': 'javascript',
\ 'name': 'closurecompiler',
\ 'exec': 'java'})
\ 'exec': get(g:, 'syntastic_javascript_closurecompiler_script', 'java')})
let &cpo = s:save_cpo
unlet s:save_cpo

View file

@ -14,6 +14,10 @@ if exists('g:loaded_syntastic_javascript_eslint_checker')
endif
let g:loaded_syntastic_javascript_eslint_checker = 1
if !exists('g:syntastic_javascript_eslint_sort')
let g:syntastic_javascript_eslint_sort = 1
endif
let s:save_cpo = &cpo
set cpo&vim
@ -47,8 +51,6 @@ function! SyntaxCheckers_javascript_eslint_GetLocList() dict
let e['col'] += 1
endfor
call self.setWantSort(1)
return loclist
endfunction

View file

@ -14,6 +14,10 @@ if exists("g:loaded_syntastic_javascript_jscs_checker")
endif
let g:loaded_syntastic_javascript_jscs_checker = 1
if !exists('g:syntastic_javascript_jscs_sort')
let g:syntastic_javascript_jscs_sort = 1
endif
let s:save_cpo = &cpo
set cpo&vim
@ -22,16 +26,12 @@ function! SyntaxCheckers_javascript_jscs_GetLocList() dict
let errorformat = '%f:%t:%l:%c:%m'
let loclist = SyntasticMake({
return SyntasticMake({
\ 'makeprg': makeprg,
\ 'errorformat': errorformat,
\ 'subtype': 'Style',
\ 'preprocess': 'checkstyle',
\ 'returns': [0, 2] })
call self.setWantSort(1)
return loclist
endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({

View file

@ -14,6 +14,10 @@ if exists('g:loaded_syntastic_javascript_jshint_checker')
endif
let g:loaded_syntastic_javascript_jshint_checker = 1
if !exists('g:syntastic_javascript_jshint_sort')
let g:syntastic_javascript_jshint_sort = 1
endif
let s:save_cpo = &cpo
set cpo&vim
@ -43,8 +47,6 @@ function! SyntaxCheckers_javascript_jshint_GetLocList() dict
\ '%A%f: line %l\, col %v\, %m \(%t%*\d\)' :
\ '%E%f: line %l\, col %v\, %m'
call self.setWantSort(1)
return SyntasticMake({
\ 'makeprg': makeprg,
\ 'errorformat': errorformat,

View file

@ -15,6 +15,10 @@ if exists("g:loaded_syntastic_markdown_mdl_checker")
endif
let g:loaded_syntastic_markdown_mdl_checker = 1
if !exists('g:syntastic_markdown_mdl_sort')
let g:syntastic_markdown_mdl_sort = 1
endif
let s:save_cpo = &cpo
set cpo&vim
@ -25,14 +29,10 @@ function! SyntaxCheckers_markdown_mdl_GetLocList() dict
\ '%E%f:%l: %m,'.
\ '%W%f: Kramdown Warning: %m found on line %l'
let loclist = SyntasticMake({
return SyntasticMake({
\ 'makeprg': makeprg,
\ 'errorformat': errorformat,
\ 'subtype': 'Style' })
call self.setWantSort(1)
return loclist
endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({

View file

@ -0,0 +1,78 @@
"============================================================================
"File: prospector.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_python_prospector_checker")
finish
endif
let g:loaded_syntastic_python_prospector_checker = 1
if !exists('g:syntastic_python_prospector_sort')
let g:syntastic_python_prospector_sort = 1
endif
let s:save_cpo = &cpo
set cpo&vim
function! SyntaxCheckers_python_prospector_IsAvailable() dict
if !executable(self.getExec())
return 0
endif
let ver = syntastic#util#getVersion(self.getExecEscaped() . ' --version')
call self.log(self.getExec() . ' version =', ver)
return syntastic#util#versionIsAtLeast(ver, [0, 7])
endfunction
function! SyntaxCheckers_python_prospector_GetLocList() dict
let makeprg = self.makeprgBuild({
\ 'args': '--external-config merge',
\ 'args_after': '--messages-only --absolute-paths --die-on-tool-error --zero-exit --output-format json' })
let errorformat = '%f:%l:%c: %m'
let env = syntastic#util#isRunningWindows() ? {} : { 'TERM': 'dumb' }
let loclist = SyntasticMake({
\ 'makeprg': makeprg,
\ 'errorformat': errorformat,
\ 'env': env,
\ 'preprocess': 'prospector',
\ 'returns': [0] })
for e in loclist
if e['text'] =~# '\v\[%(dodgy|mccabe|pep8|pep257|pyroma)\]$'
let e['subtype'] = 'Style'
endif
if e['text'] =~# '\v\[pylint\]$'
let e['type'] = e['text'] =~? '\m^[CRW]' ? 'W' : 'E'
elseif e['text'] =~# '\v\[%(frosted|pep8)\]$'
let e['type'] = e['text'] =~? '\m^W' ? 'W' : 'E'
elseif e['text'] =~# '\v\[%(dodgy|pyroma|vulture)\]$'
let e['type'] = 'W'
else
let e['type'] = 'E'
endif
endfor
return loclist
endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({
\ 'filetype': 'python',
\ 'name': 'prospector'})
let &cpo = s:save_cpo
unlet s:save_cpo
" vim: set et sts=4 sw=4:

View file

@ -15,6 +15,10 @@ if exists('g:loaded_syntastic_python_pylama_checker')
endif
let g:loaded_syntastic_python_pylama_checker = 1
if !exists('g:syntastic_python_pylama_sort')
let g:syntastic_python_pylama_sort = 1
endif
let s:save_cpo = &cpo
set cpo&vim
@ -55,8 +59,6 @@ function! SyntaxCheckers_python_pylama_GetLocList() dict
endif
endfor
call self.setWantSort(1)
return loclist
endfunction

View file

@ -10,11 +10,15 @@ if exists("g:loaded_syntastic_python_pylint_checker")
endif
let g:loaded_syntastic_python_pylint_checker = 1
let s:pylint_new = -1
if !exists('g:syntastic_python_pylint_sort')
let g:syntastic_python_pylint_sort = 1
endif
let s:save_cpo = &cpo
set cpo&vim
let s:pylint_new = -1
function! SyntaxCheckers_python_pylint_IsAvailable() dict
if !executable(self.getExec())
return 0
@ -81,8 +85,6 @@ function! SyntaxCheckers_python_pylint_GetLocList() dict
let e['vcol'] = 0
endfor
call self.setWantSort(1)
return loclist
endfunction

View file

@ -19,6 +19,10 @@ if !exists('g:syntastic_r_lint_styles')
let g:syntastic_r_lint_styles = 'lint.style'
endif
if !exists('g:syntastic_r_lint_sort')
let g:syntastic_r_lint_sort = 1
endif
let s:save_cpo = &cpo
set cpo&vim
@ -65,8 +69,6 @@ function! SyntaxCheckers_r_lint_GetLocList() dict
endif
endfor
call self.setWantSort(1)
return loclist
endfunction

View file

@ -19,6 +19,10 @@ if !exists('g:syntastic_racket_code_ayatollah_script')
let g:syntastic_racket_code_ayatollah_script = 'code-ayatollah.rkt'
endif
if !exists('g:syntastic_racket_code_ayatollah_sort')
let g:syntastic_racket_code_ayatollah_sort = 1
endif
let s:save_cpo = &cpo
set cpo&vim
@ -44,8 +48,6 @@ function! SyntaxCheckers_racket_code_ayatollah_GetLocList() dict
let e['col'] += 1
endfor
call self.setWantSort(1)
return loclist
endfunction

View file

@ -0,0 +1,48 @@
"============================================================================
"File: bashate.vim
"Description: Bash script style checking plugin for syntastic.vim
"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_sh_bashate_checker")
finish
endif
let g:loaded_syntastic_sh_bashate_checker = 1
let s:save_cpo = &cpo
set cpo&vim
function! SyntaxCheckers_sh_bashate_GetLocList() dict
let makeprg = self.makeprgBuild({})
let errorformat =
\ '%EE%n: %m,' .
\ '%Z - %f: L%l,' .
\ '%-G%.%#'
let loclist = SyntasticMake({
\ 'makeprg': makeprg,
\ 'errorformat': errorformat,
\ 'subtype': 'Style',
\ 'returns': [0, 1] })
for e in loclist
let e['text'] = substitute(e['text'], "\\m: '.*", '', '')
endfor
return loclist
endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({
\ 'filetype': 'sh',
\ 'name': 'bashate' })
let &cpo = s:save_cpo
unlet s:save_cpo
" vim: set et sts=4 sw=4:

View file

@ -15,13 +15,17 @@ if exists('g:loaded_syntastic_tex_chktex_checker')
endif
let g:loaded_syntastic_tex_chktex_checker = 1
let s:save_cpo = &cpo
set cpo&vim
if !exists('g:syntastic_tex_chktex_showmsgs')
let g:syntastic_tex_chktex_showmsgs = 1
endif
if !exists('g:syntastic_tex_chktex_sort')
let g:syntastic_tex_chktex_sort = 1
endif
let s:save_cpo = &cpo
set cpo&vim
function! SyntaxCheckers_tex_chktex_GetLocList() dict
let makeprg = self.makeprgBuild({ 'args_after': '-q -v1' })
@ -32,14 +36,10 @@ function! SyntaxCheckers_tex_chktex_GetLocList() dict
\ '%Z%p^,' .
\ '%-G%.%#'
let loclist = SyntasticMake({
return SyntasticMake({
\ 'makeprg': makeprg,
\ 'errorformat': errorformat,
\ 'subtype': 'Style' })
call self.setWantSort(1)
return loclist
endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({

View file

@ -15,6 +15,10 @@ if exists("g:loaded_syntastic_text_atdtool_checker")
endif
let g:loaded_syntastic_text_atdtool_checker = 1
if !exists('g:syntastic_text_atdtool_sort')
let g:syntastic_text_atdtool_sort = 1
endif
let s:save_cpo = &cpo
set cpo&vim
@ -44,8 +48,6 @@ function! SyntaxCheckers_text_atdtool_GetLocList() dict
let e['text'] = substitute(e['text'], '\m\n\s\+', ' | ', 'g')
endfor
call self.setWantSort(1)
return loclist
endfunction

View file

@ -9,6 +9,10 @@ if exists("g:loaded_syntastic_typescript_tsc_checker")
endif
let g:loaded_syntastic_typescript_tsc_checker = 1
if !exists('g:syntastic_typescript_tsc_sort')
let g:syntastic_typescript_tsc_sort = 1
endif
let s:save_cpo = &cpo
set cpo&vim
@ -23,14 +27,10 @@ function! SyntaxCheckers_typescript_tsc_GetLocList() dict
\ '%Eerror %m,' .
\ '%C%\s%\+%m'
let loclist = SyntasticMake({
return SyntasticMake({
\ 'makeprg': makeprg,
\ 'errorformat': errorformat,
\ 'defaults': {'bufnr': bufnr("")} })
call self.setWantSort(1)
return loclist
endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({

View file

@ -9,6 +9,10 @@ if exists("g:loaded_syntastic_typescript_tslint_checker")
endif
let g:loaded_syntastic_typescript_tslint_checker = 1
if !exists('g:syntastic_typescript_tslint_sort')
let g:syntastic_typescript_tslint_sort = 1
endif
let s:save_cpo = &cpo
set cpo&vim
@ -25,15 +29,11 @@ function! SyntaxCheckers_typescript_tslint_GetLocList() dict
" (comment-format) ts/app.ts[12, 36]: comment must start with lowercase letter
let errorformat = '%f[%l\, %c]: %m'
let loclist = SyntasticMake({
return SyntasticMake({
\ 'makeprg': makeprg,
\ 'errorformat': errorformat,
\ 'preprocess': 'tslint',
\ 'returns': [0, 2] })
call self.setWantSort(1)
return loclist
endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({

View file

@ -29,7 +29,7 @@ set cpo&vim
" TODO: join this with html.vim DRY's sake?
function! s:TidyEncOptByFenc()
let tidy_opts = {
let TIDY_OPTS = {
\ 'utf-8': '-utf8',
\ 'ascii': '-ascii',
\ 'latin1': '-latin1',
@ -43,7 +43,7 @@ function! s:TidyEncOptByFenc()
\ 'sjis': '-shiftjis',
\ 'cp850': '-ibm858',
\ }
return get(tidy_opts, &fileencoding, '-utf8')
return get(TIDY_OPTS, &fileencoding, '-utf8')
endfunction
function! s:IgnoreError(text)

View file

@ -144,6 +144,16 @@ Finally, you can add the convenience variable `let g:airline_powerline_fonts = 1
Solutions to common problems can be found in the [Wiki][27].
# Performance
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.
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.
# Screenshots
A full list of screenshots for various themes can be found in the [Wiki][14].

View file

@ -20,12 +20,24 @@ function! airline#extensions#eclim#get_warnings()
if !empty(eclimList)
" Remove any non-eclim signs (see eclim#display#signs#Update)
call filter(eclimList, 'v:val.name =~ "^\\(qf_\\)\\?\\(error\\|info\\|warning\\)$"')
" First check for just errors since they are more important.
" If there are no errors, then check for warnings.
let errorList = filter(copy(eclimList), 'v:val.name =~ "^\\(qf_\\)\\?\\(error\\)$"')
if (empty(errorList))
" use the warnings
call filter(eclimList, 'v:val.name =~ "^\\(qf_\\)\\?\\(warning\\)$"')
let type = 'W'
else
" Use the errors
let eclimList = errorList
let type = 'E'
endif
if !empty(eclimList)
let errorsLine = eclimList[0]['line']
let errorsNumber = len(eclimList)
let errors = "[Eclim: line:".string(errorsLine)." (".string(errorsNumber).")]"
let errors = "[Eclim:" . type . " line:".string(errorsLine)." (".string(errorsNumber).")]"
if !exists(':SyntasticCheck') || SyntasticStatuslineFlag() == ''
return errors.(g:airline_symbols.space)
endif

View file

@ -17,8 +17,8 @@ let s:builder_context = {
\ 'right_alt_sep' : get(g:, 'airline#extensions#tabline#right_alt_sep', g:airline_right_alt_sep),
\ }
if get(g:, 'airline_powerline_fonts', 0)
let s:builder_context.left_sep = get(g:, 'airline#extensions#tabline#left_sep' , "\ue0b0")
let s:builder_context.left_alt_sep = get(g:, 'airline#extensions#tabline#left_alt_sep' , "\ue0b1")
let s:builder_context.left_sep = get(g:, 'airline#extensions#tabline#left_sep' , g:airline_left_sep)
let s:builder_context.left_alt_sep = get(g:, 'airline#extensions#tabline#left_alt_sep' , g:airline_left_alt_sep)
else
let s:builder_context.left_sep = get(g:, 'airline#extensions#tabline#left_sep' , ' ')
let s:builder_context.left_alt_sep = get(g:, 'airline#extensions#tabline#left_alt_sep' , '|')

View file

@ -2,26 +2,19 @@
" Colorscheme: Kalisi for airline. Inspired by powerline.
" Arthur Jaron
" hifreeo@gmail.com
" 30.07.2014
" 24.10.2014
" Insert mode
let s:I1 = [ '#ffffff' , '#e80000','','']
let s:I2 = [ '#c5c5c5' , '#901010','','']
let s:I3 = [ '#c5c5c5' , '#500000','','']
" Visual mode
let s:V1 = [ '#2a5d8e' , '#ffffff','','']
let s:V2 = [ '#87e7ff' , '#4077df','','']
let s:V3 = [ '#87e7ff' , '#2a5d8e','','']
let s:V1 = [ '#0087ff' , '#ffffff','33','231']
let s:V2 = [ '#005faf' , '#5fafff','25','75']
let s:V3 = [ '#87d7ff' , '#005faf','117','25']
" Replace mode
let s:R1 = [ '#6e00ba' , '#ffffff','','']
let s:R2 = [ '#6e00ba' , '#d358ff','','']
let s:R3 = [ '#ce99ff' , '#6e00ba','','']
let s:R1 = [ '#d75fff' , '#ffffff','171','231']
let s:R2 = [ '#5f005f' , '#d75fff','53','171']
let s:R3 = [ '#ff87ff' , '#8700af','213','91']
let g:airline#themes#kalisi#palette = {}
let g:airline#themes#kalisi#palette.accents = {'red': ['#FF0000', '', 88, '']}
function! airline#themes#kalisi#refresh()
@ -29,35 +22,37 @@ function! airline#themes#kalisi#refresh()
let s:StatusLine = airline#themes#get_highlight('StatusLine')
let s:StatusLineNC = airline#themes#get_highlight('StatusLineNC')
" Normal mode
let s:N1 = [ '#005f00' , '#afd700','','']
let s:N2 = [ '#afd700' , '#005f00','','']
let s:N3 = s:StatusLine
" Insert mode
let s:I1 = [ '#ffffff' , '#e80000','231','160']
let s:I2 = [ '#ff0000' , '#5f0000','196','52']
let s:I3 = s:StatusLine
" Normal mode
let s:N1 = [ '#005f00' , '#afd700','22','148']
let s:N2 = [ '#afd700' , '#005f00','148','22']
let s:N3 = s:StatusLine
" Tabline Plugin
let g:airline#themes#kalisi#palette.tabline = {
\ 'airline_tab': ['#A6DB29', '#005f00','',''],
\ 'airline_tabsel': ['#404042', '#A6DB29','',''],
\ 'airline_tabtype': ['#afd700', '#204d20','',''],
\ 'airline_tabfill': s:StatusLine,
\ 'airline_tabhid': ['#c5c5c5', '#404042','',''],
\ 'airline_tabmod': ['#ffffff', '#F1266F','','']
\ 'airline_tab': ['#bcbcbc', '#005f00','250','22'],
\ 'airline_tabsel': ['#404042', '#A6DB29','238','148'],
\ 'airline_tabtype':['#afd700', '#204d20','148','22'],
\ 'airline_tabfill': s:StatusLine,
\ 'airline_tabhid': ['#c5c5c5', '#404042','251','238'],
\ 'airline_tabmod': ['#d7ff00', '#afd700','190','148'],
\ 'airline_tabmod_unsel': ['#d7ff00', '#005f00','190','22']
\ }
" \ 'airline_tabfill': ['#ffffff', '#2b2b2b','',''],
let g:airline#themes#kalisi#palette.normal = airline#themes#generate_color_map(s:N1, s:N2, s:N3)
let g:airline#themes#kalisi#palette.visual = airline#themes#generate_color_map(s:V1, s:V2, s:V3)
let g:airline#themes#kalisi#palette.insert = airline#themes#generate_color_map(s:I1, s:I2, s:I3)
let g:airline#themes#kalisi#palette.replace = airline#themes#generate_color_map(s:R1, s:R2, s:R3)
" Inactive Mode
" let s:IA = [ '#c5c5c5' , '#505052' , 239 , 234 , '' ]
let s:IA = airline#themes#get_highlight('StatusLineNC')
let g:airline#themes#kalisi#palette.inactive = airline#themes#generate_color_map(s:IA, s:IA, s:IA)
let g:airline#themes#kalisi#palette.inactive_modified = {
\ 'statusline': [ '#F1266F' , '' , '53' , '' , '' ] ,
\ 'airline_c': ['#d7ff00', s:IA[1],'190',s:IA[3]],
\ }
endfunction
@ -68,7 +63,8 @@ if !get(g:, 'loaded_ctrlp', 0)
finish
endif
let g:airline#themes#kalisi#palette.ctrlp = airline#extensions#ctrlp#generate_color_map(
\ s:StatusLineNC,
\ s:StatusLine,
\ [ '#005f00' , '#afd700' , '','', ''] )
\ ['#afd700', '#005f00','148','22'],
\ [ '#005f00' , '#afd700' , '22','148']
\)

View file

@ -1,39 +1,75 @@
let g:airline#themes#murmur#palette = {}
let s:termbg = 237 " Background for branch and file format blocks
let s:termbg2= 234 " Background for middle block
let s:normalbg= 27 " Background for normal mode and file position blocks
let s:insertbg= 70 " Background for insert mode and file position blocks
let s:visualbg= 166 " Background for visual mode and file position blocks
let s:replacebg=88 " Background for replace mode and file position blocks
let s:alert= 88 " Modefied file alert color
" Color palette
let s:cterm_termbg = 237 " Background for branch and file format blocks
let s:gui_termbg = '#5F5F5F'
let s:cterm_termfg = 144 " Foreground for branch and file format blocks
let s:gui_termfg = '#AFAF87'
let s:BB = ['#AFAF87', '#5F5F5F', 144, s:termbg] " Branch and file format blocks
let s:cterm_termbg2 = 234 " Background for middle block
let s:gui_termbg2 = '#1C1C1C'
let s:cterm_termfg2 = 39 " Foreground for middle block
let s:gui_termfg2 = '#F5F5F5'
let s:N1 = ['#FFFFFF', '#5F87FF', 15, s:normalbg] " Outside blocks in normal mode
let s:N2 = ['#AFAF87', '#5F5F5F', 39, s:termbg2] " Middle block
let s:cterm_normalbg = 27 " Background for normal mode and file position blocks
let s:gui_normalbg = '#5F87FF'
let s:cterm_normalfg = 15 " Foreground for normal mode and file position blocks
let s:gui_normalfg = '#FFFFFF'
let s:cterm_insertbg = 70 " Background for insert mode and file position blocks
let s:gui_insertbg = '#87AF5F'
let s:cterm_insertfg = 15 " Foreground for insert mode and file position blocks
let s:gui_insertfg = '#FFFFFF'
let s:cterm_visualbg = 166 " Background for visual mode and file position blocks
let s:gui_visualbg = '#ff8c00'
let s:cterm_visualfg = 15 " Foreground for visual mode and file position blocks
let s:gui_visualfg = '#FFFFFF'
let s:cterm_replacebg = 88 " Background for replace mode and file position blocks
let s:gui_replacebg = '#870000'
let s:cterm_replacefg = 15 " Foreground for replace mode and file position blocks
let s:gui_replacefg = '#FFFFFF'
let s:cterm_alert = 88 " Modified file alert color
let s:gui_alert = '#870000'
let s:cterm_inactivebg = 234 " Background for inactive mode
let s:gui_inactivebg = '#1C1C1C'
let s:cterm_inactivefg = 239 " Foreground for inactive mode
let s:gui_inactivefg = '#4E4E4E'
" Branch and file format
let s:BB = [s:gui_termfg, s:gui_termbg, s:cterm_termfg, s:cterm_termbg] " Branch and file format blocks
" Normal mode
let s:N1 = [s:gui_normalfg, s:gui_normalbg, s:cterm_normalfg, s:cterm_normalbg] " Outside blocks in normal mode
let s:N2 = [s:gui_termfg2, s:gui_termbg2, s:cterm_normalbg, s:cterm_termbg2] " Middle block
let g:airline#themes#murmur#palette.normal = airline#themes#generate_color_map(s:N1, s:BB, s:N2)
let g:airline#themes#murmur#palette.normal_modified = {'airline_c': ['#ffffff', '#5f005f', s:alert, s:termbg2, 'bold'] ,}
let g:airline#themes#murmur#palette.normal_modified = {'airline_c': [s:gui_alert, s:gui_termbg2, s:cterm_alert, s:cterm_termbg2, 'bold'] ,}
let s:I1 = ['#FFFFFF', '#87AF5F', 15, s:insertbg] " Outside blocks in insert mode
let s:I2 = ['#AFAF87', '#5F5F5F', s:insertbg, s:termbg2] " Middle block
" Insert mode
let s:I1 = [s:gui_insertfg, s:gui_insertbg, s:cterm_insertfg, s:cterm_insertbg] " Outside blocks in insert mode
let s:I2 = [s:gui_insertbg, s:gui_termbg2, s:cterm_insertbg, s:cterm_termbg2] " Middle block
let g:airline#themes#murmur#palette.insert = airline#themes#generate_color_map(s:I1, s:BB, s:I2)
let g:airline#themes#murmur#palette.insert_modified = {'airline_c': ['#AFAF87', '#5F5F5F', s:alert, s:termbg2, 'bold'] ,}
let g:airline#themes#murmur#palette.insert_modified = {'airline_c': [s:gui_alert, s:gui_termbg2, s:cterm_alert, s:cterm_termbg2, 'bold'] ,}
let s:R1 = ['#FFFFFF', '#870000', 15, s:replacebg] " Outside blocks in replace mode
let s:R2 = ['#AFAF87', '#5F5F5F', 255, s:termbg2] " Middle block
" Replace mode
let s:R1 = [s:gui_replacefg, s:gui_replacebg, s:cterm_replacefg, s:cterm_replacebg] " Outside blocks in replace mode
let s:R2 = [s:gui_termfg, s:gui_termbg2, s:cterm_termfg, s:cterm_termbg2] " Middle block
let g:airline#themes#murmur#palette.replace = airline#themes#generate_color_map(s:R1, s:BB, s:R2)
let g:airline#themes#murmur#palette.replace_modified = {'airline_c': ['#AFAF87', '#5f005f', s:alert, s:termbg2, 'bold'] ,}
let g:airline#themes#murmur#palette.replace_modified = {'airline_c': [s:gui_alert, s:gui_termbg2, s:cterm_alert, s:cterm_termbg2, 'bold'] ,}
let s:V1 = ['#FFFFFF', '#AF5F00', 15, s:visualbg] " Outside blocks in visual mode
let s:V2 = ['#AFAF87', '#5F5F5F', s:visualbg, s:termbg2] " Middle block
" Visual mode
let s:V1 = [s:gui_visualfg, s:gui_visualbg, s:cterm_visualfg, s:cterm_visualbg] " Outside blocks in visual mode
let s:V2 = [s:gui_visualbg, s:gui_termbg2, s:cterm_visualbg, s:cterm_termbg2] " Middle block
let g:airline#themes#murmur#palette.visual = airline#themes#generate_color_map(s:V1, s:BB, s:V2)
let g:airline#themes#murmur#palette.visual_modified = {'airline_c': [ '#AFAF87', '#5f005f', s:alert, s:termbg2, 'bold'] ,}
let g:airline#themes#murmur#palette.visual_modified = {'airline_c': [s:gui_alert, s:gui_termbg2, s:cterm_alert, s:cterm_termbg2, 'bold'] ,}
" Inactive mode
let s:IA1 = ['#4E4E4E', '#1C1C1C', 239, 234, '']
let s:IA2 = ['#4E4E4E', '#1C1C1C', 239, 234, '']
let s:IA3 = ['#4E4E4E', '#1C1C1C', 239, 234, '']
let s:IA1 = [s:gui_inactivefg, s:gui_inactivebg, s:cterm_inactivefg, s:cterm_inactivebg, '']
let s:IA2 = [s:gui_inactivefg, s:gui_inactivebg, s:cterm_inactivefg, s:cterm_inactivebg, '']
let s:IA3 = [s:gui_inactivefg, s:gui_inactivebg, s:cterm_inactivefg, s:cterm_inactivebg, '']
let g:airline#themes#murmur#palette.inactive = airline#themes#generate_color_map(s:IA1, s:IA2, s:IA3)
" CtrlP plugin colors
@ -41,6 +77,6 @@ if !get(g:, 'loaded_ctrlp', 0)
finish
endif
let g:airline#themes#murmur#palette.ctrlp = airline#extensions#ctrlp#generate_color_map(
\ ['#FFFFFF', '#5F87FF', 15, s:normalbg, ''],
\ ['#AFAF87', '#5F5F5F', 144, s:termbg, ''],
\ ['#AFAF87', '#5F5F5F', 39, s:termbg2, 'bold'])
\ [s:gui_normalfg, s:gui_normalbg, s:cterm_normalfg, s:cterm_normalbg, ''],
\ [s:gui_termfg, s:gui_termbg, s:cterm_termfg, s:cterm_termbg, ''],
\ [s:gui_termfg2, s:gui_termbg2, s:cterm_termfg2, s:cterm_termbg2, 'bold'])

View file

@ -81,7 +81,7 @@ nnoremap <silent> <Plug>ChangeCommentary c:<C-U>call <SID>textobject(1)<CR>
nmap <silent> <Plug>CommentaryUndo <Plug>Commentary<Plug>Commentary
command! -range -bar Commentary call s:go(<line1>,<line2>)
if 1 || !hasmapto('<Plug>Commentary') || maparg('gc','n') ==# ''
if !hasmapto('<Plug>Commentary') || maparg('gc','n') ==# ''
xmap gc <Plug>Commentary
nmap gc <Plug>Commentary
omap gc <Plug>Commentary

1
sources_non_forked/vim-go/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
doc/tags

View file

@ -0,0 +1,269 @@
# vim-go
Go (golang) support for Vim. It comes with pre-defined sensible settings (like
auto gofmt on save), has autocomplete, snippet support, improved syntax
highlighting, go toolchain commands, etc... If needed vim-go installs all
necessary binaries for providing seamless Vim integration with current
commands. It's highly customizable and each individual feature can be
disabled/enabled easily.
![vim-go](https://dl.dropboxusercontent.com/u/174404/vim-go-2.png)
## Features
* Improved Syntax highlighting, such as Functions, Operators, Methods..
* Auto completion support via `gocode`
* Better `gofmt` on save, keeps cursor position and doesn't break your undo
history
* Go to symbol/declaration with `godef`
* Look up documentation with `godoc` inside Vim or open it in browser.
* Automatically import packages via `goimports`
* Compile and `go build` your package, install it with `go install`
* `go run` quickly your current file/files
* 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`
* Run your code through `go vet` to catch static errors.
* Advanced source analysis tool with `oracle`
* Precise type-safe renaming of identifiers with `gorename`
* List all source files and dependencies
* Checking with `errcheck` for unchecked errors.
* Integrated and improved snippets. Supports `ultisnips` or `neosnippet`
* Share your current code to [play.golang.org](http://play.golang.org)
* 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`
## Install
First of all, do not use it with other Go plugins. If you use pathogen, just
clone it into your bundle directory:
```bash
$ cd ~/.vim/bundle
$ git clone https://github.com/fatih/vim-go.git
```
For Vundle add this line to your vimrc:
```vimrc
Plugin 'fatih/vim-go'
```
and execute `:PluginInstall` (or `:BundleInstall` for older versions of Vundle)
Please be sure all necessary binaries are installed (such as `gocode`, `godef`,
`goimports`, etc..). You can easily install them with the included
`:GoInstallBinaries`. Those binaries will be automatically downloaded and
installed to your `$GOBIN` environment (if not set it will use `$GOPATH/bin`).
It requires `git` and `hg` for fetching the individual Go packages.
### Optional
* Autocompletion is enabled by default via `<C-x><C-o>`, to get real-time
completion (completion by type) install:
[YCM](https://github.com/Valloric/YouCompleteMe) or
[neocomplete](https://github.com/Shougo/neocomplete.vim).
* To get displayed source code tag informations on a sidebar install
[tagbar](https://github.com/majutsushi/tagbar).
* For snippet feature install:
[ultisnips](https://github.com/SirVer/ultisnips) or
[neosnippet](https://github.com/Shougo/neosnippet.vim).
* Screenshot color scheme is a slightly modified molokai: [fatih/molokai](https://github.com/fatih/molokai).
## Usage
All [features](#features) are enabled by default. There are no additional
settings needed. Usage and commands are listed in `doc/vim-go.txt`. Just open
the help page to see all commands:
:help vim-go
## Mappings
vim-go has several `<Plug>` mappings which can be used to create custom
mappings. Below are some examples you might find useful:
Show a list of interfaces which is implemented by the type under your cursor
with `<leader>s`
```vim
au FileType go nmap <Leader>s <Plug>(go-implements)
```
Show type info for the word under your cursor with `<leader>i` (useful if you
have disabled auto showing type info via `g:go_auto_type_info`)
```vim
au FileType go nmap <Leader>i <Plug>(go-info)
```
Open the relevant Godoc for the word under the cursor with `<leader>gd` or open
it vertically with `<leader>gv`
```vim
au FileType go nmap <Leader>gd <Plug>(go-doc)
au FileType go nmap <Leader>gv <Plug>(go-doc-vertical)
```
Or open the Godoc in browser
```vim
au FileType go nmap <Leader>gb <Plug>(go-doc-browser)
```
Run commands, such as `go run` with `<leader>r` for the current file or `go
build` and `go test` for the current package with `<leader>b` and `<leader>t`.
Display a beautiful annotated source code to see which functions are covered
with `<leader>c`.
```vim
au FileType go nmap <leader>r <Plug>(go-run)
au FileType go nmap <leader>b <Plug>(go-build)
au FileType go nmap <leader>t <Plug>(go-test)
au FileType go nmap <leader>c <Plug>(go-coverage)
```
By default the mapping `gd` is enabled which opens the target identifier in
current buffer. You can also open the definition/declaration in a new vertical,
horizontal or tab for the word under your cursor:
```vim
au FileType go nmap <Leader>ds <Plug>(go-def-split)
au FileType go nmap <Leader>dv <Plug>(go-def-vertical)
au FileType go nmap <Leader>dt <Plug>(go-def-tab)
```
Rename the identifier under the cursor to a new name
```vim
au FileType go nmap <Leader>e <Plug>(go-rename)
```
More `<Plug>` mappings can be seen with `:he go-mappings`. Also these are just
recommendations, you are free to create more advanced mappings or functions
based on `:he go-commands`.
## Settings
Below are some settings you might find useful. For the full list see `:he go-settings`.
Disable opening browser after posting to your snippet to `play.golang.org`:
```vim
let g:go_play_open_browser = 0
```
By default vim-go shows errors for the fmt command, to disable it:
```vim
let g:go_fmt_fail_silently = 1
```
Enable goimports to automatically insert import paths instead of gofmt:
```vim
let g:go_fmt_command = "goimports"
```
Disable auto fmt on save:
```vim
let g:go_fmt_autosave = 0
```
By default binaries are installed to `$GOBIN` or `$GOPATH/bin`. To change it:
```vim
let g:go_bin_path = expand("~/.gotools")
let g:go_bin_path = "/home/fatih/.mypath" "or give absolute path
```
## Snippets
Snippets are useful and very powerful. By default ultisnips is
used, however you can change it to neosnippet with:
```vim
let g:go_snippet_engine = "neosnippet"
```
Snippet feature is enabled only if the snippet plugins are installed. Below are
some examples snippets and the corresponding trigger keywords, The `|`
character defines the cursor. Ultisnips has support for multiple cursors
`ff` is useful for debugging:
```go
fmt.Printf(" | %+v\n", |)
```
`errn` expands to:
```go
if err != nil {
return err
}
```
Use `gof` to quickly create a anonymous goroutine :
```go
go func() {
|
}()
```
To add `json` tags to a struct field, use `json` trigger:
```
type foo struct {
bar string `json:"myField"
^ type `json` here, hit tab and type "myField". It will expand to `json:"myField"`
}
```
...
And many more! For the full list have a look at the
[included snippets](https://github.com/fatih/vim-go/blob/master/gosnippets/):
## Troubleshooting
### I'm using Fish shell but have some problems using Vim-go
First environment variables in Fish are applied differently, it should be like:
set -x GOPATH /your/own/gopath
Second, Vim needs a POSIX compatible shell (more info here:
https://github.com/dag/vim-fish#teach-a-vim-to-fish). If you use Fish to open
vim, it will make certain shell based commands fail (means vim-go will fail
too). To overcome this problem change the default shell by adding the following
into your .vimrc (on the top of the file):
if $SHELL =~ 'fish'
set shell='/bin/bash'
endif
or
set shell='/bin/bash'
## Why another plugin?
This plugin/package is born mainly from frustration. I had to re-install my Vim
plugins and especially for Go I had to install a lot of separate different
plugins, setup the necessary binaries to make them work together and hope not
to lose them again. Lots of plugins out there lack proper settings.
This plugin is improved and contains all my fixes/changes that I'm using for
months under heavy go development environment.
Give it a try. I hope you like it. Feel free to contribute to the project.
## Credits
* Go Authors for official vim plugins
* Gocode, Godef, Golint, Oracle, Goimports, Gotags, Errcheck projects and authors of those projects.
* Other vim-plugins, thanks for inspiration (vim-golang, go.vim, vim-gocode, vim-godef)

View file

@ -0,0 +1,6 @@
{
"name": "vim-go",
"description": "Full featured Go (golang) support for Vim.",
"author": "Fatih Arslan <fatih@arslan.io>",
"repository" : {"type": "git", "url": "https://github.com/fatih/vim-go.git"}
}

View file

@ -0,0 +1,144 @@
if !exists("g:go_jump_to_error")
let g:go_jump_to_error = 1
endif
function! go#cmd#Run(bang, ...)
let default_makeprg = &makeprg
if !len(a:000)
let &makeprg = "go run " . join(go#tool#Files(), ' ')
else
let &makeprg = "go run " . expand(a:1)
endif
exe 'make!'
if !a:bang
cwindow
let errors = getqflist()
if !empty(errors)
if g:go_jump_to_error
cc 1 "jump to first error if there is any
endif
endif
endif
let &makeprg = default_makeprg
endfunction
function! go#cmd#Install(...)
let pkgs = join(a:000, ' ')
let command = 'go install '.pkgs
let out = go#tool#ExecuteInDir(command)
if v:shell_error
call go#tool#ShowErrors(out)
cwindow
return
endif
if exists("$GOBIN")
echon "vim-go: " | echohl Function | echon "installed to ". $GOBIN | echohl None
else
echon "vim-go: " | echohl Function | echon "installed to ". $GOPATH . "/bin" | echohl None
endif
endfunction
function! go#cmd#Build(bang)
let default_makeprg = &makeprg
let gofiles = join(go#tool#Files(), ' ')
if v:shell_error
let &makeprg = "go build . errors"
else
let &makeprg = "go build -o /dev/null " . gofiles
endif
echon "vim-go: " | echohl Identifier | echon "building ..."| echohl None
silent! exe 'make!'
redraw!
if !a:bang
cwindow
let errors = getqflist()
if !empty(errors)
if g:go_jump_to_error
cc 1 "jump to first error if there is any
endif
else
redraws! | echon "vim-go: " | echohl Function | echon "[build] SUCCESS"| echohl None
endif
endif
let &makeprg = default_makeprg
endfunction
function! go#cmd#Test(...)
let command = "go test ."
if len(a:000)
let command = "go test " . expand(a:1)
endif
echon "vim-go: " | echohl Identifier | echon "testing ..." | echohl None
let out = go#tool#ExecuteInDir(command)
if v:shell_error
call go#tool#ShowErrors(out)
else
call setqflist([])
endif
cwindow
let errors = getqflist()
if !empty(errors)
if g:go_jump_to_error
cc 1 "jump to first error if there is any
endif
else
redraw | echon "vim-go: " | echohl Function | echon "[test] PASS" | echohl None
endif
endfunction
function! go#cmd#Coverage(...)
let l:tmpname=tempname()
let command = "go test -coverprofile=".l:tmpname
let out = go#tool#ExecuteInDir(command)
if v:shell_error
call go#tool#ShowErrors(out)
else
" clear previous quick fix window
call setqflist([])
let openHTML = 'go tool cover -html='.l:tmpname
call go#tool#ExecuteInDir(openHTML)
endif
cwindow
let errors = getqflist()
if !empty(errors)
if g:go_jump_to_error
cc 1 "jump to first error if there is any
endif
endif
call delete(l:tmpname)
endfunction
function! go#cmd#Vet()
echon "vim-go: " | echohl Identifier | echon "calling vet..." | echohl None
let out = go#tool#ExecuteInDir('go vet')
if v:shell_error
call go#tool#ShowErrors(out)
else
call setqflist([])
endif
cwindow
let errors = getqflist()
if !empty(errors)
if g:go_jump_to_error
cc 1 "jump to first error if there is any
endif
else
redraw | echon "vim-go: " | echohl Function | echon "[vet] PASS" | echohl None
endif
endfunction
" vim:ts=4:sw=4:et
"

View file

@ -0,0 +1,142 @@
if !exists("g:go_gocode_bin")
let g:go_gocode_bin = "gocode"
endif
fu! s:gocodeCurrentBuffer()
let buf = getline(1, '$')
if &encoding != 'utf-8'
let buf = map(buf, 'iconv(v:val, &encoding, "utf-8")')
endif
if &l:fileformat == 'dos'
" XXX: line2byte() depend on 'fileformat' option.
" so if fileformat is 'dos', 'buf' must include '\r'.
let buf = map(buf, 'v:val."\r"')
endif
let file = tempname()
call writefile(buf, file)
return file
endf
let s:vim_system = get(g:, 'gocomplete#system_function', 'system')
fu! s:system(str, ...)
return call(s:vim_system, [a:str] + a:000)
endf
fu! s:gocodeShellescape(arg)
try
let ssl_save = &shellslash
set noshellslash
return shellescape(a:arg)
finally
let &shellslash = ssl_save
endtry
endf
fu! s:gocodeCommand(cmd, preargs, args)
for i in range(0, len(a:args) - 1)
let a:args[i] = s:gocodeShellescape(a:args[i])
endfor
for i in range(0, len(a:preargs) - 1)
let a:preargs[i] = s:gocodeShellescape(a:preargs[i])
endfor
let bin_path = go#tool#BinPath(g:go_gocode_bin)
if empty(bin_path)
return
endif
let result = s:system(printf('%s %s %s %s', bin_path, join(a:preargs), a:cmd, join(a:args)))
if v:shell_error != 0
return "[\"0\", []]"
else
if &encoding != 'utf-8'
let result = iconv(result, 'utf-8', &encoding)
endif
return result
endif
endf
fu! s:gocodeCurrentBufferOpt(filename)
return '-in=' . a:filename
endf
fu! s:gocodeCursor()
if &encoding != 'utf-8'
let sep = &l:fileformat == 'dos' ? "\r\n" : "\n"
let c = col('.')
let buf = line('.') == 1 ? "" : (join(getline(1, line('.')-1), sep) . sep)
let buf .= c == 1 ? "" : getline('.')[:c-2]
return printf('%d', len(iconv(buf, &encoding, "utf-8")))
endif
return printf('%d', line2byte(line('.')) + (col('.')-2))
endf
fu! s:gocodeAutocomplete()
let filename = s:gocodeCurrentBuffer()
let result = s:gocodeCommand('autocomplete',
\ [s:gocodeCurrentBufferOpt(filename), '-f=vim'],
\ [expand('%:p'), s:gocodeCursor()])
call delete(filename)
return result
endf
function! go#complete#GetInfo()
let filename = s:gocodeCurrentBuffer()
let result = s:gocodeCommand('autocomplete',
\ [s:gocodeCurrentBufferOpt(filename), '-f=godit'],
\ [expand('%:p'), s:gocodeCursor()])
call delete(filename)
" first line is: Charcount,,NumberOfCandidates, i.e: 8,,1
" following lines are candiates, i.e: func foo(name string),,foo(
let out = split(result, '\n')
" no candidates are found
if len(out) == 1
return
endif
" only one candiate is found
if len(out) == 2
return split(out[1], ',,')[0]
endif
" to many candidates are available, pick one that maches the word under the
" cursor
let infos = []
for info in out[1:]
call add(infos, split(info, ',,')[0])
endfor
let wordMatch = '\<' . expand("<cword>") . '\>'
" escape single quotes in wordMatch before passing it to filter
let wordMatch = substitute(wordMatch, "'", "''", "g")
let filtered = filter(infos, "v:val =~ '".wordMatch."'")
if len(filtered) == 1
return filtered[0]
endif
endfunction
function! go#complete#Info()
let result = go#complete#GetInfo()
if len(result) > 0
echo "vim-go: " | echohl Function | echon result | echohl None
endif
endfunction!
fu! go#complete#Complete(findstart, base)
"findstart = 1 when we need to get the text length
if a:findstart == 1
execute "silent let g:gocomplete_completions = " . s:gocodeAutocomplete()
return col('.') - g:gocomplete_completions[0] - 1
"findstart = 0 when we need to return the list of completions
else
return g:gocomplete_completions[1]
endif
endf
" vim:ts=4:sw=4:et

View file

@ -0,0 +1,106 @@
if !exists("g:go_godef_bin")
let g:go_godef_bin = "godef"
endif
" modified and improved version of vim-godef
function! go#def#Jump(...)
if !len(a:000)
" gives us the offset of the word, basicall the position of the word under
" he cursor
let arg = s:getOffset()
else
let arg = a:1
endif
let bin_path = go#tool#BinPath(g:go_godef_bin)
if empty(bin_path)
return
endif
let command = bin_path . " -f=" . expand("%:p") . " -i " . shellescape(arg)
" get output of godef
let out=system(command, join(getbufline(bufnr('%'), 1, '$'), "\n"))
" jump to it
call s:godefJump(out, "")
endfunction
function! go#def#JumpMode(mode)
let arg = s:getOffset()
let bin_path = go#tool#BinPath(g:go_godef_bin)
if empty(bin_path)
return
endif
let command = bin_path . " -f=" . expand("%:p") . " -i " . shellescape(arg)
" get output of godef
let out=system(command, join(getbufline(bufnr('%'), 1, '$'), "\n"))
call s:godefJump(out, a:mode)
endfunction
function! s:getOffset()
let pos = getpos(".")[1:2]
if &encoding == 'utf-8'
let offs = line2byte(pos[0]) + pos[1] - 2
else
let c = pos[1]
let buf = line('.') == 1 ? "" : (join(getline(1, pos[0] - 1), "\n") . "\n")
let buf .= c == 1 ? "" : getline(pos[0])[:c-2]
let offs = len(iconv(buf, &encoding, "utf-8"))
endif
let argOff = "-o=" . offs
return argOff
endfunction
function! s:godefJump(out, mode)
let old_errorformat = &errorformat
let &errorformat = "%f:%l:%c"
if a:out =~ 'godef: '
let out=substitute(a:out, '\n$', '', '')
echom out
else
let parts = split(a:out, ':')
" parts[0] contains filename
let fileName = parts[0]
" put the error format into location list so we can jump automatically to
" it
lgetexpr a:out
" needed for restoring back user setting this is because there are two
" modes of switchbuf which we need based on the split mode
let old_switchbuf = &switchbuf
if a:mode == "tab"
let &switchbuf = "usetab"
if bufloaded(fileName) == 0
tab split
endif
else
if a:mode == "split"
split
elseif a:mode == "vsplit"
vsplit
endif
endif
" jump to file now
ll 1
normal zz
let &switchbuf = old_switchbuf
end
let &errorformat = old_errorformat
endfunction

View file

@ -0,0 +1,159 @@
" Copyright 2011 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" godoc.vim: Vim command to see godoc.
"
"
" Commands:
"
" :GoDoc
"
" Open the relevant Godoc for either the word[s] passed to the command or
" the, by default, the word under the cursor.
"
" Options:
"
" g:go_godoc_commands [default=1]
"
" Flag to indicate whether to enable the commands listed above.
let s:buf_nr = -1
if !exists("g:go_doc_command")
let g:go_doc_command = "godoc"
endif
if !exists("g:go_doc_options")
let g:go_doc_options = ""
endif
" returns the package and exported name. exported name might be empty.
" ie: fmt and Println
" ie: github.com/fatih/set and New
function! s:godocWord(args)
if !executable('godoc')
echohl WarningMsg
echo "godoc command not found."
echo " install with: go get code.google.com/p/go.tools/cmd/godoc"
echohl None
return []
endif
if !len(a:args)
let oldiskeyword = &iskeyword
setlocal iskeyword+=.
let word = expand('<cword>')
let &iskeyword = oldiskeyword
let word = substitute(word, '[^a-zA-Z0-9\\/._~-]', '', 'g')
let words = split(word, '\.\ze[^./]\+$')
else
let words = a:args
endif
if !len(words)
return []
endif
let pkg = words[0]
if len(words) == 1
let exported_name = ""
else
let exported_name = words[1]
endif
let packages = go#tool#Imports()
if has_key(packages, pkg)
let pkg = packages[pkg]
endif
return [pkg, exported_name]
endfunction
function! go#doc#OpenBrowser(...)
let pkgs = s:godocWord(a:000)
if empty(pkgs)
return
endif
let pkg = pkgs[0]
let exported_name = pkgs[1]
" example url: https://godoc.org/github.com/fatih/set#Set
let godoc_url = "https://godoc.org/" . pkg . "#" . exported_name
call go#tool#OpenBrowser(godoc_url)
endfunction
function! go#doc#Open(mode, ...)
let pkgs = s:godocWord(a:000)
if empty(pkgs)
return
endif
let pkg = pkgs[0]
let exported_name = pkgs[1]
let command = g:go_doc_command . ' ' . g:go_doc_options . ' ' . pkg
silent! let content = system(command)
if v:shell_error || !len(content)
echo 'No documentation found for "' . pkg . '".'
return -1
endif
call s:GodocView(a:mode, content)
" jump to the specified name
if search('^func ' . exported_name . '(')
silent! normal zt
return -1
endif
if search('^type ' . exported_name)
silent! normal zt
return -1
endif
if search('^\%(const\|var\|type\|\s\+\) ' . pkg . '\s\+=\s')
silent! normal zt
return -1
endif
" nothing found, jump to top
silent! normal gg
endfunction
function! s:GodocView(position, content)
" reuse existing buffer window if it exists otherwise create a new one
if !bufexists(s:buf_nr)
execute a:position
file `="[Godoc]"`
let s:buf_nr = bufnr('%')
elseif bufwinnr(s:buf_nr) == -1
execute a:position
execute s:buf_nr . 'buffer'
elseif bufwinnr(s:buf_nr) != bufwinnr('%')
execute bufwinnr(s:buf_nr) . 'wincmd w'
endif
setlocal filetype=godoc
setlocal bufhidden=delete
setlocal buftype=nofile
setlocal noswapfile
setlocal nobuflisted
setlocal nocursorline
setlocal nocursorcolumn
setlocal iskeyword+=:
setlocal iskeyword-=-
setlocal modifiable
%delete _
call append(0, split(a:content, "\n"))
$delete _
setlocal nomodifiable
endfunction
" vim:ts=4:sw=4:et

View file

@ -0,0 +1,36 @@
if !exists("g:go_errcheck_bin")
let g:go_errcheck_bin = "errcheck"
endif
function! go#errcheck#Run() abort
let bin_path = go#tool#BinPath(g:go_errcheck_bin)
if empty(bin_path)
return
endif
let out = system(bin_path . ' ' . shellescape(expand('%:p:h')))
if v:shell_error
let errors = []
let mx = '^\(.\{-}\):\(\d\+\):\(\d\+\)\s*\(.*\)'
for line in split(out, '\n')
let tokens = matchlist(line, mx)
if !empty(tokens)
call add(errors, {"filename": tokens[1],
\"lnum": tokens[2],
\"col": tokens[3],
\"text": tokens[4]})
endif
endfor
if empty(errors)
% | " Couldn't detect error format, output errors
endif
if !empty(errors)
call setqflist(errors, 'r')
endif
echohl Error | echomsg "GoErrCheck returned error" | echohl None
else
call setqflist([])
endif
cwindow
endfunction

View file

@ -0,0 +1,141 @@
" Copyright 2011 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" fmt.vim: Vim command to format Go files with gofmt.
"
" This filetype plugin add a new commands for go buffers:
"
" :Fmt
"
" Filter the current Go buffer through gofmt.
" It tries to preserve cursor position and avoids
" replacing the buffer with stderr output.
"
" Options:
"
" g:go_fmt_command [default="gofmt"]
"
" Flag naming the gofmt executable to use.
"
" g:go_fmt_autosave [default=1]
"
" Flag to auto call :Fmt when saved file
"
if !exists("g:go_fmt_command")
let g:go_fmt_command = "gofmt"
endif
if !exists("g:go_goimports_bin")
let g:go_goimports_bin = "goimports"
endif
if !exists('g:go_fmt_fail_silently')
let g:go_fmt_fail_silently = 0
endif
if !exists('g:go_fmt_options')
let g:go_fmt_options = ''
endif
let s:got_fmt_error = 0
" we have those problems :
" http://stackoverflow.com/questions/12741977/prevent-vim-from-updating-its-undo-tree
" http://stackoverflow.com/questions/18532692/golang-formatter-and-vim-how-to-destroy-history-record?rq=1
"
" The below function is an improved version that aims to fix all problems.
" it doesn't undo changes and break undo history. If you are here reading
" this and have VimL experience, please look at the function for
" improvements, patches are welcome :)
function! go#fmt#Format(withGoimport)
" save cursor position and many other things
let l:curw=winsaveview()
" needed for testing if gofmt fails or not
let l:tmpname=tempname()
call writefile(getline(1,'$'), l:tmpname)
" save our undo file to be restored after we are done. This is needed to
" prevent an additional undo jump due to BufWritePre auto command and also
" restore 'redo' history because it's getting being destroyed every
" BufWritePre
let tmpundofile=tempname()
exe 'wundo! ' . tmpundofile
" get the command first so we can test it
let fmt_command = g:go_fmt_command
if a:withGoimport == 1
" check if the user has installed goimports
let bin_path = go#tool#BinPath(g:go_goimports_bin)
if empty(bin_path)
return
endif
let fmt_command = bin_path
endif
" populate the final command with user based fmt options
let command = fmt_command . ' ' . g:go_fmt_options
" execute our command...
let out = system(command . " " . l:tmpname)
"if there is no error on the temp file, gofmt again our original file
if v:shell_error == 0
" remove undo point caused via BufWritePre
try | silent undojoin | catch | endtry
" do not include stderr to the buffer, this is due to goimports/gofmt
" tha fails with a zero exit return value (sad yeah).
let default_srr = &srr
set srr=>%s
" execufe gofmt on the current buffer and replace it
silent execute "%!" . command
" only clear quickfix if it was previously set, this prevents closing
" other quickfixes
if s:got_fmt_error
let s:got_fmt_error = 0
call setqflist([])
cwindow
endif
" put back the users srr setting
let &srr = default_srr
elseif g:go_fmt_fail_silently == 0
"otherwise get the errors and put them to quickfix window
let errors = []
for line in split(out, '\n')
let tokens = matchlist(line, '^\(.\{-}\):\(\d\+\):\(\d\+\)\s*\(.*\)')
if !empty(tokens)
call add(errors, {"filename": @%,
\"lnum": tokens[2],
\"col": tokens[3],
\"text": tokens[4]})
endif
endfor
if empty(errors)
% | " Couldn't detect gofmt error format, output errors
endif
if !empty(errors)
call setqflist(errors, 'r')
echohl Error | echomsg "Gofmt returned error" | echohl None
endif
let s:got_fmt_error = 1
cwindow
endif
" restore our undo history
silent! exe 'rundo ' . tmpundofile
call delete(tmpundofile)
" restore our cursor/windows positions
call delete(l:tmpname)
call winrestview(l:curw)
endfunction
" vim:ts=4:sw=4:et

View file

@ -0,0 +1,236 @@
" Copyright 2011 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" import.vim: Vim commands to import/drop Go packages.
"
" This filetype plugin adds three new commands for go buffers:
"
" :GoImport {path}
"
" Import ensures that the provided package {path} is imported
" in the current Go buffer, using proper style and ordering.
" If {path} is already being imported, an error will be
" displayed and the buffer will be untouched.
"
" :GoImportAs {localname} {path}
"
" Same as Import, but uses a custom local name for the package.
"
" :GoDrop {path}
"
" Remove the import line for the provided package {path}, if
" present in the current Go buffer. If {path} is not being
" imported, an error will be displayed and the buffer will be
" untouched.
"
" If you would like to add shortcuts, you can do so by doing the following:
"
" Import fmt
" au Filetype go nnoremap <buffer> <LocalLeader>f :Import fmt<CR>
"
" Drop fmt
" au Filetype go nnoremap <buffer> <LocalLeader>F :Drop fmt<CR>
"
" Import the word under your cursor
" au Filetype go nnoremap <buffer> <LocalLeader>k
" \ :exe 'Import ' . expand('<cword>')<CR>
"
" The backslash '\' is the default maplocalleader, so it is possible that
" your vim is set to use a different character (:help maplocalleader).
"
function! go#import#SwitchImport(enabled, localname, path)
let view = winsaveview()
let path = a:path
" Quotes are not necessary, so remove them if provided.
if path[0] == '"'
let path = strpart(path, 1)
endif
if path[len(path)-1] == '"'
let path = strpart(path, 0, len(path) - 1)
endif
if path == ''
call s:Error('Import path not provided')
return
endif
let exists = go#tool#Exists(path)
if exists == -1
call s:Error("Can't find import: " . path)
return
endif
" Extract any site prefix (e.g. github.com/).
" If other imports with the same prefix are grouped separately,
" we will add this new import with them.
" Only up to and including the first slash is used.
let siteprefix = matchstr(path, "^[^/]*/")
let qpath = '"' . path . '"'
if a:localname != ''
let qlocalpath = a:localname . ' ' . qpath
else
let qlocalpath = qpath
endif
let indentstr = 0
let packageline = -1 " Position of package name statement
let appendline = -1 " Position to introduce new import
let deleteline = -1 " Position of line with existing import
let linesdelta = 0 " Lines added/removed
" Find proper place to add/remove import.
let line = 0
while line <= line('$')
let linestr = getline(line)
if linestr =~# '^package\s'
let packageline = line
let appendline = line
elseif linestr =~# '^import\s\+('
let appendstr = qlocalpath
let indentstr = 1
let appendline = line
let firstblank = -1
let lastprefix = ""
while line <= line("$")
let line = line + 1
let linestr = getline(line)
let m = matchlist(getline(line), '^\()\|\(\s\+\)\(\S*\s*\)"\(.\+\)"\)')
if empty(m)
if siteprefix == "" && a:enabled
" must be in the first group
break
endif
" record this position, but keep looking
if firstblank < 0
let firstblank = line
endif
continue
endif
if m[1] == ')'
" if there's no match, add it to the first group
if appendline < 0 && firstblank >= 0
let appendline = firstblank
endif
break
endif
let lastprefix = matchstr(m[4], "^[^/]*/")
if a:localname != '' && m[3] != ''
let qlocalpath = printf('%-' . (len(m[3])-1) . 's %s', a:localname, qpath)
endif
let appendstr = m[2] . qlocalpath
let indentstr = 0
if m[4] == path
let appendline = -1
let deleteline = line
break
elseif m[4] < path
" don't set candidate position if we have a site prefix,
" we've passed a blank line, and this doesn't share the same
" site prefix.
if siteprefix == "" || firstblank < 0 || match(m[4], "^" . siteprefix) >= 0
let appendline = line
endif
elseif siteprefix != "" && match(m[4], "^" . siteprefix) >= 0
" first entry of site group
let appendline = line - 1
break
endif
endwhile
break
elseif linestr =~# '^import '
if appendline == packageline
let appendstr = 'import ' . qlocalpath
let appendline = line - 1
endif
let m = matchlist(linestr, '^import\(\s\+\)\(\S*\s*\)"\(.\+\)"')
if !empty(m)
if m[3] == path
let appendline = -1
let deleteline = line
break
endif
if m[3] < path
let appendline = line
endif
if a:localname != '' && m[2] != ''
let qlocalpath = printf("%s %" . len(m[2])-1 . "s", a:localname, qpath)
endif
let appendstr = 'import' . m[1] . qlocalpath
endif
elseif linestr =~# '^\(var\|const\|type\|func\)\>'
break
endif
let line = line + 1
endwhile
" Append or remove the package import, as requested.
if a:enabled
if deleteline != -1
call s:Error(qpath . ' already being imported')
elseif appendline == -1
call s:Error('No package line found')
else
if appendline == packageline
call append(appendline + 0, '')
call append(appendline + 1, 'import (')
call append(appendline + 2, ')')
let appendline += 2
let linesdelta += 3
let appendstr = qlocalpath
let indentstr = 1
endif
call append(appendline, appendstr)
execute appendline + 1
if indentstr
execute 'normal >>'
endif
let linesdelta += 1
endif
else
if deleteline == -1
call s:Error(qpath . ' not being imported')
else
execute deleteline . 'd'
let linesdelta -= 1
if getline(deleteline-1) =~# '^import\s\+(' && getline(deleteline) =~# '^)'
" Delete empty import block
let deleteline -= 1
execute deleteline . "d"
execute deleteline . "d"
let linesdelta -= 2
endif
if getline(deleteline) == '' && getline(deleteline - 1) == ''
" Delete spacing for removed line too.
execute deleteline . "d"
let linesdelta -= 1
endif
endif
endif
" Adjust view for any changes.
let view.lnum += linesdelta
let view.topline += linesdelta
if view.topline < 0
let view.topline = 0
endif
" Put buffer back where it was.
call winrestview(view)
endfunction
function! s:Error(s)
echohl Error | echo a:s | echohl None
endfunction
" vim:ts=4:sw=4:et

View file

@ -0,0 +1,30 @@
" Copyright 2013 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" lint.vim: Vim command to lint Go files with golint.
"
" https://github.com/golang/lint
"
" This filetype plugin add a new commands for go buffers:
"
" :GoLint
"
" Run golint for the current Go file.
"
if !exists("g:go_golint_bin")
let g:go_golint_bin = "golint"
endif
function! go#lint#Run() abort
let bin_path = go#tool#BinPath(g:go_golint_bin)
if empty(bin_path)
return
endif
silent cexpr system(bin_path . " " . shellescape(expand('%')))
cwindow
endfunction
" vim:ts=4:sw=4:et

View file

@ -0,0 +1,224 @@
" -*- text -*-
" oracle.vim -- Vim integration for the Go oracle.
"
" Part of this plugin was taken directly from the oracle repo, however it's
" massively changed for a better integration into vim-go. Thanks Alan Donovan
" for the first iteration based on quickfix! - fatih arslan
"
"
if !exists("g:go_oracle_bin")
let g:go_oracle_bin = "oracle"
endif
func! s:qflist(output)
let qflist = []
" Parse GNU-style 'file:line.col-line.col: message' format.
let mx = '^\(\a:[\\/][^:]\+\|[^:]\+\):\(\d\+\):\(\d\+\):\(.*\)$'
for line in split(a:output, "\n")
let ml = matchlist(line, mx)
" Ignore non-match lines or warnings
if ml == [] || ml[4] =~ '^ warning:'
continue
endif
let item = {
\ 'filename': ml[1],
\ 'text': ml[4],
\ 'lnum': ml[2],
\ 'col': ml[3],
\}
let bnr = bufnr(fnameescape(ml[1]))
if bnr != -1
let item['bufnr'] = bnr
endif
call add(qflist, item)
endfor
call setqflist(qflist)
cwindow
endfun
func! s:getpos(l, c)
if &encoding != 'utf-8'
let buf = a:l == 1 ? '' : (join(getline(1, a:l-1), "\n") . "\n")
let buf .= a:c == 1 ? '' : getline('.')[:a:c-2]
return len(iconv(buf, &encoding, 'utf-8'))
endif
return line2byte(a:l) + (a:c-2)
endfun
func! s:RunOracle(mode, selected) range abort
let fname = expand('%:p')
let dname = expand('%:p:h')
let pkg = go#package#ImportPath(dname)
if exists('g:go_oracle_scope_file')
" let the user defines the scope
let sname = shellescape(get(g:, 'go_oracle_scope_file'))
elseif exists('g:go_oracle_include_tests') && pkg != -1
" give import path so it includes all _test.go files too
let sname = shellescape(pkg)
else
" best usable way, only pass the package itself, without the test
" files
let sname = join(go#tool#Files(), ' ')
endif
"return with a warning if the bin doesn't exist
let bin_path = go#tool#BinPath(g:go_oracle_bin)
if empty(bin_path)
return
endif
if a:selected != -1
let pos1 = s:getpos(line("'<"), col("'<"))
let pos2 = s:getpos(line("'>"), col("'>"))
let cmd = printf('%s -format json -pos=%s:#%d,#%d %s %s',
\ bin_path,
\ shellescape(fname), pos1, pos2, a:mode, sname)
else
let pos = s:getpos(line('.'), col('.'))
let cmd = printf('%s -format json -pos=%s:#%d %s %s',
\ bin_path,
\ shellescape(fname), pos, a:mode, sname)
endif
echon "vim-go: " | echohl Identifier | echon "analysing ..." | echohl None
let out = system(cmd)
if v:shell_error
" unfortunaly oracle outputs a very long stack trace that is not
" parsable to show the real error. But the main issue is usually the
" package which doesn't build.
" echo out
" redraw | echon 'vim-go: could not run static analyser (does it build?)'
redraw | echon "vim-go: " | echohl Statement | echon out | echohl None
return {}
else
let json_decoded = webapi#json#decode(out)
return json_decoded
endif
endfun
" Show 'implements' relation for selected package
function! go#oracle#Implements(selected)
let out = s:RunOracle('implements', a:selected)
if empty(out)
return
endif
" be sure they exists before we retrieve them from the map
if !has_key(out, "implements")
return
endif
if has_key(out.implements, "from")
let interfaces = out.implements.from
elseif has_key(out.implements, "fromptr")
let interfaces = out.implements.fromptr
else
redraw | echon "vim-go: " | echon "does not satisfy any interface"| echohl None
return
endif
" get the type name from the type under the cursor
let typeName = out.implements.type.name
" prepare the title
let title = typeName . " implements:"
" start to populate our buffer content
let result = [title, ""]
for interface in interfaces
" don't add runtime interfaces
if interface.name !~ '^runtime'
let line = interface.name . "\t" . interface.pos
call add(result, line)
endif
endfor
" open a window and put the result
call go#ui#OpenWindow(result)
" define some buffer related mappings:
"
" go to definition when hit enter
nnoremap <buffer> <CR> :<C-u>call go#ui#OpenDefinition()<CR>
" close the window when hit ctrl-c
nnoremap <buffer> <c-c> :<C-u>call go#ui#CloseWindow()<CR>
endfunction
" Describe selected syntax: definition, methods, etc
function! go#oracle#Describe(selected)
let out = s:RunOracle('describe', a:selected)
if empty(out)
return
endif
echo out
return
let detail = out["describe"]["detail"]
let desc = out["describe"]["desc"]
echo '# detail: '. detail
" package, constant, variable, type, function or statement labe
if detail == "package"
echo desc
return
endif
if detail == "value"
echo desc
echo out["describe"]["value"]
return
endif
" the rest needs to be implemented
echo desc
endfunction
" Show possible targets of selected function call
function! go#oracle#Callees(selected)
let out = s:RunOracle('callees', a:selected)
echo out
endfunction
" Show possible callers of selected function
function! go#oracle#Callers(selected)
let out = s:RunOracle('callers', a:selected)
echo out
endfunction
" Show the callgraph of the current program.
function! go#oracle#Callgraph(selected)
let out = s:RunOracle('callgraph', a:selected)
echo out
endfunction
" Show path from callgraph root to selected function
function! go#oracle#Callstack(selected)
let out = s:RunOracle('callstack', a:selected)
echo out
endfunction
" Show free variables of selection
function! go#oracle#Freevars(selected)
let out = s:RunOracle('freevars', a:selected)
echo out
endfunction
" Show send/receive corresponding to selected channel op
function! go#oracle#Peers(selected)
let out = s:RunOracle('peers', a:selected)
echo out
endfunction
" Show all refs to entity denoted by selected identifier
function! go#oracle#Referrers(selected)
let out = s:RunOracle('referrers', a:selected)
echo out
endfunction
" vim:ts=4:sw=4:et

View file

@ -0,0 +1,152 @@
" Copyright 2011 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" This file provides a utility function that performs auto-completion of
" package names, for use by other commands.
let s:goos = $GOOS
let s:goarch = $GOARCH
if len(s:goos) == 0
if exists('g:golang_goos')
let s:goos = g:golang_goos
elseif has('win32') || has('win64')
let s:goos = 'windows'
elseif has('macunix')
let s:goos = 'darwin'
else
let s:goos = '*'
endif
endif
if len(s:goarch) == 0
if exists('g:golang_goarch')
let s:goarch = g:golang_goarch
else
let s:goarch = '*'
endif
endif
function! go#package#Paths()
let dirs = []
if executable('go')
let goroot = substitute(system('go env GOROOT'), '\n', '', 'g')
if v:shell_error
echomsg '''go env GOROOT'' failed'
endif
else
let goroot = $GOROOT
endif
if len(goroot) != 0 && isdirectory(goroot)
let dirs += [goroot]
endif
let pathsep = ':'
if s:goos == 'windows'
let pathsep = ';'
endif
let workspaces = split($GOPATH, pathsep)
if workspaces != []
let dirs += workspaces
endif
return dirs
endfunction
function! go#package#ImportPath(arg)
let path = fnamemodify(resolve(a:arg), ':p')
let dirs = go#package#Paths()
for dir in dirs
if len(dir) && match(path, dir) == 0
let workspace = dir
endif
endfor
if !exists('workspace')
return -1
endif
return substitute(path, workspace . '/src/', '', '')
endfunction
function! go#package#FromPath(arg)
let path = fnamemodify(resolve(a:arg), ':p')
let dirs = go#package#Paths()
for dir in dirs
if len(dir) && match(path, dir) == 0
let workspace = dir
endif
endfor
if !exists('workspace')
return -1
endif
if isdirectory(path)
return substitute(path, workspace . 'src/', '', '')
else
return substitute(substitute(path, workspace . 'src/', '', ''),
\ '/' . fnamemodify(path, ':t'), '', '')
endif
endfunction
function! go#package#CompleteMembers(package, member)
silent! let content = system('godoc ' . a:package)
if v:shell_error || !len(content)
return []
endif
let lines = filter(split(content, "\n"),"v:val !~ '^\\s\\+$'")
try
let mx1 = '^\s\+\(\S+\)\s\+=\s\+.*'
let mx2 = '^\%(const\|var\|type\|func\) \([A-Z][^ (]\+\).*'
let candidates = map(filter(copy(lines), 'v:val =~ mx1'),
\ 'substitute(v:val, mx1, "\\1", "")')
\ + map(filter(copy(lines), 'v:val =~ mx2'),
\ 'substitute(v:val, mx2, "\\1", "")')
return filter(candidates, '!stridx(v:val, a:member)')
catch
return []
endtry
endfunction
function! go#package#Complete(ArgLead, CmdLine, CursorPos)
let words = split(a:CmdLine, '\s\+', 1)
if len(words) > 2 && words[0] != "GoImportAs"
" Complete package members
return go#package#CompleteMembers(words[1], words[2])
endif
let dirs = go#package#Paths()
if len(dirs) == 0
" should not happen
return []
endif
let ret = {}
for dir in dirs
" this may expand to multiple lines
let root = split(expand(dir . '/pkg/' . s:goos . '_' . s:goarch), "\n")
call add(root, expand(dir . '/src'))
for r in root
for i in split(globpath(r, a:ArgLead.'*'), "\n")
if isdirectory(i)
let i .= '/'
elseif i !~ '\.a$'
continue
endif
let i = substitute(substitute(i[len(r)+1:], '[\\]', '/', 'g'),
\ '\.a$', '', 'g')
let ret[i] = i
endfor
endfor
endfor
return sort(keys(ret))
endfunction
" vim:sw=4:et

View file

@ -0,0 +1,94 @@
if !exists("g:go_play_open_browser")
let g:go_play_open_browser = 1
endif
function! go#play#Share(count, line1, line2)
if !executable('curl')
echohl ErrorMsg | echomsg "vim-go: require 'curl' command" | echohl None
return
endif
let content = join(getline(a:line1, a:line2), "\n")
let share_file = tempname()
call writefile(split(content, "\n"), share_file, "b")
let command = "curl -s -X POST http://play.golang.org/share --data-binary '@".share_file."'"
let snippet_id = system(command)
" we can remove the temp file because it's now posted.
call delete(share_file)
if v:shell_error
echo 'A error has occured. Run this command to see what the problem is:'
echo command
return
endif
let url = "http://play.golang.org/p/".snippet_id
" copy to clipboard
if has('unix') && !has('xterm_clipboard') && !has('clipboard')
let @" = url
else
let @+ = url
endif
if g:go_play_open_browser != 0
call go#tool#OpenBrowser(url)
endif
echo "vim-go: snippet uploaded: ".url
endfunction
function! s:get_visual_content()
let save_regcont = @"
let save_regtype = getregtype('"')
silent! normal! gvy
let content = @"
call setreg('"', save_regcont, save_regtype)
return content
endfunction
" modified version of
" http://stackoverflow.com/questions/1533565/how-to-get-visually-selected-text-in-vimscript
" another function that returns the content of visual selection, it's not used
" but might be useful in the future
function! s:get_visual_selection()
let [lnum1, col1] = getpos("'<")[1:2]
let [lnum2, col2] = getpos("'>")[1:2]
" check if the the visual mode is used before
if lnum1 == 0 || lnum2 == 0 || col1 == 0 || col2 == 0
return
endif
let lines = getline(lnum1, lnum2)
let lines[-1] = lines[-1][: col2 - (&selection == 'inclusive' ? 1 : 2)]
let lines[0] = lines[0][col1 - 1:]
return join(lines, "\n")
endfunction
" following two functions are from: https://github.com/mattn/gist-vim
" thanks @mattn
function! s:get_browser_command()
let go_play_browser_command = get(g:, 'go_play_browser_command', '')
if go_play_browser_command == ''
if has('win32') || has('win64')
let go_play_browser_command = '!start rundll32 url.dll,FileProtocolHandler %URL%'
elseif has('mac') || has('macunix') || has('gui_macvim') || system('uname') =~? '^darwin'
let go_play_browser_command = 'open %URL%'
elseif executable('xdg-open')
let go_play_browser_command = 'xdg-open %URL%'
elseif executable('firefox')
let go_play_browser_command = 'firefox %URL% &'
else
let go_play_browser_command = ''
endif
endif
return go_play_browser_command
endfunction
" vim:ts=4:sw=4:et

View file

@ -0,0 +1,52 @@
if !exists("g:go_gorename_bin")
let g:go_gorename_bin = "gorename"
endif
function! go#rename#Rename(...)
let to = ""
if a:0 == 0
let ask = printf("vim-go: rename '%s' to: ", expand("<cword>"))
let to = input(ask)
redraw
else
let to = a:1
endif
"return with a warning if the bin doesn't exist
let bin_path = go#tool#BinPath(g:go_gorename_bin)
if empty(bin_path)
return
endif
let fname = expand('%:p:t')
let pos = s:getpos(line('.'), col('.'))
let cmd = printf('%s -offset %s:#%d -to %s', bin_path, shellescape(fname), pos, to)
let out = go#tool#ExecuteInDir(cmd)
" strip out newline on the end that gorename puts. If we don't remove, it
" will trigger the 'Hit ENTER to continue' prompt
let clean = split(out, '\n')
if v:shell_error
redraw | echon "vim-go: " | echohl Statement | echon clean[0] | echohl None
else
redraw | echon "vim-go: " | echohl Function | echon clean[0] | echohl None
endif
" refresh the buffer so we can see the new content
silent execute ":e"
endfunction
func! s:getpos(l, c)
if &encoding != 'utf-8'
let buf = a:l == 1 ? '' : (join(getline(1, a:l-1), "\n") . "\n")
let buf .= a:c == 1 ? '' : getline('.')[:a:c-2]
return len(iconv(buf, &encoding, 'utf-8'))
endif
return line2byte(a:l) + (a:c-2)
endfun
" vim:ts=4:sw=4:et
"

View file

@ -0,0 +1,181 @@
function! go#tool#Files()
if has ("win32")
let command = 'go list -f "{{range $f := .GoFiles}}{{$.Dir}}/{{$f}}{{printf \"\n\"}}{{end}}"'
else
" let command = "go list -f $'{{range $f := .GoFiles}}{{$.Dir}}/{{$f}}\n{{end}}'"
let command = "go list -f '{{range $f := .GoFiles}}{{$.Dir}}/{{$f}}{{printf \"\\n\"}}{{end}}'"
endif
let out = go#tool#ExecuteInDir(command)
return split(out, '\n')
endfunction
function! go#tool#Deps()
if has ("win32")
let command = 'go list -f "{{range $f := .Deps}}{{$f}}{{printf \"\n\"}}{{end}}"'
else
let command = "go list -f $'{{range $f := .Deps}}{{$f}}\n{{end}}'"
endif
let out = go#tool#ExecuteInDir(command)
return split(out, '\n')
endfunction
function! go#tool#Imports()
let imports = {}
if has ("win32")
let command = 'go list -f "{{range $f := .Imports}}{{$f}}{{printf \"\n\"}}{{end}}"'
else
let command = "go list -f $'{{range $f := .Imports}}{{$f}}\n{{end}}'"
endif
let out = go#tool#ExecuteInDir(command)
if v:shell_error
echo out
return imports
endif
for package_path in split(out, '\n')
let package_name = fnamemodify(package_path, ":t")
let imports[package_name] = package_path
endfor
return imports
endfunction
function! go#tool#ShowErrors(out)
let errors = []
for line in split(a:out, '\n')
let tokens = matchlist(line, '^\s*\(.\{-}\):\(\d\+\):\s*\(.*\)')
if !empty(tokens)
call add(errors, {"filename" : expand("%:p:h:") . "/" . tokens[1],
\"lnum": tokens[2],
\"text": tokens[3]})
elseif !empty(errors)
" Preserve indented lines.
" This comes up especially with multi-line test output.
if match(line, '^\s') >= 0
call add(errors, {"text": line})
endif
endif
endfor
if !empty(errors)
call setqflist(errors, 'r')
return
endif
if empty(errors)
" Couldn't detect error format, output errors
echo a:out
endif
endfunction
function! go#tool#ExecuteInDir(cmd) abort
let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd '
let dir = getcwd()
try
execute cd.'`=expand("%:p:h")`'
let out = system(a:cmd)
finally
execute cd.'`=dir`'
endtry
return out
endfunction
" Exists checks whether the given importpath exists or not. It returns 0 if
" the importpath exists under GOPATH.
function! go#tool#Exists(importpath)
let command = "go list ". a:importpath
let out = go#tool#ExecuteInDir(command)
if v:shell_error
return -1
endif
return 0
endfunction
" BinPath checks whether the given binary exists or not and returns the path
" of the binary. It returns an empty string doesn't exists.
function! go#tool#BinPath(binpath)
" remove whitespaces if user applied something like 'goimports '
let binpath = substitute(a:binpath, '^\s*\(.\{-}\)\s*$', '\1', '')
" if it's in PATH just return it
if executable(binpath)
return binpath
endif
" just get the basename
let basename = fnamemodify(binpath, ":t")
" check if we have an appropriate bin_path
let go_bin_path = GetBinPath()
if empty(go_bin_path)
echo "vim-go: could not find '" . basename . "'. Run :GoInstallBinaries to fix it."
return ""
endif
" append our GOBIN and GOPATH paths and be sure they can be found there...
" let us search in our GOBIN and GOPATH paths
let old_path = $PATH
let $PATH = $PATH . ":" .go_bin_path
if !executable(binpath)
echo "vim-go: could not find '" . basename . "'. Run :GoInstallBinaries to fix it."
return ""
endif
" restore back!
if go_bin_path
let $PATH = old_path
endif
return go_bin_path . '/' . basename
endfunction
" following two functions are from: https://github.com/mattn/gist-vim
" thanks @mattn
function! s:get_browser_command()
let go_play_browser_command = get(g:, 'go_play_browser_command', '')
if go_play_browser_command == ''
if has('win32') || has('win64')
let go_play_browser_command = '!start rundll32 url.dll,FileProtocolHandler %URL%'
elseif has('mac') || has('macunix') || has('gui_macvim') || system('uname') =~? '^darwin'
let go_play_browser_command = 'open %URL%'
elseif executable('xdg-open')
let go_play_browser_command = 'xdg-open %URL%'
elseif executable('firefox')
let go_play_browser_command = 'firefox %URL% &'
else
let go_play_browser_command = ''
endif
endif
return go_play_browser_command
endfunction
function! go#tool#OpenBrowser(url)
let cmd = s:get_browser_command()
if len(cmd) == 0
redraw
echohl WarningMsg
echo "It seems that you don't have general web browser. Open URL below."
echohl None
echo a:url
return
endif
if cmd =~ '^!'
let cmd = substitute(cmd, '%URL%', '\=shellescape(a:url)', 'g')
silent! exec cmd
elseif cmd =~ '^:[A-Z]'
let cmd = substitute(cmd, '%URL%', '\=a:url', 'g')
exec cmd
else
let cmd = substitute(cmd, '%URL%', '\=shellescape(a:url)', 'g')
call system(cmd)
endif
endfunction
" vim:ts=4:sw=4:et

View file

@ -0,0 +1,89 @@
let s:buf_nr = -1
"OpenWindow opens a new scratch window and put's the content into the window
function! go#ui#OpenWindow(content)
" reuse existing buffer window if it exists otherwise create a new one
if !bufexists(s:buf_nr)
execute 'botright new'
file `="[Implements]"`
let s:buf_nr = bufnr('%')
elseif bufwinnr(s:buf_nr) == -1
execute 'botright new'
execute s:buf_nr . 'buffer'
elseif bufwinnr(s:buf_nr) != bufwinnr('%')
execute bufwinnr(s:buf_nr) . 'wincmd w'
endif
" Keep minimum height to 10, if there is more just increase it that it
" occupies all results
let implements_height = 10
if len(a:content) < implements_height
exe 'resize ' . implements_height
else
exe 'resize ' . len(a:content)
endif
" some sane default values for a readonly buffer
setlocal filetype=vimgo
setlocal bufhidden=delete
setlocal buftype=nofile
setlocal noswapfile
setlocal nobuflisted
setlocal winfixheight
setlocal cursorline " make it easy to distinguish
" we need this to purge the buffer content
setlocal modifiable
"delete everything first from the buffer
%delete _
" add the content
call append(0, a:content)
" delete last line that comes from the append call
$delete _
" set it back to non modifiable
setlocal nomodifiable
endfunction
" CloseWindow closes the current window
function! go#ui#CloseWindow()
close
echo ""
endfunction
" OpenDefinition parses the current line and jumps to it by openening a new
" tab
function! go#ui#OpenDefinition()
let curline = getline('.')
" don't touch our first line and any blank line
if curline =~ "implements" || curline =~ "^$"
" supress information about calling this function
echo ""
return
endif
" format: 'interface file:lnum:coln'
let mx = '^\(^\S*\)\s*\(.\{-}\):\(\d\+\):\(\d\+\)'
" parse it now into the list
let tokens = matchlist(curline, mx)
" convert to: 'file:lnum:coln'
let expr = tokens[2] . ":" . tokens[3] . ":" . tokens[4]
" jump to it in a new tab, we use explicit lgetexpr so we can later change
" the behaviour via settings (like opening in vsplit instead of tab)
lgetexpr expr
tab split
ll 1
" center the word
norm! zz
endfunction

View file

@ -0,0 +1,135 @@
" json
" Last Change: 2012-03-08
" Maintainer: Yasuhiro Matsumoto <mattn.jp@gmail.com>
" License: This file is placed in the public domain.
" Reference:
"
let s:save_cpo = &cpo
set cpo&vim
function! webapi#json#null()
return 0
endfunction
function! webapi#json#true()
return 1
endfunction
function! webapi#json#false()
return 0
endfunction
function! s:nr2byte(nr)
if a:nr < 0x80
return nr2char(a:nr)
elseif a:nr < 0x800
return nr2char(a:nr/64+192).nr2char(a:nr%64+128)
else
return nr2char(a:nr/4096%16+224).nr2char(a:nr/64%64+128).nr2char(a:nr%64+128)
endif
endfunction
function! s:nr2enc_char(charcode)
if &encoding == 'utf-8'
return nr2char(a:charcode)
endif
let char = s:nr2byte(a:charcode)
if strlen(char) > 1
let char = strtrans(iconv(char, 'utf-8', &encoding))
endif
return char
endfunction
function! s:fixup(val, tmp)
if type(a:val) == 0
return a:val
elseif type(a:val) == 1
if a:val == a:tmp.'null'
return function('webapi#json#null')
elseif a:val == a:tmp.'true'
return function('webapi#json#true')
elseif a:val == a:tmp.'false'
return function('webapi#json#false')
endif
return a:val
elseif type(a:val) == 2
return a:val
elseif type(a:val) == 3
return map(a:val, 's:fixup(v:val, a:tmp)')
elseif type(a:val) == 4
return map(a:val, 's:fixup(v:val, a:tmp)')
else
return string(a:val)
endif
endfunction
function! webapi#json#decode(json)
let json = iconv(a:json, "utf-8", &encoding)
if get(g:, 'webapi#json#parse_strict', 1) == 1 && substitute(substitute(substitute(
\ json,
\ '\\\%(["\\/bfnrt]\|u[0-9a-fA-F]\{4}\)', '\@', 'g'),
\ '"[^\"\\\n\r]*\"\|true\|false\|null\|-\?\d\+'
\ . '\%(\.\d*\)\?\%([eE][+\-]\{-}\d\+\)\?', ']', 'g'),
\ '\%(^\|:\|,\)\%(\s*\[\)\+', '', 'g') !~ '^[\],:{} \t\n]*$'
throw json
endif
let json = substitute(json, '\n', '', 'g')
let json = substitute(json, '\\u34;', '\\"', 'g')
if v:version >= 703 && has('patch780')
let json = substitute(json, '\\u\(\x\x\x\x\)', '\=iconv(nr2char(str2nr(submatch(1), 16), 1), "utf-8", &encoding)', 'g')
else
let json = substitute(json, '\\u\(\x\x\x\x\)', '\=s:nr2enc_char("0x".submatch(1))', 'g')
endif
if get(g:, 'webapi#json#allow_nil', 0) != 0
let tmp = '__WEBAPI_JSON__'
while 1
if stridx(json, tmp) == -1
break
endif
let tmp .= '_'
endwhile
let [null,true,false] = [
\ tmp.'null',
\ tmp.'true',
\ tmp.'false']
sandbox let ret = eval(json)
call s:fixup(ret, tmp)
else
let [null,true,false] = [0,1,0]
sandbox let ret = eval(json)
endif
return ret
endfunction
function! webapi#json#encode(val)
if type(a:val) == 0
return a:val
elseif type(a:val) == 1
let json = '"' . escape(a:val, '\"') . '"'
let json = substitute(json, "\r", '\\r', 'g')
let json = substitute(json, "\n", '\\n', 'g')
let json = substitute(json, "\t", '\\t', 'g')
let json = substitute(json, '\([[:cntrl:]]\)', '\=printf("\x%02d", char2nr(submatch(1)))', 'g')
return iconv(json, &encoding, "utf-8")
elseif type(a:val) == 2
let s = string(a:val)
if s == "function('webapi#json#null')"
return 'null'
elseif s == "function('webapi#json#true')"
return 'true'
elseif s == "function('webapi#json#false')"
return 'false'
endif
elseif type(a:val) == 3
return '[' . join(map(copy(a:val), 'webapi#json#encode(v:val)'), ',') . ']'
elseif type(a:val) == 4
return '{' . join(map(keys(a:val), 'webapi#json#encode(v:val).":".webapi#json#encode(a:val[v:val])'), ',') . '}'
else
return string(a:val)
endif
endfunction
let &cpo = s:save_cpo
unlet s:save_cpo
" vim:set et:

View file

@ -0,0 +1,31 @@
" Copyright 2013 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" compiler/go.vim: Vim compiler file for Go.
if exists("current_compiler")
finish
endif
let current_compiler = "go"
if exists(":CompilerSet") != 2
command -nargs=* CompilerSet setlocal <args>
endif
let s:save_cpo = &cpo
set cpo-=C
CompilerSet makeprg=go\ build
CompilerSet errorformat=
\%-G#\ %.%#,
\%-G%.%#panic:\ %m,
\%A%f:%l:%c:\ %m,
\%A%f:%l:\ %m,
\%C%*\\s%m,
\%-G%.%#
let &cpo = s:save_cpo
unlet s:save_cpo
" vim:ts=4:sw=4:et

View file

@ -0,0 +1,571 @@
*vim-go.txt* Go development plugin
*vim-go*
===============================================================================
# #
# ## ## #### ## ## ###### ####### #
# ## ## ## ### ### ## ## ## ## #
# ## ## ## #### #### ## ## ## #
# ## ## ## ## ### ## ####### ## #### ## ## #
# ## ## ## ## ## ## ## ## ## #
# ## ## ## ## ## ## ## ## ## #
# ### #### ## ## ###### ####### #
# #
===============================================================================
CONTENTS *go-contents*
1. Intro........................................|go-intro|
2. Install......................................|go-install|
3. Commands.....................................|go-commands|
4. Settings.....................................|go-settings|
5. Mappings.....................................|go-mappings|
6. Troubleshooting..............................|go-troubleshooting|
7. Credits......................................|go-credits|
===============================================================================
INTRO *go-intro*
Go (golang) support for Vim. vim-go installs automatically all necessary
binaries for providing seamless Vim integration. It comes with pre-defined
sensible settings (like auto gofmt on save), has autocomplete, snippet
support, improved syntax highlighting, go toolchain commands, etc... It's
highly customizable and each individual feature can be disabled/enabled
easily.
* Improved Syntax highlighting, such as Functions, Operators, Methods..
* Auto completion support via `gocode`
* Better `gofmt` on save, keeps cursor position and doesn't break your undo
history
* Go to symbol/declaration with `godef`
* Automatically import packages via `goimports`
* Compile and `go build` your package, install it with `go install`
* `go run` quickly your current file/files
* Run `go test` and see any errors in quickfix window
* Lint your code with `golint`
* Run your code trough `go vet` to catch static errors.
* Advanced source analysis tool with `oracle`
* Precise type-safe renaming of identifiers with `gorename`
* List all source files and dependencies
* Checking with `errcheck` for unchecked errors.
* Integrated and improved snippets. Supports `ultisnips` or `neosnippet`
* Share your current code to play.golang.org
* Type information about the underlying identifier
* Tagbar support to show tags of the source code in a sidebar with `gotags`
===============================================================================
INSTALL *go-install*
If you use pathogen, just clone it into your bundle directory: >
$ cd ~/.vim/bundle
$ git clone https://github.com/fatih/vim-go.git
<
For Vundle add this line to your vimrc:
>
Plugin 'fatih/vim-go'
<
and execute `:PluginInstall` (or `:BundleInstall` for older versions of Vundle)
Please be sure all necessary binares are installed (such as `gocode`, `godef`,
`goimports`, etc..). You can easily install them with the included
|GoInstallBinaries|. Those binaries will be automatically downloaded and
installed to your `$GOBIN` environment (if not set it will use `$GOPATH/bin`).
It requires `git` and `hg` for fetching the individual Go packages.
* Autocompletion is enabled by default via `<C-x><C-o>`, to get real-time
completion (completion by type) install:
https://github.com/Valloric/YouCompleteMe or
https://github.com/Shougo/neocomplete.vim
* To get displayed source code tag informations on a sidebar install
https://github.com/majutsushi/tagbar.
* For snippet feature install:
https://github.com/SirVer/ultisnips or
https://github.com/Shougo/neosnippet.vim.
===============================================================================
COMMANDS *go-commands*
*:GoImport*
:GoImport [path]
Import ensures that the provided package {path} is imported in the current
Go buffer, using proper style and ordering. If {path} is already being
imported, an error will be displayed and the buffer will be untouched.
*:GoImportAs*
:GoImportAs [localname] [path]
Same as Import, but uses a custom local name for the package.
*:GoDrop*
:GoDrop [path]
Remove the import line for the provided package {path}, if present in the
current Go buffer. If {path} is not being imported, an error will be
displayed and the buffer will be untouched.
*:GoLint*
:GoLint
Run golint for the current Go file.
*:GoDoc*
:GoDoc [word]
Open the relevant GoDoc in split window for either the word[s] passed to
the command or by default, the word under the cursor.
*:GoDocBrowser*
:GoDocBrowser [word]
Open the relevant GoDoc in browser for either the word[s] passed to the
command or by default, the word under the cursor.
*:GoFmt*
:GoFmt
Filter the current Go buffer through gofmt. It tries to preserve cursor
position and avoids replacing the buffer with stderr output.
*:GoImports*
:GoImports
Filter the current Go buffer through goimports (needs to be installed).
`goimports` automatically discards/add import path based on the code. Like
|GoFmt|, It tries to preserve cursor position and avoids replacing the
buffer with stderr output.
*:GoPlay*
:[range]GoPlay
Share snippet to play.golang.org. If no [range] is given it shares
the whole file, otherwise the selected lines are shared. Snippet URL
is copied to system clipboard if Vim is compiled with 'clipboard' or
'xterm-clipboard' otherwise it's get yanked into the `""` register.
*:GoVet*
:GoVet
Run `go vet` for the directory under your current file. Vet examines Go
source code and reports suspicious constructs, such as Printf calls whose
arguments do not align with the format string. Vet uses heuristics that do not
guarantee all reports are genuine problems, but it can find errors not caught
by the compilers.
*:GoDef*
:GoDef [identifier]
Goto declaration/definition for the given [identifier]. If no argument is
given, it will jump to the declaration under the cursor. By default the
mapping `gd` is enabled to invoke GoDef for the identifier under the cursor.
See |g:go_def_mapping_enabled| to disable it.
*:GoRun*
:GoRun[!] [expand]
Build and run your current main package. By default all main files for the
current file is used. If an argument is passed, 'expand' is used as file
selector. For example use `:GoRun %` to select the current file only.
If [!] is not given the first error is jumped to.
*:GoBuild*
:GoBuild[!]
Build your package with `go build`. It automatically builds only the files
that depends on the current file. GoBuild doesn't produce a result file.
Use 'make' to create a result file.
If [!] is not given the first error is jumped to.
*:GoInfo*
:GoInfo
Show type information about the identifer under the cursor. For example
putting it above a function call is going to show the full function
signature. It uses gocode to get the type informations.
*:GoInstall*
:GoInstall
Install your package with `go install`.
*:GoTest*
:GoTest [expand]
Test 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 ./...`).
*:GoCoverage*
:GoCoverage
Create a coverage profile and open a browser to display the annotated
source code of the current package.
*:GoErrCheck*
:GoErrCheck
Check for unchecked errors in you current package. Errors are populated in
quickfix window.
*:GoFiles*
:GoFiles
Show source files that depends for the current package
*:GoDeps*
:GoDeps
Show dependencies for the current package
*:GoInstallBinaries*
:GoInstallBinaries
Download and Install all necessary Go tool binaries such as `godef`,
`goimports`, `gocode`, etc.. under `g:go_bin_path`
*:GoUpdateBinaries*
:GoUpdateBinaries
Download and Update previously installed Go tool binaries such as `godef`,
`goimports`, `gocode`, etc.. under `g:go_bin_path`. This can be used to
update the necessary Go binaries.
*:GoImplements*
:GoImplements
Show 'implements' relation for a selected package. A list of interfaces
for the type under the cursor (or selected package) is shown in a custom
window. Hit `<enter>` to jump in a new tab or close it via `<c-c>`.
*:GoRename*
:GoRename [to]
Rename the identifier under the cursor to the desired new name. If no
argument is given a prompt will ask for the desired identifier.
===============================================================================
MAPPINGS *go-mappings*
vim-go has several <Plug> keys which can be used to create custom mappings
For example, to create a mapping that `go run` the current file create a
mapping for the `(go-run)`: >
au FileType go nmap <leader>r <Plug>(go-run)
As always one is free to create more advanced mappings or functions based
with |go-commands|. Available <Plug> keys are:
*(go-run)*
Calls `go run` for the current file
*(go-build)*
Calls `go build` for the current package
*(go-info)*
Shows type information for the word under the cursor
*(go-install)*
Calls `go install` for the current package
*(go-test)*
Calls `go test` for the current package
*(go-coverage)*
Calls `go test -coverprofile-temp.out` for the current package
*(go-vet)*
Calls `go vet` for the current package
*(go-files)*
Show source files that depends for the current package
*(go-deps)*
Show dependencies for the current package
*(go-doc)*
Show the relevant GoDoc for the word under the cursor in a split window
leftabove (default mode).
*(go-doc-split)*
Show the relevant GoDoc for the word under the cursor in a split window.
*(go-doc-vertical)*
Show the relevant GoDoc for the word under the cursor in a vertical split
window.
*(go-doc-tab)*
Show the relevant GoDoc for the word under the cursor in a tab window.
*(go-doc-browser)*
Show the relevant GoDoc for the word under in browser
*(go-def)*
Goto declaration/definition. Results are shown in the current buffer.
*(go-def-split)*
Goto declaration/definition. Results are shown in a split window.
*(go-def-vertical)*
Goto declaration/definition. Results are shown in a vertical split window.
*(go-def-tab)*
Goto declaration/definition. Results are shown in a tab window.
*(go-implements)*
Show the interfaces that the type under the cursor implements.
*(go-rename)*
Rename the identifier under the cursor to the desired new name
===============================================================================
SETTINGS *go-settings*
*'g:go_play_browser_command'*
Use this option to change the browser that is used to open the snippet url
posted to play.golang.org with |:GoPlay| or for the relevant documentation
used with |:GoDocBrowser|. By default it tries to find it automatically for
the current OS. >
let g:play_browser_command = ''
<
*'g:go_play_open_browser'*
Use this option to open browser after posting the snippet to play.golang.org
with |:GoPlay|. By default it's enabled. >
let g:go_play_open_browser = 1
<
*'g:go_auto_type_info'*
Use this option to show the type info (|:GoInfo|) for the word under the cursor
automatically. Whenever the cursor changes the type info will be updated.
By default it's disabled >
let g:go_auto_type_info = 0
<
*'g:go_fmt_autosave'*
Use this option to auto |:GoFmt| on save. By default it's enabled >
let g:go_fmt_autosave = 1
<
*'g:go_fmt_command'*
Use this option to define which tool is used to gofmt. By default `gofmt` is
used >
let g:go_fmt_command = "gofmt"
<
*'g:go_fmt_options'*
Use this option to add additional options to the |g:go_fmt_command|. Default
is empty. >
let g:go_fmt_options = ''
<
*'g:go_fmt_fail_silently'*
Use this option to disable showing a quickfix window when |g:go_fmt_command|
fails. By default it's disabled. >
let g:go_fmt_fail_silently = 0
<
*'g:go_doc_keywordprg_enabled'*
Use this option to change the enable GoDoc to run on words under the cursor
with the default K , keywordprg shortcut. This shortcut is by default set to
use the program man. However in go using godoc is more idiomatic. Default is
enabled. >
let g:go_doc_keywordprg_enabled = 1
<
*'g:go_def_mapping_enabled'*
Use this option to enabled/ disable the default mapping (`gd`) for GoDef
enabled. Disabling it allows you to map something else to the mapping `gd`.
Default is enabled. >
let g:go_def_mapping_enabled = 1
<
*'g:go_doc_command'*
Use this option to define which tool is used to godoc. By default `godoc` is
used >
let g:go_doc_command = "godoc"
<
*'g:go_doc_options'*
Use this option to add additional options to the |g:go_doc_command|. Default
is empty. >
let g:go_doc_options = ''
< *'g:go_bin_path'*
Use this option to change default path for vim-go tools when using
|GoInstallBinaries| and |GoUpdateBinaries|. If not set `$GOBIN` or
`$GOPATH/bin` is used. >
let g:go_bin_path = ""
<
*'g:go_snippet_engine'*
Use this option to define the default snippet engine. By default "ultisnips"
is used. Use "neosnippet" for neosnippet.vim: >
let g:go_snippet_engine = "ultisnips"
<
*'g:go_highlight_array_whitespace_error'*
Highlights white space after "[]". >
let g:go_highlight_array_whitespace_error = 1
<
*'g:go_highlight_chan_whitespace_error'*
Highlights white space around the communications operator that don't follow
the standard style. >
let g:go_highlight_chan_whitespace_error = 1
<
*'g:go_highlight_extra_types'*
Highlights commonly used library types (io.Reader, etc.). >
let g:go_highlight_extra_types = 1
<
*'g:go_highlight_space_tab_error'*
Highlights instances of tabs following spaces. >
let g:go_highlight_space_tab_error = 1
<
*'g:go_highlight_trailing_whitespace_error'*
Highlights trailing white space. >
let g:go_highlight_trailing_whitespace_error = 1
<
*'g:go_highlight_operators'*
Highlights operators such as `:=` , `==`, `-=`, etc ...By default it's
disabled. >
let g:go_highlight_operators = 0
<
*'g:go_highlight_functions'*
Highlights function names. By default it's disabled. >
let g:go_highlight_functions = 0
<
*'g:go_highlight_methods'*
Highlights method names. By default it's disabled. >
let g:go_highlight_methods = 0
<
*'g:go_highlight_structs'*
Highlights struct names. By default it's disabled. >
let g:go_highlight_structs = 0
<
===============================================================================
TROUBLESHOOTING *go-troubleshooting*
I'm using Fish shell but have some problems using Vim-go~
First environment variables in Fish are applied differently, it should be like:
>
set -x GOPATH /your/own/gopath
<
Second, Vim needs a POSIX compatible shell (more info here:
https://github.com/dag/vim-fish#teach-a-vim-to-fish). If you use Fish to open
vim, it will make certainx shell based commands fail (means vim-go will fail
too). To overcome this problem change the default shell by adding the
following into your .vimrc (on the top of the file):
>
if $SHELL =~ 'fish'
set shell='/bin/sh'
endif
<
or
>
set shell='/bin/sh'
>
I'm seeing weirds errors during the startup~
If you see errors like this:
>
Error installing code.google.com/p/go.tools/cmd/goimports:
Error installing code.google.com/p/rog-go/exp/cmd/godef:
<
that means your local Go setup is broken or the remote website is down. For
example sometimes code.google.com times out. To test, just execute a simple go
get:
>
go get code.google.com/p/go.tools/cmd/goimports
<
You'll see a more detailed error. If this works, vim-go will work too.
===============================================================================
CREDITS *go-credits*
* Go Authors for offical vim plugins
* Gocode, Godef, Golint, Oracle, Goimports, Errcheck projects and authors of
those projects.
* Other vim-plugins, thanks for inspiration (vim-golang, go.vim, vim-gocode,
vim-godef)
* vim-go contributors: https://github.com/fatih/vim-go/graphs/contributors
vim:ft=help:et:ts=2:sw=2:sts=2:norl

View file

@ -0,0 +1,23 @@
" We take care to preserve the user's fileencodings and fileformats,
" because those settings are global (not buffer local), yet we want
" to override them for loading Go files, which are defined to be UTF-8.
let s:current_fileformats = ''
let s:current_fileencodings = ''
" define fileencodings to open as utf-8 encoding even if it's ascii.
function! s:gofiletype_pre()
let s:current_fileformats = &g:fileformats
let s:current_fileencodings = &g:fileencodings
set fileencodings=utf-8 fileformats=unix
setlocal filetype=go
endfunction
" restore fileencodings as others
function! s:gofiletype_post()
let &g:fileformats = s:current_fileformats
let &g:fileencodings = s:current_fileencodings
endfunction
au BufNewFile *.go setlocal filetype=go fileencoding=utf-8 fileformat=unix
au BufRead *.go call s:gofiletype_pre()
au BufReadPost *.go call s:gofiletype_post()

View file

@ -0,0 +1,63 @@
" Copyright 2013 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" go.vim: Vim filetype plugin for Go.
if exists("b:did_ftplugin")
finish
endif
let b:did_ftplugin = 1
if !exists("g:go_auto_type_info")
let g:go_auto_type_info = 0
endif
setlocal formatoptions-=t
setlocal comments=s1:/*,mb:*,ex:*/,://
setlocal commentstring=//\ %s
setlocal noexpandtab
compiler go
if !exists("g:go_doc_keywordprg_enabled")
let g:go_doc_keywordprg_enabled = 1
endif
if g:go_doc_keywordprg_enabled
" keywordprg doesn't allow to use vim commands, override it
nnoremap <buffer> <silent> K :GoDoc<cr>
endif
if !exists("g:go_def_mapping_enabled")
let g:go_def_mapping_enabled = 1
endif
if g:go_def_mapping_enabled
nnoremap <buffer> <silent> gd :GoDef<cr>
endif
let b:undo_ftplugin = "setl fo< com< cms<"
" Set gocode completion
setlocal omnifunc=go#complete#Complete
" GoInfo automatic update
if g:go_auto_type_info != 0
setlocal updatetime=300
au! CursorHold *.go nested call go#complete#Info()
endif
" autoload settings
if !exists('g:go_fmt_autosave')
let g:go_fmt_autosave = 1
endif
if g:go_fmt_autosave
autocmd BufWritePre <buffer> call go#fmt#Format(-1)
endif
" vim:ts=4:sw=4:et

View file

@ -0,0 +1,92 @@
if exists("g:go_loaded_commands")
finish
endif
let g:go_loaded_commands = 1
" Some handy plug mappings
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-install) :<C-u>call go#cmd#Install()<CR>
nnoremap <silent> <Plug>(go-test) :<C-u>call go#cmd#Test('')<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-files) :<C-u>call go#tool#Files()<CR>
nnoremap <silent> <Plug>(go-deps) :<C-u>call go#tool#Deps()<CR>
nnoremap <silent> <Plug>(go-info) :<C-u>call go#complete#Info()<CR>
nnoremap <silent> <Plug>(go-import) :<C-u>call go#import#SwitchImport(1, '', expand('<cword>'))<CR>
nnoremap <silent> <Plug>(go-implements) :<C-u>call go#oracle#Implements(-1)<CR>
nnoremap <silent> <Plug>(go-rename) :<C-u>call go#rename#Rename()<CR>
nnoremap <silent> <Plug>(go-def) :<C-u>call go#def#Jump()<CR>
nnoremap <silent> <Plug>(go-def-vertical) :<C-u>call go#def#JumpMode("vsplit")<CR>
nnoremap <silent> <Plug>(go-def-split) :<C-u>call go#def#JumpMode("split")<CR>
nnoremap <silent> <Plug>(go-def-tab) :<C-u>call go#def#JumpMode("tab")<CR>
nnoremap <silent> <Plug>(go-doc) :<C-u>call go#doc#Open("leftabove new")<CR>
nnoremap <silent> <Plug>(go-doc-tab) :<C-u>call go#doc#Open("tabnew")<CR>
nnoremap <silent> <Plug>(go-doc-vertical) :<C-u>call go#doc#Open("vnew")<CR>
nnoremap <silent> <Plug>(go-doc-split) :<C-u>call go#doc#Open("split")<CR>
nnoremap <silent> <Plug>(go-doc-browser) :<C-u>call go#doc#OpenBrowser()<CR>
" gorename
command! -nargs=? GoRename call go#rename#Rename(<f-args>)
" oracle
command! -range=% GoImplements call go#oracle#Implements(<count>)
" tool
command! -nargs=0 GoFiles echo go#tool#Files()
command! -nargs=0 GoDeps echo go#tool#Deps()
command! -nargs=* GoInfo call go#complete#Info()
" cmd
command! -nargs=* -bang GoRun call go#cmd#Run(<bang>0,<f-args>)
command! -nargs=? -bang GoBuild call go#cmd#Build(<bang>0)
command! -nargs=* GoInstall call go#cmd#Install(<f-args>)
command! -nargs=* GoTest call go#cmd#Test(<f-args>)
command! -nargs=* GoCoverage call go#cmd#Coverage(<f-args>)
command! -nargs=0 GoVet call go#cmd#Vet()
" -- play
command! -nargs=0 -range=% GoPlay call go#play#Share(<count>, <line1>, <line2>)
" -- def
command! -nargs=* -range GoDef :call go#def#Jump(<f-args>)
" -- doc
command! -nargs=* -range -complete=customlist,go#package#Complete GoDoc call go#doc#Open('leftabove new', <f-args>)
command! -nargs=* -range -complete=customlist,go#package#Complete GoDocBrowser call go#doc#OpenBrowser(<f-args>)
" -- fmt
command! -nargs=0 GoFmt call go#fmt#Format(-1)
command! -nargs=0 GoImports call go#fmt#Format(1)
" -- import
command! -nargs=? -complete=customlist,go#package#Complete GoDrop call go#import#SwitchImport(0, '', <f-args>)
command! -nargs=1 -complete=customlist,go#package#Complete GoImport call go#import#SwitchImport(1, '', <f-args>)
command! -nargs=* -complete=customlist,go#package#Complete GoImportAs call go#import#SwitchImport(1, <f-args>)
" -- lint
command! GoLint call go#lint#Run()
" -- errcheck
command! GoErrCheck call go#errcheck#Run()
" Disable all commands until they are fully integrated.
"
" command! -range=% GoOracleDescribe call go#oracle#Describe(<count>)
" command! -range=% GoOracleCallees call go#oracle#Callees(<count>)
" command! -range=% GoOracleCallers call go#oracle#Callers(<count>)
" command! -range=% GoOracleCallgraph call go#oracle#Callgraph(<count>)
" command! -range=% GoOracleCallstack call go#oracle#Callstack(<count>)
" command! -range=% GoOracleFreevars call go#oracle#Freevars(<count>)
" command! -range=% GoOraclePeers call go#oracle#Peers(<count>)
" command! -range=% GoOracleReferrers call go#oracle#Referrers(<count>)
" vim:ts=4:sw=4:et
"

View file

@ -0,0 +1,36 @@
if exists("g:go_loaded_gosnippets")
finish
endif
let g:go_loaded_gosnippets = 1
" by default UltiSnips
if !exists("g:go_snippet_engine")
let g:go_snippet_engine = "ultisnips"
endif
function! s:GoUltiSnips()
if globpath(&rtp, 'plugin/UltiSnips.vim') == ""
return
endif
if !exists("g:UltiSnipsSnippetDirectories")
let g:UltiSnipsSnippetDirectories = ["gosnippets/UltiSnips"]
else
let g:UltiSnipsSnippetDirectories += ["gosnippets/UltiSnips"]
endif
endfunction
function! s:GoNeosnippet()
if globpath(&rtp, 'plugin/neosnippet.vim') == ""
return
endif
let g:neosnippet#enable_snipmate_compatibility = 1
exec 'NeoSnippetSource' globpath(&rtp, 'gosnippets/snippets/go.snip')
endfunction
if g:go_snippet_engine == "ultisnips"
call s:GoUltiSnips()
elseif g:go_snippet_engine == "neosnippet"
call s:GoNeosnippet()
endif

View file

@ -0,0 +1,55 @@
" Check if tagbar is installed under plugins or is directly under rtp
" this covers pathgen + Vundle/Bundle
"
" Also make sure the ctags command exists
"
if !executable('ctags')
finish
elseif globpath(&rtp, 'plugin/tagbar.vim') == ""
finish
endif
if !exists("g:go_gotags_bin")
let g:go_gotags_bin = "gotags"
endif
function! s:SetTagbar()
let bin_path = go#tool#BinPath(g:go_gotags_bin)
if empty(bin_path)
return
endif
if !exists("g:tagbar_type_go")
let g:tagbar_type_go = {
\ 'ctagstype' : 'go',
\ 'kinds' : [
\ 'p:package',
\ 'i:imports:1',
\ 'c:constants',
\ 'v:variables',
\ 't:types',
\ 'n:interfaces',
\ 'w:fields',
\ 'e:embedded',
\ 'm:methods',
\ 'r:constructor',
\ 'f:functions'
\ ],
\ 'sro' : '.',
\ 'kind2scope' : {
\ 't' : 'ctype',
\ 'n' : 'ntype'
\ },
\ 'scope2kind' : {
\ 'ctype' : 't',
\ 'ntype' : 'n'
\ },
\ 'ctagsbin' : expand(bin_path),
\ 'ctagsargs' : '-sort -silent'
\ }
endif
endfunction
call s:SetTagbar()

View file

@ -0,0 +1,215 @@
# Snippets for Go
priority -10
# when to abbriviate and when not?
# b doesn't work here, because it ignores whitespace
# optional local name?
snippet import "Import declaration" b
import (
"${1:package}"
)
endsnippet
snippet package "Package declaration" b
// Package $1 provides ${2:...}
package ${1:main}
${0:${VISUAL}}
endsnippet
# Mostly converted from: https://github.com/AlanQuatermain/go-tmbundle
snippet /^cons/ "Constants declaration" r
const (
${1:constant}${2/(.+)/ /}${2:type} = ${0:value}
)
endsnippet
snippet /^con/ "Constant declaration" r
const ${1:name}${2/(.+)/ /}${2:type} = ${0:value}
endsnippet
snippet iota "Iota constant generator" b
const (
${1:constant}${2/(.+)/ /}${2:type} = iota
)
endsnippet
snippet struct "Struct declaration" b
type ${1:Struct} struct {
${0:${VISUAL}}
}
endsnippet
snippet interface "Interface declaration" b
type ${1:Interface} interface {
${0:${VISUAL}}
}
endsnippet
# statements
snippet for "For loop" b
for ${1:condition} {
${0:${VISUAL}}
}
endsnippet
snippet fori "Integer for loop" b
for ${1:i} := 0; $1 < ${2:N}; $1++ {
${0:${VISUAL}}
}
endsnippet
snippet forr "For range loop" b
for ${2:name} := range ${1:collection} {
${0:${VISUAL}}
}
endsnippet
snippet if "If statement" b
if ${1:condition}${1/(.+)/ /}{
${0:${VISUAL}}
}
endsnippet
snippet switch "Switch statement" b
switch ${1:expression}${1/(.+)/ /}{
case${0}
}
endsnippet
snippet select "Select statement" b
select {
case${0}
}
endsnippet
snippet case "Case clause" b
case ${1:condition}:
${0:${VISUAL}}
endsnippet
snippet default "Default clause" b
default:
${0:${VISUAL}}
endsnippet
# functions
snippet /^main/ "Main function" r
func main() {
${0:${VISUAL}}
}
endsnippet
snippet /^meth/ "Method" r
func (${1:receiver} ${2:type}) ${3:name}(${4:params})${5/(.+)/ /}${5:type} {
${0:${VISUAL}}
}
endsnippet
snippet func "Function" b
func ${1:name}(${2:params})${3/(.+)/ /}${3:type} {
${0:${VISUAL}}
}
endsnippet
snippet anon "Anonymous Function" !b
${1:fn} := func() {
${2}
}
endsnippet
# types and variables
snippet map "Map type" b
map[${1:keytype}]${2:valtype}
endsnippet
snippet : "Short variable declaration :=" !b
${1:name} := ${0:value}
endsnippet
snippet var "Variable declaration" b
var ${1:name}${2/(.+)/ /}${2:type}${3: = ${0:value}}
endsnippet
snippet vars "Variables declaration" b
var (
${1:name}${2/(.+)/ /}${2:type}${3: = ${0:value} }
)
endsnippet
snippet json "JSON field"
\`json:"${1:displayName}"\`
endsnippet
snippet er "Error clause " !b
if err != nil {
${0}
}
endsnippet
snippet errn "Error return " !b
if err != nil {
return err
}
${0}
endsnippet
snippet errn, "Error return with two return values" !b
if err != nil {
return ${1:nil}, err
}
${0}
endsnippet
snippet errn,, "Error return with three return values" !b
if err != nil {
return ${1:nil}, ${2:nil}, err
}
${0}
endsnippet
snippet ok "OK statement" !b
if !ok {
${0:${VISUAL}}
}
endsnippet
snippet gof "Anonymous Goroutine" !b
go func() {
${1}
}()
endsnippet
snippet def "Anonymous Defer" !b
defer func() {
${1}
}()
endsnippet
snippet ff "Fmt Printf debug" !b
fmt.Printf("${1} %+v\n", $1)
endsnippet
snippet fn "Fmt Println debug" !b
fmt.Println("${1}")
endsnippet
snippet lf "Log Printf debug" !b
log.Printf("${1} %+v\n", $1)
endsnippet
snippet ln "Log Println debug" !b
log.Println("${1}")
endsnippet
snippet make "make allocation" !b
make(${1:Type}, ${2:size})${0}
endsnippet
snippet test "test function" b
func Test${1:Function}(t *testing.T) {
${2}
}
endsnippet
# vim:ft=snippets:

View file

@ -0,0 +1,243 @@
# shorthand variable declaration
snippet v
${1} := ${2}
# variable initialization
snippet vr
var ${1:t} ${0:string}
# variable declaration
snippet var
var ${1} ${2} = ${3}
# variables declaration
snippet vars
var (
${1} ${2} = ${3}
)
# append
snippet ap
append(${1:slice}, ${0:value})
# bool
snippet bl
bool
# byte
snippet bt
byte
# break
snippet br
break
# channel
snippet ch
chan ${0:int}
# case
snippet cs
case ${1:value}:
${0}
# const
snippet c
const ${1:NAME} = ${0:0}
# constants with iota
snippet co
const (
${1:NAME1} = iota
${0:NAME2}
)
# continue
snippet cn
continue
# defer
snippet df
defer ${0:func}()
# defer recover
snippet dfr
defer func() {
if err := recover(); err != nil {
${0}
}
}()
# gpl
snippet gpl
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
* Copyright (C) ${1:Author}, `strftime("%Y")`
*/
${0}
# int
snippet i
int
# import
snippet im
import (
"${1:package}"
)
# interface
snippet in
interface{}
# full interface snippet
snippet inf
interface ${1:name} {
${2:/* methods */}
}
# if condition
snippet if
if ${1:/* condition */} {
${2}
}
# else snippet
snippet el
else {
${1}
}
# error snippet
snippet ir
if err != nil {
return err
}
${0}
# false
snippet f
false
# fallthrough
snippet ft
fallthrough
# float
snippet fl
float32
# float32
snippet f3
float32
# float64
snippet f6
float64
# if else
snippet ie
if ${1:/* condition */} {
${2}
} else {
${3}
}
${0}
# for loop
snippet fo
for ${2:i} := 0; $2 < ${1:count}; $2${3:++} {
${4}
}
${0}
# for range loop
snippet fr
for ${1:k}, ${2:v} := range ${3} {
${4}
}
${0}
# function simple
snippet fun
func ${1:funcName}(${2}) ${3:error} {
${4}
}
${0}
# function on receiver
snippet fum
func (self ${1:type}) ${2:funcName}(${3}) ${4:error} {
${5}
}
${0}
# Fmt Printf debug
snippet ff
fmt.Printf("${1} %+v\n", ${0})
# Fmt Println debug
snippet fn
fmt.Println("${1}")
# log printf
snippet lf
log.Printf("%${1:s}", ${2:var})
# log printf
snippet lp
log.Println("${1}")
# make
snippet mk
make(${1:[]string}, ${0:0})
# map
snippet mp
map[${1:string}]${0:int}
# main()
snippet main
func main() {
${1}
}
${0}
# new
snippet nw
new(${0:type})
# panic
snippet pn
panic("${0:msg}")
# print
snippet pr
fmt.Printf("%${1:s}\n", ${2:var})
# range
snippet rn
range ${0}
# return
snippet rt
return ${0}
# result
snippet rs
result
# select
snippet sl
select {
case ${1:v1} := <-${2:chan1}
${3}
case ${4:v2} := <-${5:chan2}
${6}
default:
${0}
}
# string
snippet sr
string
# struct
snippet st
struct ${1:name} {
${2:/* data */}
}
${0}
# switch
snippet sw
switch ${1:var} {
case ${2:value1}:
${3}
case ${4:value2}:
${5}
default:
${0}
}
snippet sp
fmt.Sprintf("%${1:s}", ${2:var})
# true
snippet t
true
# goroutine named function
snippet g
go ${1:funcName}(${0})
# goroutine anonymous function
snippet ga
go func(${1} ${2:type}) {
${3:/* code */}
}(${0})
# test function
snippet test
func Test${1:Function}(t *testing.T) {
${2}
}

View file

@ -0,0 +1,65 @@
" Copyright 2011 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" indent/go.vim: Vim indent file for Go.
"
" TODO:
" - function invocations split across lines
" - general line splits (line ends in an operator)
if exists("b:did_indent")
finish
endif
let b:did_indent = 1
" C indentation is too far off useful, mainly due to Go's := operator.
" Let's just define our own.
setlocal nolisp
setlocal autoindent
setlocal indentexpr=GoIndent(v:lnum)
setlocal indentkeys+=<:>,0=},0=)
if exists("*GoIndent")
finish
endif
function! GoIndent(lnum)
let prevlnum = prevnonblank(a:lnum-1)
if prevlnum == 0
" top of file
return 0
endif
" grab the previous and current line, stripping comments.
let prevl = substitute(getline(prevlnum), '//.*$', '', '')
let thisl = substitute(getline(a:lnum), '//.*$', '', '')
let previ = indent(prevlnum)
let ind = previ
if prevl =~ '[({]\s*$'
" previous line opened a block
let ind += &sw
endif
if prevl =~# '^\s*\(case .*\|default\):$'
" previous line is part of a switch statement
let ind += &sw
endif
" TODO: handle if the previous line is a label.
if thisl =~ '^\s*[)}]'
" this line closed a block
let ind -= &sw
endif
" Colons are tricky.
" We want to outdent if it's part of a switch ("case foo:" or "default:").
" We ignore trying to deal with jump labels because (a) they're rare, and
" (b) they're hard to disambiguate from a composite literal key.
if thisl =~# '^\s*\(case .*\|default\):$'
let ind -= &sw
endif
return ind
endfunction

View file

@ -0,0 +1,134 @@
" install necessary Go tools
if exists("g:go_loaded_install")
finish
endif
let g:go_loaded_install = 1
" these packages are used by vim-go and can be automatically installed if
" needed by the user with GoInstallBinaries
let s:packages = [
\ "github.com/nsf/gocode",
\ "code.google.com/p/go.tools/cmd/goimports",
\ "code.google.com/p/rog-go/exp/cmd/godef",
\ "code.google.com/p/go.tools/cmd/oracle",
\ "code.google.com/p/go.tools/cmd/gorename",
\ "github.com/golang/lint/golint",
\ "github.com/kisielk/errcheck",
\ "github.com/jstemmer/gotags",
\ ]
" Commands
command! GoErrCheck call go#errcheck#Run()
command! GoInstallBinaries call s:GoInstallBinaries(-1)
command! GoUpdateBinaries call s:GoInstallBinaries(1)
" GetBinPath returns the binary path of installed go tools
function! GetBinPath()
let bin_path = ""
" check if our global custom path is set, if not check if $GOBIN is set so
" we can use it, otherwise use $GOPATH + '/bin'
if exists("g:go_bin_path")
let bin_path = g:go_bin_path
elseif $GOBIN != ""
let bin_path = $GOBIN
elseif $GOPATH != ""
" take care of multi element GOPATH's
let go_paths = split($GOPATH, ":")
if len(go_paths) == 1
" one single PATH
let bin_path = $GOPATH . '/bin/'
else
" multiple paths, use the first one
let bin_path = go_paths[0]. '/bin/'
endif
else
" could not find anything
return ""
endif
" add trailing slash if there is no one
if bin_path[-1:-1] != '/' | let bin_path .= '/' | endif
return bin_path
endfunction
" GoInstallBinaries downloads and install all necessary binaries stated in the
" packages variable. It uses by default $GOBIN or $GOPATH/bin as the binary
" target install directory. GoInstallBinaries doesn't install binaries if they
" exist, to update current binaries pass 1 to the argument.
function! s:GoInstallBinaries(updateBinaries)
if $GOPATH == ""
echohl Error
echomsg "vim.go: $GOPATH is not set"
echohl None
return
endif
let err = s:CheckBinaries()
if err != 0
return
endif
let go_bin_path = GetBinPath()
" change $GOBIN so go get can automatically install to it
let $GOBIN = go_bin_path
" old_path is used to restore users own path
let old_path = $PATH
" vim's executable path is looking in PATH so add our go_bin path to it
let $PATH = $PATH . ":" .go_bin_path
for pkg in s:packages
let basename = fnamemodify(pkg, ":t")
let binname = "go_" . basename . "_bin"
let bin = basename
if exists("g:{binname}")
let bin = g:{binname}
endif
if !executable(bin) || a:updateBinaries == 1
if a:updateBinaries == 1
echo "vim-go: Updating ". basename .". Reinstalling ". pkg . " to folder " . go_bin_path
else
echo "vim-go: ". basename ." not found. Installing ". pkg . " to folder " . go_bin_path
endif
let out = system("go get -u -v ".shellescape(pkg))
if v:shell_error
echo "Error installing ". pkg . ": " . out
endif
endif
endfor
" restore back!
let $PATH = old_path
endfunction
" CheckBinaries checks if the necessary binaries to install the Go tool
" commands are available.
function! s:CheckBinaries()
if !executable('go')
echohl Error | echomsg "vim-go: go executable not found." | echohl None
return -1
endif
if !executable('git')
echohl Error | echomsg "vim-go: git executable not found." | echohl None
return -1
endif
if !executable('hg')
echohl Error | echomsg "vim.go: hg (mercurial) executable not found." | echohl None
return -1
endif
endfunction
" vim:ts=4:sw=4:et

View file

@ -0,0 +1,78 @@
#!/bin/bash -e
#
# Copyright 2012 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
#
# Tests for import.vim.
cd $(dirname $0)
cat > base.go <<EOF
package test
import (
"bytes"
"io"
"net"
"mycorp/foo"
)
EOF
fail=0
# usage: test_one command pattern
# Pattern is a PCRE expression that will match across lines.
test_one() {
echo 2>&1 -n "$1: "
vim -e -s -u /dev/null -U /dev/null --noplugin -c "source import.vim" \
-c "$1" -c 'wq! test.go' base.go
# ensure blank lines are treated correctly
if ! gofmt test.go | cmp test.go -; then
echo 2>&1 "gofmt conflict"
gofmt test.go | diff -u test.go - | sed "s/^/ /" 2>&1
fail=1
return
fi
if ! [[ $(cat test.go) =~ $2 ]]; then
echo 2>&1 "$2 did not match"
cat test.go | sed "s/^/ /" 2>&1
fail=1
return
fi
echo 2>&1 "ok"
}
# Tests for Import
test_one "Import baz" '"baz".*"bytes"'
test_one "Import io/ioutil" '"io".*"io/ioutil".*"net"'
test_one "Import myc" '"io".*"myc".*"net"' # prefix of a site prefix
test_one "Import nat" '"io".*"nat".*"net"'
test_one "Import net/http" '"net".*"net/http".*"mycorp/foo"'
test_one "Import zoo" '"net".*"zoo".*"mycorp/foo"'
test_one "Import mycorp/bar" '"net".*"mycorp/bar".*"mycorp/foo"'
test_one "Import mycorp/goo" '"net".*"mycorp/foo".*"mycorp/goo"'
# Tests for Drop
cat > base.go <<EOF
package test
import (
"foo"
"something"
"zoo"
)
EOF
test_one "Drop something" '\([^"]*"foo"[^"]*"zoo"[^"]*\)'
rm -f base.go test.go
if [ $fail -gt 0 ]; then
echo 2>&1 "FAIL"
exit 1
fi
echo 2>&1 "PASS"

View file

@ -0,0 +1,276 @@
" Copyright 2009 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" go.vim: Vim syntax file for Go.
"
" Options:
" There are some options for customizing the highlighting; the recommended
" settings are the default values, but you can write:
" let OPTION_NAME = 0
" in your ~/.vimrc file to disable particular options. You can also write:
" let OPTION_NAME = 1
" to enable particular options. At present, all options default to on.
"
" - go_highlight_array_whitespace_error
" Highlights white space after "[]".
" - go_highlight_chan_whitespace_error
" Highlights white space around the communications operator that don't follow
" the standard style.
" - go_highlight_extra_types
" Highlights commonly used library types (io.Reader, etc.).
" - go_highlight_space_tab_error
" Highlights instances of tabs following spaces.
" - go_highlight_trailing_whitespace_error
" Highlights trailing white space.
" Quit when a (custom) syntax file was already loaded
if exists("b:current_syntax")
finish
endif
if !exists("g:go_highlight_array_whitespace_error")
let g:go_highlight_array_whitespace_error = 1
endif
if !exists("g:go_highlight_chan_whitespace_error")
let g:go_highlight_chan_whitespace_error = 1
endif
if !exists("g:go_highlight_extra_types")
let g:go_highlight_extra_types = 1
endif
if !exists("g:go_highlight_space_tab_error")
let g:go_highlight_space_tab_error = 1
endif
if !exists("g:go_highlight_trailing_whitespace_error")
let g:go_highlight_trailing_whitespace_error = 1
endif
if !exists("g:go_highlight_operators")
let g:go_highlight_operators = 1
endif
if !exists("g:go_highlight_functions")
let g:go_highlight_functions = 0
endif
if !exists("g:go_highlight_methods")
let g:go_highlight_methods = 0
endif
if !exists("g:go_highlight_structs")
let g:go_highlight_structs = 0
endif
syn case match
syn keyword goDirective package import
syn keyword goDeclaration var const type
syn keyword goDeclType struct interface
hi def link goDirective Statement
hi def link goDeclaration Keyword
hi def link goDeclType Keyword
" Keywords within functions
syn keyword goStatement defer go goto return break continue fallthrough
syn keyword goConditional if else switch select
syn keyword goLabel case default
syn keyword goRepeat for range
hi def link goStatement Statement
hi def link goConditional Conditional
hi def link goLabel Label
hi def link goRepeat Repeat
" Predefined types
syn keyword goType chan map bool string error
syn keyword goSignedInts int int8 int16 int32 int64 rune
syn keyword goUnsignedInts byte uint uint8 uint16 uint32 uint64 uintptr
syn keyword goFloats float32 float64
syn keyword goComplexes complex64 complex128
hi def link goType Type
hi def link goSignedInts Type
hi def link goUnsignedInts Type
hi def link goFloats Type
hi def link goComplexes Type
" Treat func specially: it's a declaration at the start of a line, but a type
" elsewhere. Order matters here.
syn match goDeclaration /\<func\>/
" Predefined functions and values
syn keyword goBuiltins append cap close complex copy delete imag len
syn keyword goBuiltins make new panic print println real recover
syn keyword goConstants iota true false nil
hi def link goBuiltins Keyword
hi def link goConstants Keyword
" Comments; their contents
syn keyword goTodo contained TODO FIXME XXX BUG
syn cluster goCommentGroup contains=goTodo
syn region goComment start="/\*" end="\*/" contains=@goCommentGroup,@Spell
syn region goComment start="//" end="$" contains=@goCommentGroup,@Spell
hi def link goComment Comment
hi def link goTodo Todo
" Go escapes
syn match goEscapeOctal display contained "\\[0-7]\{3}"
syn match goEscapeC display contained +\\[abfnrtv\\'"]+
syn match goEscapeX display contained "\\x\x\{2}"
syn match goEscapeU display contained "\\u\x\{4}"
syn match goEscapeBigU display contained "\\U\x\{8}"
syn match goEscapeError display contained +\\[^0-7xuUabfnrtv\\'"]+
hi def link goEscapeOctal goSpecialString
hi def link goEscapeC goSpecialString
hi def link goEscapeX goSpecialString
hi def link goEscapeU goSpecialString
hi def link goEscapeBigU goSpecialString
hi def link goSpecialString Special
hi def link goEscapeError Error
" Strings and their contents
syn cluster goStringGroup contains=goEscapeOctal,goEscapeC,goEscapeX,goEscapeU,goEscapeBigU,goEscapeError
syn region goString start=+"+ skip=+\\\\\|\\"+ end=+"+ contains=@goStringGroup
syn region goRawString start=+`+ end=+`+
hi def link goString String
hi def link goRawString String
" Characters; their contents
syn cluster goCharacterGroup contains=goEscapeOctal,goEscapeC,goEscapeX,goEscapeU,goEscapeBigU
syn region goCharacter start=+'+ skip=+\\\\\|\\'+ end=+'+ contains=@goCharacterGroup
hi def link goCharacter Character
" Regions
syn region goBlock start="{" end="}" transparent fold
syn region goParen start='(' end=')' transparent
" Integers
syn match goDecimalInt "\<\d\+\([Ee]\d\+\)\?\>"
syn match goHexadecimalInt "\<0x\x\+\>"
syn match goOctalInt "\<0\o\+\>"
syn match goOctalError "\<0\o*[89]\d*\>"
hi def link goDecimalInt Integer
hi def link goHexadecimalInt Integer
hi def link goOctalInt Integer
hi def link Integer Number
" Floating point
syn match goFloat "\<\d\+\.\d*\([Ee][-+]\d\+\)\?\>"
syn match goFloat "\<\.\d\+\([Ee][-+]\d\+\)\?\>"
syn match goFloat "\<\d\+[Ee][-+]\d\+\>"
hi def link goFloat Float
" Imaginary literals
syn match goImaginary "\<\d\+i\>"
syn match goImaginary "\<\d\+\.\d*\([Ee][-+]\d\+\)\?i\>"
syn match goImaginary "\<\.\d\+\([Ee][-+]\d\+\)\?i\>"
syn match goImaginary "\<\d\+[Ee][-+]\d\+i\>"
hi def link goImaginary Number
" Spaces after "[]"
if g:go_highlight_array_whitespace_error != 0
syn match goSpaceError display "\(\[\]\)\@<=\s\+"
endif
" Spacing errors around the 'chan' keyword
if g:go_highlight_chan_whitespace_error != 0
" receive-only annotation on chan type
syn match goSpaceError display "\(<-\)\@<=\s\+\(chan\>\)\@="
" send-only annotation on chan type
syn match goSpaceError display "\(\<chan\)\@<=\s\+\(<-\)\@="
" value-ignoring receives in a few contexts
syn match goSpaceError display "\(\(^\|[={(,;]\)\s*<-\)\@<=\s\+"
endif
" Extra types commonly seen
if g:go_highlight_extra_types != 0
syn match goExtraType /\<bytes\.\(Buffer\)\>/
syn match goExtraType /\<io\.\(Reader\|Writer\|ReadWriter\|ReadWriteCloser\)\>/
syn match goExtraType /\<reflect\.\(Kind\|Type\|Value\)\>/
syn match goExtraType /\<unsafe\.Pointer\>/
endif
" Space-tab error
if g:go_highlight_space_tab_error != 0
syn match goSpaceError display " \+\t"me=e-1
endif
" Trailing white space error
if g:go_highlight_trailing_whitespace_error != 0
syn match goSpaceError display excludenl "\s\+$"
endif
hi def link goExtraType Type
hi def link goSpaceError Error
" included from: https://github.com/athom/more-colorful.vim/blob/master/after/syntax/go.vim
"
" Comments; their contents
syn keyword goTodo contained NOTE
hi def link goTodo Todo
" Operators;
if g:go_highlight_operators != 0
syn match goOperator /:=/
syn match goOperator />=/
syn match goOperator /<=/
syn match goOperator /==/
syn match goOperator /!=/
syn match goOperator /+=/
syn match goOperator /-=/
syn match goOperator /\s>\s/
syn match goOperator /\s<\s/
syn match goOperator /\s+\s/
syn match goOperator /\s-\s/
syn match goOperator /\s\*\s/
syn match goOperator /\s\/\s/
syn match goOperator /\s%\s/
endif
hi def link goOperator Operator
" Functions;
if g:go_highlight_functions != 0
syn match goFunction /\(func\s\+\)\@<=\w\+\((\)\@=/
syn match goFunction /\()\s\+\)\@<=\w\+\((\)\@=/
endif
hi def link goFunction Function
" Methods;
if g:go_highlight_methods != 0
syn match goMethod /\(\.\)\@<=\w\+\((\)\@=/
endif
hi def link goMethod Type
" Structs;
if g:go_highlight_structs != 0
syn match goStruct /\(.\)\@<=\w\+\({\)\@=/
syn match goStructDef /\(type\s\+\)\@<=\w\+\(\s\+struct\s\+{\)\@=/
endif
hi def link goStruct Function
hi def link goStructDef Function
" Search backwards for a global declaration to start processing the syntax.
"syn sync match goSync grouphere NONE /^\(const\|var\|type\|func\)\>/
" There's a bug in the implementation of grouphere. For now, use the
" following as a more expensive/less precise workaround.
syn sync minlines=500
let b:current_syntax = "go"

View file

@ -0,0 +1,47 @@
" Copyright 2011 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
if exists("b:current_syntax")
finish
endif
syn case match
syn match godocTitle "^\([A-Z][A-Z ]*\)$"
hi def link godocTitle Title
" Single Line Definitions
syn match godocMethodRec /\i\+\ze)/ contained
syn match godocMethodName /) \zs\i\+\ze(/ contained
syn match godocMethod /^func \((\i\+ [^)]*)\) \i\+(/ contains=godocMethodRec,godocMethodName
syn match godocFunction /^func \zs\i\+\ze(/
syn match godocType /^type \zs\i\+\ze.*/
syn match godocVar /^var \zs\i\+\ze.*/
syn match godocConst /^const \zs\i\+\ze.*/
hi def link godocMethodRec Type
hi def link godocType Type
hi def link godocMethodName Function
hi def link godocFunction Function
hi def link godocVar Identifier
hi def link godocConst Identifier
" Definition Blocks
syn region godocComment start="/\*" end="\*/" contained
syn region godocComment start="//" end="$" contained
syn match godocDefinition /^\s\+\i\+/ contained
syn region godocVarBlock start=/^var (/ end=/^)/ contains=godocComment,godocDefinition
syn region godocConstBlock start=/^const (/ end=/^)/ contains=godocComment,godocDefinition
syn region godocTypeBlock start=/^type \i\+ \(interface\|struct\) {/ end=/^}/ matchgroup=godocType contains=godocComment,godocType
hi def link godocComment Comment
hi def link godocDefinition Identifier
syn sync minlines=500
let b:current_syntax = "godoc"
" vim:ts=4 sts=2 sw=2:

View file

@ -0,0 +1,11 @@
if exists("b:current_syntax")
finish
endif
let b:current_syntax = "vimgo"
syn match goInterface /^\S*/
syn region goTitle start="\%1l" end=":"
hi def link goInterface Type
hi def link goTitle Label

View file

@ -1,8 +0,0 @@
## Vim plugins have moved
The vim plugins have been removed from the Go repository along with all other
editor plugins. Please visit [The Go Wiki][1] for a current list of plugins. I
have personally moved over to the [vim-go][2] suite of plugins.
[1]: https://code.google.com/p/go-wiki/wiki/IDEsAndTextEditorPlugins
[2]: https://github.com/fatih/vim-go

View file

@ -1,19 +1,131 @@
priority -50
snippet . "selector { }"
$1 {
$0
}
endsnippet
snippet p "padding"
padding: ${1:0};$0
endsnippet
snippet m "margin"
margin: ${1:0};$0
endsnippet
snippet bd "border"
border: ${1:0};$0
endsnippet
snippet d "display"
display: ${1:none};$0
endsnippet
snippet bg "background"
background: ${1:none};$0
endsnippet
snippet ff "font-family"
font-family: ${1:"Helvetica Neue", Helvetica, Arial, sans-serif};$0
endsnippet
snippet h "height"
height: ${1:auto};$0
endsnippet
snippet w "width"
width: ${1:auto};$0
endsnippet
snippet pos "position"
position: ${1:relative};$0
endsnippet
snippet tt "text-transform"
text-transform: ${1:none};$0
endsnippet
snippet ! "!important CSS (!)"
!important
endsnippet
snippet tsh "text-shadow: color-hex x y blur (text)"
text-shadow: ${1:${2:color} ${3:offset-x} ${4:offset-y} ${5:blur}};$0
endsnippet
snippet bxsh "box-shadow: color-hex x y blur (text)"
box-shadow: ${1:${2:offset-x} ${3:offset-y} ${4:blur} ${5:spread} ${6:color}};$0
endsnippet
#
# Colors
#
snippet rgb "color rgb"
rgb(${1:255}, ${2:255}, ${3:255})$0
endsnippet
snippet rgba "color rgba"
rgba(${1:255}, ${2:255}, ${3:255}, ${4:0.5})$0
endsnippet
snippet hsl "color hsl"
hsl(${1:360}, ${2:100}%, ${3:100}%)$0
endsnippet
snippet hsla "color hsla"
hsla(${1:360}, ${2:100}%, ${3:100}%, ${4:0.5})$0
endsnippet
#
# Selectors
#
snippet :fc
:first-child
endsnippet
snippet :lc
:last-child
endsnippet
snippet :nc
:nth-child($0)
endsnippet
snippet :nlc
:nth-last-child($0)
endsnippet
snippet :oc
:only-child
endsnippet
#
# Pseudo-elements
#
snippet :a
:after
endsnippet
snippet :b
:before
endsnippet
snippet ::a
::after
endsnippet
snippet ::b
::before
endsnippet
###########################################################################
# Most of these came from TextMate #
###########################################################################
priority -50
snippet ! "!important CSS (!)"
${1:!important}
endsnippet
snippet fixed "Fixed Position Bottom 100% wide IE6"
${2:bottom: auto;}top: expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-${1:THE HEIGHT OF THIS THING IN PIXELS}));
${3:left: expression(eval(document.documentElement.scrollLeft));
}${4:width: expression(eval(document.documentElement.clientWidth));}$0
endsnippet
snippet background "background-attachment: scroll:fixed (background)"
background-attachment: ${1:scroll/fixed};$0
endsnippet
@ -360,26 +472,10 @@ snippet text "text-indent: length (text)"
text-indent: ${1:10}px;$0
endsnippet
snippet text "text-shadow: color-hex x y blur (text)"
text-shadow: #${1:DDD} ${2:10px} ${3:10px} ${4:2px};$0
endsnippet
snippet text "text-shadow: color-rgb x y blur (text)"
text-shadow: rgb(${1:255},${2:255},${3:255}) ${4:10px} ${5:10px} ${6:2px};$0
endsnippet
snippet text "text-shadow: none (text)"
text-shadow: none;$0
endsnippet
snippet text "text-transform: capitalize:upper:lower (text)"
text-transform: ${1:capitalize/uppercase/lowercase};$0
endsnippet
snippet text "text-transform: none (text)"
text-transform: none;$0
endsnippet
snippet vertical "vertical-align: type (vertical)"
vertical-align: ${1:baseline/sub/super/top/text-top/middle/bottom/text-bottom/length/%};$0
endsnippet
@ -396,10 +492,6 @@ snippet word "word-spacing: length (word)"
word-spacing: ${1:10px};$0
endsnippet
snippet word "word-spacing: normal (word)"
word-spacing: normal;$0
endsnippet
snippet z "z-index: index (z)"
z-index: $1;$0
endsnippet

View file

@ -17,7 +17,7 @@ ${1:name} :: ${2:Type} -> ${3:Type}
endsnippet
snippet => "Type constraint"
(${1:Class} ${2:Type var}) => ${3:$2}
(${1:Class} ${2:a}) => $2
endsnippet
snippet def "Function definition"
@ -50,7 +50,7 @@ snippet | "Guard"
endsnippet
snippet \ "Lambda expression"
\ ${1:pattern} -> ${2:expression}
\\${1:pattern} -> ${2:expression}
endsnippet
snippet [|] "List comprehension"
@ -61,3 +61,8 @@ snippet let "let ... in ..."
let ${1:name} = ${2:expression}
in ${3:expression}
endsnippet
snippet wh "where x = expression"
where
${1:name} = ${2:expression}
endsnippet

View file

@ -160,10 +160,6 @@ snippet base "XHTML <base>" w
<base href="$1"${2: target="$3"}`!p x(snip)`>
endsnippet
snippet img "XHTML <img>" w
<img src="${1:imgsrc}">
endsnippet
snippet body "XHTML <body>"
<body id="${1:`!p
snip.rv = snip.fn and 'Hallo' or 'Nothin'
@ -172,7 +168,13 @@ snip.rv = snip.fn and 'Hallo' or 'Nothin'
</body>
endsnippet
snippet div "XHTML <div>" 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 ""`>
$0
</div>
endsnippet
snippet div# "<div> with ID & class" w
<div`!p snip.rv=' id="' if t[1] else ""`${1:name}`!p snip.rv = '"' if t[1] else ""``!p snip.rv=' class="' if t[2] else ""`${2:name}`!p snip.rv = '"' if t[2] else ""`>
$0
</div>

View file

@ -169,3 +169,16 @@ endsnippet
snippet noscw "expect was not called with (js)" b
expect(${1:target}).wasNotCalledWith(${2:arguments});
endsnippet
snippet ethbc "expect to have been called (js)" b
expect(${1:target}).toHaveBeenCalled();
endsnippet
snippet nthbc "expect not to have been called (js)" b
expect(${1:target}).not.toHaveBeenCalled();
endsnippet
snippet ethbcw "expect to have been called with (js)" b
expect(${1:target}).toHaveBeenCalledWith(${2:arguments});
endsnippet

View file

@ -36,8 +36,8 @@ DOXYGEN = 0x2
SPHINX = 0x3
GOOGLE = 0x4
SINGLE_QUOTES = 0x1
DOUBLE_QUOTES = 0x2
SINGLE_QUOTES = "'"
DOUBLE_QUOTES = '"'
class Arg(object):
@ -69,9 +69,35 @@ def get_quoting_style(snip):
return DOUBLE_QUOTES
def triple_quotes(snip):
if get_quoting_style(snip) == SINGLE_QUOTES:
return "'''"
return '"""'
return get_quoting_style(snip) * 3
def triple_quotes_handle_trailing(snip, quoting_style):
"""
Generate triple quoted strings and handle any trailing quote char,
which might be there from some autoclose/autopair plugin,
i.e. when expanding ``"|"``.
"""
if not snip.c:
# Do this only once, otherwise the following error would happen:
# RuntimeError: The snippets content did not converge: …
_, col = vim.current.window.cursor
line = vim.current.line
# Handle already existing quote chars after the trigger.
_ret = quoting_style * 3
while True:
try:
nextc = line[col]
except IndexError:
break
if nextc == quoting_style and len(_ret):
_ret = _ret[1:]
col = col+1
else:
break
snip.rv = _ret
else:
snip.rv = snip.c
def get_style(snip):
style = snip.opt("g:ultisnips_python_style", "normal")
@ -613,4 +639,22 @@ class Test${1:Class}(${2:unittest.TestCase}):
${7:pass}
endsnippet
snippet " "triple quoted string (double quotes)" b
"""
${1:doc}
`!p triple_quotes_handle_trailing(snip, '"')`
endsnippet
snippet ' "triple quoted string (single quotes)" b
'''
${1:doc}
`!p triple_quotes_handle_trailing(snip, "'")`
endsnippet
snippet doc "doc block (triple quotes)"
`!p snip.rv = triple_quotes(snip)`
${1:doc}
`!p snip.rv = triple_quotes(snip)`
endsnippet
# vim:ft=snippets:

View file

@ -128,4 +128,4 @@ snippet ife
${0}
<% end %>
snippet pry
<% require 'pry'; binding.pry %>
<% require 'pry'; binding.pry %>

View file

@ -14,10 +14,14 @@ snippet info
--
-- ${0:Description}
--
snippet imp
import ${0:Data.Text}
snippet import
import ${0:Data.Text}
snippet import2
import ${1:Data.Text} (${0:head})
snippet impq
import qualified ${1:Data.Text} as ${0:T}
snippet importq
import qualified ${1:Data.Text} as ${0:T}
snippet inst
@ -52,9 +56,11 @@ snippet do
do
snippet λ
\${1:x} -> ${0}
\\${1:x} -> ${0:expression}
snippet \
\${1:x} -> ${0}
\\${1:x} -> ${0:expression}
snippet (\
(\\${1:x} -> ${0:expression})
snippet <-
${1:a} <- ${0:m a}
snippet ←

View file

@ -674,11 +674,11 @@ snippet ol
${0}
</ol>
snippet ol.
<ol class="${1}>
<ol class="${1}">
${0}
</ol>
snippet ol#
<ol id="${1}>
<ol id="${1}">
${0}
</ol>
snippet ol+

View file

@ -42,6 +42,11 @@ snippet fori
for (${1:i} <- ${2:0} to ${3:obj}.length) {
${0}
}
#for comprehension
snippet fory
for {
${1:item} <- ${2:obj}
} yield ${0}
#exceptions
snippet try
try {

View file

@ -7,3 +7,5 @@ snippet msnip
${0}
snippet v
{VISUAL}
snippet $
${${1:1}:${0:text}}

View file

@ -38,7 +38,7 @@ vim-zenroom2 https://github.com/amix/vim-zenroom2
syntastic https://github.com/scrooloose/syntastic
vim-repeat https://github.com/tpope/vim-repeat
vim-commentary https://github.com/tpope/vim-commentary
vim-golang https://github.com/jnwhiteh/vim-golang
vim-go https://github.com/fatih/vim-go
""".strip()
GITHUB_ZIP = '%s/archive/master.zip'