1
0
mirror of https://github.com/amix/vimrc synced 2025-06-16 09:35:01 +08: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

@ -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: