1
0
mirror of https://github.com/amix/vimrc synced 2025-06-16 09:35:01 +08:00

Updated vim plugins

This commit is contained in:
amix
2015-02-24 10:45:22 +00:00
parent 8fa0bd4574
commit d195ccb777
104 changed files with 1743 additions and 1464 deletions

View File

@ -37,26 +37,28 @@ disabled/enabled easily.
## Install
First of all, do not use it with other Go plugins. If you use pathogen, just
clone it into your bundle directory:
Vim-go follows the standard runtime path structure, so I highly recommend to use
a common and well known plugin manager to install vim-go. Do not use vim-go with
other Go plugins. For Pathogen just clone the repo, for other plugin managers
add the appropriate lines and execute the plugin's install command.
```bash
$ cd ~/.vim/bundle
$ git clone https://github.com/fatih/vim-go.git
```
* [Pathogen](https://github.com/tpope/vim-pathogen)
* `git clone https://github.com/fatih/vim-go.git ~/.vim/bundle/vim-go`
* [vim-plug](https://github.com/junegunn/vim-plug)
* `Plug 'fatih/vim-go'`
* [NeoBundle](https://github.com/Shougo/neobundle.vim)
* `NeoBundle 'fatih/vim-go'`
* [Vundle](https://github.com/gmarik/vundle)
* `Plugin 'fatih/vim-go'`
* Manual
* Copy all of the files into your `~/.vim` directory
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` command. 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
`:GoInstallBinaries` command. If you invoke it, all necessary binaries will be
automatically downloaded and installed to your `$GOBIN` environment (if not set
it will use `$GOPATH/bin`). It requires `git` for fetching the individual Go
packages.
### Optional

View File

@ -68,7 +68,7 @@ function! go#fmt#Format(withGoimport)
" restore 'redo' history because it's getting being destroyed every
" BufWritePre
let tmpundofile=tempname()
exe 'wundo! ' . Tmpundofile
exe 'wundo! ' . tmpundofile
endif
" get the command first so we can test it

View File

@ -10,16 +10,20 @@ if !exists("g:go_oracle_bin")
let g:go_oracle_bin = "oracle"
endif
" Parses (via regex) Oracle's 'plain' format output and puts them into a
" quickfix list.
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],
@ -36,6 +40,31 @@ func! s:qflist(output)
cwindow
endfun
" This uses Vim's errorformat to parse the output from Oracle's 'plain output
" and put it into quickfix list. I believe using errorformat is much more
" easier to use. If we need more power we can always switch back to parse it
" via regex.
func! s:qflistSecond(output)
" backup users errorformat, will be restored once we are finished
let old_errorformat = &errorformat
" match two possible styles of errorformats:
"
" 'file:line.col-line2.col2: message'
" 'file:line:col: message'
"
" We discard line2 and col2 for the first errorformat, because it's not
" useful and quickfix only has the ability to show one line and column
" number
let &errorformat = "%f:%l.%c-%.%#:\ %m,%f:%l:%c:\ %m"
" create the quickfix list and open it
cgetexpr split(a:output, "\n")
cwindow
let &errorformat = old_errorformat
endfun
func! s:getpos(l, c)
if &encoding != 'utf-8'
let buf = a:l == 1 ? '' : (join(getline(1, a:l-1), "\n") . "\n")
@ -50,16 +79,21 @@ func! s:RunOracle(mode, selected) range abort
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'))
if exists('g:go_oracle_scope')
" let the user defines the scope, must be a space separated string,
" example: 'fmt math net/http'
let unescaped_scopes = split(get(g:, 'go_oracle_scope'))
let scopes = []
for unescaped_scope in unescaped_scopes
call add(scopes, shellescape(unescaped_scope))
endfor
elseif exists('g:go_oracle_include_tests') && pkg != -1
" give import path so it includes all _test.go files too
let sname = shellescape(pkg)
let scopes = [shellescape(pkg)]
else
" best usable way, only pass the package itself, without the test
" files
let sname = join(go#tool#Files(), ' ')
let scopes = go#tool#Files()
endif
"return with a warning if the bin doesn't exist
@ -71,16 +105,24 @@ func! s:RunOracle(mode, selected) range abort
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',
let cmd = printf('%s -format plain -pos=%s:#%d,#%d %s',
\ bin_path,
\ shellescape(fname), pos1, pos2, a:mode, sname)
\ shellescape(fname), pos1, pos2, a:mode)
else
let pos = s:getpos(line('.'), col('.'))
let cmd = printf('%s -format json -pos=%s:#%d %s %s',
let cmd = printf('%s -format plain -pos=%s:#%d %s',
\ bin_path,
\ shellescape(fname), pos, a:mode, sname)
\ shellescape(fname), pos, a:mode)
endif
" now append each scope to the end as Oracle's scope parameter. It can be
" a packages or go files, dependent on the User's own choice. For more
" info check Oracle's User Manual section about scopes:
" https://docs.google.com/document/d/1SLk36YRjjMgKqe490mSRzOPYEDe0Y_WQNRv-EiFYUyw/view#heading=h.nwso96pj07q8
for scope in scopes
let cmd .= ' ' . scope
endfor
echon "vim-go: " | echohl Identifier | echon "analysing ..." | echohl None
let out = system(cmd)
@ -89,169 +131,65 @@ func! s:RunOracle(mode, selected) range abort
" parsable to show the real error. But the main issue is usually the
" package which doesn't build.
redraw | echon "vim-go: " | echohl Statement | echon out | echohl None
return {}
return ""
else
let json_decoded = webapi#json#decode(out)
return json_decoded
endif
return out
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("Implements", result)
" define some buffer related mappings:
"
" go to definition when hit enter
nnoremap <buffer> <CR> :<C-u>call go#ui#OpenDefinition("implements")<CR>
" close the window when hit ctrl-c
nnoremap <buffer> <c-c> :<C-u>call go#ui#CloseWindow()<CR>
call s:qflistSecond(out)
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
call s:qflistSecond(out)
endfunction
" Show possible targets of selected function call
function! go#oracle#Callees(selected)
let out = s:RunOracle('callees', a:selected)
if empty(out)
return
endif
" be sure the callees object exists which contains the position and names
" of the callees, before we continue
if !has_key(out, "callees")
return
endif
" get the callees list
if has_key(out.callees, "callees")
let callees = out.callees.callees
else
redraw | echon "vim-go: " | echon "no callees available"| echohl None
return
endif
let title = "Call targets:"
" start to populate our buffer content
let result = [title, ""]
for calls in callees
let line = calls.name . "\t" . calls.pos
call add(result, line)
endfor
" open a window and put the result
call go#ui#OpenWindow("Callees", result)
" define some buffer related mappings:
"
" go to definition when hit enter
nnoremap <buffer> <CR> :<C-u>call go#ui#OpenDefinition("call targets")<CR>
" close the window when hit ctrl-c
nnoremap <buffer> <c-c> :<C-u>call go#ui#CloseWindow()<CR>
call s:qflistSecond(out)
endfunction
" Show possible callers of selected function
function! go#oracle#Callers(selected)
let out = s:RunOracle('callers', a:selected)
echo out
call s:qflistSecond(out)
endfunction
" Show the callgraph of the current program.
function! go#oracle#Callgraph(selected)
let out = s:RunOracle('callgraph', a:selected)
echo out
call s:qflistSecond(out)
endfunction
" Show path from callgraph root to selected function
function! go#oracle#Callstack(selected)
let out = s:RunOracle('callstack', a:selected)
echo out
call s:qflistSecond(out)
endfunction
" Show free variables of selection
function! go#oracle#Freevars(selected)
let out = s:RunOracle('freevars', a:selected)
echo out
call s:qflistSecond(out)
endfunction
" Show send/receive corresponding to selected channel op
function! go#oracle#Peers(selected)
function! go#oracle#ChannelPeers(selected)
let out = s:RunOracle('peers', a:selected)
echo out
call s:qflistSecond(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
call s:qflistSecond(out)
endfunction
" vim:ts=4:sw=4:et

View File

@ -1,135 +0,0 @@
" 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

@ -243,9 +243,7 @@ COMMANDS *go-commands*
Show 'implements' relation for a selected package. A list of interfaces
for the type that implements an interface 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>`.
package) is shown quickfix list.
*:GoRename*
:GoRename [to]
@ -255,11 +253,73 @@ COMMANDS *go-commands*
*:GoCallees*
:GoCallees
Show 'callees' relation for a selected package. A list of call targets
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>`. For
example if called for a interface method call, it will show all call targets
that has implemented the method.
Show 'callees' relation for a selected package. A list of possible call
targets for the type under the cursor (or selected package) is shown in a
quickfix list.
*:GoCallers*
:GoCallers
Show 'callers' relation for a selected function. A list of possible
callers for the selected function under the cursor is shown in a quickfix
list.
*:GoDescribe*
:GoDescribe
Shows various properties of the selected syntax: its syntactic kind, its
type (for an expression), its value (for a constant expression), its size,
alignment, method set and interfaces (for a type), its declaration (for an
identifier), etc. Almost any piece of syntax may be described, and the
oracle will try to print all the useful information it can.
*:GoCallgraph*
:GoCallgraph
Shows the 'callgraph' for the entire program. For more info about the
indentation checkout the Oracle User Manual:
golang.org/s/oracle-user-manual
*:GoCallstack*
:GoCallstack
Shows 'callstack' relation for the selected function. An arbitrary path
from the root of the callgrap to the selected function is showed in a
quickfix list. This may be useful to understand how the function is
reached in a given program.
*:GoFreevars*
:GoFreevars
Enumerates the free variables of the selection. “Free variables” is a
technical term meaning the set of variables that are referenced but not
defined within the selection, or loosely speaking, its inputs.
This information is useful if youre considering whether to refactor the
selection into a function of its own, as the free variables would be the
necessary parameters of that function. Its also useful when you want to
understand what the inputs are to a complex block of code even if you
dont plan to change it.
*:GoChannelPeers*
:GoChannelPeers
Shows the set of possible sends/receives on the channel operand of the
selected send or receive operation; the selection must be a <- token.
For example, visually select a channel operand in the form of:
"done <- true"
and call |GoChannelPeers| on it. It will show where it was allocated, and
the sending and receiving endings.
*:GoReferrers*
:GoReferrers
The referrers query shows the set of identifiers that refer to the same
object as does the selected identifier, within any package in the analysis
scope.
===============================================================================
@ -271,8 +331,9 @@ 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:
As always one is free to create more advanced mappings or functions based with
|go-commands|. For more information please check out the mappings command
documentation in the |go-commands| section. Available <Plug> keys are:
*(go-run)*
@ -372,6 +433,36 @@ Rename the identifier under the cursor to the desired new name
Show the call targets for the type under the cursor
*(go-callers)*
Show possible callers of selected function
*(go-describe)*
Describe selected syntax: definition, methods, etc
*(go-callgraph)*
Show the callgraph of the current program.
*(go-callstack)*
Show path from callgraph root to selected function
*(go-freevars)*
Show free variables of selection
*(go-channelpeers)*
Show send/receive corresponding to selected channel op
*(go-referrers)*
Show all refs to entity denoted by selected identifier
===============================================================================
TEXT OBJECTS *go-text-objects*
@ -387,6 +478,7 @@ if "inside a function", select contents of a function,
excluding the function definition and the closing bracket.
===============================================================================
SETTINGS *go-settings*
@ -499,6 +591,18 @@ is used. Use "neosnippet" for neosnippet.vim: >
let g:go_snippet_engine = "ultisnips"
<
*'g:go_oracle_scope'*
Use this option to define the scope of the analysis to be passed for Oracle
related commands, such as |GoImplements|, |GoCallers|, etc.. By default it's
not set, so only the current packages go files are passed as scope. For more
info please have look at Oracle's User Manual:
https://docs.google.com/document/d/1SLk36YRjjMgKqe490mSRzOPYEDe0Y_WQNRv-EiFYUyw/view#heading=h.nwso96pj07q8
>
let g:go_oracle_scope = ''
<
*'g:go_highlight_array_whitespace_error'*
Highlights white space after "[]". >

View File

@ -18,6 +18,13 @@ nnoremap <silent> <Plug>(go-import) :<C-u>call go#import#SwitchImport(1, '', exp
nnoremap <silent> <Plug>(go-implements) :<C-u>call go#oracle#Implements(-1)<CR>
nnoremap <silent> <Plug>(go-callees) :<C-u>call go#oracle#Callees(-1)<CR>
nnoremap <silent> <Plug>(go-callers) :<C-u>call go#oracle#Callers(-1)<CR>
nnoremap <silent> <Plug>(go-describe) :<C-u>call go#oracle#Describe(-1)<CR>
nnoremap <silent> <Plug>(go-callgraph) :<C-u>call go#oracle#Callgraph(-1)<CR>
nnoremap <silent> <Plug>(go-callstack) :<C-u>call go#oracle#Callstack(-1)<CR>
nnoremap <silent> <Plug>(go-freevars) :<C-u>call go#oracle#Freevars(-1)<CR>
nnoremap <silent> <Plug>(go-channelpeers) :<C-u>call go#oracle#ChannelPeers(-1)<CR>
nnoremap <silent> <Plug>(go-referrers) :<C-u>call go#oracle#Referrers(-1)<CR>
nnoremap <silent> <Plug>(go-rename) :<C-u>call go#rename#Rename()<CR>
@ -39,6 +46,13 @@ command! -nargs=? GoRename call go#rename#Rename(<f-args>)
" oracle
command! -range=% GoImplements call go#oracle#Implements(<count>)
command! -range=% GoCallees call go#oracle#Callees(<count>)
command! -range=% GoDescribe call go#oracle#Describe(<count>)
command! -range=% GoCallers call go#oracle#Callers(<count>)
command! -range=% GoCallgraph call go#oracle#Callgraph(<count>)
command! -range=% GoCallstack call go#oracle#Callstack(<count>)
command! -range=% GoFreevars call go#oracle#Freevars(<count>)
command! -range=% GoChannelPeers call go#oracle#ChannelPeers(<count>)
command! -range=% GoReferrers call go#oracle#Referrers(<count>)
" tool
command! -nargs=0 GoFiles echo go#tool#Files()
@ -78,16 +92,4 @@ command! GoLint call go#lint#Run()
" -- errcheck
command! -nargs=? -complete=customlist,go#package#Complete GoErrCheck call go#errcheck#Run(<f-args>)
" Disable all commands until they are fully integrated.
"
" command! -range=% GoOracleDescribe call go#oracle#Describe(<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

@ -20,6 +20,11 @@ snippet ap "append(slice, value)"
append(${1:slice}, ${0:value})
endsnippet
# append assignment
snippet ap= "a = append(a, value)"
${1:slice} = append($1, ${0:value})
endsnippet
# break
snippet br "break"
break
@ -147,6 +152,14 @@ if err != nil {
${0}
endsnippet
# error snippet
snippet errt "Error test fatal " !b
if err != nil {
t.Fatal(err)
}
${0}
endsnippet
snippet errn, "Error return with two return values" !b
if err != nil {
return ${1:nil}, err
@ -307,6 +320,30 @@ func Test${1:Function}(t *testing.T) {
}
endsnippet
# quick test server
snippet tsrv "httptest.NewServer"
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, ${1:`response`})
}))
defer ts.Close()
${0:someUrl} = ts.URL
endsnippet
# test error handling
snippet ter "if err != nil { t.Errorf(...) }"
if err != nil {
t.Errorf("${0:message}")
}
endsnippet
# test fatal error
snippet terf "if err != nil { t.Fatalf(...) }"
if err != nil {
t.Fatalf("${0:message}")
}
endsnippet
# variable declaration
snippet var "var x Type [= ...]"
var ${1:x} ${2:Type}${3: = ${0:value\}}
@ -344,6 +381,4 @@ def closing_par(snip, pos):
endglobal
# vim:ft=snippets:

View File

@ -12,6 +12,10 @@ abbr fn := func() { ... }
snippet ap
abbr append(slice, value)
append(${1:slice}, ${0:value})
# append assign
snippet ap=
abbr slice = append(slice, value)
${1:slice} = append($1, ${0:value})
# break
snippet br
abbr break
@ -120,6 +124,12 @@ abbr if err != nil { ... }
if err != nil {
return err
}
# error snippet in TestFunc
snippet errt
abbr if err != nil { ... }
if err != nil {
t.Fatal(err)
}
# error snippet with two return values
snippet errn,
@ -262,6 +272,28 @@ abbr func TestXYZ(t *testing.T) { ... }
func Test${1:Function}(t *testing.T) {
${0}
}
# test server
snippet tsrv
abbr ts := httptest.NewServer(...)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, ${1:`response`})
}))
defer ts.Close()
//Use testing server url (type string) somewhere
${0:someUrl} = ts.URL
# test error
snippet ter
abbr if err != nil { t.Errorf(...) }
if err != nil {
t.Errorf("${1}")
}
# test fatal error
snippet terf
abbr if err != nil { t.Fatalf(...) }
if err != nil {
t.Fatalf("${1}")
}
# variable declaration
snippet var
abbr var x Type [= ...]

View File

@ -9,7 +9,7 @@
" - general line splits (line ends in an operator)
if exists("b:did_indent")
finish
finish
endif
let b:did_indent = 1
@ -21,46 +21,58 @@ setlocal indentexpr=GoIndent(v:lnum)
setlocal indentkeys+=<:>,0=},0=)
if exists("*GoIndent")
finish
finish
endif
" use shiftwidth function only if it's available
if exists('*shiftwidth')
func s:sw()
return shiftwidth()
endfunc
else
func s:sw()
return &sw
endfunc
endif
function! GoIndent(lnum)
let prevlnum = prevnonblank(a:lnum-1)
if prevlnum == 0
" top of file
return 0
endif
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)
" 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
let s:shiftwidth = shiftwidth()
let ind = previ
if prevl =~ '[({]\s*$'
" previous line opened a block
let ind += s:shiftwidth
endif
if prevl =~# '^\s*\(case .*\|default\):$'
" previous line is part of a switch statement
let ind += s:shiftwidth
endif
" TODO: handle if the previous line is a label.
if prevl =~ '[({]\s*$'
" previous line opened a block
let ind += s:sw()
endif
if prevl =~# '^\s*\(case .*\|default\):$'
" previous line is part of a switch statement
let ind += s:sw()
endif
" TODO: handle if the previous line is a label.
if thisl =~ '^\s*[)}]'
" this line closed a block
let ind -= s:shiftwidth
endif
if thisl =~ '^\s*[)}]'
" this line closed a block
let ind -= s: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 -= s:shiftwidth
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 -= s:sw()
endif
return ind
return ind
endfunction
" vim:ts=4:sw=4:et